View Javadoc

1   package com.melloware.jukes.file;
2   
3   import java.io.File;
4   import java.io.IOException;
5   import java.util.HashMap;
6   import java.util.Iterator;
7   import java.util.Map;
8   
9   import org.apache.commons.lang.StringUtils;
10  import org.apache.commons.lang.SystemUtils;
11  import org.apache.commons.lang.WordUtils;
12  import org.apache.commons.logging.Log;
13  import org.apache.commons.logging.LogFactory;
14  
15  import com.melloware.jukes.exception.InfrastructureException;
16  
17  /**
18   * Static class of file utilities.
19   * <p>
20   * Copyright: Copyright (c) 2006
21   * Company: Melloware, Inc.
22   * @author Emil A. Lefkof III
23   * @version 4.0
24   */
25  public final class FileUtil {
26  
27      private static final Log LOG = LogFactory.getLog(FileUtil.class);
28      public static final String WINDOWS_COMMAND = "attrib -R ";
29      public static final String NIX_COMMAND = "chmod u+w ";
30      private static final String INVALID_OUTPUT_NAME_REGEX = "[\\\\\\/\\:\\*\\\"\\<\\>\\|\\?]";
31      private static final char[] CAPS_CHARS = new char[] { ' ', '.', '"', '(', '[', ',', ':', '-', ']', ')', '/', '\\'};
32  
33      /**
34       * Private constructor for no instantiation of static class
35       */
36      private FileUtil() {
37      	//empty constructor
38      }
39  
40      /**
41       * Sets a file read only or not using the OS specific commands.  For JDK6 
42       * this is not needed as it has File.setReadable(true);
43       * <p>
44       * @param aFile the file to set readonly
45       * @param flag true for readonly, false for writeable
46       */
47      public static void setReadOnly(final File aFile, final boolean flag) {
48          if (flag) {
49              aFile.setReadOnly();
50          } else {
51              String path = aFile.getAbsolutePath();
52              if (path.indexOf(' ') >= 0) {
53                  path = String.valueOf(String.valueOf((new StringBuffer(String.valueOf(String.valueOf('"')))).append(path).append('"')));
54              }
55  
56              final String command = getCommand() + path;
57              try {
58                  LOG.debug(command);
59                  Runtime.getRuntime().exec(command).waitFor();
60              } catch (IOException ioexception) {
61                  LOG.error("Error clearing the read-only attribute of ".concat(String.valueOf(String.valueOf(path))),
62                            ioexception);
63              } catch (InterruptedException interruptedexception) {
64                  LOG.error("Error clearing the read-only attribute of ".concat(String.valueOf(String.valueOf(path))),
65                            interruptedexception);
66              }
67          }
68      }
69  
70      /**
71       * Provides title casing for a string and a set of characters to always
72       * capitalize after like "(".
73       * <p>
74       * @param aStringToCapitalize the string to capitalize
75       * @return the captilized string
76       */
77      public static String capitalize(final String aStringToCapitalize) {
78      	String word = WordUtils.capitalizeFully(aStringToCapitalize, CAPS_CHARS);
79      	word = StringUtils.replace(word, "Ii", "II");
80      	word = StringUtils.replace(word, "IIi", "III");
81      	word = StringUtils.replace(word, "Iv", "IV");
82          return word;
83      }
84  
85      /**
86       * Checks a file name for invalid characters \\, /, :, , *, ?, ", <, >, or |
87       * <p>
88       * @param aFilename the filename to check
89       */
90      public static void checkValidFileName(final String aFilename, final String message) {
91          if (aFilename.matches(INVALID_OUTPUT_NAME_REGEX)) {
92              throw new InfrastructureException(message);
93          }
94      }
95  
96      /**
97       * Corrects a file name for invalid characters.
98       * e.g. \\, /, :, , *, ?, ", <, >, or |
99       * <p>
100      * @param aFilename the filename to check
101      * @return the corrected file name
102      */
103     public static String correctFileName(final String aFilename) {
104         return aFilename.replaceAll(INVALID_OUTPUT_NAME_REGEX, "_");
105     }
106 
107     /**
108      * Deep copy of a Map.
109      * <p>
110      * @param src the source Map
111      * @return return the deep copy.
112      */
113     @SuppressWarnings("unchecked")
114     public static Map deepCopy(final Map src) {
115         final HashMap map = new HashMap();
116         if (src != null) {
117             final Iterator it = src.keySet().iterator();
118             while (it.hasNext()) {
119                 final Object key = it.next();
120                 final Object value = src.get(key);
121                 map.put(key, value);
122             }
123         }
124         return map;
125     }
126 
127     /**
128      * Renames a file.
129      * <p>
130      * @param sOldname The current (old) name of the file.
131      * @param sNewname The new name of the file.
132      * @return true/false if the rename was successful.
133      */
134     public static boolean rename(final String sOldname, final String sNewname) {
135         if (LOG.isDebugEnabled()) {
136             LOG.debug("Renaming: '" + sOldname + "' to '" + sNewname + "'");
137         }
138 
139         final File oldFile = new File(sOldname);
140         final File newFile = new File(sNewname);
141 
142         final boolean success = oldFile.renameTo(newFile);
143 
144         if (LOG.isDebugEnabled()) {
145             LOG.debug("Completed reanaming: " + success);
146         }
147 
148         return success;
149     }    // End rename
150 
151     /**
152      * Gets the correct command for setting a file read only in the correct
153      * operating system.
154      * <p>
155      * @return the command line string
156      */
157     private static String getCommand() {
158         if (SystemUtils.IS_OS_WINDOWS) {
159             return WINDOWS_COMMAND;
160         } else {
161             return NIX_COMMAND;
162         }
163     }
164 
165 }