1 23 24 package org.infoglue.cms.util; 25 26 import java.io.IOException ; 27 import java.io.InputStream ; 28 import java.io.InputStreamReader ; 29 import java.io.Reader ; 30 import java.net.URL ; 31 import java.util.Properties ; 32 33 import org.apache.log4j.Logger; 34 import org.infoglue.cms.exception.ConfigurationError; 35 36 37 42 public class ResourceHelper { 43 45 private static final int CHAR_BUFFER_SIZE = 4096; 47 48 49 50 53 private static final StringManager sm = StringManagerFactory.getSystemStringManager(Constants.PACKAGE_NAME); 55 56 private static final Logger logger = Logger.getLogger(RegexpHelper.class.getName()); 58 59 60 61 63 66 private ResourceHelper() {} 67 68 69 70 72 79 public static synchronized Properties loadProperties(String name) { 80 logger.debug(sm.getString("resource.loadProperties.info", name)); 81 try { 82 final Properties properties = new Properties (); 83 properties.load(getResourceAsStream(name, ResourceHelper.class)); 84 return properties; 85 } catch(Exception e) { 86 throw new ConfigurationError(sm.getString("resource.loadProperties.error", name), e); 87 } 88 } 89 90 97 public static synchronized String readResource(String name) { 98 logger.debug(sm.getString("resource.readResource.info", name)); 99 try { 100 final StringBuffer sb = new StringBuffer (); 101 final Reader reader = new InputStreamReader (getResourceAsStream(name, ResourceHelper.class)); 102 char[] buf = new char[CHAR_BUFFER_SIZE]; 103 int count = 0; 104 while((count = reader.read(buf, 0, CHAR_BUFFER_SIZE)) > 0) { 105 sb.append(buf, 0, count); 106 } 107 return sb.toString(); 108 } catch(Exception e) { 109 throw new ConfigurationError(sm.getString("resource.readResource.error", name), e); 110 } 111 } 112 113 120 public static InputStream getResourceAsStream(String resourceName, Class callingClass) 121 { 122 URL url = null; 123 124 url = Thread.currentThread().getContextClassLoader().getResource(resourceName); 125 126 if (url == null) 127 url = ResourceHelper.class.getClassLoader().getResource(resourceName); 128 129 if (url == null) 130 url = callingClass.getClassLoader().getResource(resourceName); 131 132 try 133 { 134 return url != null ? url.openStream() : null; 135 } 136 catch (IOException e) 137 { 138 return null; 139 } 140 } 141 } | Popular Tags |