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.exception.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) throws PortalException {
051 try {
052 File file = getFile(image.getImageId(), image.getType());
053
054 if (!file.exists()) {
055 throw new NoSuchFileException(file.getPath());
056 }
057
058 return FileUtil.getBytes(file);
059 }
060 catch (IOException ioe) {
061 throw new SystemException(ioe);
062 }
063 }
064
065 @Override
066 public InputStream getImageAsStream(Image image) throws PortalException {
067 try {
068 File file = getFile(image.getImageId(), image.getType());
069
070 if (!file.exists()) {
071 throw new NoSuchFileException(file.getPath());
072 }
073
074 return new FileInputStream(file);
075 }
076 catch (IOException ioe) {
077 throw new SystemException(ioe);
078 }
079 }
080
081 @Override
082 public void updateImage(Image image, String type, byte[] bytes) {
083 try {
084 File file = getFile(image.getImageId(), type);
085
086 FileUtil.write(file, bytes);
087 }
088 catch (IOException ioe) {
089 throw new SystemException(ioe);
090 }
091 }
092
093 protected String buildPath(String fileNameFragment) {
094 int fileNameFragmentLength = fileNameFragment.length();
095
096 if (fileNameFragmentLength <= 2) {
097 return StringPool.BLANK;
098 }
099
100 StringBundler sb = new StringBundler(
101 fileNameFragmentLength / 2 + fileNameFragmentLength);
102
103 for (int i = 0; i < fileNameFragmentLength; i += 2) {
104 if ((i + 2) < fileNameFragmentLength) {
105 sb.append(StringPool.SLASH);
106 sb.append(fileNameFragment.substring(i, i + 2));
107 }
108 }
109
110 return sb.toString();
111 }
112
113 protected File getFile(long imageId, String type) {
114 String path = buildPath(String.valueOf(imageId));
115
116 return new File(
117 _rootDir + StringPool.SLASH + path + StringPool.SLASH +
118 imageId + StringPool.PERIOD + type);
119 }
120
121 private final File _rootDir;
122
123 }