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