001
014
015 package com.liferay.portal.image;
016
017 import com.liferay.portal.kernel.exception.PortalException;
018 import com.liferay.portal.kernel.exception.SystemException;
019 import com.liferay.portal.kernel.util.FileUtil;
020 import com.liferay.portal.kernel.util.StringBundler;
021 import com.liferay.portal.kernel.util.StringPool;
022 import com.liferay.portal.model.Image;
023 import com.liferay.portal.util.PropsValues;
024 import com.liferay.portlet.documentlibrary.NoSuchFileException;
025
026 import java.io.File;
027 import java.io.FileInputStream;
028 import java.io.IOException;
029 import java.io.InputStream;
030
031
034 public class FileSystemHook extends BaseHook {
035
036 public FileSystemHook() throws IOException {
037 _rootDir = new File(PropsValues.IMAGE_HOOK_FILE_SYSTEM_ROOT_DIR);
038
039 FileUtil.mkdirs(_rootDir);
040 }
041
042 @Override
043 public void deleteImage(Image image) {
044 File file = getFile(image.getImageId(), image.getType());
045
046 FileUtil.delete(file);
047 }
048
049 @Override
050 public byte[] getImageAsBytes(Image image)
051 throws PortalException, SystemException {
052
053 try {
054 File file = getFile(image.getImageId(), image.getType());
055
056 if (!file.exists()) {
057 throw new NoSuchFileException(file.getPath());
058 }
059
060 return FileUtil.getBytes(file);
061 }
062 catch (IOException ioe) {
063 throw new SystemException(ioe);
064 }
065 }
066
067 @Override
068 public InputStream getImageAsStream(Image image)
069 throws PortalException, SystemException {
070
071 try {
072 File file = getFile(image.getImageId(), image.getType());
073
074 if (!file.exists()) {
075 throw new NoSuchFileException(file.getPath());
076 }
077
078 return new FileInputStream(file);
079 }
080 catch (IOException ioe) {
081 throw new SystemException(ioe);
082 }
083 }
084
085 @Override
086 public void updateImage(Image image, String type, byte[] bytes)
087 throws SystemException {
088
089 try {
090 File file = getFile(image.getImageId(), type);
091
092 FileUtil.write(file, bytes);
093 }
094 catch (IOException ioe) {
095 throw new SystemException(ioe);
096 }
097 }
098
099 protected String buildPath(String fileNameFragment) {
100 int fileNameFragmentLength = fileNameFragment.length();
101
102 if (fileNameFragmentLength <= 2) {
103 return StringPool.BLANK;
104 }
105
106 StringBundler sb = new StringBundler(
107 fileNameFragmentLength / 2 + fileNameFragmentLength);
108
109 for (int i = 0; i < fileNameFragmentLength; i += 2) {
110 if ((i + 2) < fileNameFragmentLength) {
111 sb.append(StringPool.SLASH);
112 sb.append(fileNameFragment.substring(i, i + 2));
113 }
114 }
115
116 return sb.toString();
117 }
118
119 protected File getFile(long imageId, String type) {
120 String path = buildPath(String.valueOf(imageId));
121
122 return new File(
123 _rootDir + StringPool.SLASH + path + StringPool.SLASH +
124 imageId + StringPool.PERIOD + type);
125 }
126
127 private File _rootDir;
128
129 }