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