001/* 002 * ModeShape (http://www.modeshape.org) 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 */ 016package org.modeshape.common.util; 017 018import java.io.InputStream; 019 020/** 021 * Utility to search and load resources from the CP. 022 * 023 * @author Horia Chiorean (hchiorea@redhat.com) 024 */ 025public final class ResourceLookup { 026 027 private ResourceLookup() { 028 } 029 030 /** 031 * Returns the stream of a resource at a given path, using some optional class loaders. 032 * 033 * @param path the path to search 034 * @param classLoader a {@link java.lang.ClassLoader} instance to use when searching; may be null. 035 * @param useTLCL {@code true} if the thread local class loader should be used as well, in addition to {@code classLoader} 036 * @return a {@link java.io.InputStream} if the resource was found, or {@code null} otherwise 037 */ 038 public static InputStream read( String path, ClassLoader classLoader, boolean useTLCL ) { 039 if (useTLCL) { 040 InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(path); 041 if (stream != null) { 042 return stream; 043 } 044 } 045 return classLoader != null ? classLoader.getResourceAsStream(path) : ResourceLookup.class.getResourceAsStream(path); 046 } 047 048 /** 049 * Returns the stream of a resource at a given path, using the CL of a class. 050 * 051 * @param path the path to search 052 * @param clazz a {@link java.lang.Class} instance which class loader should be used when doing the lookup. 053 * @param useTLCL {@code true} if the thread local class loader should be used as well, in addition to {@code classLoader} 054 * @return a {@link java.io.InputStream} if the resource was found, or {@code null} otherwise 055 * @see org.modeshape.common.util.ResourceLookup#read(String, ClassLoader, boolean) 056 */ 057 public static InputStream read( String path, Class<?> clazz, boolean useTLCL ) { 058 return read(path, clazz.getClassLoader(), useTLCL); 059 } 060}