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