001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.core.util;
015
016import java.io.FileNotFoundException;
017import java.net.MalformedURLException;
018import java.net.URL;
019
020/**
021 * A static utility method that converts a string that describes the location of
022 * a resource into a {@link URL} object.
023 *
024 * @author Carl Harris
025 */
026public class LocationUtil {
027
028    /** Regex pattern for a URL scheme (reference RFC 2396 section 3) */
029    public static final String SCHEME_PATTERN = "^\\p{Alpha}[\\p{Alnum}+.-]*:.*$";
030
031    /** Scheme name for a classpath resource */
032    public static final String CLASSPATH_SCHEME = "classpath:";
033
034    /**
035     * Converts a string describing the location of a resource into a URL object.
036     * 
037     * @param location String describing the location
038     * @return URL object that refers to {@code location}
039     * @throws MalformedURLException if {@code location} is not a syntatically valid
040     *                               URL
041     * @throws FileNotFoundException if {@code location} specifies a non-existent
042     *                               classpath resource
043     * @throws NullPointerException  if {@code location} is {@code null}
044     */
045    public static URL urlForResource(String location) throws MalformedURLException, FileNotFoundException {
046        if (location == null) {
047            throw new NullPointerException("location is required");
048        }
049        URL url = null;
050        if (!location.matches(SCHEME_PATTERN)) {
051            url = Loader.getResourceBySelfClassLoader(location);
052        } else if (location.startsWith(CLASSPATH_SCHEME)) {
053            String path = location.substring(CLASSPATH_SCHEME.length());
054            if (path.startsWith("/")) {
055                path = path.substring(1);
056            }
057            if (path.length() == 0) {
058                throw new MalformedURLException("path is required");
059            }
060            url = Loader.getResourceBySelfClassLoader(path);
061        } else {
062            url = new URL(location);
063        }
064        if (url == null) {
065            throw new FileNotFoundException(location);
066        }
067        return url;
068    }
069
070}