View Javadoc

1   /*
2    * $Id: IOUtils.java 11338 2008-03-12 23:10:14Z aperepel $
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, 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      * @return
202      */
203     private static String parseResourceName(String src)
204     {
205         String var;
206         String[] split;
207         String ps = File.separator;
208 
209         if (src.indexOf('$') > -1)
210         {
211             split = src.split("}");
212         }
213         else
214         {
215             return src;
216         }
217 
218         var = split[0].substring(2);
219         var = SystemUtils.getenv(var);
220         if (split.length > 1)
221         {
222             if (var == null)
223             {
224                 var = System.getProperty(split[0].substring(2));
225                 if (var == null)
226                 {
227                     return split[1].substring(1);
228                 }
229                 else
230                 {
231                     return var + ps + split[1].substring(1);
232                 }
233             }
234             else
235             {
236                 return var + ps + split[1].substring(1);
237             }
238         }
239         else
240         {
241             if (var == null)
242             {
243                 return "";
244             }
245             else
246             {
247                 return var;
248             }
249         }
250     }
251     
252     /**
253      * This method wraps {@link org.apache.commons.io.IOUtils}' <code>toString(InputStream)</code>
254      * method but catches any {@link IOException} and wraps it into a {@link RuntimeException}.
255      */
256     public static String toString(InputStream input)
257     {
258         try
259         {
260             return org.apache.commons.io.IOUtils.toString(input);
261         }
262         catch (IOException iox)
263         {
264             throw new RuntimeException(iox);
265         }
266     }
267     
268     /**
269      * This method wraps {@link org.apache.commons.io.IOUtils}' <code>toByteArray(InputStream)</code>
270      * method but catches any {@link IOException} and wraps it into a {@link RuntimeException}.
271      */
272     public static byte[] toByteArray(InputStream input)
273     {
274         try
275         {
276             return org.apache.commons.io.IOUtils.toByteArray(input);
277         }
278         catch (IOException iox)
279         {
280             throw new RuntimeException(iox);
281         }
282     }
283 }