001/*
002 * Copyright (c) 2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     Florent Guillaume
011 */
012package org.nuxeo.theme;
013
014import java.io.InputStream;
015import java.net.URL;
016
017/**
018 * Resolver for resources.
019 * <p>
020 * This default implementation uses the thread context ClassLoader.
021 *
022 * @since 5.5
023 */
024public class ResourceResolver {
025
026    private static final ResourceResolver DEFAULT = new ResourceResolver();
027
028    private static ResourceResolver instance = DEFAULT;
029
030    /**
031     * Gets the current resolver (thread local).
032     */
033    public static ResourceResolver getInstance() {
034        return instance;
035    }
036
037    /**
038     * Called by the framework to set the current resolver or clear it.
039     */
040    public static void setInstance(ResourceResolver resolver) {
041        instance = resolver == null ? DEFAULT : resolver;
042    }
043
044    /**
045     * Gets a resource URL at the given path.
046     *
047     * @param path the path, which must not start with a /
048     * @see javax.servlet.ServletContext#getResource
049     * @see java.lang.ClassLoader#getResource
050     */
051    public URL getResource(String path) {
052        ClassLoader cl = Thread.currentThread().getContextClassLoader();
053        URL url = cl.getResource(path);
054        if (url == null) {
055            url = cl.getResource("nuxeo.war/" + path);
056        }
057        return url;
058    }
059
060    /**
061     * Gets a resource at the given path.
062     *
063     * @param path the path, which must not start with a /
064     * @see javax.servlet.ServletContext#getResourceAsStream
065     * @see java.lang.ClassLoader#getResourceAsStream
066     */
067    public InputStream getResourceAsStream(String path) {
068        ClassLoader cl = Thread.currentThread().getContextClassLoader();
069        InputStream is = cl.getResourceAsStream(path);
070        if (is == null) {
071            is = cl.getResourceAsStream("nuxeo.war/" + path);
072        }
073        return is;
074    }
075
076}