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 location of
22 * 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 *
37 * @param location String describing the location
38 * @return URL object that refers to {@code location}
39 * @throws MalformedURLException if {@code location} is not a syntactically valid
40 * URL
41 * @throws FileNotFoundException if {@code location} specifies a non-existent
42 * classpath resource
43 * @throws NullPointerException if {@code location} is {@code null}
44 */
45 public static URL urlForResource(String location) throws MalformedURLException, FileNotFoundException {
46 if (location == null) {
47 throw new NullPointerException("location is required");
48 }
49 URL url = null;
50 if (!location.matches(SCHEME_PATTERN)) {
51 url = Loader.getResourceBySelfClassLoader(location);
52 } else if (location.startsWith(CLASSPATH_SCHEME)) {
53 String path = location.substring(CLASSPATH_SCHEME.length());
54 if (path.startsWith("/")) {
55 path = path.substring(1);
56 }
57 if (path.length() == 0) {
58 throw new MalformedURLException("path is required");
59 }
60 url = Loader.getResourceBySelfClassLoader(path);
61 } else {
62 url = new URL(location);
63 }
64 if (url == null) {
65 throw new FileNotFoundException(location);
66 }
67 return url;
68 }
69
70 }