KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > j2biz > blogunity > util > ResourceUtils


1 /*
2  * $Id: ResourceUtils.java,v 1.10 2005/01/08 15:52:29 michelson Exp $
3  *
4  * Copyright (c) 2004 j2biz Group, http://www.j2biz.com
5  * Koeln / Duesseldorf , Germany
6  *
7  * @author Max Kalina
8  *
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23  *
24  */

25
26 package com.j2biz.blogunity.util;
27
28 import java.io.File JavaDoc;
29 import java.io.FileInputStream JavaDoc;
30 import java.io.FileNotFoundException JavaDoc;
31 import java.io.FileOutputStream JavaDoc;
32 import java.io.IOException JavaDoc;
33 import java.io.InputStream JavaDoc;
34 import java.io.OutputStream JavaDoc;
35 import java.text.DecimalFormat JavaDoc;
36 import java.util.zip.ZipEntry JavaDoc;
37 import java.util.zip.ZipInputStream JavaDoc;
38 import java.util.zip.ZipOutputStream JavaDoc;
39
40 import org.apache.commons.lang.StringUtils;
41 import org.apache.commons.logging.Log;
42 import org.apache.commons.logging.LogFactory;
43
44 import com.j2biz.blogunity.BlogunityManager;
45 import com.j2biz.blogunity.exception.BlogunityException;
46 import com.j2biz.blogunity.i18n.I18N;
47 import com.j2biz.blogunity.i18n.I18NStatusFactory;
48
49 /**
50  * @author michelson
51  * @version $$
52  * @since 0.1
53  *
54  *
55  */

