KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > util > IOUtils


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.cocoon.util;
17
18 import java.io.BufferedInputStream JavaDoc;
19 import java.io.ByteArrayInputStream JavaDoc;
20 import java.io.ByteArrayOutputStream JavaDoc;
21 import java.io.File JavaDoc;
22 import java.io.FileInputStream JavaDoc;
23 import java.io.FileOutputStream JavaDoc;
24 import java.io.FileReader JavaDoc;
25 import java.io.FileWriter JavaDoc;
26 import java.io.IOException JavaDoc;
27 import java.io.ObjectInputStream JavaDoc;
28 import java.io.ObjectOutputStream JavaDoc;
29 import java.io.OutputStreamWriter JavaDoc;
30 import java.io.Writer JavaDoc;
31 import java.text.Collator JavaDoc;
32 import java.util.Arrays JavaDoc;
33 import java.util.Locale JavaDoc;
34
35 import org.apache.commons.lang.StringUtils;
36 import org.apache.log.Hierarchy;
37
38 /**
39  * A collection of <code>File</code>, <code>URL</code> and filename
40  * utility methods
41  *
42  * @author <a HREF="mailto:ricardo@apache.org">Ricardo Rocha</a>
43  * @author <a HREF="mailto:stefano@apache.org">Stefano Mazzocchi</a>
44  * @version CVS $Id: IOUtils.java 37206 2004-08-30 14:52:42Z cziegeler $
45  */

