View Javadoc

1   /*
2    * $Id: IOUtils.java 19191 2010-08-25 21:05:23Z tcarlson $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.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, tryAsUrl);
91  
92          if (url == null)
93          {
94              return null;
95          }
96          else
97          {
98              return url.openStream();
99          }
100     }
101 
102     /**
103      * Attempts to load a resource from the file system or from the classpath, in
104      * that order.
105      * 
106      * @param resourceName The name of the resource to load
107      * @param callingClass The Class object of the calling object
108      * @return an URL to the resource or null if resource not found
109      */
110     public static URL getResourceAsUrl(final String resourceName, final Class callingClass)
111     {
112         return getResourceAsUrl(resourceName, callingClass, true, true);
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      * @param tryAsFile - try to load the resource from the local file system
122      * @param tryAsUrl - try to load the resource as a Url string
123      * @return an URL to the resource or null if resource not found
124      */
125     public static URL getResourceAsUrl(final String resourceName,
126                                        final Class callingClass,
127                                        boolean tryAsFile, boolean tryAsUrl)
128     {
129         if (resourceName == null)
130         {
131             throw new IllegalArgumentException(
132                 CoreMessages.objectIsNull("Resource name").getMessage());
133         }
134         URL url = null;
135 
136         // Try to load the resource from the file system.
137         if (tryAsFile)
138         {
139             try
140             {
141                 File file = FileUtils.newFile(resourceName);
142                 if (file.exists())
143                 {
144                     url = file.getAbsoluteFile().toURL();
145                 }
146                 else
147                 {
148                     logger.debug("Unable to load resource from the file system: "
149                                  + file.getAbsolutePath());
150                 }
151             }
152             catch (Exception e)
153             {
154                 logger.debug("Unable to load resource from the file system: " + e.getMessage());
155             }
156         }
157 
158         // Try to load the resource from the classpath.
159         if (url == null)
160         {
161             try
162             {
163                 url = (URL)AccessController.doPrivileged(new PrivilegedAction()
164                 {
165                     public Object run()
166                     {
167                         return ClassUtils.getResource(resourceName, callingClass);
168                     }
169                 });
170                 if (url == null)
171                 {
172                     logger.debug("Unable to load resource " + resourceName + " from the classpath");
173                 }
174             }
175             catch (Exception e)
176             {
177                 logger.debug("Unable to load resource " + resourceName + " from the classpath: " + e.getMessage());
178             }
179         }
180 
181         if(url==null)
182         {
183             try
184             {
185                 url = new URL(resourceName);
186             }
187             catch (MalformedURLException e)
188             {
189                 //ignore
190             }
191         }
192         return url;
193     }
194 
195     /**
196      * This method checks whether the name of the resource needs to be parsed. If it
197      * is, it parses the name and tries to get the variable from the Environmental
198      * Variables configured on the system.
199      * 
200      * @param src
201      */
202     private static String parseResourceName(String src)
203     {
204         String var;
205         String[] split;
206         String ps = File.separator;
207 
208         if (src.indexOf('$') > -1)
209         {
210             split = src.split("}");
211         }
212         else
213         {
214             return src;
215         }
216 
217         var = split[0].substring(2);
218         var = SystemUtils.getenv(var);
219         if (split.length > 1)
220         {
221             if (var == null)
222             {
223                 var = System.getProperty(split[0].substring(2));
224                 if (var == null)
225                 {
226                     return split[1].substring(1);
227                 }
228                 else
229                 {
230                     return var + ps + split[1].substring(1);
231                 }
232             }
233             else
234             {
235                 return var + ps + split[1].substring(1);
236             }
237         }
238         else
239         {
240             if (var == null)
241             {
242                 return "";
243             }
244             else
245             {
246                 return var;
247             }
248         }
249     }
250     
251     /**
252      * This method wraps {@link org.apache.commons.io.IOUtils}' <code>toString(InputStream)</code>
253      * method but catches any {@link IOException} and wraps it into a {@link RuntimeException}.
254      */
255     public static String toString(InputStream input)
256     {
257         try
258         {
259             return org.apache.commons.io.IOUtils.toString(input);
260         }
261         catch (IOException iox)
262         {
263             throw new RuntimeException(iox);
264         }
265     }
266     
267     /**
268      * This method wraps {@link org.apache.commons.io.IOUtils}' <code>toByteArray(InputStream)</code>
269      * method but catches any {@link IOException} and wraps it into a {@link RuntimeException}.
270      */
271     public static byte[] toByteArray(InputStream input)
272     {
273         try
274         {
275             return org.apache.commons.io.IOUtils.toByteArray(input);
276         }
277         catch (IOException iox)
278         {
279             throw new RuntimeException(iox);
280         }
281     }
282 }