001/*
002 * (C) Copyright 2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Florent Guillaume
018 */
019package org.nuxeo.theme;
020
021import java.io.InputStream;
022import java.net.URL;
023
024/**
025 * Resolver for resources.
026 * <p>
027 * This default implementation uses the thread context ClassLoader.
028 *
029 * @since 5.5
030 */
031public class ResourceResolver {
032
033    private static final ResourceResolver DEFAULT = new ResourceResolver();
034
035    private static ResourceResolver instance = DEFAULT;
036
037    /**
038     * Gets the current resolver (thread local).
039     */
040    public static ResourceResolver getInstance() {
041        return instance;
042    }
043
044    /**
045     * Called by the framework to set the current resolver or clear it.
046     */
047    public static void setInstance(ResourceResolver resolver) {
048        instance = resolver == null ? DEFAULT : resolver;
049    }
050
051    /**
052     * Gets a resource URL at the given path.
053     *
054     * @param path the path, which must not start with a /
055     * @see javax.servlet.ServletContext#getResource
056     * @see java.lang.ClassLoader#getResource
057     */
058    public URL getResource(String path) {
059        ClassLoader cl = Thread.currentThread().getContextClassLoader();
060        URL url = cl.getResource(path);
061        if (url == null) {
062            url = cl.getResource("nuxeo.war/" + path);
063        }
064        return url;
065    }
066
067    /**
068     * Gets a resource at the given path.
069     *
070     * @param path the path, which must not start with a /
071     * @see javax.servlet.ServletContext#getResourceAsStream
072     * @see java.lang.ClassLoader#getResourceAsStream
073     */
074    public InputStream getResourceAsStream(String path) {
075        ClassLoader cl = Thread.currentThread().getContextClassLoader();
076        InputStream is = cl.getResourceAsStream(path);
077        if (is == null) {
078            is = cl.getResourceAsStream("nuxeo.war/" + path);
079        }
080        return is;
081    }
082
083}