View Javadoc

1   package com.zmicer.utils;
2   
3   import org.apache.log4j.Logger;
4   
5   import java.io.File;
6   import java.io.FileInputStream;
7   import java.util.ArrayList;
8   import java.util.List;
9   import java.util.PropertyResourceBundle;
10  import java.util.ResourceBundle;
11  import java.util.StringTokenizer;
12  import java.util.regex.Pattern;
13  
14  /**
15   * This utility class is used for all the file related operations.
16   * <p/>
17   * $Author:: zmicer             $<br/>
18   * $Rev:: 57                    $<br/> * $Date:: 2007-08-23 09:16:37 #$<br/>
19   */
20  public class FileUtils
21  {
22      /**
23       * Logger instance.
24       */
25      final public static Logger LOG = Logger.getLogger(ZmicerUtilsConstants.LoggingCategory.OBTAIN_RESOURCES.toString());
26  
27      /**
28       * Accumulate all the files by the provided Regular Expression Patterns. All the dirs are searched reqursively
29       *
30       * @param dirName          the dir name.
31       * @param reFileDefinition Pattern for the regular expression to find all the files
32       *
33       * @return the List of File objects with the valid values
34       */
35      public static List<File> findFilesByRE(final String dirName, final Pattern reFileDefinition)
36      {
37          InputArgumentUtils.checkObjects(dirName, reFileDefinition);
38          LoggingUtils.debug(LOG, FileUtils.class, "Start finding the files using string dir [" + dirName + "] using pattern [" +
39              reFileDefinition.pattern() + "]");
40          final File dir = new File(dirName);
41          if (!dir.isDirectory())
42          {
43              final String loggingMessage = "The dir [" + dirName + "] doesn't point to the real dir.";
44              LoggingUtils.debug(LOG, FileUtils.class, loggingMessage);
45              throw new IllegalArgumentException(loggingMessage);
46          }
47          return findFilesByRE(dir, reFileDefinition);
48      }
49  
50      /**
51       * Find files by regular expression provided.
52       * Accumulate all the files by the provided Regular Expression Patterns. All the dirs are searched reqursively
53       *
54       * @param dirFile          dir file where we would find the file defined by Regular Expression
55       *                         Can not be null (otherwise <code>IllegalArgumentException</code> would appear). It should be the valid
56       *                         directory, otherwise <code>IllegalArgumentException</code> would appear
57       * @param reFileDefinition regular expression for the file name
58       *                         Can not be null (otherwise <code>IllegalArgumentException</code> would appear).
59       *
60       * @return the List of File objects found using the provided search criteria, or null in another case
61       */
62      public static List<File> findFilesByRE(final File dirFile, final Pattern reFileDefinition)
63      {
64          InputArgumentUtils.checkObjects(dirFile, reFileDefinition);
65          final List<File> result = new ArrayList<File>();
66          if (!dirFile.isDirectory())
67          {
68              final String loggingMessage = "The dir [" + dirFile.getAbsolutePath() + "] doesn't point to the real dir.";
69              LoggingUtils.debug(LOG, FileUtils.class, loggingMessage);
70              throw new IllegalArgumentException(loggingMessage);
71          }
72          final File[] files = dirFile.listFiles();
73          final List<File> dirsToBeChecked = new ArrayList<File>();
74          // 01: check the files.
75          for (final File fileToBeChecked : files)
76          {
77              if (fileToBeChecked.isDirectory())
78              {
79                  dirsToBeChecked.add(fileToBeChecked);
80              }
81              else if (fileToBeChecked.isFile())
82              {
83                  final String fileName = fileToBeChecked.getName();
84                  if (REUtils.matches(fileName, reFileDefinition))
85                  {
86                      result.add(fileToBeChecked);
87                  }
88              }
89          }
90          for (final File dirToBeChecked : dirsToBeChecked)
91          {
92              result.addAll(findFilesByRE(dirToBeChecked, reFileDefinition));
93          }
94          return result;
95      }
96  
97      /**
98       * Accumulate all the files by the provided Regular Expression Patterns. All the dirs are searched reqursively
99       *
100      * @param dirName            the dir name.
101      * @param reFolderDefinition Pattern for the regular expression to find all the files
102      *
103      * @return the List of File objects with the valid values
104      */
105     public static List<File> findFoldersByRE(final String dirName, final Pattern reFolderDefinition)
106     {
107         InputArgumentUtils.checkObjects(dirName, reFolderDefinition);
108         LoggingUtils.debug(LOG, FileUtils.class, "Start finding the folders using string dir [" + dirName + "] and pattern [" +
109             reFolderDefinition.pattern() + "]");
110         final File dir = new File(dirName);
111         if (!dir.isDirectory())
112         {
113             final String loggingMessage = "The dir [" + dirName + "] doesn't point to the real dir.";
114             LoggingUtils.debug(LOG, FileUtils.class, loggingMessage);
115             throw new IllegalArgumentException(loggingMessage);
116         }
117         return findFoldersByRE(dir, reFolderDefinition);
118     }
119 
120     /**
121      * Find files by regular expression provided.
122      * Accumulate all the files by the provided Regular Expression Patterns. All the dirs are searched reqursively
123      *
124      * @param dirFile            dir file where we would find the file defined by Regular Expression
125      *                           Can not be null (otherwise <code>IllegalArgumentException</code> would appear). It should be the valid
126      *                           directory, otherwise <code>IllegalArgumentException</code> would appear
127      * @param reFolderDefinition pattern object for the name of the folder we are looking for
128      *                           Can not be null (otherwise <code>IllegalArgumentException</code> would appear).
129      *
130      * @return the List of File objects found using the provided search criteria, or empty List in another case
131      */
132     public static List<File> findFoldersByRE(final File dirFile, final Pattern reFolderDefinition)
133     {
134         InputArgumentUtils.checkObjects(dirFile, reFolderDefinition);
135         final List<File> result = new ArrayList<File>();
136         if (!dirFile.isDirectory())
137         {
138             final String loggingMessage = "The dir [" + dirFile.getAbsolutePath() + "] doesn't point to the real dir.";
139             LoggingUtils.debug(LOG, FileUtils.class, loggingMessage);
140             throw new IllegalArgumentException(loggingMessage);
141         }
142         if (REUtils.matches(dirFile.getName(), reFolderDefinition))
143         {
144             result.add(dirFile);
145         }
146         final File[] files = dirFile.listFiles();
147         final List<File> dirsToBeChecked = new ArrayList<File>();
148         // 01: check the files.
149         for (final File fileToBeChecked : files)
150         {
151             if (fileToBeChecked.isDirectory())
152             {
153                 dirsToBeChecked.add(fileToBeChecked);
154                 final String folderName = fileToBeChecked.getName();
155                 if (REUtils.matches(folderName, reFolderDefinition))
156                 {
157                     result.add(fileToBeChecked);
158                 }
159             }
160         }
161         for (final File dirToBeChecked : dirsToBeChecked)
162         {
163             result.addAll(findFilesByRE(dirToBeChecked, reFolderDefinition));
164         }
165         return result;
166     }
167 
168     /**
169      * Find the files using the provided regular expression (e.g.
170      * ".*jpatterns.*(?<!^jpatterns_framework)(?<!^jpatterns_framework_custom)\.xml") and the List of String which are the
171      * class path entities (study the {@link com.zmicer.utils.ClassPathUtils#getClassPathes()} for details).
172      * <br/>
173      * The class path entities allow us to use this method not only for the class path but with other pathes, dirs etc.
174      *
175      * @param classPathStrings the List of String objects, Can not be null (otherwise <code>IllegalArgumentException</code> would appear).
176      * @param reFileDefinition the Pattern compliled before,
177      *                         Can not be null (otherwise <code>IllegalArgumentException</code> would appear).
178      *
179      * @return the List of the valid <code>File</code> object (<code>file.isFile</code> would be return <code>true</code>)
180      *
181      * @version 1.0
182      */
183     public static List<File> findFilesByREInClassPath(final List<String> classPathStrings, final Pattern reFileDefinition)
184     {
185         InputArgumentUtils.checkObjects(classPathStrings, reFileDefinition);
186 
187         // logging the information for the debug pusposes.
188         List<String> forLog = new ArrayList<String>();
189         forLog.add("Searching for the files using pattern [" + reFileDefinition.pattern() + "] in the following classpathes dirs");
190         forLog.addAll(classPathStrings);
191         LoggingUtils.debug(LOG, FileUtils.class, StringUtils.joinStringsWithLineFolding(forLog));
192 
193         final List<File> result = new ArrayList<File>();
194         final List<String> files = ClassPathUtils.getFileNames(classPathStrings, true);
195         final List<String> dirs = ClassPathUtils.getDirNames(classPathStrings, true);
196         if (null != files)
197         {
198             for (String fileName : files)
199             {
200                 int counter = 0;
201                 if (REUtils.matches(fileName, reFileDefinition))
202                 {
203                     File file = new File(fileName);
204                     // won't check here anything, cause it was checked at the ClassPathUtils.getFileNames
205                     result.add(file);
206                     counter++;
207                     LoggingUtils.debug(LOG, FileUtils.class, "Found file number [" + counter + "] with name [" + fileName +
208                         "]matching the regexp using the provided classpath.");
209                 }
210             }
211         }
212         if (null != dirs)
213         {
214             for (String dir : dirs)
215             {
216                 int counter = 0;
217                 final List<File> dirObjects = findFilesByRE(dir, reFileDefinition);
218                 if (null != dirObjects && !dirObjects.isEmpty())
219                 {
220                     counter += dirObjects.size();
221                     result.addAll(dirObjects);
222                     forLog = new ArrayList<String>();
223                     forLog.add("Found [" + counter + "] more files matching the regexp.");
224                     for (File fileObject : dirObjects)
225                     {
226                         forLog.add(fileObject.getAbsolutePath());
227                     }
228                     LoggingUtils.debug(LOG, FileUtils.class, StringUtils.joinStringsWithLineFolding(forLog));
229                 }
230             }
231         }
232         return result;
233     }
234 
235     /**
236      * Get the folder name inself using the provided full or relative folder name
237      *
238      * @param folderFullName the folder name we should analyze, Can not be null (otherwise <code>IllegalArgumentException</code> would
239      *                       appear).
240      *
241      * @return String, folder base name
242      *
243      * @version 1.0
244      */
245     public static String getFolderBaseName(final String folderFullName)
246     {
247         InputArgumentUtils.checkStrings(true, folderFullName);
248         final StringTokenizer tokenizer = new StringTokenizer(folderFullName, File.separator);
249         String result = null;
250         while (tokenizer.hasMoreTokens())
251         {
252             result = tokenizer.nextToken();
253         }
254         return result;
255     }
256 
257     /**
258      * Get the resource bundle using the <code>File</code> class facilities (inside the method the {@link PropertyResourceBundle} is used).
259      *
260      * @param resourceName the name of the resource, Can not be null (otherwise <code>IllegalArgumentException</code> would appear).
261      *                     Be noticed it could take the following types of values: 1. the full or relative path to the resource using the
262      *                     File.separator 2. the relative path to the resource where the dot (".") is used as the separator.
263      *                     <br/> note [zmicer]: it could contains ".properties" or could not.
264      *
265      * @return the resource bundle we are looking for or <code>null</code> in the case there is no appropriate resource bundle or it has
266      *         wrong format, or smth else went in the wrong way.
267      */
268     public static ResourceBundle getResourceBundleViaFile(final String resourceName)
269     {
270         InputArgumentUtils.checkStrings(true, resourceName);
271 
272         final String propertiesExtension = ".properties";
273         String resourceForFile = ((resourceName.contains(File.separator)) ? resourceName : resourceName.replace(".", File.separator)) +
274             (resourceName.contains(propertiesExtension) ? "" : propertiesExtension);
275 
276         // check the case it is the full path to the resource.
277         LoggingUtils.debug(LOG, FileUtils.class, "Trying to obtain resource [" + resourceName + "] using File class facility. Name " +
278             "of file [" + resourceForFile + "]");
279         final File resourceFile = new File(resourceForFile);
280         if (resourceFile.isFile())
281         {
282             try
283             {
284                 LoggingUtils.debug(LOG, FileUtils.class, "The ResourceBundle with the name [" + resourceForFile +
285                     "] was obtained via the FileInputStream (name is anot a base name but file name)");
286                 FileInputStream inputStream = new FileInputStream(resourceFile);
287                 return new PropertyResourceBundle(inputStream);
288             }
289             catch (Exception ex)
290             {
291                 // oops, exception occured.
292             }
293         }
294         LoggingUtils.debug(LOG, FileUtils.class, "Can not obtain resource [" + resourceName + "] using File class facility. Name " +
295             "of file [" + resourceForFile + "]");
296         return null;
297     }
298 
299     /**
300      * Construct the full path using the provide variable args.
301      *
302      * @param args the variable args, Can not be null (otherwise <code>IllegalArgumentException</code> would appear). The members of this
303      *             cannot be <code>null</code>.
304      *
305      * @return the full path. The File.separator is used for the constructing the path
306      */
307     public static String constructPath(final String... args)
308     {
309         InputArgumentUtils.checkStrings(true, args);
310         String result = "";
311         boolean isEmpty = true;
312         for (final String part : args)
313         {
314             result += ((isEmpty) ? "" : File.separator) + part;
315             isEmpty = false;
316         }
317         return result;
318     }
319 }
320