1
22
23 package com.liferay.portal.image;
24
25 import com.liferay.documentlibrary.NoSuchFileException;
26 import com.liferay.portal.PortalException;
27 import com.liferay.portal.SystemException;
28 import com.liferay.portal.kernel.util.FileUtil;
29 import com.liferay.portal.kernel.util.StringPool;
30 import com.liferay.portal.model.Image;
31 import com.liferay.portal.util.PropsValues;
32
33 import java.io.File;
34 import java.io.FileInputStream;
35 import java.io.IOException;
36 import java.io.InputStream;
37
38
44 public class FileSystemHook extends BaseHook {
45
46 public FileSystemHook() {
47 _rootDir = new File(PropsValues.IMAGE_HOOK_FILE_SYSTEM_ROOT_DIR);
48
49 if (!_rootDir.exists()) {
50 _rootDir.mkdirs();
51 }
52 }
53
54 public void deleteImage(Image image) {
55 File file = getFile(image.getImageId(), image.getType());
56
57 FileUtil.delete(file);
58 }
59
60 public byte[] getImageAsBytes(Image image)
61 throws PortalException, SystemException {
62
63 try {
64 File file = getFile(image.getImageId(), image.getType());
65
66 if (!file.exists()) {
67 throw new NoSuchFileException(file.getPath());
68 }
69
70 return FileUtil.getBytes(file);
71 }
72 catch (IOException ioe) {
73 throw new SystemException(ioe);
74 }
75 }
76
77 public InputStream getImageAsStream(Image image)
78 throws PortalException, SystemException {
79
80 try {
81 File file = getFile(image.getImageId(), image.getType());
82
83 if (!file.exists()) {
84 throw new NoSuchFileException(file.getPath());
85 }
86
87 return new FileInputStream(file);
88 }
89 catch (IOException ioe) {
90 throw new SystemException(ioe);
91 }
92 }
93
94 public void updateImage(Image image, String type, byte[] bytes)
95 throws SystemException {
96
97 try {
98 File file = getFile(image.getImageId(), type);
99
100 FileUtil.write(file, bytes);
101 }
102 catch (IOException ioe) {
103 throw new SystemException(ioe);
104 }
105 }
106
107 protected void buildPath(StringBuilder sb, String fileNameFragment) {
108 if (fileNameFragment.length() <= 2) {
109 return;
110 }
111
112 sb.append(StringPool.SLASH);
113 sb.append(fileNameFragment.substring(0, 2));
114
115 buildPath(sb, fileNameFragment.substring(2));
116 }
117
118 protected File getFile(long imageId, String type) {
119 StringBuilder sb = new StringBuilder();
120
121 buildPath(sb, String.valueOf(imageId));
122
123 return new File(
124 _rootDir + StringPool.SLASH + sb.toString() + StringPool.SLASH +
125 imageId + StringPool.PERIOD + type);
126 }
127
128 private File _rootDir;
129
130 }