001
014
015 package com.liferay.portal.image;
016
017 import com.liferay.documentlibrary.NoSuchFileException;
018 import com.liferay.portal.kernel.exception.PortalException;
019 import com.liferay.portal.kernel.exception.SystemException;
020 import com.liferay.portal.kernel.util.FileUtil;
021 import com.liferay.portal.kernel.util.StringBundler;
022 import com.liferay.portal.kernel.util.StringPool;
023 import com.liferay.portal.model.Image;
024 import com.liferay.portal.util.PropsValues;
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() {
037 _rootDir = new File(PropsValues.IMAGE_HOOK_FILE_SYSTEM_ROOT_DIR);
038
039 if (!_rootDir.exists()) {
040 _rootDir.mkdirs();
041 }
042 }
043
044 public void deleteImage(Image image) {
045 File file = getFile(image.getImageId(), image.getType());
046
047 FileUtil.delete(file);
048 }
049
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 public InputStream getImageAsStream(Image image)
068 throws PortalException, SystemException {
069
070 try {
071 File file = getFile(image.getImageId(), image.getType());
072
073 if (!file.exists()) {
074 throw new NoSuchFileException(file.getPath());
075 }
076
077 return new FileInputStream(file);
078 }
079 catch (IOException ioe) {
080 throw new SystemException(ioe);
081 }
082 }
083
084 public void updateImage(Image image, String type, byte[] bytes)
085 throws SystemException {
086
087 try {
088 File file = getFile(image.getImageId(), type);
089
090 FileUtil.write(file, bytes);
091 }
092 catch (IOException ioe) {
093 throw new SystemException(ioe);
094 }
095 }
096
097 protected String buildPath(String fileNameFragment) {
098 int fileNameFragmentLength = fileNameFragment.length();
099
100 if (fileNameFragmentLength <= 2) {
101 return StringPool.BLANK;
102 }
103
104 StringBundler sb = new StringBundler(
105 fileNameFragmentLength / 2 + fileNameFragmentLength);
106
107 for (int i = 0; i < fileNameFragmentLength; i += 2) {
108 if ((i + 2) < fileNameFragmentLength) {
109 sb.append(StringPool.SLASH);
110 sb.append(fileNameFragment.substring(i, i + 2));
111 }
112 }
113
114 return sb.toString();
115 }
116
117 protected File getFile(long imageId, String type) {
118 String path = buildPath(String.valueOf(imageId));
119
120 return new File(
121 _rootDir + StringPool.SLASH + path + StringPool.SLASH +
122 imageId + StringPool.PERIOD + type);
123 }
124
125 private File _rootDir;
126
127 }