56 public class ResourceUtils {
57     /**
58      * Logger for this class
59      */

60     private static final Log log = LogFactory.getLog(ResourceUtils.class);
61
62     private static final long KB = 1024;
63
64     private static final long MB = 1024 * 1024;
65
66     private static final long GB = 1024 * 1024 * 1024;
67
68     private static DecimalFormat JavaDoc FILESIZE_FORMATER = new DecimalFormat JavaDoc("####.##");
69
70     /*
71      * (non-Javadoc)
72      *
73      * @see com.j2biz.blogunity.model.ResourceManager#getResourceAsStream(java.lang.String)
74      */

75     public static InputStream JavaDoc getResourceAsStream(String JavaDoc url) throws BlogunityException {
76         if (log.isDebugEnabled()) {
77             log.debug("Getting InputStream for requested resource url=" + url);
78         }
79
80         if (url.charAt(0) != '/') url = "/" + url;
81
82         String JavaDoc mainDataDirectory = BlogunityManager.getSystemConfiguration().getDataDir();
83
84         File JavaDoc f = new File JavaDoc(mainDataDirectory, url);
85         if (f.exists() && f.isFile() && f.canRead()) {
86             FileInputStream JavaDoc in;
87             try {
88                 in = new FileInputStream JavaDoc(f);
89                 return in;
90             } catch (FileNotFoundException JavaDoc e) {
91                 log.error("getThemeResourceAsStream(String)", e);
92                 throw new BlogunityException(I18NStatusFactory.create(
93                         I18N.ERRORS.RESOURCE_NOT_FOUND, url));
94             }
95
96         }
97
98         throw new BlogunityException(I18NStatusFactory.create(I18N.ERRORS.RESOURCE_NOT_FOUND, url));
99     }
100
101     public static synchronized void copyDirectory(File JavaDoc source, File JavaDoc destination)
102             throws BlogunityException {
103
104         if (source.isDirectory()) {
105             if (!destination.exists()) {
106                 destination.mkdir();
107             }
108
109             String JavaDoc[] children = source.list();
110             for (int i = 0; i < children.length; i++) {
111                 copyDirectory(new File JavaDoc(source, children[i]), new File JavaDoc(destination, children[i]));
112             }
113         } else {
114             copyFile(source, destination);
115         }
116
117     }
118
119     public static synchronized void copyFile(File JavaDoc source, File JavaDoc destination)
120             throws BlogunityException {
121         try {
122             InputStream JavaDoc in = new FileInputStream JavaDoc(source);
123             OutputStream JavaDoc out = new FileOutputStream JavaDoc(destination);
124
125             // Transfer bytes from in to out
126
byte[] buf = new byte[1024];
127             int len;
128             while ((len = in.read(buf)) > 0) {
129                 out.write(buf, 0, len);
130             }
131             in.close();
132             out.close();
133         } catch (Throwable JavaDoc t) {
134             throw new BlogunityException(I18NStatusFactory.createUnknown(t));
135         }
136     }
137
138     public static synchronized void copyFile(InputStream JavaDoc in, File JavaDoc destination)
139             throws BlogunityException {
140         try {
141             OutputStream JavaDoc out = new FileOutputStream JavaDoc(destination);
142
143             // Transfer bytes from in to out
144
byte[] buf = new byte[1024];
145             int len;
146             while ((len = in.read(buf)) > 0) {
147                 out.write(buf, 0, len);
148             }
149             in.close();
150             out.close();
151         } catch (Throwable JavaDoc t) {
152             throw new BlogunityException(I18NStatusFactory.createUnknown(t));
153         }
154     }
155
156     public static synchronized File JavaDoc zipDirectory(File JavaDoc sourceDirectory) throws BlogunityException {
157         return zipDirectory(sourceDirectory, sourceDirectory.getName());
158     }
159
160     public static synchronized File JavaDoc zipDirectory(File JavaDoc sourceDirectory, String JavaDoc rootDirName)
161             throws BlogunityException {
162
163         try {
164             File JavaDoc zippedFile = new File JavaDoc(BlogunityManager.getSystemConfiguration().getTempDir(),
165                     sourceDirectory.getName() + System.currentTimeMillis() + ".zip");
166
167             ZipOutputStream JavaDoc zos = new ZipOutputStream JavaDoc(new FileOutputStream JavaDoc(zippedFile));
168
169             // first put top-level directory into zip-archive with the name =
170
// filename
171
ZipEntry JavaDoc anEntry = new ZipEntry JavaDoc(rootDirName);
172             zipDir(sourceDirectory, zos, sourceDirectory.getAbsolutePath(), rootDirName);
173             zos.close();
174
175             return zippedFile;
176         } catch (Throwable JavaDoc t) {
177             throw new BlogunityException(I18NStatusFactory.createUnknown(t));
178         }
179
180     }
181
182     private static synchronized void zipDir(File JavaDoc zipDir, ZipOutputStream JavaDoc zos,
183             String JavaDoc absolutePathToThemeDir, String JavaDoc rootDirName) throws IOException JavaDoc {
184
185         //get a listing of the directory content
186
String JavaDoc[] dirList = zipDir.list();
187         byte[] readBuffer = new byte[2156];
188         int bytesIn = 0;
189         //loop through dirList, and zip the files
190
for (int i = 0; i < dirList.length; i++) {
191             File JavaDoc f = new File JavaDoc(zipDir, dirList[i]);
192             if (f.isDirectory()) {
193                 zipDir(f, zos, absolutePathToThemeDir, rootDirName);
194                 continue;
195             }
196
197             //if we reached here, the File object f was not a directory
198
//create a FileInputStream on top of f
199
FileInputStream JavaDoc fis = new FileInputStream JavaDoc(f);
200
201             // create a new zip entry
202
String JavaDoc path = (StringUtils.isNotEmpty(rootDirName) ? rootDirName : "")
203                     + "/"
204                     + f.getAbsolutePath().substring(absolutePathToThemeDir.length() + 1,
205                             f.getAbsolutePath().length());
206
207             ZipEntry JavaDoc anEntry = new ZipEntry JavaDoc(path);
208             //place the zip entry in the ZipOutputStream object
209
zos.putNextEntry(anEntry);
210
211             //now write the content of the file to the ZipOutputStream
212
while ((bytesIn = fis.read(readBuffer)) != -1) {
213                 zos.write(readBuffer, 0, bytesIn);
214             }
215
216             //close the Stream
217
fis.close();
218         }
219     }
220
221     public static synchronized void removeDirectory(File JavaDoc dir) throws BlogunityException {
222         if (dir.isDirectory()) {
223             String JavaDoc[] children = dir.list();
224             for (int i = 0; i < children.length; i++) {
225                 removeDirectory(new File JavaDoc(dir, children[i]));
226             }
227         }
228
229         removeFile(dir);
230     }
231
232     public static synchronized void removeFile(File JavaDoc file) throws BlogunityException {
233         boolean result = file.delete();
234         if (!result) { throw new BlogunityException(I18NStatusFactory.create(
235                 I18N.ERRORS.DELETE_FILE, file.getAbsolutePath())); }
236
237     }
238
239     public static synchronized void unzipFile(File JavaDoc zipFile, File JavaDoc destinationDir)
240             throws BlogunityException {
241         try {
242             ZipInputStream JavaDoc in = new ZipInputStream JavaDoc(new FileInputStream JavaDoc(zipFile));
243             unzipFile(in, destinationDir);
244             in.close();
245         } catch (Throwable JavaDoc t) {
246             throw new BlogunityException(I18NStatusFactory.createUnknown(t));
247         }
248     }
249
250     public static synchronized void unzipFile(ZipInputStream JavaDoc zin, File JavaDoc destinationDir)
251             throws BlogunityException {
252
253         try {
254             ZipEntry JavaDoc e;
255             while ((e = zin.getNextEntry()) != null) {
256                 if (e.isDirectory()) {
257                     // first create directory
258
new File JavaDoc(destinationDir, e.getName()).mkdir();
259                 } else {
260                     // check, if name contains directory + file
261
// name at once
262
// (e.g. dir1/dir2/file1).
263
// if it true, first create directories and
264
// than the file.
265
String JavaDoc tempName = e.getName();
266                     int indx = tempName.lastIndexOf("/");
267                     if (indx > 0) {
268                         String JavaDoc dirs = tempName.substring(0, indx);
269                         new File JavaDoc(destinationDir, dirs).mkdirs();
270                     } else
271                         indx = 0;
272
273                     File JavaDoc f = new File JavaDoc(destinationDir, e.getName());
274                     f.createNewFile();
275                     unzipEntry(zin, f);
276                 }
277             }
278             zin.close();
279         } catch (Throwable JavaDoc t) {
280             throw new BlogunityException(I18NStatusFactory.createUnknown(t));
281         }
282
283     }
284
285     private static synchronized void unzipEntry(ZipInputStream JavaDoc zin, File JavaDoc outFile)
286             throws IOException JavaDoc {
287         FileOutputStream JavaDoc out = new FileOutputStream JavaDoc(outFile);
288         byte[] buf = new byte[1024];
289         int len;
290         while ((len = zin.read(buf)) > 0) {
291             out.write(buf, 0, len);
292         }
293         out.close();
294     }
295
296     public static String JavaDoc getPreformattedFilesize(long size) {
297
298         if (size < KB) { return size + " Bytes"; }
299
300         if (size < MB) {
301             double kbytes = (double) size / KB;
302             return FILESIZE_FORMATER.format(kbytes) + " KB";
303
304         }
305
306         if (size < GB) {
307             double gbytes = (double) size / MB;
308             return FILESIZE_FORMATER.format(gbytes) + " MB";
309
310         }
311
312         double gbytes = (double) size / GB;
313         return FILESIZE_FORMATER.format(gbytes) + " GB";
314
315     }
316
317 }
Popular Tags