46 public class IOUtils {
47
48     // **********************
49
// Serialize Methods
50
// **********************
51

52     /**
53      * Dump a <code>String</code> to a text file.
54      *
55      * @param file The output file
56      * @param string The string to be dumped
57      * @exception IOException IO Error
58      * @deprecated To be removed in cocoon 2.3
59      */

60     public static void serializeString(File JavaDoc file, String JavaDoc string)
61     throws IOException JavaDoc {
62         serializeString(file, string, null);
63     }
64
65     /**
66      * Dump a <code>String</code> to a text file.
67      *
68      * @param file The output file
69      * @param string The string to be dumped
70      * @param encoding The encoding for the output file or null for default platform encoding
71      * @exception IOException IO Error
72      * @deprecated To be removed in cocoon 2.3
73      */

74     public static void serializeString(File JavaDoc file, String JavaDoc string, String JavaDoc encoding)
75     throws IOException JavaDoc {
76         final Writer JavaDoc fw =
77                 (encoding == null)?
78                 new FileWriter JavaDoc(file):
79                 new OutputStreamWriter JavaDoc(new FileOutputStream JavaDoc(file), encoding);
80         try {
81             fw.write(string);
82             fw.flush();
83         } finally {
84             if (fw != null) fw.close();
85         }
86     }
87
88     /**
89      * Load a text file contents as a <code>String<code>.
90      * This method does not perform enconding conversions
91      *
92      * @param file The input file
93      * @return The file contents as a <code>String</code>
94      * @exception IOException IO Error
95      */

96     public static String JavaDoc deserializeString(File JavaDoc file)
97     throws IOException JavaDoc {
98         int len;
99         char[] chr = new char[4096];
100         final StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
101         final FileReader JavaDoc reader = new FileReader JavaDoc(file);
102         try {
103             while ((len = reader.read(chr)) > 0) {
104                 buffer.append(chr, 0, len);
105             }
106         } finally {
107             if (reader != null) reader.close();
108         }
109         return buffer.toString();
110     }
111
112     /**
113      * This method serializes an object to an output stream.
114      *
115      * @param file The output file
116      * @param object The object to be serialized
117      * @exception IOException IOError
118      * @deprecated To be removed in cocoon 2.3
119      */

120     public static void serializeObject(File JavaDoc file, Object JavaDoc object)
121     throws IOException JavaDoc {
122         FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(file);
123         try {
124             ObjectOutputStream JavaDoc oos = new ObjectOutputStream JavaDoc(new BufferedOutputStream(fos));
125             oos.writeObject(object);
126             oos.flush();
127         } finally {
128             if (fos != null) fos.close();
129         }
130     }
131
132     /**
133      * This method deserializes an object from an input stream.
134      *
135      * @param file The input file
136      * @return The deserialized object
137      * @exception IOException IOError
138      * @deprecated To be removed in cocoon 2.3
139      */

140     public static Object JavaDoc deserializeObject(File JavaDoc file)
141     throws IOException JavaDoc, ClassNotFoundException JavaDoc {
142         FileInputStream JavaDoc fis = new FileInputStream JavaDoc(file);
143         Object JavaDoc object = null;
144         try {
145             ObjectInputStream JavaDoc ois = new ObjectInputStream JavaDoc(new BufferedInputStream JavaDoc(fis));
146             object = ois.readObject();
147         } finally {
148             if (fis != null) fis.close();
149         }
150         return object;
151     }
152
153   /**
154    * These are java keywords as specified at the following URL (sorted alphabetically).
155    * http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#229308
156    */

157   static final String JavaDoc keywords[] =
158   {
159       "abstract", "boolean", "break", "byte", "case",
160       "catch", "char", "class", "const", "continue",
161       "default", "do", "double", "else", "extends",
162       "final", "finally", "float", "for", "goto",
163       "if", "implements", "import", "instanceof", "int",
164       "interface", "long", "native", "new", "package",
165       "private", "protected", "public", "return", "short",
166       "static", "strictfp", "super", "switch", "synchronized",
167       "this", "throw", "throws", "transient", "try",
168       "void", "volatile", "while"
169   };
170
171   /** Collator for comparing the strings */
172   static final Collator JavaDoc englishCollator = Collator.getInstance(Locale.ENGLISH);
173
174   /** Use this character as suffix */
175   static final char keywordSuffix = '_';
176
177   /**
178    * checks if the input string is a valid java keyword.
179    * @return boolean true/false
180    */

181   private static boolean isJavaKeyword(String JavaDoc keyword) {
182     return (Arrays.binarySearch(keywords, keyword, englishCollator) >= 0);
183   }
184
185   // **********************
186
// File Methods
187
// **********************
188

189   /**
190    * Return a modified filename suitable for replicating directory
191    * structures below the store's base directory. The following
192    * conversions are performed:
193    * <ul>
194    * <li>Path separators are converted to regular directory names</li>
195    * <li>File path components are transliterated to make them valid (?)
196    * programming language identifiers. This transformation may well
197    * generate collisions for unusual filenames.</li>
198    * </ul>
199    * @return The transformed filename
200    */

201   public static String JavaDoc normalizedFilename(String JavaDoc filename) {
202     if ("".equals(filename)) {
203         return "";
204     }
205     filename = (File.separatorChar == '\\') ? filename.replace('/','\\') : filename.replace('\\','/');
206     String JavaDoc[] path = StringUtils.split(filename, File.separator);
207     int start = (path[0].length() == 0) ? 1 : 0;
208
209     StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
210     for (int i = start; i < path.length; i++) {
211
212       if (i > start) {
213         buffer.append(File.separator);
214       }
215
216       if(path[i].equals("..")) {
217         int lio;
218         for (lio = buffer.length() - 2; lio >= 0; lio--) {
219           if (buffer.substring(lio).startsWith(File.separator)) {
220             break;
221         }
222         }
223         if (lio >= 0) {
224           buffer.setLength(lio);
225         }
226       } else {
227         char[] chars = path[i].toCharArray();
228
229         if (chars.length < 1 || !Character.isLetter(chars[0])) {
230           buffer.append('_');
231         }
232
233         for (int j = 0; j < chars.length; j++) {
234           if (org.apache.cocoon.util.StringUtils.isAlphaNumeric(chars[j])) {
235             buffer.append(chars[j]);
236           } else {
237             buffer.append('_');
238           }
239         }
240
241         // Append the suffix if necessary.
242
if(isJavaKeyword(path[i]))
243           buffer.append(keywordSuffix);
244       }
245
246     }
247     return buffer.toString();
248   }
249
250   /**
251    * Remove file information from a filename returning only its path
252    * component
253    *
254    * @param filename The filename
255    * @return The path information
256    * @deprecated To be removed in cocoon 2.3
257    */

258   public static String JavaDoc pathComponent(String JavaDoc filename) {
259     int i = filename.lastIndexOf(File.separator);
260     return (i > -1) ? filename.substring(0, i) : filename;
261   }
262
263   /**
264    * Remove path information from a filename returning only its file
265    * component
266    *
267    * @param filename The filename
268    * @return The filename sans path information
269    * @deprecated To be removed in cocoon 2.3
270    */

271   public static String JavaDoc fileComponent(String JavaDoc filename) {
272     int i = filename.lastIndexOf(File.separator);
273     return (i > -1) ? filename.substring(i + 1) : filename;
274   }
275
276   /**
277    * Strip a filename of its <i>last</i> extension (the portion
278    * immediately following the last dot character, if any)
279    *
280    * @param filename The filename
281    * @return The filename sans extension
282    * @deprecated To be removed in cocoon 2.3
283    */

284   public static String JavaDoc baseName(String JavaDoc filename) {
285     int i = filename.lastIndexOf('.');
286     return (i > -1) ? filename.substring(0, i) : filename;
287   }
288
289   /**
290    * Get the complete filename corresponding to a (typically relative)
291    * <code>File</code>.
292    * This method accounts for the possibility of an error in getting
293    * the filename's <i>canonical</i> path, returning the io/error-safe
294    * <i>absolute</i> form instead
295    *
296    * @param file The file
297    * @return The file's absolute filename
298    */

299   public static String JavaDoc getFullFilename(File JavaDoc file) {
300     try {
301       return file.getCanonicalPath();
302     } catch (Exception JavaDoc e) {
303       Hierarchy.getDefaultHierarchy().getLoggerFor("cocoon").debug("IOUtils.getFullFilename", e);
304       return file.getAbsolutePath();
305     }
306   }
307
308   /**
309    * Return the path within a base directory
310    */

311   public static String JavaDoc getContextFilePath(String JavaDoc directoryPath, String JavaDoc filePath) {
312       try
313       {
314           File JavaDoc directory = new File JavaDoc(directoryPath);
315           File JavaDoc file = new File JavaDoc(filePath);
316
317           directoryPath = directory.getCanonicalPath();
318           filePath = file.getCanonicalPath();
319
320           // If the context directory does not have a File.separator
321
// at the end then add one explicitly
322
if(!directoryPath.endsWith(File.separator)){
323             directoryPath += File.separator;
324           }
325
326           // If the context dir contains both kinds of separator
327
// then standardize on using the File.separator
328
if ((directoryPath.indexOf('/') !=-1) && (directoryPath.indexOf('\\') !=-1)) {
329             directoryPath = directoryPath.replace('\\', File.separator.charAt(0));
330             directoryPath = directoryPath.replace('/', File.separator.charAt(0));
331           }
332
333           // If the file path contains both kinds of separator
334
// then standardize on using the File.separator
335
if ((filePath.indexOf('/') !=-1) && (filePath.indexOf('\\') !=-1)) {
336             filePath = filePath.replace('\\', File.separator.charAt(0));
337             filePath = filePath.replace('/', File.separator.charAt(0));
338           }
339
340           if (filePath.startsWith(directoryPath)) {
341               filePath = filePath.substring(directoryPath.length());
342           }
343       } catch (Exception JavaDoc e){
344           Hierarchy.getDefaultHierarchy().getLoggerFor("cocoon").debug("IOUtils.getContextFilePath", e);
345       }
346
347       return filePath;
348   }
349
350   /**
351    * Return a file with the given filename creating the necessary
352    * directories if not present.
353    *
354    * @param filename The file
355    * @return The created File instance
356    */

357   public static File JavaDoc createFile(File JavaDoc destDir, String JavaDoc filename) {
358     File JavaDoc file = new File JavaDoc(destDir, filename);
359     File JavaDoc parent = file.getParentFile();
360     if (parent != null) parent.mkdirs();
361     return file;
362   }
363
364   /**
365    * Returns a byte array from the given object.
366    *
367    * @param object to convert
368    * @return byte array from the object
369    * @deprecated To be removed in cocoon 2.3
370    */

371   public static byte[] objectToBytes(Object JavaDoc object) throws IOException JavaDoc {
372     ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
373     ObjectOutputStream JavaDoc os = new ObjectOutputStream JavaDoc(baos);
374     os.writeObject(object);
375     return baos.toByteArray();
376   }
377
378   /**
379    * Returns a object from the given byte array.
380    *
381    * @param bytes array to convert
382    * @return object
383    * @deprecated To be removed in cocoon 2.3
384    */

385   public static Object JavaDoc bytesToObject(byte[] bytes) throws IOException JavaDoc, ClassNotFoundException JavaDoc {
386     ByteArrayInputStream JavaDoc bais = new ByteArrayInputStream JavaDoc(bytes);
387     ObjectInputStream JavaDoc is = new ObjectInputStream JavaDoc(bais);
388     return is.readObject();
389   }
390 }
391
Popular Tags