View Javadoc

1   /*
2    * $Id: IOUtils.java 7963 2007-08-21 08:53:15Z dirk.olmes $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSource, Inc.  All rights reserved.  http://www.mulesource.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.util;
12  
13  import org.mule.config.i18n.CoreMessages;
14  
15  import java.io.File;
16  import java.io.IOException;
17  import java.io.InputStream;
18  import java.net.MalformedURLException;
19  import java.net.URL;
20  import java.security.AccessController;
21  import java.security.PrivilegedAction;
22  
23  import org.apache.commons.logging.Log;
24  import org.apache.commons.logging.LogFactory;
25  
26  // @ThreadSafe
27  /**
28   * Mule input/output utilities.
29   */
30  public class IOUtils extends org.apache.commons.io.IOUtils
31  {
32      /** Logger. */
33      private static final Log logger = LogFactory.getLog(IOUtils.class);
34  
35      /**
36       * Attempts to load a resource from the file system, from a URL, or from the
37       * classpath, in that order.
38       * 
39       * @param resourceName The name of the resource to load
40       * @param callingClass The Class object of the calling object
41       * @return the requested resource as a string
42       * @throws java.io.IOException IO error
43       */
44      public static String getResourceAsString(final String resourceName, final Class callingClass)
45          throws IOException
46      {
47          InputStream is = getResourceAsStream(resourceName, callingClass);
48          if (is != null)
49          {
50              return toString(is);
51          }
52          else
53          {
54              throw new IOException("Unable to load resource " + resourceName);
55          }
56      }
57  
58      /**
59       * Attempts to load a resource from the file system, from a URL, or from the
60       * classpath, in that order.
61       * 
62       * @param resourceName The name of the resource to load
63       * @param callingClass The Class object of the calling object
64       * @return an InputStream to the resource or null if resource not found
65       * @throws java.io.IOException IO error
66       */
67      public static InputStream getResourceAsStream(final String resourceName,
68                                                    final Class callingClass) throws IOException
69      {
70          return getResourceAsStream(parseResourceName(resourceName), callingClass, true, true);
71      }
72  
73      /**
74       * Attempts to load a resource from the file system, from a URL, or from the
75       * classpath, in that order.
76       * 
77       * @param resourceName The name of the resource to load
78       * @param callingClass The Class object of the calling object
79       * @param tryAsFile - try to load the resource from the local file system
80       * @param tryAsUrl - try to load the resource as a URL
81       * @return an InputStream to the resource or null if resource not found
82       * @throws java.io.IOException IO error
83       */
84      public static InputStream getResourceAsStream(final String resourceName,
85                                                    final Class callingClass,
86                                                    boolean tryAsFile,
87                                                    boolean tryAsUrl) throws IOException
88      {
89  
90          URL url = getResourceAsUrl(resourceName, callingClass, tryAsFile);
91  
92          // Try to load the resource itself as a URL.
93          if ((url == null) && (tryAsUrl))
94          {
95              try
96              {
97                  url = new URL(resourceName);
98              }
99              catch (MalformedURLException e)
100             {
101                 logger.debug("Unable to load resource as a URL: " + resourceName);
102             }
103         }
104 
105         if (url == null)
106         {
107             return null;
108         }
109         else
110         {
111             return url.openStream();
112         }
113     }
114 
115     /**
116      * Attempts to load a resource from the file system or from the classpath, in
117      * that order.
118      * 
119      * @param resourceName The name of the resource to load
120      * @param callingClass The Class object of the calling object
121      * @return an URL to the resource or null if resource not found
122      */
123     public static URL getResourceAsUrl(final String resourceName, final Class callingClass)
124     {
125         return getResourceAsUrl(resourceName, callingClass, true);
126     }
127 
128     /**
129      * Attempts to load a resource from the file system or from the classpath, in
130      * that order.
131      * 
132      * @param resourceName The name of the resource to load
133      * @param callingClass The Class object of the calling object
134      * @param tryAsFile - try to load the resource from the local file system
135      * @return an URL to the resource or null if resource not found
136      */
137     public static URL getResourceAsUrl(final String resourceName,
138                                        final Class callingClass,
139                                        boolean tryAsFile)
140     {
141         if (resourceName == null)
142         {
143             throw new IllegalArgumentException(
144                 CoreMessages.objectIsNull("Resource name").getMessage());
145         }
146         URL url = null;
147 
148         // Try to load the resource from the file system.
149         if (tryAsFile)
150         {
151             try
152             {
153                 File file = FileUtils.newFile(resourceName);
154                 if (file.exists())
155                 {
156                     url = file.getAbsoluteFile().toURL();
157                 }
158                 else
159                 {
160                     logger.debug("Unable to load resource from the file system: "
161                                  + file.getAbsolutePath());
162                 }
163             }
164             catch (Exception e)
165             {
166                 logger.debug("Unable to load resource from the file system: " + e.getMessage());
167             }
168         }
169 
170         // Try to load the resource from the classpath.
171         if (url == null)
172         {
173             try
174             {
175                 url = (URL)AccessController.doPrivileged(new PrivilegedAction()
176                 {
177                     public Object run()
178                     {
179                         return ClassUtils.getResource(resourceName, callingClass);
180                     }
181                 });
182                 if (url == null)
183                 {
184                     logger.debug("Unable to load resource from the classpath");
185                 }
186             }
187             catch (Exception e)
188             {
189                 logger.debug("Unable to load resource from the classpath: " + e.getMessage());
190             }
191         }
192 
193         return url;
194     }
195 
196     /**
197      * This method checks whether the name of the resource needs to be parsed. If it
198      * is, it parses the name and tries to get the variable from the Environmental
199      * Variables configured on the system.
200      * 
201      * @param src
202      * @return
203      */
204     private static String parseResourceName(String src)
205     {
206         String var;
207         String[] split;
208         String ps = File.separator;
209 
210         if (src.indexOf('$') > -1)
211         {
212             split = src.split("}");
213         }
214         else
215         {
216             return src;
217         }
218 
219         var = split[0].substring(2);
220         var = SystemUtils.getenv(var);
221         if (split.length > 1)
222         {
223             if (var == null)
224             {
225                 var = System.getProperty(split[0].substring(2));
226                 if (var == null)
227                 {
228                     return split[1].substring(1);
229                 }
230                 else
231                 {
232                     return var + ps + split[1].substring(1);
233                 }
234             }
235             else
236             {
237                 return var + ps + split[1].substring(1);
238             }
239         }
240         else
241         {
242             if (var == null)
243             {
244                 return "";
245             }
246             else
247             {
248                 return var;
249             }
250         }
251     }
252 }