View Javadoc

    1   /*
    2    * Copyright 2001-2004 The Apache Software Foundation.
    3    *
    4    * Licensed under the Apache License, Version 2.0 (the "License")
    5    * you may not use this file except in compliance with the License.
    6    * You may obtain a copy of the License at
    7    *
    8    *     http://www.apache.org/licenses/LICENSE-2.0
    9    *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16
    17  package org.apache.commons.configuration;
    18
    19  import java.io.File;
    20  import java.io.IOException;
    21  import java.io.PrintStream;
    22  import java.io.PrintWriter;
    23  import java.io.StringWriter;
    24  import java.net.MalformedURLException;
    25  import java.net.URL;
    26  import java.util.Iterator;
    27
    28  import org.apache.commons.lang.StringUtils;
    29  import org.apache.commons.logging.Log;
    30  import org.apache.commons.logging.LogFactory;
    31
    32  /***
    33   * Miscellaneous utility methods for configurations.
    34   *
    35   * @author <a href="mailto:herve.quiroz@esil.univ-mrs.fr">Herve Quiroz</a>
    36   * @author <a href="mailto:oliver.heger@t-online.de">Oliver Heger</a>
    37   * @author Emmanuel Bourg
    38   * @version $Revision: 1.9 $, $Date: 2004/09/23 11:42:00 $
    39   */
    40  public final class ConfigurationUtils
    41  {
    42      private static Log log = LogFactory.getLog(ConfigurationUtils.class);
    43
    44      private ConfigurationUtils()
    45      {
    46          // to prevent instanciation...
    47      }
    48
    49      /***
    50       * Dump the configuration key/value mappings to some ouput stream.
    51       *
    52       * @param configuration the configuration
    53       * @param out the output stream to dump the configuration to
    54       */
    55      public static void dump(Configuration configuration, PrintStream out)
    56      {
    57          dump(configuration, new PrintWriter(out));
    58      }
    59
    60      /***
    61       * Dump the configuration key/value mappings to some writer.
    62       *
    63       * @param configuration the configuration
    64       * @param out the writer to dump the configuration to
    65       */
    66      public static void dump(Configuration configuration, PrintWriter out)
    67      {
    68          Iterator keys = configuration.getKeys();
    69          while (keys.hasNext())
    70          {
    71              String key = (String) keys.next();
    72              Object value = configuration.getProperty(key);
    73              out.print(key);
    74              out.print("=");
    75              out.print(value);
    76
    77              if (keys.hasNext())
    78              {
    79                  out.println();
    80              }
    81          }
    82
    83          out.flush();
    84      }
    85
    86      /***
    87       * Get a string representation of the key/value mappings of a
    88       * configuration.
    89       *
    90       * @param configuration the configuration
    91       * @return a string representation of the configuration
    92       */
    93      public static String toString(Configuration configuration)
    94      {
    95          StringWriter writer = new StringWriter();
    96          dump(configuration, new PrintWriter(writer));
    97          return writer.toString();
    98      }
    99
    100     /***
    101      * Constructs a URL from a base path and a file name. The file name can
    102      * be absolute, relative or a full URL. If necessary the base path URL is
    103      * applied.
    104      *
    105      * @param basePath the base path URL (can be <b>null</b>)
    106      * @param file the file name
    107      * @return the resulting URL
    108      * @throws MalformedURLException if URLs are invalid
    109      */
    110     public static URL getURL(String basePath, String file) throws MalformedURLException
    111     {
    112         File f = new File(file);
    113         if (f.isAbsolute())     // already absolute?
    114         {
    115             return f.toURL();
    116         }
    117
    118         try
    119         {
    120             if (basePath == null)
    121             {
    122                 return new URL(file);
    123             }
    124             else
    125             {
    126                 URL base = new URL(basePath);
    127                 return new URL(base, file);
    128             }
    129         }
    130         catch (MalformedURLException uex)
    131         {
    132             return constructFile(basePath, file).toURL();
    133         }
    134     }
    135
    136     /***
    137      * Helper method for constructing a file object from a base path and a
    138      * file name. This method is called if the base path passed to
    139      * <code>getURL()</code> does not seem to be a valid URL.
    140      *
    141      * @param basePath the base path
    142      * @param fileName the file name
    143      * @return the resulting file
    144      */
    145     static File constructFile(String basePath, String fileName)
    146     {
    147         File file = null;
    148
    149         File absolute = null;
    150         if (fileName != null)
    151         {
    152             absolute = new File(fileName);
    153         }
    154
    155         if (StringUtils.isEmpty(basePath) || (absolute != null && absolute.isAbsolute()))
    156         {
    157             file = new File(fileName);
    158         }
    159         else
    160         {
    161             StringBuffer fName = new StringBuffer();
    162             fName.append(basePath);
    163
    164             // My best friend. Paranoia.
    165             if (!basePath.endsWith(File.separator))
    166             {
    167                 fName.append(File.separator);
    168             }
    169
    170             //
    171             // We have a relative path, and we have
    172             // two possible forms here. If we have the
    173             // "./" form then just strip that off first
    174             // before continuing.
    175             //
    176             if (fileName.startsWith("." + File.separator))
    177             {
    178                 fName.append(fileName.substring(2));
    179             }
    180             else
    181             {
    182                 fName.append(fileName);
    183             }
    184
    185             file = new File(fName.toString());
    186         }
    187
    188         return file;
    189     }
    190
    191
    192     /***
    193      * Return the location of the specified resource by searching the user home
    194      * directory, the current classpath and the system classpath.
    195      *
    196      * @param name the name of the resource
    197      *
    198      * @return the location of the resource
    199      */
    200     public static URL locate(String name)
    201     {
    202         return locate(null, name);
    203     }
    204
    205     /***
    206      * Return the location of the specified resource by searching the user home
    207      * directory, the current classpath and the system classpath.
    208      *
    209      * @param base the base path of the resource
    210      * @param name the name of the resource
    211      *
    212      * @return the location of the resource
    213      */
    214     public static URL locate(String base, String name)
    215     {
    216         URL url = null;
    217
    218         // attempt to create an URL directly
    219         try
    220         {
    221             if (base == null)
    222             {
    223                 url = new URL(name);
    224             }
    225             else
    226             {
    227                 URL baseURL = new URL(base);
    228                 url = new URL(baseURL, name);
    229             }
    230
    231             log.debug("Configuration loaded from the URL " + url);
    232         }
    233         catch (MalformedURLException e)
    234         {
    235
    236         }
    237
    238         // attempt to load from an absolute path
    239         if (url == null)
    240         {
    241             File file = new File(name);
    242             if (file.isAbsolute())     // already absolute?
    243             {
    244                 try
    245                 {
    246                     url = file.toURL();
    247                     log.debug("Configuration loaded from the absolute path " + name);
    248                 }
    249                 catch (MalformedURLException e)
    250                 {
    251                     e.printStackTrace();
    252                 }
    253             }
    254         }
    255
    256         // attempt to load from the base directory
    257         if (url == null)
    258         {
    259             try
    260             {
    261                 File file = constructFile(base, name);
    262                 if (file != null && file.exists())
    263                 {
    264                     url = file.toURL();
    265                 }
    266
    267                 if (url != null)
    268                 {
    269                     log.debug("Configuration loaded from the base path " + name);
    270                 }
    271             }
    272             catch (IOException e)
    273             {
    274                 e.printStackTrace();
    275             }
    276         }
    277
    278
    279         // attempt to load from the user home directory
    280         if (url == null)
    281         {
    282             try
    283             {
    284                 File file = constructFile(System.getProperty("user.home"), name);
    285                 if (file != null && file.exists())
    286                 {
    287                     url = file.toURL();
    288                 }
    289
    290                 if (url != null)
    291                 {
    292                     log.debug("Configuration loaded from the home path " + name);
    293                 }
    294
    295             }
    296             catch (IOException e)
    297             {
    298                 e.printStackTrace();
    299             }
    300         }
    301
    302         // attempt to load from the context classpath
    303         if (url == null)
    304         {
    305             ClassLoader loader = Thread.currentThread().getContextClassLoader();
    306             url = loader.getResource(name);
    307
    308             if (url != null)
    309             {
    310                 log.debug("Configuration loaded from the context classpath (" + name + ")");
    311             }
    312         }
    313
    314         // attempt to load from the system classpath
    315         if (url == null)
    316         {
    317             url = ClassLoader.getSystemResource(name);
    318
    319             if (url != null)
    320             {
    321                 log.debug("Configuration loaded from the system classpath (" + name + ")");
    322             }
    323         }
    324
    325         return url;
    326     }
    327
    328     /***
    329      * Return the path without the file name, for example http://xyz.net/foo/bar.xml
    330      * results in http://xyz.net/foo/
    331      *
    332      * @param url
    333      * @return
    334      */
    335     static String getBasePath(URL url)
    336     {
    337         String s = url.toString();
    338
    339         if (s.endsWith("/") || StringUtils.isEmpty(url.getPath()))
    340         {
    341             return s;
    342         }
    343         else
    344         {
    345             return s.substring(0, s.lastIndexOf("/") + 1);
    346         }
    347     }
    348
    349     /***
    350      * Extract the file name from the specified URL.
    351      */
    352     static String getFileName(URL url)
    353     {
    354         if (url == null)
    355         {
    356             return null;
    357         }
    358
    359         String path = url.getPath();
    360
    361         if (path.endsWith("/") || StringUtils.isEmpty(path))
    362         {
    363             return null;
    364         }
    365         else
    366         {
    367             return path.substring(path.lastIndexOf("/") + 1);
    368         }
    369     }
    370
    371 }