001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019 020package org.apache.isis.core.commons.lang; 021 022import java.io.InputStream; 023import java.net.URL; 024 025/** 026 * Adapted from Ibatis Common, now with some additional guava stuff. 027 */ 028public class ResourceUtil { 029 030 private ResourceUtil(){} 031 032 /** 033 * Returns the URL, or null if not available. 034 */ 035 public static URL getResourceURL(final String resource) { 036 037 // try thread's classloader 038 ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 039 URL url = classLoader.getResource(resource); 040 if (url != null) { 041 return url; 042 } 043 044 // try this class' classloader 045 classLoader = ResourceUtil.class.getClassLoader(); 046 url = classLoader.getResource(resource); 047 if (url != null) { 048 return url; 049 } 050 051 // try system class loader (could return null) 052 // wrapping in a try...catch because when running tests by Maven for a 053 // non-existing 054 // resource, seems to bomb out. Is okay when run from Eclipse. A bit of 055 // a puzzle. 056 try { 057 return ClassLoader.getSystemResource(resource); 058 } catch (final NullPointerException ignore) { 059 return null; 060 } 061 } 062 063 public static InputStream getResourceAsStream(final String resource) { 064 065 // try thread's classloader 066 ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 067 InputStream is = classLoader.getResourceAsStream(resource); 068 if (is != null) { 069 return is; 070 } 071 072 // try this class' classloader 073 classLoader = ResourceUtil.class.getClassLoader(); 074 is = classLoader.getResourceAsStream(resource); 075 if (is != null) { 076 return is; 077 } 078 079 // try system class loader (could return null) 080 // have wrapped in a try...catch because for same reason as 081 // getResourceURL 082 try { 083 return ClassLoader.getSystemResourceAsStream(resource); 084 } catch (final NullPointerException ignore) { 085 return null; 086 } 087 } 088 089}