1 61 62 package org.apache.commons.discovery.tools; 63 64 import java.io.IOException ; 65 import java.io.InputStream ; 66 import java.util.Properties ; 67 68 import org.apache.commons.discovery.DiscoveryException; 69 import org.apache.commons.discovery.Resource; 70 import org.apache.commons.discovery.listeners.FirstResourceListener; 71 import org.apache.commons.discovery.resource.ClassLoaders; 72 import org.apache.commons.discovery.resource.DiscoverResources; 73 74 75 85 public class ResourceUtils { 86 93 public static String getPackageName(Class clazz) { 94 Package clazzPackage = clazz.getPackage(); 95 String packageName; 96 if (clazzPackage != null) { 97 packageName = clazzPackage.getName(); 98 } else { 99 String clazzName = clazz.getName(); 100 packageName = new String (clazzName.toCharArray(), 0, clazzName.lastIndexOf('.')); 101 } 102 return packageName; 103 } 104 105 106 117 public static Resource getResource(Class spi, 118 String resourceName, 119 ClassLoaders loaders) 120 throws DiscoveryException 121 { 122 FirstResourceListener listener = new FirstResourceListener(); 123 124 DiscoverResources explorer = new DiscoverResources(loaders); 125 explorer.setListener(listener); 126 explorer.find(resourceName); 127 128 if (spi != null && 129 (listener.getFirst() == null) && 130 resourceName.charAt(0) != '/') 131 { 132 137 explorer.find(getPackageName(spi).replace('.','/') + "/" + resourceName); 138 } 139 140 return listener.getFirst(); 141 } 142 143 166 public static Properties loadProperties(Class spi, 167 String propertiesFileName, 168 ClassLoaders classLoaders) 169 throws DiscoveryException 170 { 171 Properties properties = null; 172 173 if (propertiesFileName != null) { 174 try { 175 Resource resource = getResource(spi, propertiesFileName, classLoaders); 176 if (resource != null) { 177 InputStream stream = resource.getResourceAsStream(); 178 179 if (stream != null) { 180 properties = new Properties (); 181 try { 182 properties.load(stream); 183 } finally { 184 stream.close(); 185 } 186 } 187 } 188 } catch (IOException e) { 189 ; } catch (SecurityException e) { 191 ; } 193 } 194 195 return properties; 196 } 197 } 198 | Popular Tags |