View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.core.util;
15  
16  import java.io.FileNotFoundException;
17  import java.net.MalformedURLException;
18  import java.net.URL;
19  
20  /**
21   * A static utility method that converts a string that describes the
22   * location of a resource into a {@link URL} object.
23   *
24   * @author Carl Harris
25   */
26  public class LocationUtil {
27  
28      /** Regex pattern for a URL scheme (reference RFC 2396 section 3) */
29      public static final String SCHEME_PATTERN = "^\\p{Alpha}[\\p{Alnum}+.-]*:.*$";
30  
31      /** Scheme name for a classpath resource */
32      public static final String CLASSPATH_SCHEME = "classpath:";
33  
34      /**
35       * Converts a string describing the location of a resource into a URL object.
36       * @param location String describing the location
37       * @return URL object that refers to {@code location}
38       * @throws MalformedURLException if {@code location} is not a syntatically
39       *    valid URL
40       * @throws FileNotFoundException if {@code location} specifies a non-existent
41       *    classpath resource
42       * @throws NullPointerException if {@code location} is {@code null}
43       */
44      public static URL urlForResource(String location) throws MalformedURLException, FileNotFoundException {
45          if (location == null) {
46              throw new NullPointerException("location is required");
47          }
48          URL url = null;
49          if (!location.matches(SCHEME_PATTERN)) {
50              url = Loader.getResourceBySelfClassLoader(location);
51          } else if (location.startsWith(CLASSPATH_SCHEME)) {
52              String path = location.substring(CLASSPATH_SCHEME.length());
53              if (path.startsWith("/")) {
54                  path = path.substring(1);
55              }
56              if (path.length() == 0) {
57                  throw new MalformedURLException("path is required");
58              }
59              url = Loader.getResourceBySelfClassLoader(path);
60          } else {
61              url = new URL(location);
62          }
63          if (url == null) {
64              throw new FileNotFoundException(location);
65          }
66          return url;
67      }
68  
69  }