1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
package compbio.util;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import org.apache.log4j.Logger;
/**
* A common interface for finding the installation settings for the
* implementation.
*
* @author Petr Troshin
* @version 1.0 October 2009
*/
public class PropertyHelper {
private final java.util.Properties properties;
private static Logger log = Logger.getLogger(PropertyHelper.class);
public PropertyHelper(StringReader input) {
try {
this.properties = new java.util.Properties();
this.properties.load(input);
} catch (IOException e) {
throw new RuntimeException("Properties file could not be found !",
e);
}
}
public PropertyHelper(String... propertyPaths) throws IOException {
this(getReader(propertyPaths));
}
public PropertyHelper(File... propertyPaths) throws IOException {
this(getReader(propertyPaths));
}
/**
* @param propertiesFile
* @throws FileNotFoundException
*
* public PropertyHelper(File propertiesFile) throws
* FileNotFoundException { this(new
* java.io.FileInputStream(propertiesFile)); }
*/
/**
* @return input stream for default location for properties
* @throws IOException
*/
private static StringReader getReader(String... propertyPaths)
throws IOException {
String props = "";
for (String path : propertyPaths) {
File prop = new File(path);
props += PropertyHelper.readProp(prop);
}
return new StringReader(props);
}
private static String readProp(File propFile) throws IOException {
String props = "";
if (propFile == null) {
log.error("PropFile is expected!");
return "";
}
if (propFile.exists() && propFile.canRead()) {
props += FileUtil.readFileToString(propFile) + SysPrefs.newlinechar;
} else {
log.debug("Cannot read properties file: "
+ propFile.getAbsolutePath());
}
return props;
}
private static StringReader getReader(File... propertyPaths)
throws IOException {
String props = "";
assert propertyPaths != null && propertyPaths.length > 0 : " No property files provided!";
for (File prop : propertyPaths) {
log.debug("Reading properties from file: " + prop.getAbsolutePath());
props += PropertyHelper.readProp(prop);
}
return new StringReader(props);
}
public String getProperty(String name) {
// load from context first
String property = null;
// load from file
if (property == null && this.properties != null)
property = this.properties.getProperty(name);
// it is an error if both do not have this name
if (property == null) {
log.warn("Properties '" + name + "' not found in file.");
}
return property;
}
public java.util.Properties getProperties() {
return this.properties;
}
}
|