1 package org.andromda.core.common; 2 3 import java.io.BufferedReader; 4 import java.io.InputStreamReader; 5 import java.net.URL; 6 7 import org.apache.log4j.Logger; 8 9 /*** 10 * Provides utilities for loading resources. 11 * 12 * @author Chad Brandon 13 */ 14 public class ResourceUtils { 15 16 private static final Logger logger = Logger.getLogger(ResourceUtils.class); 17 18 /*** 19 * Retrieves a resource from the class package 20 * @param resourceName the name of the resource 21 * @return java.net.URL 22 */ 23 public static URL getResource(String resourceName) { 24 final String methodName = "ResourceUtils.getResource"; 25 if (logger.isDebugEnabled()) 26 logger.debug("performing '" + methodName 27 + "' with resourceName '" + resourceName + "'"); 28 ExceptionUtils.checkEmpty(methodName, "resourceName", resourceName); 29 ClassLoader loader = Thread.currentThread().getContextClassLoader(); 30 URL resource = loader.getResource(resourceName); 31 return resource; 32 } 33 34 /*** 35 * Loads the file resource and returns the contents 36 * as a String. 37 * @param resourceName the name of the resource. 38 * @return String 39 */ 40 public static String getContents(URL resource) { 41 final String methodName = "ResourceUtils.getContents"; 42 if (logger.isDebugEnabled()) 43 logger.debug("performing " + methodName 44 + " with resource '" + resource + "'"); 45 StringBuffer contents = new StringBuffer(); 46 try { 47 if (resource != null) { 48 BufferedReader in = 49 new BufferedReader( 50 new InputStreamReader(resource.openStream())); 51 String line; 52 while ((line = in.readLine()) != null){ 53 contents.append(line + "\n"); 54 } 55 in.close(); 56 } 57 } catch (Exception ex) { 58 String errMsg = "Error performing " + methodName; 59 logger.error(errMsg, ex); 60 throw new RuntimeException(errMsg, ex); 61 } 62 return contents.toString(); 63 } 64 65 /*** 66 * Loads the file resource and returns the contents 67 * as a String. 68 * @param resourceName the name of the resource. 69 * @return String 70 */ 71 public static String getContents(String resourceName) { 72 return getContents(getResource(resourceName)); 73 } 74 /*** 75 * Takes a className as an argument and returns the URL for the 76 * class. 77 * @param className 78 * @return java.net.URL 79 */ 80 public static URL getClassResource(String className) { 81 final String methodName = "ResourceUtils.getClassResource"; 82 ExceptionUtils.checkEmpty(methodName, "className", className); 83 return getResource(getClassNameAsResource(className)); 84 } 85 86 /*** 87 * Private helper method. 88 * @param className 89 * @return String 90 */ 91 private static String getClassNameAsResource(String className) { 92 return className.replace('.', '/') + ".class"; 93 } 94 95 }