asmuts 02/01/14 22:34:35
Added: src/java/org/apache/stratum/jcs/config OptionConverter.java
PropertySetter.java PropertySetterException.java
Log:
log4j modified props to plugin config file parser
Revision Changes Path
1.1
jakarta-turbine-stratum/src/java/org/apache/stratum/jcs/config/OptionConverter.java
Index: OptionConverter.java
===================================================================
package org.apache.stratum.jcs.config;
import java.util.Properties;
//import org.apache.stratum.jcs.auxiliary.*;
import org.apache.stratum.jcs.auxiliary.behavior.*;
import org.apache.stratum.jcs.engine.*;
import org.apache.stratum.jcs.engine.behavior.*;
import org.apache.stratum.jcs.utils.log.*;
/** This class is based on the log4j class org.apache.log4j.helpers.OptionConverter
* that was made by
* Ceki Gülcü
* Simon Kitching;
* Avy Sharell ([EMAIL PROTECTED])
* Anders Kristensen
* Matthieu Verbert ([EMAIL PROTECTED])
*/
/**
A convenience class to convert property values to specific types.
*/
public class OptionConverter {
static String DELIM_START = "${";
static char DELIM_STOP = '}';
static int DELIM_START_LEN = 2;
static int DELIM_STOP_LEN = 1;
static StringBuffer sbuf = new StringBuffer();
private static Logger log = LoggerManager.getLogger( OptionConverter.class );
/** OptionConverter is a static class. */
private OptionConverter() {}
public
static
String[] concatanateArrays(String[] l, String[] r) {
int len = l.length + r.length;
String[] a = new String[len];
System.arraycopy(l, 0, a, 0, l.length);
System.arraycopy(r, 0, a, l.length, r.length);
return a;
}
public
static
String convertSpecialChars(String s) {
char c;
int len = s.length();
StringBuffer sbuf = new StringBuffer(len);
int i = 0;
while(i < len) {
c = s.charAt(i++);
if (c == '\\') {
c = s.charAt(i++);
if(c == 'n') c = '\n';
else if(c == 'r') c = '\r';
else if(c == 't') c = '\t';
else if(c == 'f') c = '\f';
else if(c == '\b') c = '\b';
else if(c == '\"') c = '\"';
else if(c == '\'') c = '\'';
else if(c == '\\') c = '\\';
}
sbuf.append(c);
}
return sbuf.toString();
}
/**
Very similar to <code>System.getProperty</code> except
that the {@link SecurityException} is hidden.
@param key The key to search for.
@param def The default value to return.
@return the string value of the system property, or the default
value if there is no property with that key.
@since 1.1 */
public
static
String getSystemProperty(String key, String def) {
try {
return System.getProperty(key, def);
} catch(Throwable e) { // MS-Java throws com.ms.security.SecurityExceptionEx
log.debug("Was not allowed to read system property \""+key+"\".");
return def;
}
}
public
static
Object instantiateByKey(Properties props, String key, Class superClass,
Object defaultValue) {
// Get the value of the property in string form
String className = findAndSubst(key, props);
if(className == null) {
log.warn("Could not find value for key " + key);
return defaultValue;
}
// Trim className to avoid trailing spaces that cause problems.
return OptionConverter.instantiateByClassName(className.trim(), superClass,
defaultValue);
}
/**
If <code>value</code> is "true", then <code>true</code> is
returned. If <code>value</code> is "false", then
<code>true</code> is returned. Otherwise, <code>default</code> is
returned.
<p>Case of value is unimportant. */
public
static
boolean toBoolean(String value, boolean dEfault) {
if(value == null)
return dEfault;
String trimmedVal = value.trim();
if("true".equalsIgnoreCase(trimmedVal))
return true;
if("false".equalsIgnoreCase(trimmedVal))
return false;
return dEfault;
}
public
static
int toInt(String value, int dEfault) {
if(value != null) {
String s = value.trim();
try {
return Integer.valueOf(s).intValue();
}
catch (NumberFormatException e) {
log.error("[" + s + "] is not in proper int form.");
e.printStackTrace();
}
}
return dEfault;
}
public
static
long toFileSize(String value, long dEfault) {
if(value == null)
return dEfault;
String s = value.trim().toUpperCase();
long multiplier = 1;
int index;
if((index = s.indexOf("KB")) != -1) {
multiplier = 1024;
s = s.substring(0, index);
}
else if((index = s.indexOf("MB")) != -1) {
multiplier = 1024*1024;
s = s.substring(0, index);
}
else if((index = s.indexOf("GB")) != -1) {
multiplier = 1024*1024*1024;
s = s.substring(0, index);
}
if(s != null) {
try {
return Long.valueOf(s).longValue() * multiplier;
}
catch (NumberFormatException e) {
log.error("[" + s + "] is not in proper int form.");
log.error(e, "[" + value + "] not in expected format.");
}
}
return dEfault;
}
/**
Find the value corresponding to <code>key</code> in
<code>props</code>. Then perform variable substitution on the
found value.
*/
public
static
String findAndSubst(String key, Properties props) {
String value = props.getProperty(key);
if(value == null)
return null;
try {
return substVars(value, props);
} catch(IllegalArgumentException e) {
log.error( e, "Bad option value ["+value+"].");
return value;
}
}
/**
Instantiate an object given a class name. Check that the
<code>className</code> is a subclass of
<code>superClass</code>. If that test fails or the object could
not be instantiated, then <code>defaultValue</code> is returned.
@param className The fully qualified class name of the object to instantiate.
@param superClass The class to which the new object should belong.
@param defaultValue The object to return in case of non-fulfillment
*/
public
static
Object instantiateByClassName(String className, Class superClass,
Object defaultValue) {
if(className != null) {
try {
Class classObj = Class.forName(className);
if(!superClass.isAssignableFrom(classObj)) {
log.error("A \""+className+"\" object is not assignable to a \""+
superClass.getName() + "\" variable.");
return defaultValue;
}
return classObj.newInstance();
}
catch (Exception e) {
log.error(e, "Could not instantiate class [" + className + "].");
}
}
return defaultValue;
}
/**
Perform variable substitution in string <code>val</code> from the
values of keys found in the system propeties.
<p>The variable substitution delimeters are <b>${</b> and <b>}</b>.
<p>For example, if the System properties contains "key=value", then
the call
<pre>
String s = OptionConverter.substituteVars("Value of key is ${key}.");
</pre>
will set the variable <code>s</code> to "Value of key is value.".
<p>If no value could be found for the specified key, then the
<code>props</code> parameter is searched, if the value could not
be found there, then substitution defaults to the empty string.
<p>For example, if system propeties contains no value for the key
"inexistentKey", then the call
<pre>
String s = OptionConverter.subsVars("Value of inexistentKey is
[${inexistentKey}]");
</pre>
will set <code>s</code> to "Value of inexistentKey is []"
<p>An {@link java.lang.IllegalArgumentException} is thrown if
<code>val</code> contains a start delimeter "${" which is not
balanced by a stop delimeter "}". </p>
<p><b>Author</b> Avy Sharell</a></p>
@param val The string on which variable substitution is performed.
@throws IllegalArgumentException if <code>val</code> is malformed.
*/
public static
String substVars(String val, Properties props) throws
IllegalArgumentException {
sbuf.setLength(0);
int i = 0;
int j, k;
while(true) {
j=val.indexOf(DELIM_START, i);
if(j == -1) {
if(i==0)
return val;
else {
sbuf.append(val.substring(i, val.length()));
return sbuf.toString();
}
}
else {
sbuf.append(val.substring(i, j));
k = val.indexOf(DELIM_STOP, j);
if(k == -1) {
throw new IllegalArgumentException('"'+val+
"\" has no closing brace. Opening brace at position " + j
+ '.');
}
else {
j += DELIM_START_LEN;
String key = val.substring(j, k);
// first try in System properties
String replacement = getSystemProperty(key, null);
// then try props parameter
if(replacement == null && props != null) {
replacement = props.getProperty(key);
}
if(replacement != null)
sbuf.append(replacement);
i = k + DELIM_STOP_LEN;
}
}
}
}
} // end class
1.1
jakarta-turbine-stratum/src/java/org/apache/stratum/jcs/config/PropertySetter.java
Index: PropertySetter.java
===================================================================
package org.apache.stratum.jcs.config;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
//import org.apache.stratum.jcs.auxiliary.*;
import org.apache.stratum.jcs.auxiliary.behavior.*;
import org.apache.stratum.jcs.engine.*;
import org.apache.stratum.jcs.engine.behavior.*;
import org.apache.stratum.jcs.utils.log.*;
/** This class is based on the log4j class org.apache.log4j.config.PropertySetter
* that was made by
* Anders Kristensen
*/
/**
General purpose Object property setter. Clients repeatedly invokes
{@link #setProperty setProperty(name,value)} in order to invoke setters
on the Object specified in the constructor. This class relies on the
JavaBeans {@link Introspector} to analyze the given Object Class using
reflection.
<p>Usage:
<pre>
PropertySetter ps = new PropertySetter(anObject);
ps.set("name", "Joe");
ps.set("age", "32");
ps.set("isMale", "true");
</pre>
will cause the invocations anObject.setName("Joe"), anObject.setAge(32),
and setMale(true) if such methods exist with those signatures.
Otherwise an {@link IntrospectionException} are thrown.
@author Anders Kristensen
@since 1.1
*/
public class PropertySetter {
protected Object obj;
protected PropertyDescriptor[] props;
private static Logger log = LoggerManager.getLogger( PropertySetter.class );
/**
Create a new PropertySetter for the specified Object. This is done
in prepartion for invoking {@link #setProperty} one or more times.
@param obj the object for which to set properties
*/
public PropertySetter(Object obj) {
this.obj = obj;
}
/**
Uses JavaBeans {@link Introspector} to computer setters of object to be
configured.
*/
protected void introspect() {
try {
BeanInfo bi = Introspector.getBeanInfo(obj.getClass());
props = bi.getPropertyDescriptors();
} catch (IntrospectionException ex) {
log.error("Failed to introspect "+obj+": " + ex.getMessage());
props = new PropertyDescriptor[0];
}
}
/**
Set the properties of an object passed as a parameter in one
go. The <code>properties</code> are parsed relative to a
<code>prefix</code>.
@param obj The object to configure.
@param properties A java.util.Properties containing keys and values.
@param prefix Only keys having the specified prefix will be set.
*/
public static void setProperties(Object obj, Properties properties, String prefix)
{
new PropertySetter(obj).setProperties(properties, prefix);
}
/**
Set the properites for the object that match the
<code>prefix</code> passed as parameter.
*/
public void setProperties(Properties properties, String prefix) {
int len = prefix.length();
for (Enumeration e = properties.keys(); e.hasMoreElements(); ) {
String key = (String) e.nextElement();
// handle only properties that start with the desired frefix.
if (key.startsWith(prefix)) {
// ignore key if it contains dots after the prefix
if (key.indexOf('.', len + 1) > 0) {
//System.err.println("----------Ignoring---["+key
// +"], prefix=["+prefix+"].");
continue;
}
String value = OptionConverter.findAndSubst(key, properties);
key = key.substring(len);
setProperty(key, value);
}
}
}
/**
Set a property on this PropertySetter's Object. If successful, this
method will invoke a setter method on the underlying Object. The
setter is the one for the specified property name and the value is
determined partly from the setter argument type and partly from the
value specified in the call to this method.
<p>If the setter expects a String no conversion is necessary.
If it expects an int, then an attempt is made to convert 'value'
to an int using new Integer(value). If the setter expects a boolean,
the conversion is by new Boolean(value).
@param name name of the property
@param value String value of the property
*/
public
void setProperty(String name, String value) {
if (value == null) return;
name = Introspector.decapitalize(name);
PropertyDescriptor prop = getPropertyDescriptor(name);
//log.debug("---------Key: "+name+", type="+prop.getPropertyType());
if (prop == null) {
log.warn("No such property [" + name + "] in "+
obj.getClass().getName()+"." );
} else {
try {
setProperty(prop, name, value);
} catch (PropertySetterException ex) {
log.warn("Failed to set property " + name +
" to value \"" + value + "\". " + ex.getMessage());
}
}
}
/**
Set the named property given a {@link PropertyDescriptor}.
@param prop A PropertyDescriptor describing the characteristics
of the property to set.
@param name The named of the property to set.
@param value The value of the property.
*/
public
void setProperty(PropertyDescriptor prop, String name, String value)
throws PropertySetterException {
Method setter = prop.getWriteMethod();
if (setter == null) {
throw new PropertySetterException("No setter for property");
}
Class[] paramTypes = setter.getParameterTypes();
if (paramTypes.length != 1) {
throw new PropertySetterException("#params for setter != 1");
}
Object arg;
try {
arg = convertArg(value, paramTypes[0]);
} catch (Throwable t) {
throw new PropertySetterException("Conversion to type ["+paramTypes[0]+
"] failed. Reason: "+t);
}
if (arg == null) {
throw new PropertySetterException(
"Conversion to type ["+paramTypes[0]+"] failed.");
}
log.debug("Setting property [" + name + "] to [" +arg+"].");
try {
setter.invoke(obj, new Object[] { arg });
} catch (Exception ex) {
throw new PropertySetterException(ex);
}
}
/**
Convert <code>val</code> a String parameter to an object of a
given type.
*/
protected Object convertArg(String val, Class type) {
if(val == null)
return null;
String v = val.trim();
if (String.class.isAssignableFrom(type)) {
return val;
} else if (Integer.TYPE.isAssignableFrom(type)) {
return new Integer(v);
} else if (Long.TYPE.isAssignableFrom(type)) {
return new Long(v);
} else if (Boolean.TYPE.isAssignableFrom(type)) {
if ("true".equalsIgnoreCase(v)) {
return Boolean.TRUE;
} else if ("false".equalsIgnoreCase(v)) {
return Boolean.FALSE;
}
}
return null;
}
protected PropertyDescriptor getPropertyDescriptor(String name) {
if (props == null) introspect();
for (int i = 0; i < props.length; i++) {
if (name.equals(props[i].getName())) {
return props[i];
}
}
return null;
}
}
1.1
jakarta-turbine-stratum/src/java/org/apache/stratum/jcs/config/PropertySetterException.java
Index: PropertySetterException.java
===================================================================
package org.apache.stratum.jcs.config;
/** This class is based on the log4j class org.apache.log4j.config.PropertySetter
* that was made by
* Anders Kristensen
*/
/**
* Thrown when an error is encountered whilst attempting to set a property
* using the {@link PropertySetter} utility class.
*
* @author Anders Kristensen
* @since 1.1
*/
public class PropertySetterException extends Exception {
protected Throwable rootCause;
public
PropertySetterException(String msg) {
super(msg);
}
public
PropertySetterException(Throwable rootCause)
{
super();
this.rootCause = rootCause;
}
/**
Returns descriptive text on the cause of this exception.
*/
public
String getMessage() {
String msg = super.getMessage();
if (msg == null && rootCause != null) {
msg = rootCause.getMessage();
}
return msg;
}
}
--
To unsubscribe, e-mail: <mailto:[EMAIL PROTECTED]>
For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>