first commit

This commit is contained in:
2025-07-28 13:56:49 +05:30
commit e9eb805edb
3438 changed files with 520990 additions and 0 deletions

View File

@@ -0,0 +1,445 @@
package org.apache.commons.beanutils;
import java.beans.IndexedPropertyDescriptor;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.collections.FastHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class BeanUtils {
private static FastHashMap dummy = new FastHashMap();
private static Log log = LogFactory.getLog(BeanUtils.class);
private static int debug = 0;
public static int getDebug() {
return debug;
}
public static void setDebug(int newDebug) {
debug = newDebug;
}
public static Object cloneBean(Object bean) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
if (log.isDebugEnabled())
log.debug("Cloning bean: " + bean.getClass().getName());
Class clazz = bean.getClass();
Object newBean = clazz.newInstance();
PropertyUtils.copyProperties(newBean, bean);
return newBean;
}
public static void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException {
if (dest == null)
throw new IllegalArgumentException("No destination bean specified");
if (orig == null)
throw new IllegalArgumentException("No origin bean specified");
if (log.isDebugEnabled())
log.debug("BeanUtils.copyProperties(" + dest + ", " + orig + ")");
if (orig instanceof DynaBean) {
DynaProperty[] origDescriptors = ((DynaBean)orig).getDynaClass().getDynaProperties();
for (int i = 0; i < origDescriptors.length; i++) {
String name = origDescriptors[i].getName();
if (PropertyUtils.isWriteable(dest, name)) {
Object value = ((DynaBean)orig).get(name);
copyProperty(dest, name, value);
}
}
} else if (orig instanceof Map) {
Iterator names = ((Map)orig).keySet().iterator();
while (names.hasNext()) {
String name = names.next();
if (PropertyUtils.isWriteable(dest, name)) {
Object value = ((Map)orig).get(name);
copyProperty(dest, name, value);
}
}
} else {
PropertyDescriptor[] origDescriptors = PropertyUtils.getPropertyDescriptors(orig);
for (int i = 0; i < origDescriptors.length; i++) {
String name = origDescriptors[i].getName();
if (!"class".equals(name))
if (PropertyUtils.isReadable(orig, name) && PropertyUtils.isWriteable(dest, name))
try {
Object value = PropertyUtils.getSimpleProperty(orig, name);
copyProperty(dest, name, value);
} catch (NoSuchMethodException e) {}
}
}
}
public static void copyProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException {
if (log.isTraceEnabled()) {
StringBuffer sb = new StringBuffer(" copyProperty(");
sb.append(bean);
sb.append(", ");
sb.append(name);
sb.append(", ");
if (value == null) {
sb.append("<NULL>");
} else if (value instanceof String) {
sb.append((String)value);
} else if (value instanceof String[]) {
String[] values = (String[])value;
sb.append('[');
for (int k = 0; k < values.length; k++) {
if (k > 0)
sb.append(',');
sb.append(values[k]);
}
sb.append(']');
} else {
sb.append(value.toString());
}
sb.append(')');
log.trace(sb.toString());
}
Object target = bean;
int delim = name.lastIndexOf('.');
if (delim >= 0) {
try {
target = PropertyUtils.getProperty(bean, name.substring(0, delim));
} catch (NoSuchMethodException e) {
return;
}
name = name.substring(delim + 1);
if (log.isTraceEnabled()) {
log.trace(" Target bean = " + target);
log.trace(" Target name = " + name);
}
}
String propName = null;
Class type = null;
int index = -1;
String key = null;
propName = name;
int i = propName.indexOf('[');
if (i >= 0) {
int k = propName.indexOf(']');
try {
index = Integer.parseInt(propName.substring(i + 1, k));
} catch (NumberFormatException e) {}
propName = propName.substring(0, i);
}
int j = propName.indexOf('(');
if (j >= 0) {
int k = propName.indexOf(')');
try {
key = propName.substring(j + 1, k);
} catch (IndexOutOfBoundsException e) {}
propName = propName.substring(0, j);
}
if (target instanceof DynaBean) {
DynaClass dynaClass = ((DynaBean)target).getDynaClass();
DynaProperty dynaProperty = dynaClass.getDynaProperty(propName);
if (dynaProperty == null)
return;
type = dynaProperty.getType();
} else {
PropertyDescriptor descriptor = null;
try {
descriptor = PropertyUtils.getPropertyDescriptor(target, name);
if (descriptor == null)
return;
} catch (NoSuchMethodException e) {
return;
}
type = descriptor.getPropertyType();
if (type == null) {
if (log.isTraceEnabled())
log.trace(" target type for property '" + propName + "' is null, so skipping ths setter");
return;
}
}
if (log.isTraceEnabled())
log.trace(" target propName=" + propName + ", type=" + type + ", index=" + index + ", key=" + key);
if (index >= 0) {
Converter converter = ConvertUtils.lookup(type.getComponentType());
if (converter != null) {
log.trace(" USING CONVERTER " + converter);
value = converter.convert(type, value);
}
try {
PropertyUtils.setIndexedProperty(target, propName, index, value);
} catch (NoSuchMethodException e) {
throw new InvocationTargetException(e, "Cannot set " + propName);
}
} else if (key != null) {
try {
PropertyUtils.setMappedProperty(target, propName, key, value);
} catch (NoSuchMethodException e) {
throw new InvocationTargetException(e, "Cannot set " + propName);
}
} else {
Converter converter = ConvertUtils.lookup(type);
if (converter != null) {
log.trace(" USING CONVERTER " + converter);
value = converter.convert(type, value);
}
try {
PropertyUtils.setSimpleProperty(target, propName, value);
} catch (NoSuchMethodException e) {
throw new InvocationTargetException(e, "Cannot set " + propName);
}
}
}
public static Map describe(Object bean) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if (bean == null)
return new HashMap();
if (log.isDebugEnabled())
log.debug("Describing bean: " + bean.getClass().getName());
Map description = new HashMap();
if (bean instanceof DynaBean) {
DynaProperty[] descriptors = ((DynaBean)bean).getDynaClass().getDynaProperties();
for (int i = 0; i < descriptors.length; i++) {
String name = descriptors[i].getName();
description.put(name, getProperty(bean, name));
}
} else {
PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(bean);
for (int i = 0; i < descriptors.length; i++) {
String name = descriptors[i].getName();
if (descriptors[i].getReadMethod() != null)
description.put(name, getProperty(bean, name));
}
}
return description;
}
public static String[] getArrayProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Object value = PropertyUtils.getProperty(bean, name);
if (value == null)
return null;
if (value instanceof Collection) {
ArrayList values = new ArrayList();
Iterator items = ((Collection)value).iterator();
while (items.hasNext()) {
Object item = items.next();
if (item == null) {
values.add((String)null);
continue;
}
values.add(item.toString());
}
return values.<String>toArray(new String[values.size()]);
}
if (value.getClass().isArray()) {
int n = Array.getLength(value);
String[] arrayOfString = new String[n];
for (int i = 0; i < n; i++) {
Object item = Array.get(value, i);
if (item == null) {
arrayOfString[i] = null;
} else {
arrayOfString[i] = item.toString();
}
}
return arrayOfString;
}
String[] results = new String[1];
results[0] = value.toString();
return results;
}
public static String getIndexedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Object value = PropertyUtils.getIndexedProperty(bean, name);
return ConvertUtils.convert(value);
}
public static String getIndexedProperty(Object bean, String name, int index) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Object value = PropertyUtils.getIndexedProperty(bean, name, index);
return ConvertUtils.convert(value);
}
public static String getMappedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Object value = PropertyUtils.getMappedProperty(bean, name);
return ConvertUtils.convert(value);
}
public static String getMappedProperty(Object bean, String name, String key) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Object value = PropertyUtils.getMappedProperty(bean, name, key);
return ConvertUtils.convert(value);
}
public static String getNestedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Object value = PropertyUtils.getNestedProperty(bean, name);
return ConvertUtils.convert(value);
}
public static String getProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
return getNestedProperty(bean, name);
}
public static String getSimpleProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Object value = PropertyUtils.getSimpleProperty(bean, name);
return ConvertUtils.convert(value);
}
public static void populate(Object bean, Map properties) throws IllegalAccessException, InvocationTargetException {
if (bean == null || properties == null)
return;
if (log.isDebugEnabled())
log.debug("BeanUtils.populate(" + bean + ", " + properties + ")");
Iterator names = properties.keySet().iterator();
while (names.hasNext()) {
String name = names.next();
if (name == null)
continue;
Object value = properties.get(name);
setProperty(bean, name, value);
}
}
public static void setProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException {
if (log.isTraceEnabled()) {
StringBuffer sb = new StringBuffer(" setProperty(");
sb.append(bean);
sb.append(", ");
sb.append(name);
sb.append(", ");
if (value == null) {
sb.append("<NULL>");
} else if (value instanceof String) {
sb.append((String)value);
} else if (value instanceof String[]) {
String[] values = (String[])value;
sb.append('[');
for (int k = 0; k < values.length; k++) {
if (k > 0)
sb.append(',');
sb.append(values[k]);
}
sb.append(']');
} else {
sb.append(value.toString());
}
sb.append(')');
log.trace(sb.toString());
}
Object target = bean;
int delim = name.lastIndexOf('.');
if (delim >= 0) {
try {
target = PropertyUtils.getProperty(bean, name.substring(0, delim));
} catch (NoSuchMethodException e) {
return;
}
name = name.substring(delim + 1);
if (log.isTraceEnabled()) {
log.trace(" Target bean = " + target);
log.trace(" Target name = " + name);
}
}
String propName = null;
Class type = null;
int index = -1;
String key = null;
propName = name;
int i = propName.indexOf('[');
if (i >= 0) {
int k = propName.indexOf(']');
try {
index = Integer.parseInt(propName.substring(i + 1, k));
} catch (NumberFormatException e) {}
propName = propName.substring(0, i);
}
int j = propName.indexOf('(');
if (j >= 0) {
int k = propName.indexOf(')');
try {
key = propName.substring(j + 1, k);
} catch (IndexOutOfBoundsException e) {}
propName = propName.substring(0, j);
}
if (target instanceof DynaBean) {
DynaClass dynaClass = ((DynaBean)target).getDynaClass();
DynaProperty dynaProperty = dynaClass.getDynaProperty(propName);
if (dynaProperty == null)
return;
type = dynaProperty.getType();
} else {
PropertyDescriptor descriptor = null;
try {
descriptor = PropertyUtils.getPropertyDescriptor(target, name);
if (descriptor == null)
return;
} catch (NoSuchMethodException e) {
return;
}
if (descriptor instanceof MappedPropertyDescriptor) {
if (((MappedPropertyDescriptor)descriptor).getMappedWriteMethod() == null) {
if (log.isDebugEnabled())
log.debug("Skipping read-only property");
return;
}
type = ((MappedPropertyDescriptor)descriptor).getMappedPropertyType();
} else if (descriptor instanceof IndexedPropertyDescriptor) {
if (((IndexedPropertyDescriptor)descriptor).getIndexedWriteMethod() == null) {
if (log.isDebugEnabled())
log.debug("Skipping read-only property");
return;
}
type = ((IndexedPropertyDescriptor)descriptor).getIndexedPropertyType();
} else {
if (descriptor.getWriteMethod() == null) {
if (log.isDebugEnabled())
log.debug("Skipping read-only property");
return;
}
type = descriptor.getPropertyType();
}
}
Object newValue = null;
if (type.isArray() && index < 0) {
if (value == null) {
String[] values = new String[1];
values[0] = (String)value;
newValue = ConvertUtils.convert(values, type);
} else if (value instanceof String) {
String[] values = new String[1];
values[0] = (String)value;
newValue = ConvertUtils.convert(values, type);
} else if (value instanceof String[]) {
newValue = ConvertUtils.convert((String[])value, type);
} else {
newValue = value;
}
} else if (type.isArray()) {
if (value instanceof String) {
newValue = ConvertUtils.convert((String)value, type.getComponentType());
} else if (value instanceof String[]) {
newValue = ConvertUtils.convert(((String[])value)[0], type.getComponentType());
} else {
newValue = value;
}
} else if (value instanceof String || value == null) {
newValue = ConvertUtils.convert((String)value, type);
} else if (value instanceof String[]) {
newValue = ConvertUtils.convert(((String[])value)[0], type);
} else if (ConvertUtils.lookup(value.getClass()) != null) {
newValue = ConvertUtils.convert(value.toString(), type);
} else {
newValue = value;
}
try {
if (index >= 0) {
PropertyUtils.setIndexedProperty(target, propName, index, newValue);
} else if (key != null) {
PropertyUtils.setMappedProperty(target, propName, key, newValue);
} else {
PropertyUtils.setProperty(target, propName, newValue);
}
} catch (NoSuchMethodException e) {
throw new InvocationTargetException(e, "Cannot set " + propName);
}
}
}

View File

@@ -0,0 +1,26 @@
package org.apache.commons.beanutils;
public class ConversionException extends RuntimeException {
protected Throwable cause;
public ConversionException(String message) {
super(message);
this.cause = null;
}
public ConversionException(String message, Throwable cause) {
super(message);
this.cause = null;
this.cause = cause;
}
public ConversionException(Throwable cause) {
super(cause.getMessage());
this.cause = null;
this.cause = cause;
}
public Throwable getCause() {
return this.cause;
}
}

View File

@@ -0,0 +1,244 @@
package org.apache.commons.beanutils;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import org.apache.commons.beanutils.converters.BigDecimalConverter;
import org.apache.commons.beanutils.converters.BigIntegerConverter;
import org.apache.commons.beanutils.converters.BooleanArrayConverter;
import org.apache.commons.beanutils.converters.BooleanConverter;
import org.apache.commons.beanutils.converters.ByteArrayConverter;
import org.apache.commons.beanutils.converters.ByteConverter;
import org.apache.commons.beanutils.converters.CharacterArrayConverter;
import org.apache.commons.beanutils.converters.CharacterConverter;
import org.apache.commons.beanutils.converters.ClassConverter;
import org.apache.commons.beanutils.converters.DoubleArrayConverter;
import org.apache.commons.beanutils.converters.DoubleConverter;
import org.apache.commons.beanutils.converters.FloatArrayConverter;
import org.apache.commons.beanutils.converters.FloatConverter;
import org.apache.commons.beanutils.converters.IntegerArrayConverter;
import org.apache.commons.beanutils.converters.IntegerConverter;
import org.apache.commons.beanutils.converters.LongArrayConverter;
import org.apache.commons.beanutils.converters.LongConverter;
import org.apache.commons.beanutils.converters.ShortArrayConverter;
import org.apache.commons.beanutils.converters.ShortConverter;
import org.apache.commons.beanutils.converters.SqlDateConverter;
import org.apache.commons.beanutils.converters.SqlTimeConverter;
import org.apache.commons.beanutils.converters.SqlTimestampConverter;
import org.apache.commons.beanutils.converters.StringArrayConverter;
import org.apache.commons.beanutils.converters.StringConverter;
import org.apache.commons.collections.FastHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ConvertUtils {
private static Boolean defaultBoolean = Boolean.FALSE;
public static boolean getDefaultBoolean() {
return defaultBoolean.booleanValue();
}
public static void setDefaultBoolean(boolean newDefaultBoolean) {
defaultBoolean = new Boolean(newDefaultBoolean);
converters.put(boolean.class, new BooleanConverter(defaultBoolean));
converters.put(Boolean.class, new BooleanConverter(defaultBoolean));
}
private static Byte defaultByte = new Byte((byte)0);
public static byte getDefaultByte() {
return defaultByte.byteValue();
}
public static void setDefaultByte(byte newDefaultByte) {
defaultByte = new Byte(newDefaultByte);
converters.put(byte.class, new ByteConverter(defaultByte));
converters.put(Byte.class, new ByteConverter(defaultByte));
}
private static Character defaultCharacter = new Character(' ');
public static char getDefaultCharacter() {
return defaultCharacter.charValue();
}
public static void setDefaultCharacter(char newDefaultCharacter) {
defaultCharacter = new Character(newDefaultCharacter);
converters.put(char.class, new CharacterConverter(defaultCharacter));
converters.put(Character.class, new CharacterConverter(defaultCharacter));
}
private static Double defaultDouble = new Double(0.0D);
public static double getDefaultDouble() {
return defaultDouble.doubleValue();
}
public static void setDefaultDouble(double newDefaultDouble) {
defaultDouble = new Double(newDefaultDouble);
converters.put(double.class, new DoubleConverter(defaultDouble));
converters.put(Double.class, new DoubleConverter(defaultDouble));
}
private static Float defaultFloat = new Float(0.0F);
public static float getDefaultFloat() {
return defaultFloat.floatValue();
}
public static void setDefaultFloat(float newDefaultFloat) {
defaultFloat = new Float(newDefaultFloat);
converters.put(float.class, new FloatConverter(defaultFloat));
converters.put(Float.class, new FloatConverter(defaultFloat));
}
private static Integer defaultInteger = new Integer(0);
public static int getDefaultInteger() {
return defaultInteger.intValue();
}
public static void setDefaultInteger(int newDefaultInteger) {
defaultInteger = new Integer(newDefaultInteger);
converters.put(int.class, new IntegerConverter(defaultInteger));
converters.put(Integer.class, new IntegerConverter(defaultInteger));
}
private static Long defaultLong = new Long(0L);
public static long getDefaultLong() {
return defaultLong.longValue();
}
public static void setDefaultLong(long newDefaultLong) {
defaultLong = new Long(newDefaultLong);
converters.put(long.class, new LongConverter(defaultLong));
converters.put(Long.class, new LongConverter(defaultLong));
}
private static Short defaultShort = new Short((short)0);
public static short getDefaultShort() {
return defaultShort.shortValue();
}
public static void setDefaultShort(short newDefaultShort) {
defaultShort = new Short(newDefaultShort);
converters.put(short.class, new ShortConverter(defaultShort));
converters.put(Short.class, new ShortConverter(defaultShort));
}
private static FastHashMap converters = new FastHashMap();
static {
converters.setFast(false);
deregister();
converters.setFast(true);
}
private static Log log = LogFactory.getLog(ConvertUtils.class);
public static String convert(Object value) {
if (value == null)
return (String)null;
if (value.getClass().isArray()) {
if (Array.getLength(value) < 1)
return null;
value = Array.get(value, 0);
if (value == null)
return (String)null;
Converter converter1 = (Converter)converters.get(String.class);
return (String)converter1.convert(String.class, value);
}
Converter converter = (Converter)converters.get(String.class);
return (String)converter.convert(String.class, value);
}
public static Object convert(String value, Class clazz) {
if (log.isDebugEnabled())
log.debug("Convert string '" + value + "' to class '" + clazz.getName() + "'");
Converter converter = (Converter)converters.get(clazz);
if (converter == null)
converter = (Converter)converters.get(String.class);
if (log.isTraceEnabled())
log.trace(" Using converter " + converter);
return converter.convert(clazz, value);
}
public static Object convert(String[] values, Class clazz) {
Class type = clazz;
if (clazz.isArray())
type = clazz.getComponentType();
if (log.isDebugEnabled())
log.debug("Convert String[" + values.length + "] to class '" + type.getName() + "[]'");
Converter converter = (Converter)converters.get(type);
if (converter == null)
converter = (Converter)converters.get(String.class);
if (log.isTraceEnabled())
log.trace(" Using converter " + converter);
Object array = Array.newInstance(type, values.length);
for (int i = 0; i < values.length; i++)
Array.set(array, i, converter.convert(type, values[i]));
return array;
}
public static void deregister() {
boolean[] booleanArray = new boolean[0];
byte[] byteArray = new byte[0];
char[] charArray = new char[0];
double[] doubleArray = new double[0];
float[] floatArray = new float[0];
int[] intArray = new int[0];
long[] longArray = new long[0];
short[] shortArray = new short[0];
String[] stringArray = new String[0];
converters.clear();
converters.put(BigDecimal.class, new BigDecimalConverter());
converters.put(BigInteger.class, new BigIntegerConverter());
converters.put(boolean.class, new BooleanConverter(defaultBoolean));
converters.put(Boolean.class, new BooleanConverter(defaultBoolean));
converters.put(booleanArray.getClass(), new BooleanArrayConverter(booleanArray));
converters.put(byte.class, new ByteConverter(defaultByte));
converters.put(Byte.class, new ByteConverter(defaultByte));
converters.put(byteArray.getClass(), new ByteArrayConverter(byteArray));
converters.put(char.class, new CharacterConverter(defaultCharacter));
converters.put(Character.class, new CharacterConverter(defaultCharacter));
converters.put(charArray.getClass(), new CharacterArrayConverter(charArray));
converters.put(Class.class, new ClassConverter());
converters.put(double.class, new DoubleConverter(defaultDouble));
converters.put(Double.class, new DoubleConverter(defaultDouble));
converters.put(doubleArray.getClass(), new DoubleArrayConverter(doubleArray));
converters.put(float.class, new FloatConverter(defaultFloat));
converters.put(Float.class, new FloatConverter(defaultFloat));
converters.put(floatArray.getClass(), new FloatArrayConverter(floatArray));
converters.put(int.class, new IntegerConverter(defaultInteger));
converters.put(Integer.class, new IntegerConverter(defaultInteger));
converters.put(intArray.getClass(), new IntegerArrayConverter(intArray));
converters.put(long.class, new LongConverter(defaultLong));
converters.put(Long.class, new LongConverter(defaultLong));
converters.put(longArray.getClass(), new LongArrayConverter(longArray));
converters.put(short.class, new ShortConverter(defaultShort));
converters.put(Short.class, new ShortConverter(defaultShort));
converters.put(shortArray.getClass(), new ShortArrayConverter(shortArray));
converters.put(String.class, new StringConverter());
converters.put(stringArray.getClass(), new StringArrayConverter(stringArray));
converters.put(Date.class, new SqlDateConverter());
converters.put(Time.class, new SqlTimeConverter());
converters.put(Timestamp.class, new SqlTimestampConverter());
}
public static void deregister(Class clazz) {
converters.remove(clazz);
}
public static Converter lookup(Class clazz) {
return (Converter)converters.get(clazz);
}
public static void register(Converter converter, Class clazz) {
converters.put(clazz, converter);
}
}

View File

@@ -0,0 +1,5 @@
package org.apache.commons.beanutils;
public interface Converter {
Object convert(Class paramClass, Object paramObject);
}

View File

@@ -0,0 +1,21 @@
package org.apache.commons.beanutils;
public interface DynaBean {
boolean contains(String paramString1, String paramString2);
Object get(String paramString);
Object get(String paramString, int paramInt);
Object get(String paramString1, String paramString2);
DynaClass getDynaClass();
void remove(String paramString1, String paramString2);
void set(String paramString, Object paramObject);
void set(String paramString, int paramInt, Object paramObject);
void set(String paramString1, String paramString2, Object paramObject);
}

View File

@@ -0,0 +1,11 @@
package org.apache.commons.beanutils;
public interface DynaClass {
String getName();
DynaProperty getDynaProperty(String paramString);
DynaProperty[] getDynaProperties();
DynaBean newInstance() throws IllegalAccessException, InstantiationException;
}

View File

@@ -0,0 +1,140 @@
package org.apache.commons.beanutils;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.StreamCorruptedException;
import java.util.List;
import java.util.Map;
public class DynaProperty implements Serializable {
private static final int BOOLEAN_TYPE = 1;
private static final int BYTE_TYPE = 2;
private static final int CHAR_TYPE = 3;
private static final int DOUBLE_TYPE = 4;
private static final int FLOAT_TYPE = 5;
private static final int INT_TYPE = 6;
private static final int LONG_TYPE = 7;
private static final int SHORT_TYPE = 8;
protected String name;
protected transient Class type;
public DynaProperty(String name) {
this(name, Object.class);
}
public DynaProperty(String name, Class type) {
this.name = null;
this.type = null;
this.name = name;
this.type = type;
}
public String getName() {
return this.name;
}
public Class getType() {
return this.type;
}
public boolean isIndexed() {
if (this.type == null)
return false;
if (this.type.isArray())
return true;
if (List.class.isAssignableFrom(this.type))
return true;
return false;
}
public boolean isMapped() {
if (this.type == null)
return false;
return Map.class.isAssignableFrom(this.type);
}
public String toString() {
StringBuffer sb = new StringBuffer("DynaProperty[name=");
sb.append(this.name);
sb.append(",type=");
sb.append(this.type);
sb.append("]");
return sb.toString();
}
private void writeObject(ObjectOutputStream out) throws IOException {
int primitiveType = 0;
if (boolean.class.equals(this.type)) {
primitiveType = 1;
} else if (byte.class.equals(this.type)) {
primitiveType = 2;
} else if (char.class.equals(this.type)) {
primitiveType = 3;
} else if (double.class.equals(this.type)) {
primitiveType = 4;
} else if (float.class.equals(this.type)) {
primitiveType = 5;
} else if (int.class.equals(this.type)) {
primitiveType = 6;
} else if (long.class.equals(this.type)) {
primitiveType = 7;
} else if (short.class.equals(this.type)) {
primitiveType = 8;
}
if (primitiveType == 0) {
out.writeBoolean(false);
out.writeObject(this.type);
} else {
out.writeBoolean(true);
out.writeInt(primitiveType);
}
out.defaultWriteObject();
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
if (in.readBoolean()) {
switch (in.readInt()) {
case 1:
this.type = boolean.class;
break;
case 2:
this.type = byte.class;
break;
case 3:
this.type = char.class;
break;
case 4:
this.type = double.class;
break;
case 5:
this.type = float.class;
break;
case 6:
this.type = int.class;
break;
case 7:
this.type = long.class;
break;
case 8:
this.type = short.class;
break;
default:
throw new StreamCorruptedException("Invalid primitive type. Check version of beanutils used to serialize is compatible.");
}
} else {
this.type = (Class)in.readObject();
}
in.defaultReadObject();
}
}

View File

@@ -0,0 +1,242 @@
package org.apache.commons.beanutils;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Hashtable;
public class MappedPropertyDescriptor extends PropertyDescriptor {
private Class mappedPropertyType;
private Method mappedReadMethod;
private Method mappedWriteMethod;
private static final Class[] stringClassArray = new Class[] { String.class };
public MappedPropertyDescriptor(String propertyName, Class beanClass) throws IntrospectionException {
super(propertyName, (Method)null, (Method)null);
if (propertyName == null || propertyName.length() == 0)
throw new IntrospectionException("bad property name: " + propertyName + " on class: " + beanClass.getClass().getName());
setName(propertyName);
String base = capitalizePropertyName(propertyName);
try {
this.mappedReadMethod = findMethod(beanClass, "get" + base, 1, stringClassArray);
Class[] params = { String.class, this.mappedReadMethod.getReturnType() };
this.mappedWriteMethod = findMethod(beanClass, "set" + base, 2, params);
} catch (IntrospectionException e) {}
if (this.mappedReadMethod == null)
this.mappedWriteMethod = findMethod(beanClass, "set" + base, 2);
if (this.mappedReadMethod == null && this.mappedWriteMethod == null)
throw new IntrospectionException("Property '" + propertyName + "' not found on " + beanClass.getName());
findMappedPropertyType();
}
public MappedPropertyDescriptor(String propertyName, Class beanClass, String mappedGetterName, String mappedSetterName) throws IntrospectionException {
super(propertyName, (Method)null, (Method)null);
if (propertyName == null || propertyName.length() == 0)
throw new IntrospectionException("bad property name: " + propertyName);
setName(propertyName);
this.mappedReadMethod = findMethod(beanClass, mappedGetterName, 1, stringClassArray);
if (this.mappedReadMethod != null) {
Class[] params = { String.class, this.mappedReadMethod.getReturnType() };
this.mappedWriteMethod = findMethod(beanClass, mappedSetterName, 2, params);
} else {
this.mappedWriteMethod = findMethod(beanClass, mappedSetterName, 2);
}
findMappedPropertyType();
}
public MappedPropertyDescriptor(String propertyName, Method mappedGetter, Method mappedSetter) throws IntrospectionException {
super(propertyName, mappedGetter, mappedSetter);
if (propertyName == null || propertyName.length() == 0)
throw new IntrospectionException("bad property name: " + propertyName);
setName(propertyName);
this.mappedReadMethod = mappedGetter;
this.mappedWriteMethod = mappedSetter;
findMappedPropertyType();
}
public Class getMappedPropertyType() {
return this.mappedPropertyType;
}
public Method getMappedReadMethod() {
return this.mappedReadMethod;
}
public void setMappedReadMethod(Method mappedGetter) throws IntrospectionException {
this.mappedReadMethod = mappedGetter;
findMappedPropertyType();
}
public Method getMappedWriteMethod() {
return this.mappedWriteMethod;
}
public void setMappedWriteMethod(Method mappedSetter) throws IntrospectionException {
this.mappedWriteMethod = mappedSetter;
findMappedPropertyType();
}
private void findMappedPropertyType() throws IntrospectionException {
try {
this.mappedPropertyType = null;
if (this.mappedReadMethod != null) {
if ((this.mappedReadMethod.getParameterTypes()).length != 1)
throw new IntrospectionException("bad mapped read method arg count");
this.mappedPropertyType = this.mappedReadMethod.getReturnType();
if (this.mappedPropertyType == void.class)
throw new IntrospectionException("mapped read method " + this.mappedReadMethod.getName() + " returns void");
}
if (this.mappedWriteMethod != null) {
Class[] params = this.mappedWriteMethod.getParameterTypes();
if (params.length != 2)
throw new IntrospectionException("bad mapped write method arg count");
if (this.mappedPropertyType != null && this.mappedPropertyType != params[1])
throw new IntrospectionException("type mismatch between mapped read and write methods");
this.mappedPropertyType = params[1];
}
} catch (IntrospectionException ex) {
throw ex;
}
}
private static String capitalizePropertyName(String s) {
if (s.length() == 0)
return s;
char[] chars = s.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
return new String(chars);
}
private static Hashtable declaredMethodCache = new Hashtable();
private static synchronized Method[] getPublicDeclaredMethods(Class clz) {
Class fclz = clz;
Method[] result = (Method[])declaredMethodCache.get(fclz);
if (result != null)
return result;
result = AccessController.<Method[]>doPrivileged(new PrivilegedAction(fclz) {
private final Class val$fclz;
public Object run() {
return this.val$fclz.getDeclaredMethods();
}
});
for (int i = 0; i < result.length; i++) {
Method method = result[i];
int mods = method.getModifiers();
if (!Modifier.isPublic(mods))
result[i] = null;
}
declaredMethodCache.put(clz, result);
return result;
}
private static Method internalFindMethod(Class start, String methodName, int argCount) {
for (Class cl = start; cl != null; cl = cl.getSuperclass()) {
Method[] methods = getPublicDeclaredMethods(cl);
for (int j = 0; j < methods.length; j++) {
Method method = methods[j];
if (method != null) {
int mods = method.getModifiers();
if (!Modifier.isStatic(mods))
if (method.getName().equals(methodName) && (method.getParameterTypes()).length == argCount)
return method;
}
}
}
Class[] ifcs = start.getInterfaces();
for (int i = 0; i < ifcs.length; i++) {
Method m = internalFindMethod(ifcs[i], methodName, argCount);
if (m != null)
return m;
}
return null;
}
private static Method internalFindMethod(Class start, String methodName, int argCount, Class[] args) {
for (Class cl = start; cl != null; cl = cl.getSuperclass()) {
Method[] methods = getPublicDeclaredMethods(cl);
for (int j = 0; j < methods.length; j++) {
Method method = methods[j];
if (method == null)
continue;
int mods = method.getModifiers();
if (Modifier.isStatic(mods))
continue;
Class[] params = method.getParameterTypes();
if (method.getName().equals(methodName) && params.length == argCount) {
boolean different = false;
if (argCount > 0) {
for (int k = 0; k < argCount; k++) {
if (params[k] != args[k])
different = true;
}
if (different)
continue;
}
return method;
}
continue;
}
}
Class[] ifcs = start.getInterfaces();
for (int i = 0; i < ifcs.length; i++) {
Method m = internalFindMethod(ifcs[i], methodName, argCount);
if (m != null)
return m;
}
return null;
}
static Method findMethod(Class cls, String methodName, int argCount) throws IntrospectionException {
if (methodName == null)
return null;
Method m = internalFindMethod(cls, methodName, argCount);
if (m != null)
return m;
throw new IntrospectionException("No method \"" + methodName + "\" with " + argCount + " arg(s)");
}
static Method findMethod(Class cls, String methodName, int argCount, Class[] args) throws IntrospectionException {
if (methodName == null)
return null;
Method m = internalFindMethod(cls, methodName, argCount, args);
if (m != null)
return m;
throw new IntrospectionException("No method \"" + methodName + "\" with " + argCount + " arg(s) of matching types.");
}
static boolean isSubclass(Class a, Class b) {
if (a == b)
return true;
if (a == null || b == null)
return false;
for (Class x = a; x != null; x = x.getSuperclass()) {
if (x == b)
return true;
if (b.isInterface()) {
Class[] interfaces = x.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
if (isSubclass(interfaces[i], b))
return true;
}
}
}
return false;
}
private boolean throwsException(Method method, Class exception) {
Class[] exs = method.getExceptionTypes();
for (int i = 0; i < exs.length; i++) {
if (exs[i] == exception)
return true;
}
return false;
}
}

View File

@@ -0,0 +1,204 @@
package org.apache.commons.beanutils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class MethodUtils {
private static Log log = LogFactory.getLog(MethodUtils.class);
private static boolean loggedAccessibleWarning = false;
private static final Class[] emptyClassArray = new Class[0];
private static final Object[] emptyObjectArray = new Object[0];
public static Object invokeMethod(Object object, String methodName, Object arg) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Object[] args = { arg };
return invokeMethod(object, methodName, args);
}
public static Object invokeMethod(Object object, String methodName, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
if (args == null)
args = emptyObjectArray;
int arguments = args.length;
Class[] parameterTypes = new Class[arguments];
for (int i = 0; i < arguments; i++)
parameterTypes[i] = args[i].getClass();
return invokeMethod(object, methodName, args, parameterTypes);
}
public static Object invokeMethod(Object object, String methodName, Object[] args, Class[] parameterTypes) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
if (parameterTypes == null)
parameterTypes = emptyClassArray;
if (args == null)
args = emptyObjectArray;
Method method = getMatchingAccessibleMethod(object.getClass(), methodName, parameterTypes);
if (method == null)
throw new NoSuchMethodException("No such accessible method: " + methodName + "() on object: " + object.getClass().getName());
return method.invoke(object, args);
}
public static Object invokeExactMethod(Object object, String methodName, Object arg) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Object[] args = { arg };
return invokeExactMethod(object, methodName, args);
}
public static Object invokeExactMethod(Object object, String methodName, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
if (args == null)
args = emptyObjectArray;
int arguments = args.length;
Class[] parameterTypes = new Class[arguments];
for (int i = 0; i < arguments; i++)
parameterTypes[i] = args[i].getClass();
return invokeExactMethod(object, methodName, args, parameterTypes);
}
public static Object invokeExactMethod(Object object, String methodName, Object[] args, Class[] parameterTypes) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
if (args == null)
args = emptyObjectArray;
if (parameterTypes == null)
parameterTypes = emptyClassArray;
Method method = getAccessibleMethod(object.getClass(), methodName, parameterTypes);
if (method == null)
throw new NoSuchMethodException("No such accessible method: " + methodName + "() on object: " + object.getClass().getName());
return method.invoke(object, args);
}
public static Method getAccessibleMethod(Class clazz, String methodName, Class parameterType) {
Class[] parameterTypes = { parameterType };
return getAccessibleMethod(clazz, methodName, parameterTypes);
}
public static Method getAccessibleMethod(Class clazz, String methodName, Class[] parameterTypes) {
try {
return getAccessibleMethod(clazz.getMethod(methodName, parameterTypes));
} catch (NoSuchMethodException e) {
return null;
}
}
public static Method getAccessibleMethod(Method method) {
if (method == null)
return null;
if (!Modifier.isPublic(method.getModifiers()))
return null;
Class clazz = method.getDeclaringClass();
if (Modifier.isPublic(clazz.getModifiers()))
return method;
method = getAccessibleMethodFromInterfaceNest(clazz, method.getName(), method.getParameterTypes());
return method;
}
private static Method getAccessibleMethodFromInterfaceNest(Class clazz, String methodName, Class[] parameterTypes) {
Method method = null;
for (; clazz != null; clazz = clazz.getSuperclass()) {
Class[] interfaces = clazz.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
if (Modifier.isPublic(interfaces[i].getModifiers())) {
try {
method = interfaces[i].getDeclaredMethod(methodName, parameterTypes);
} catch (NoSuchMethodException e) {}
if (method != null)
break;
method = getAccessibleMethodFromInterfaceNest(interfaces[i], methodName, parameterTypes);
if (method != null)
break;
}
}
}
if (method != null)
return method;
return null;
}
public static Method getMatchingAccessibleMethod(Class clazz, String methodName, Class[] parameterTypes) {
if (log.isTraceEnabled())
log.trace("Matching name=" + methodName + " on " + clazz);
try {
Method method = clazz.getMethod(methodName, parameterTypes);
if (log.isTraceEnabled()) {
log.trace("Found straight match: " + method);
log.trace("isPublic:" + Modifier.isPublic(method.getModifiers()));
}
try {
method.setAccessible(true);
} catch (SecurityException se) {
if (!loggedAccessibleWarning) {
log.warn("Cannot use JVM pre-1.4 access bug workaround die to restrictive security manager.");
loggedAccessibleWarning = true;
}
log.debug("Cannot setAccessible on method. Therefore cannot use jvm access bug workaround.", se);
}
return method;
} catch (NoSuchMethodException e) {
int paramSize = parameterTypes.length;
Method[] methods = clazz.getMethods();
for (int i = 0, size = methods.length; i < size; i++) {
if (methods[i].getName().equals(methodName)) {
if (log.isTraceEnabled()) {
log.trace("Found matching name:");
log.trace(methods[i]);
}
Class[] methodsParams = methods[i].getParameterTypes();
int methodParamSize = methodsParams.length;
if (methodParamSize == paramSize) {
boolean match = true;
for (int n = 0; n < methodParamSize; n++) {
if (log.isTraceEnabled()) {
log.trace("Param=" + parameterTypes[n].getName());
log.trace("Method=" + methodsParams[n].getName());
}
if (!isAssignmentCompatible(methodsParams[n], parameterTypes[n])) {
if (log.isTraceEnabled())
log.trace(methodsParams[n] + " is not assignable from " + parameterTypes[n]);
match = false;
break;
}
}
if (match) {
Method method = getAccessibleMethod(methods[i]);
if (method != null) {
if (log.isTraceEnabled())
log.trace(method + " accessible version of " + methods[i]);
try {
method.setAccessible(true);
} catch (SecurityException se) {
if (!loggedAccessibleWarning) {
log.warn("Cannot use JVM pre-1.4 access bug workaround die to restrictive security manager.");
loggedAccessibleWarning = true;
}
log.debug("Cannot setAccessible on method. Therefore cannot use jvm access bug workaround.", se);
}
return method;
}
log.trace("Couldn't find accessible method.");
}
}
}
}
log.trace("No match found.");
return null;
}
}
protected static final boolean isAssignmentCompatible(Class parameterType, Class parameterization) {
if (parameterType.isAssignableFrom(parameterization))
return true;
if (parameterType.isPrimitive()) {
if (boolean.class.equals(parameterType))
return Boolean.class.equals(parameterization);
if (float.class.equals(parameterType))
return Float.class.equals(parameterization);
if (long.class.equals(parameterType))
return Long.class.equals(parameterization);
if (int.class.equals(parameterType))
return Integer.class.equals(parameterization);
if (double.class.equals(parameterType))
return Double.class.equals(parameterization);
}
return false;
}
}

View File

@@ -0,0 +1,707 @@
package org.apache.commons.beanutils;
import java.beans.BeanInfo;
import java.beans.IndexedPropertyDescriptor;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.FastHashMap;
public class PropertyUtils {
public static final char INDEXED_DELIM = '[';
public static final char INDEXED_DELIM2 = ']';
public static final char MAPPED_DELIM = '(';
public static final char MAPPED_DELIM2 = ')';
public static final char NESTED_DELIM = '.';
private static int debug = 0;
public static int getDebug() {
return debug;
}
public static void setDebug(int newDebug) {
debug = newDebug;
}
private static FastHashMap descriptorsCache = null;
private static FastHashMap mappedDescriptorsCache = null;
static {
descriptorsCache = new FastHashMap();
descriptorsCache.setFast(true);
mappedDescriptorsCache = new FastHashMap();
mappedDescriptorsCache.setFast(true);
}
public static void clearDescriptors() {
descriptorsCache.clear();
mappedDescriptorsCache.clear();
Introspector.flushCaches();
}
public static void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if (dest == null)
throw new IllegalArgumentException("No destination bean specified");
if (orig == null)
throw new IllegalArgumentException("No origin bean specified");
if (orig instanceof DynaBean) {
DynaProperty[] origDescriptors = ((DynaBean)orig).getDynaClass().getDynaProperties();
for (int i = 0; i < origDescriptors.length; i++) {
String name = origDescriptors[i].getName();
if (dest instanceof DynaBean) {
if (isWriteable(dest, name)) {
Object value = ((DynaBean)orig).get(name);
((DynaBean)dest).set(name, value);
}
} else if (isWriteable(dest, name)) {
Object value = ((DynaBean)orig).get(name);
setSimpleProperty(dest, name, value);
}
}
} else if (orig instanceof Map) {
Iterator names = ((Map)orig).keySet().iterator();
while (names.hasNext()) {
String name = names.next();
if (dest instanceof DynaBean) {
if (isWriteable(dest, name)) {
Object value = ((Map)orig).get(name);
((DynaBean)dest).set(name, value);
}
continue;
}
if (isWriteable(dest, name)) {
Object value = ((Map)orig).get(name);
setSimpleProperty(dest, name, value);
}
}
} else {
PropertyDescriptor[] origDescriptors = getPropertyDescriptors(orig);
for (int i = 0; i < origDescriptors.length; i++) {
String name = origDescriptors[i].getName();
if (isReadable(orig, name))
if (dest instanceof DynaBean) {
if (isWriteable(dest, name)) {
Object value = getSimpleProperty(orig, name);
((DynaBean)dest).set(name, value);
}
} else if (isWriteable(dest, name)) {
Object value = getSimpleProperty(orig, name);
setSimpleProperty(dest, name, value);
}
}
}
}
public static Map describe(Object bean) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if (bean == null)
throw new IllegalArgumentException("No bean specified");
Map description = new HashMap();
if (bean instanceof DynaBean) {
DynaProperty[] descriptors = ((DynaBean)bean).getDynaClass().getDynaProperties();
for (int i = 0; i < descriptors.length; i++) {
String name = descriptors[i].getName();
description.put(name, getProperty(bean, name));
}
} else {
PropertyDescriptor[] descriptors = getPropertyDescriptors(bean);
for (int i = 0; i < descriptors.length; i++) {
String name = descriptors[i].getName();
if (descriptors[i].getReadMethod() != null)
description.put(name, getProperty(bean, name));
}
}
return description;
}
public static Object getIndexedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if (bean == null)
throw new IllegalArgumentException("No bean specified");
if (name == null)
throw new IllegalArgumentException("No name specified");
int delim = name.indexOf('[');
int delim2 = name.indexOf(']');
if (delim < 0 || delim2 <= delim)
throw new IllegalArgumentException("Invalid indexed property '" + name + "'");
int index = -1;
try {
String subscript = name.substring(delim + 1, delim2);
index = Integer.parseInt(subscript);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid indexed property '" + name + "'");
}
name = name.substring(0, delim);
return getIndexedProperty(bean, name, index);
}
public static Object getIndexedProperty(Object bean, String name, int index) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if (bean == null)
throw new IllegalArgumentException("No bean specified");
if (name == null)
throw new IllegalArgumentException("No name specified");
if (bean instanceof DynaBean) {
DynaProperty dynaProperty = ((DynaBean)bean).getDynaClass().getDynaProperty(name);
if (dynaProperty == null)
throw new NoSuchMethodException("Unknown property '" + name + "'");
return ((DynaBean)bean).get(name, index);
}
PropertyDescriptor descriptor = getPropertyDescriptor(bean, name);
if (descriptor == null)
throw new NoSuchMethodException("Unknown property '" + name + "'");
if (descriptor instanceof IndexedPropertyDescriptor) {
Method method = ((IndexedPropertyDescriptor)descriptor).getIndexedReadMethod();
if (method != null) {
Object[] subscript = new Object[1];
subscript[0] = new Integer(index);
try {
return method.invoke(bean, subscript);
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof ArrayIndexOutOfBoundsException)
throw (ArrayIndexOutOfBoundsException)e.getTargetException();
throw e;
}
}
}
Method readMethod = getReadMethod(descriptor);
if (readMethod == null)
throw new NoSuchMethodException("Property '" + name + "' has no getter method");
Object value = readMethod.invoke(bean, new Object[0]);
if (!value.getClass().isArray()) {
if (!(value instanceof List))
throw new IllegalArgumentException("Property '" + name + "' is not indexed");
return ((List)value).get(index);
}
return Array.get(value, index);
}
public static Object getMappedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if (bean == null)
throw new IllegalArgumentException("No bean specified");
if (name == null)
throw new IllegalArgumentException("No name specified");
int delim = name.indexOf('(');
int delim2 = name.indexOf(')');
if (delim < 0 || delim2 <= delim)
throw new IllegalArgumentException("Invalid mapped property '" + name + "'");
String key = name.substring(delim + 1, delim2);
name = name.substring(0, delim);
return getMappedProperty(bean, name, key);
}
public static Object getMappedProperty(Object bean, String name, String key) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if (bean == null)
throw new IllegalArgumentException("No bean specified");
if (name == null)
throw new IllegalArgumentException("No name specified");
if (key == null)
throw new IllegalArgumentException("No key specified");
if (bean instanceof DynaBean) {
DynaProperty dynaProperty = ((DynaBean)bean).getDynaClass().getDynaProperty(name);
if (dynaProperty == null)
throw new NoSuchMethodException("Unknown property '" + name + "'");
return ((DynaBean)bean).get(name, key);
}
Object result = null;
PropertyDescriptor descriptor = getPropertyDescriptor(bean, name);
if (descriptor == null)
throw new NoSuchMethodException("Unknown property '" + name + "'");
if (descriptor instanceof MappedPropertyDescriptor) {
Method readMethod = ((MappedPropertyDescriptor)descriptor).getMappedReadMethod();
if (readMethod != null) {
Object[] keyArray = new Object[1];
keyArray[0] = key;
result = readMethod.invoke(bean, keyArray);
} else {
throw new NoSuchMethodException("Property '" + name + "' has no mapped getter method");
}
} else {
Method readMethod = descriptor.getReadMethod();
if (readMethod != null) {
Object invokeResult = readMethod.invoke(bean, new Object[0]);
if (invokeResult instanceof Map)
result = ((Map)invokeResult).get(key);
} else {
throw new NoSuchMethodException("Property '" + name + "' has no mapped getter method");
}
}
return result;
}
public static FastHashMap getMappedPropertyDescriptors(Class beanClass) {
if (beanClass == null)
return null;
return (FastHashMap)mappedDescriptorsCache.get(beanClass);
}
public static FastHashMap getMappedPropertyDescriptors(Object bean) {
if (bean == null)
return null;
return getMappedPropertyDescriptors(bean.getClass());
}
public static Object getNestedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if (bean == null)
throw new IllegalArgumentException("No bean specified");
if (name == null)
throw new IllegalArgumentException("No name specified");
int indexOfINDEXED_DELIM = -1;
int indexOfMAPPED_DELIM = -1;
int indexOfMAPPED_DELIM2 = -1;
int indexOfNESTED_DELIM = -1;
while (true) {
indexOfNESTED_DELIM = name.indexOf('.');
indexOfMAPPED_DELIM = name.indexOf('(');
indexOfMAPPED_DELIM2 = name.indexOf(')');
if (indexOfMAPPED_DELIM2 >= 0 && indexOfMAPPED_DELIM >= 0 && (indexOfNESTED_DELIM < 0 || indexOfNESTED_DELIM > indexOfMAPPED_DELIM)) {
indexOfNESTED_DELIM = name.indexOf('.', indexOfMAPPED_DELIM2);
} else {
indexOfNESTED_DELIM = name.indexOf('.');
}
if (indexOfNESTED_DELIM < 0)
break;
String next = name.substring(0, indexOfNESTED_DELIM);
indexOfINDEXED_DELIM = next.indexOf('[');
indexOfMAPPED_DELIM = next.indexOf('(');
if (bean instanceof Map) {
bean = ((Map)bean).get(next);
} else if (indexOfMAPPED_DELIM >= 0) {
bean = getMappedProperty(bean, next);
} else if (indexOfINDEXED_DELIM >= 0) {
bean = getIndexedProperty(bean, next);
} else {
bean = getSimpleProperty(bean, next);
}
if (bean == null)
throw new IllegalArgumentException("Null property value for '" + name.substring(0, indexOfNESTED_DELIM) + "'");
name = name.substring(indexOfNESTED_DELIM + 1);
}
indexOfINDEXED_DELIM = name.indexOf('[');
indexOfMAPPED_DELIM = name.indexOf('(');
if (bean instanceof Map) {
bean = ((Map)bean).get(name);
} else if (indexOfMAPPED_DELIM >= 0) {
bean = getMappedProperty(bean, name);
} else if (indexOfINDEXED_DELIM >= 0) {
bean = getIndexedProperty(bean, name);
} else {
bean = getSimpleProperty(bean, name);
}
return bean;
}
public static Object getProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
return getNestedProperty(bean, name);
}
public static PropertyDescriptor getPropertyDescriptor(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if (bean == null)
throw new IllegalArgumentException("No bean specified");
if (name == null)
throw new IllegalArgumentException("No name specified");
while (true) {
int period = name.indexOf('.');
if (period < 0)
break;
String next = name.substring(0, period);
int indexOfINDEXED_DELIM = next.indexOf('[');
int indexOfMAPPED_DELIM = next.indexOf('(');
if (indexOfMAPPED_DELIM >= 0 && (indexOfINDEXED_DELIM < 0 || indexOfMAPPED_DELIM < indexOfINDEXED_DELIM)) {
bean = getMappedProperty(bean, next);
} else if (indexOfINDEXED_DELIM >= 0) {
bean = getIndexedProperty(bean, next);
} else {
bean = getSimpleProperty(bean, next);
}
if (bean == null)
throw new IllegalArgumentException("Null property value for '" + name.substring(0, period) + "'");
name = name.substring(period + 1);
}
int left = name.indexOf('[');
if (left >= 0)
name = name.substring(0, left);
left = name.indexOf('(');
if (left >= 0)
name = name.substring(0, left);
if (bean == null || name == null)
return null;
PropertyDescriptor[] descriptors = getPropertyDescriptors(bean);
if (descriptors != null)
for (int i = 0; i < descriptors.length; i++) {
if (name.equals(descriptors[i].getName()))
return descriptors[i];
}
PropertyDescriptor result = null;
FastHashMap mappedDescriptors = getMappedPropertyDescriptors(bean);
if (mappedDescriptors == null) {
mappedDescriptors = new FastHashMap();
mappedDescriptors.setFast(true);
mappedDescriptorsCache.put(bean.getClass(), mappedDescriptors);
}
result = (PropertyDescriptor)mappedDescriptors.get(name);
if (result == null) {
try {
result = new MappedPropertyDescriptor(name, bean.getClass());
} catch (IntrospectionException ie) {}
if (result != null)
mappedDescriptors.put(name, result);
}
return result;
}
public static PropertyDescriptor[] getPropertyDescriptors(Class beanClass) {
if (beanClass == null)
throw new IllegalArgumentException("No bean class specified");
PropertyDescriptor[] descriptors = null;
descriptors = (PropertyDescriptor[])descriptorsCache.get(beanClass);
if (descriptors != null)
return descriptors;
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo(beanClass);
} catch (IntrospectionException e) {
return new PropertyDescriptor[0];
}
descriptors = beanInfo.getPropertyDescriptors();
if (descriptors == null)
descriptors = new PropertyDescriptor[0];
descriptorsCache.put(beanClass, descriptors);
return descriptors;
}
public static PropertyDescriptor[] getPropertyDescriptors(Object bean) {
if (bean == null)
throw new IllegalArgumentException("No bean specified");
return getPropertyDescriptors(bean.getClass());
}
public static Class getPropertyEditorClass(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if (bean == null)
throw new IllegalArgumentException("No bean specified");
if (name == null)
throw new IllegalArgumentException("No name specified");
PropertyDescriptor descriptor = getPropertyDescriptor(bean, name);
if (descriptor != null)
return descriptor.getPropertyEditorClass();
return null;
}
public static Class getPropertyType(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if (bean == null)
throw new IllegalArgumentException("No bean specified");
if (name == null)
throw new IllegalArgumentException("No name specified");
if (bean instanceof DynaBean) {
DynaProperty dynaProperty = ((DynaBean)bean).getDynaClass().getDynaProperty(name);
if (dynaProperty == null)
return null;
Class type = dynaProperty.getType();
if (type == null)
return null;
if (type.isArray())
return type.getComponentType();
return type;
}
PropertyDescriptor descriptor = getPropertyDescriptor(bean, name);
if (descriptor == null)
return null;
if (descriptor instanceof IndexedPropertyDescriptor)
return ((IndexedPropertyDescriptor)descriptor).getIndexedPropertyType();
if (descriptor instanceof MappedPropertyDescriptor)
return ((MappedPropertyDescriptor)descriptor).getMappedPropertyType();
return descriptor.getPropertyType();
}
public static Method getReadMethod(PropertyDescriptor descriptor) {
return MethodUtils.getAccessibleMethod(descriptor.getReadMethod());
}
public static Object getSimpleProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if (bean == null)
throw new IllegalArgumentException("No bean specified");
if (name == null)
throw new IllegalArgumentException("No name specified");
if (name.indexOf('.') >= 0)
throw new IllegalArgumentException("Nested property names are not allowed");
if (name.indexOf('[') >= 0)
throw new IllegalArgumentException("Indexed property names are not allowed");
if (name.indexOf('(') >= 0)
throw new IllegalArgumentException("Mapped property names are not allowed");
if (bean instanceof DynaBean) {
DynaProperty dynaProperty = ((DynaBean)bean).getDynaClass().getDynaProperty(name);
if (dynaProperty == null)
throw new NoSuchMethodException("Unknown property '" + name + "'");
return ((DynaBean)bean).get(name);
}
PropertyDescriptor descriptor = getPropertyDescriptor(bean, name);
if (descriptor == null)
throw new NoSuchMethodException("Unknown property '" + name + "'");
Method readMethod = getReadMethod(descriptor);
if (readMethod == null)
throw new NoSuchMethodException("Property '" + name + "' has no getter method");
Object value = readMethod.invoke(bean, new Object[0]);
return value;
}
public static Method getWriteMethod(PropertyDescriptor descriptor) {
return MethodUtils.getAccessibleMethod(descriptor.getWriteMethod());
}
public static boolean isReadable(Object bean, String name) {
if (bean == null)
throw new IllegalArgumentException("No bean specified");
if (name == null)
throw new IllegalArgumentException("No name specified");
if (bean instanceof DynaBean)
return (((DynaBean)bean).getDynaClass().getDynaProperty(name) != null);
try {
PropertyDescriptor desc = getPropertyDescriptor(bean, name);
if (desc != null) {
Method readMethod = desc.getReadMethod();
if (readMethod == null && desc instanceof IndexedPropertyDescriptor)
readMethod = ((IndexedPropertyDescriptor)desc).getIndexedReadMethod();
return (readMethod != null);
}
return false;
} catch (IllegalAccessException e) {
return false;
} catch (InvocationTargetException e) {
return false;
} catch (NoSuchMethodException e) {
return false;
}
}
public static boolean isWriteable(Object bean, String name) {
if (bean == null)
throw new IllegalArgumentException("No bean specified");
if (name == null)
throw new IllegalArgumentException("No name specified");
if (bean instanceof DynaBean)
return (((DynaBean)bean).getDynaClass().getDynaProperty(name) != null);
try {
PropertyDescriptor desc = getPropertyDescriptor(bean, name);
if (desc != null) {
Method writeMethod = desc.getWriteMethod();
if (writeMethod == null && desc instanceof IndexedPropertyDescriptor)
writeMethod = ((IndexedPropertyDescriptor)desc).getIndexedWriteMethod();
return (writeMethod != null);
}
return false;
} catch (IllegalAccessException e) {
return false;
} catch (InvocationTargetException e) {
return false;
} catch (NoSuchMethodException e) {
return false;
}
}
public static void setIndexedProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if (bean == null)
throw new IllegalArgumentException("No bean specified");
if (name == null)
throw new IllegalArgumentException("No name specified");
int delim = name.indexOf('[');
int delim2 = name.indexOf(']');
if (delim < 0 || delim2 <= delim)
throw new IllegalArgumentException("Invalid indexed property '" + name + "'");
int index = -1;
try {
String subscript = name.substring(delim + 1, delim2);
index = Integer.parseInt(subscript);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid indexed property '" + name + "'");
}
name = name.substring(0, delim);
setIndexedProperty(bean, name, index, value);
}
public static void setIndexedProperty(Object bean, String name, int index, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if (bean == null)
throw new IllegalArgumentException("No bean specified");
if (name == null)
throw new IllegalArgumentException("No name specified");
if (bean instanceof DynaBean) {
DynaProperty dynaProperty = ((DynaBean)bean).getDynaClass().getDynaProperty(name);
if (dynaProperty == null)
throw new NoSuchMethodException("Unknown property '" + name + "'");
((DynaBean)bean).set(name, index, value);
return;
}
PropertyDescriptor descriptor = getPropertyDescriptor(bean, name);
if (descriptor == null)
throw new NoSuchMethodException("Unknown property '" + name + "'");
if (descriptor instanceof IndexedPropertyDescriptor) {
Method writeMethod = ((IndexedPropertyDescriptor)descriptor).getIndexedWriteMethod();
if (writeMethod != null) {
Object[] subscript = new Object[2];
subscript[0] = new Integer(index);
subscript[1] = value;
try {
writeMethod.invoke(bean, subscript);
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof ArrayIndexOutOfBoundsException)
throw (ArrayIndexOutOfBoundsException)e.getTargetException();
throw e;
}
return;
}
}
Method readMethod = descriptor.getReadMethod();
if (readMethod == null)
throw new NoSuchMethodException("Property '" + name + "' has no getter method");
Object array = readMethod.invoke(bean, new Object[0]);
if (!array.getClass().isArray()) {
if (array instanceof List) {
((List)array).set(index, value);
} else {
throw new IllegalArgumentException("Property '" + name + "' is not indexed");
}
} else {
Array.set(array, index, value);
}
}
public static void setMappedProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if (bean == null)
throw new IllegalArgumentException("No bean specified");
if (name == null)
throw new IllegalArgumentException("No name specified");
int delim = name.indexOf('(');
int delim2 = name.indexOf(')');
if (delim < 0 || delim2 <= delim)
throw new IllegalArgumentException("Invalid mapped property '" + name + "'");
String key = name.substring(delim + 1, delim2);
name = name.substring(0, delim);
setMappedProperty(bean, name, key, value);
}
public static void setMappedProperty(Object bean, String name, String key, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if (bean == null)
throw new IllegalArgumentException("No bean specified");
if (name == null)
throw new IllegalArgumentException("No name specified");
if (key == null)
throw new IllegalArgumentException("No key specified");
if (bean instanceof DynaBean) {
DynaProperty dynaProperty = ((DynaBean)bean).getDynaClass().getDynaProperty(name);
if (dynaProperty == null)
throw new NoSuchMethodException("Unknown property '" + name + "'");
((DynaBean)bean).set(name, key, value);
return;
}
PropertyDescriptor descriptor = getPropertyDescriptor(bean, name);
if (descriptor == null)
throw new NoSuchMethodException("Unknown property '" + name + "'");
if (descriptor instanceof MappedPropertyDescriptor) {
Method mappedWriteMethod = ((MappedPropertyDescriptor)descriptor).getMappedWriteMethod();
if (mappedWriteMethod != null) {
Object[] params = new Object[2];
params[0] = key;
params[1] = value;
mappedWriteMethod.invoke(bean, params);
} else {
throw new NoSuchMethodException("Property '" + name + "' has no mapped setter method");
}
} else {
Method readMethod = descriptor.getReadMethod();
if (readMethod != null) {
Object invokeResult = readMethod.invoke(bean, new Object[0]);
if (invokeResult instanceof Map)
((Map)invokeResult).put(key, value);
} else {
throw new NoSuchMethodException("Property '" + name + "' has no mapped getter method");
}
}
}
public static void setNestedProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if (bean == null)
throw new IllegalArgumentException("No bean specified");
if (name == null)
throw new IllegalArgumentException("No name specified");
int indexOfINDEXED_DELIM = -1;
int indexOfMAPPED_DELIM = -1;
while (true) {
int delim = name.indexOf('.');
if (delim < 0)
break;
String next = name.substring(0, delim);
indexOfINDEXED_DELIM = next.indexOf('[');
indexOfMAPPED_DELIM = next.indexOf('(');
if (bean instanceof Map) {
bean = ((Map)bean).get(next);
} else if (indexOfMAPPED_DELIM >= 0) {
bean = getMappedProperty(bean, next);
} else if (indexOfINDEXED_DELIM >= 0) {
bean = getIndexedProperty(bean, next);
} else {
bean = getSimpleProperty(bean, next);
}
if (bean == null)
throw new IllegalArgumentException("Null property value for '" + name.substring(0, delim) + "'");
name = name.substring(delim + 1);
}
indexOfINDEXED_DELIM = name.indexOf('[');
indexOfMAPPED_DELIM = name.indexOf('(');
if (bean instanceof Map) {
PropertyDescriptor descriptor = getPropertyDescriptor(bean, name);
if (descriptor == null) {
((Map)bean).put(name, value);
} else {
setSimpleProperty(bean, name, value);
}
} else if (indexOfMAPPED_DELIM >= 0) {
setMappedProperty(bean, name, value);
} else if (indexOfINDEXED_DELIM >= 0) {
setIndexedProperty(bean, name, value);
} else {
setSimpleProperty(bean, name, value);
}
}
public static void setProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
setNestedProperty(bean, name, value);
}
public static void setSimpleProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if (bean == null)
throw new IllegalArgumentException("No bean specified");
if (name == null)
throw new IllegalArgumentException("No name specified");
if (name.indexOf('.') >= 0)
throw new IllegalArgumentException("Nested property names are not allowed");
if (name.indexOf('[') >= 0)
throw new IllegalArgumentException("Indexed property names are not allowed");
if (name.indexOf('(') >= 0)
throw new IllegalArgumentException("Mapped property names are not allowed");
if (bean instanceof DynaBean) {
DynaProperty dynaProperty = ((DynaBean)bean).getDynaClass().getDynaProperty(name);
if (dynaProperty == null)
throw new NoSuchMethodException("Unknown property '" + name + "'");
((DynaBean)bean).set(name, value);
return;
}
PropertyDescriptor descriptor = getPropertyDescriptor(bean, name);
if (descriptor == null)
throw new NoSuchMethodException("Unknown property '" + name + "'");
Method writeMethod = getWriteMethod(descriptor);
if (writeMethod == null)
throw new NoSuchMethodException("Property '" + name + "' has no setter method");
Object[] values = new Object[1];
values[0] = value;
writeMethod.invoke(bean, values);
}
}

View File

@@ -0,0 +1,52 @@
package org.apache.commons.beanutils.converters;
import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
public abstract class AbstractArrayConverter implements Converter {
protected Object defaultValue = null;
protected static String[] strings = new String[0];
protected boolean useDefault = true;
public abstract Object convert(Class paramClass, Object paramObject);
protected List parseElements(String svalue) {
if (svalue == null)
throw new NullPointerException();
svalue = svalue.trim();
if (svalue.startsWith("{") && svalue.endsWith("}"))
svalue = svalue.substring(1, svalue.length() - 1);
try {
int ttype;
StreamTokenizer st = new StreamTokenizer(new StringReader(svalue));
st.whitespaceChars(44, 44);
st.ordinaryChars(48, 57);
st.ordinaryChars(46, 46);
st.ordinaryChars(45, 45);
st.wordChars(48, 57);
st.wordChars(46, 46);
st.wordChars(45, 45);
ArrayList list = new ArrayList();
while (true) {
ttype = st.nextToken();
if (ttype == -3 || ttype > 0) {
list.add(st.sval);
continue;
}
break;
}
if (ttype == -1)
return list;
throw new ConversionException("Encountered token of type " + ttype);
} catch (IOException e) {
throw new ConversionException(e);
}
}
}

View File

@@ -0,0 +1,42 @@
package org.apache.commons.beanutils.converters;
import java.math.BigDecimal;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
public final class BigDecimalConverter implements Converter {
private Object defaultValue;
private boolean useDefault;
public BigDecimalConverter() {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = null;
this.useDefault = false;
}
public BigDecimalConverter(Object defaultValue) {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = defaultValue;
this.useDefault = true;
}
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (value instanceof BigDecimal)
return value;
try {
return new BigDecimal(value.toString());
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(e);
}
}
}

View File

@@ -0,0 +1,42 @@
package org.apache.commons.beanutils.converters;
import java.math.BigInteger;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
public final class BigIntegerConverter implements Converter {
private Object defaultValue;
private boolean useDefault;
public BigIntegerConverter() {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = null;
this.useDefault = false;
}
public BigIntegerConverter(Object defaultValue) {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = defaultValue;
this.useDefault = true;
}
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (value instanceof BigInteger)
return value;
try {
return new BigInteger(value.toString());
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(e);
}
}
}

View File

@@ -0,0 +1,71 @@
package org.apache.commons.beanutils.converters;
import java.util.List;
import org.apache.commons.beanutils.ConversionException;
public final class BooleanArrayConverter extends AbstractArrayConverter {
public BooleanArrayConverter() {
this.defaultValue = null;
this.useDefault = false;
}
public BooleanArrayConverter(Object defaultValue) {
this.defaultValue = defaultValue;
this.useDefault = true;
}
private static boolean[] model = new boolean[0];
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (model.getClass() == value.getClass())
return value;
if (AbstractArrayConverter.strings.getClass() == value.getClass())
try {
String[] values = (String[])value;
boolean[] results = new boolean[values.length];
for (int i = 0; i < values.length; i++) {
String stringValue = values[i];
if (stringValue.equalsIgnoreCase("yes") || stringValue.equalsIgnoreCase("y") || stringValue.equalsIgnoreCase("true") || stringValue.equalsIgnoreCase("on") || stringValue.equalsIgnoreCase("1")) {
results[i] = true;
} else if (stringValue.equalsIgnoreCase("no") || stringValue.equalsIgnoreCase("n") || stringValue.equalsIgnoreCase("false") || stringValue.equalsIgnoreCase("off") || stringValue.equalsIgnoreCase("0")) {
results[i] = false;
} else {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(value.toString());
}
}
return results;
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(value.toString(), e);
}
try {
List list = parseElements(value.toString());
boolean[] results = new boolean[list.size()];
for (int i = 0; i < results.length; i++) {
String stringValue = list.get(i);
if (stringValue.equalsIgnoreCase("yes") || stringValue.equalsIgnoreCase("y") || stringValue.equalsIgnoreCase("true") || stringValue.equalsIgnoreCase("on") || stringValue.equalsIgnoreCase("1")) {
results[i] = true;
} else if (stringValue.equalsIgnoreCase("no") || stringValue.equalsIgnoreCase("n") || stringValue.equalsIgnoreCase("false") || stringValue.equalsIgnoreCase("off") || stringValue.equalsIgnoreCase("0")) {
results[i] = false;
} else {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(value.toString());
}
}
return results;
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(value.toString(), e);
}
}
}

View File

@@ -0,0 +1,48 @@
package org.apache.commons.beanutils.converters;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
public final class BooleanConverter implements Converter {
private Object defaultValue;
private boolean useDefault;
public BooleanConverter() {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = null;
this.useDefault = false;
}
public BooleanConverter(Object defaultValue) {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = defaultValue;
this.useDefault = true;
}
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (value instanceof Boolean)
return value;
try {
String stringValue = value.toString();
if (stringValue.equalsIgnoreCase("yes") || stringValue.equalsIgnoreCase("y") || stringValue.equalsIgnoreCase("true") || stringValue.equalsIgnoreCase("on") || stringValue.equalsIgnoreCase("1"))
return Boolean.TRUE;
if (stringValue.equalsIgnoreCase("no") || stringValue.equalsIgnoreCase("n") || stringValue.equalsIgnoreCase("false") || stringValue.equalsIgnoreCase("off") || stringValue.equalsIgnoreCase("0"))
return Boolean.FALSE;
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(stringValue);
} catch (ClassCastException e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(e);
}
}
}

View File

@@ -0,0 +1,51 @@
package org.apache.commons.beanutils.converters;
import java.util.List;
import org.apache.commons.beanutils.ConversionException;
public final class ByteArrayConverter extends AbstractArrayConverter {
public ByteArrayConverter() {
this.defaultValue = null;
this.useDefault = false;
}
public ByteArrayConverter(Object defaultValue) {
this.defaultValue = defaultValue;
this.useDefault = true;
}
private static byte[] model = new byte[0];
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (model.getClass() == value.getClass())
return value;
if (AbstractArrayConverter.strings.getClass() == value.getClass())
try {
String[] values = (String[])value;
byte[] results = new byte[values.length];
for (int i = 0; i < values.length; i++)
results[i] = Byte.parseByte(values[i]);
return results;
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(value.toString(), e);
}
try {
List list = parseElements(value.toString());
byte[] results = new byte[list.size()];
for (int i = 0; i < results.length; i++)
results[i] = Byte.parseByte((String)list.get(i));
return results;
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(value.toString(), e);
}
}
}

View File

@@ -0,0 +1,43 @@
package org.apache.commons.beanutils.converters;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
public final class ByteConverter implements Converter {
private Object defaultValue;
private boolean useDefault;
public ByteConverter() {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = null;
this.useDefault = false;
}
public ByteConverter(Object defaultValue) {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = defaultValue;
this.useDefault = true;
}
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (value instanceof Byte)
return value;
if (value instanceof Number)
return new Byte(((Number)value).byteValue());
try {
return new Byte(value.toString());
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(e);
}
}
}

View File

@@ -0,0 +1,51 @@
package org.apache.commons.beanutils.converters;
import java.util.List;
import org.apache.commons.beanutils.ConversionException;
public final class CharacterArrayConverter extends AbstractArrayConverter {
public CharacterArrayConverter() {
this.defaultValue = null;
this.useDefault = false;
}
public CharacterArrayConverter(Object defaultValue) {
this.defaultValue = defaultValue;
this.useDefault = true;
}
private static char[] model = new char[0];
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (model.getClass() == value.getClass())
return value;
if (AbstractArrayConverter.strings.getClass() == value.getClass())
try {
String[] values = (String[])value;
char[] results = new char[values.length];
for (int i = 0; i < values.length; i++)
results[i] = values[i].charAt(0);
return results;
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(value.toString(), e);
}
try {
List list = parseElements(value.toString());
char[] results = new char[list.size()];
for (int i = 0; i < results.length; i++)
results[i] = ((String)list.get(i)).charAt(0);
return results;
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(value.toString(), e);
}
}
}

View File

@@ -0,0 +1,41 @@
package org.apache.commons.beanutils.converters;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
public final class CharacterConverter implements Converter {
private Object defaultValue;
private boolean useDefault;
public CharacterConverter() {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = null;
this.useDefault = false;
}
public CharacterConverter(Object defaultValue) {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = defaultValue;
this.useDefault = true;
}
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (value instanceof Character)
return value;
try {
return new Character(value.toString().charAt(0));
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(e);
}
}
}

View File

@@ -0,0 +1,44 @@
package org.apache.commons.beanutils.converters;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
public final class ClassConverter implements Converter {
private Object defaultValue;
private boolean useDefault;
public ClassConverter() {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = null;
this.useDefault = false;
}
public ClassConverter(Object defaultValue) {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = defaultValue;
this.useDefault = true;
}
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (value instanceof Class)
return value;
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null)
classLoader = ClassConverter.class.getClassLoader();
return classLoader.loadClass(value.toString());
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(e);
}
}
}

View File

@@ -0,0 +1,51 @@
package org.apache.commons.beanutils.converters;
import java.util.List;
import org.apache.commons.beanutils.ConversionException;
public final class DoubleArrayConverter extends AbstractArrayConverter {
public DoubleArrayConverter() {
this.defaultValue = null;
this.useDefault = false;
}
public DoubleArrayConverter(Object defaultValue) {
this.defaultValue = defaultValue;
this.useDefault = true;
}
private static double[] model = new double[0];
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (model.getClass() == value.getClass())
return value;
if (AbstractArrayConverter.strings.getClass() == value.getClass())
try {
String[] values = (String[])value;
double[] results = new double[values.length];
for (int i = 0; i < values.length; i++)
results[i] = Double.parseDouble(values[i]);
return results;
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(value.toString(), e);
}
try {
List list = parseElements(value.toString());
double[] results = new double[list.size()];
for (int i = 0; i < results.length; i++)
results[i] = Double.parseDouble((String)list.get(i));
return results;
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(value.toString(), e);
}
}
}

View File

@@ -0,0 +1,43 @@
package org.apache.commons.beanutils.converters;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
public final class DoubleConverter implements Converter {
private Object defaultValue;
private boolean useDefault;
public DoubleConverter() {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = null;
this.useDefault = false;
}
public DoubleConverter(Object defaultValue) {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = defaultValue;
this.useDefault = true;
}
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (value instanceof Double)
return value;
if (value instanceof Number)
return new Double(((Number)value).doubleValue());
try {
return new Double(value.toString());
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(e);
}
}
}

View File

@@ -0,0 +1,51 @@
package org.apache.commons.beanutils.converters;
import java.util.List;
import org.apache.commons.beanutils.ConversionException;
public final class FloatArrayConverter extends AbstractArrayConverter {
public FloatArrayConverter() {
this.defaultValue = null;
this.useDefault = false;
}
public FloatArrayConverter(Object defaultValue) {
this.defaultValue = defaultValue;
this.useDefault = true;
}
private static float[] model = new float[0];
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (model.getClass() == value.getClass())
return value;
if (AbstractArrayConverter.strings.getClass() == value.getClass())
try {
String[] values = (String[])value;
float[] results = new float[values.length];
for (int i = 0; i < values.length; i++)
results[i] = Float.parseFloat(values[i]);
return results;
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(value.toString(), e);
}
try {
List list = parseElements(value.toString());
float[] results = new float[list.size()];
for (int i = 0; i < results.length; i++)
results[i] = Float.parseFloat((String)list.get(i));
return results;
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(value.toString(), e);
}
}
}

View File

@@ -0,0 +1,43 @@
package org.apache.commons.beanutils.converters;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
public final class FloatConverter implements Converter {
private Object defaultValue;
private boolean useDefault;
public FloatConverter() {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = null;
this.useDefault = false;
}
public FloatConverter(Object defaultValue) {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = defaultValue;
this.useDefault = true;
}
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (value instanceof Float)
return value;
if (value instanceof Number)
return new Float(((Number)value).floatValue());
try {
return new Float(value.toString());
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(e);
}
}
}

View File

@@ -0,0 +1,51 @@
package org.apache.commons.beanutils.converters;
import java.util.List;
import org.apache.commons.beanutils.ConversionException;
public final class IntegerArrayConverter extends AbstractArrayConverter {
public IntegerArrayConverter() {
this.defaultValue = null;
this.useDefault = false;
}
public IntegerArrayConverter(Object defaultValue) {
this.defaultValue = defaultValue;
this.useDefault = true;
}
private static int[] model = new int[0];
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (model.getClass() == value.getClass())
return value;
if (AbstractArrayConverter.strings.getClass() == value.getClass())
try {
String[] values = (String[])value;
int[] results = new int[values.length];
for (int i = 0; i < values.length; i++)
results[i] = Integer.parseInt(values[i]);
return results;
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(value.toString(), e);
}
try {
List list = parseElements(value.toString());
int[] results = new int[list.size()];
for (int i = 0; i < results.length; i++)
results[i] = Integer.parseInt((String)list.get(i));
return results;
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(value.toString(), e);
}
}
}

View File

@@ -0,0 +1,43 @@
package org.apache.commons.beanutils.converters;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
public final class IntegerConverter implements Converter {
private Object defaultValue;
private boolean useDefault;
public IntegerConverter() {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = null;
this.useDefault = false;
}
public IntegerConverter(Object defaultValue) {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = defaultValue;
this.useDefault = true;
}
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (value instanceof Integer)
return value;
if (value instanceof Number)
return new Integer(((Number)value).intValue());
try {
return new Integer(value.toString());
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(e);
}
}
}

View File

@@ -0,0 +1,51 @@
package org.apache.commons.beanutils.converters;
import java.util.List;
import org.apache.commons.beanutils.ConversionException;
public final class LongArrayConverter extends AbstractArrayConverter {
public LongArrayConverter() {
this.defaultValue = null;
this.useDefault = false;
}
public LongArrayConverter(Object defaultValue) {
this.defaultValue = defaultValue;
this.useDefault = true;
}
private static long[] model = new long[0];
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (model.getClass() == value.getClass())
return value;
if (AbstractArrayConverter.strings.getClass() == value.getClass())
try {
String[] values = (String[])value;
long[] results = new long[values.length];
for (int i = 0; i < values.length; i++)
results[i] = Long.parseLong(values[i]);
return results;
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(value.toString(), e);
}
try {
List list = parseElements(value.toString());
long[] results = new long[list.size()];
for (int i = 0; i < results.length; i++)
results[i] = Long.parseLong((String)list.get(i));
return results;
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(value.toString(), e);
}
}
}

View File

@@ -0,0 +1,43 @@
package org.apache.commons.beanutils.converters;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
public final class LongConverter implements Converter {
private Object defaultValue;
private boolean useDefault;
public LongConverter() {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = null;
this.useDefault = false;
}
public LongConverter(Object defaultValue) {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = defaultValue;
this.useDefault = true;
}
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (value instanceof Long)
return value;
if (value instanceof Number)
return new Long(((Number)value).longValue());
try {
return new Long(value.toString());
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(e);
}
}
}

View File

@@ -0,0 +1,51 @@
package org.apache.commons.beanutils.converters;
import java.util.List;
import org.apache.commons.beanutils.ConversionException;
public final class ShortArrayConverter extends AbstractArrayConverter {
public ShortArrayConverter() {
this.defaultValue = null;
this.useDefault = false;
}
public ShortArrayConverter(Object defaultValue) {
this.defaultValue = defaultValue;
this.useDefault = true;
}
private static short[] model = new short[0];
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (model.getClass() == value.getClass())
return value;
if (AbstractArrayConverter.strings.getClass() == value.getClass())
try {
String[] values = (String[])value;
short[] results = new short[values.length];
for (int i = 0; i < values.length; i++)
results[i] = Short.parseShort(values[i]);
return results;
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(value.toString(), e);
}
try {
List list = parseElements(value.toString());
short[] results = new short[list.size()];
for (int i = 0; i < results.length; i++)
results[i] = Short.parseShort((String)list.get(i));
return results;
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(value.toString(), e);
}
}
}

View File

@@ -0,0 +1,43 @@
package org.apache.commons.beanutils.converters;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
public final class ShortConverter implements Converter {
private Object defaultValue;
private boolean useDefault;
public ShortConverter() {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = null;
this.useDefault = false;
}
public ShortConverter(Object defaultValue) {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = defaultValue;
this.useDefault = true;
}
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (value instanceof Short)
return value;
if (value instanceof Number)
return new Short(((Number)value).shortValue());
try {
return new Short(value.toString());
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(e);
}
}
}

View File

@@ -0,0 +1,42 @@
package org.apache.commons.beanutils.converters;
import java.sql.Date;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
public final class SqlDateConverter implements Converter {
private Object defaultValue;
private boolean useDefault;
public SqlDateConverter() {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = null;
this.useDefault = false;
}
public SqlDateConverter(Object defaultValue) {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = defaultValue;
this.useDefault = true;
}
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (value instanceof Date)
return value;
try {
return Date.valueOf(value.toString());
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(e);
}
}
}

View File

@@ -0,0 +1,42 @@
package org.apache.commons.beanutils.converters;
import java.sql.Time;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
public final class SqlTimeConverter implements Converter {
private Object defaultValue;
private boolean useDefault;
public SqlTimeConverter() {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = null;
this.useDefault = false;
}
public SqlTimeConverter(Object defaultValue) {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = defaultValue;
this.useDefault = true;
}
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (value instanceof Time)
return value;
try {
return Time.valueOf(value.toString());
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(e);
}
}
}

View File

@@ -0,0 +1,42 @@
package org.apache.commons.beanutils.converters;
import java.sql.Timestamp;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
public final class SqlTimestampConverter implements Converter {
private Object defaultValue;
private boolean useDefault;
public SqlTimestampConverter() {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = null;
this.useDefault = false;
}
public SqlTimestampConverter(Object defaultValue) {
this.defaultValue = null;
this.useDefault = true;
this.defaultValue = defaultValue;
this.useDefault = true;
}
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (value instanceof Timestamp)
return value;
try {
return Timestamp.valueOf(value.toString());
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(e);
}
}
}

View File

@@ -0,0 +1,39 @@
package org.apache.commons.beanutils.converters;
import java.util.List;
import org.apache.commons.beanutils.ConversionException;
public final class StringArrayConverter extends AbstractArrayConverter {
public StringArrayConverter() {
this.defaultValue = null;
this.useDefault = false;
}
public StringArrayConverter(Object defaultValue) {
this.defaultValue = defaultValue;
this.useDefault = true;
}
private static String[] model = new String[0];
public Object convert(Class type, Object value) {
if (value == null) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException("No value specified");
}
if (model.getClass() == value.getClass())
return value;
try {
List list = parseElements(value.toString());
String[] results = new String[list.size()];
for (int i = 0; i < results.length; i++)
results[i] = list.get(i);
return results;
} catch (Exception e) {
if (this.useDefault)
return this.defaultValue;
throw new ConversionException(value.toString(), e);
}
}
}

View File

@@ -0,0 +1,11 @@
package org.apache.commons.beanutils.converters;
import org.apache.commons.beanutils.Converter;
public final class StringConverter implements Converter {
public Object convert(Class type, Object value) {
if (value == null)
return null;
return value.toString();
}
}

View File

@@ -0,0 +1,69 @@
package org.apache.commons.collections;
import java.util.ArrayList;
import java.util.EmptyStackException;
public class ArrayStack extends ArrayList implements Buffer {
private static final long serialVersionUID = 2130079159931574599L;
public ArrayStack() {}
public ArrayStack(int paramInt) {
super(paramInt);
}
public boolean empty() {
return isEmpty();
}
public Object get() {
int i = size();
if (i == 0)
throw new BufferUnderflowException();
return get(i - 1);
}
public Object peek() throws EmptyStackException {
int i = size();
if (i <= 0)
throw new EmptyStackException();
return get(i - 1);
}
public Object peek(int paramInt) throws EmptyStackException {
int i = size() - paramInt - 1;
if (i < 0)
throw new EmptyStackException();
return get(i);
}
public Object pop() throws EmptyStackException {
int i = size();
if (i <= 0)
throw new EmptyStackException();
return remove(i - 1);
}
public Object push(Object paramObject) {
add((E)paramObject);
return paramObject;
}
public Object remove() {
int i = size();
if (i == 0)
throw new BufferUnderflowException();
return remove(i - 1);
}
public int search(Object paramObject) {
int i = size() - 1;
for (byte b = 1; i >= 0; b++) {
E e = get(i);
if ((paramObject == null && e == null) || (paramObject != null && paramObject.equals(e)))
return b;
i--;
}
return -1;
}
}

View File

@@ -0,0 +1,9 @@
package org.apache.commons.collections;
import java.util.Collection;
public interface Buffer extends Collection {
Object get();
Object remove();
}

View File

@@ -0,0 +1,19 @@
package org.apache.commons.collections;
public class BufferUnderflowException extends RuntimeException {
private final Throwable m_throwable = null;
public BufferUnderflowException() {}
public BufferUnderflowException(String paramString) {
this(paramString, null);
}
public BufferUnderflowException(String paramString, Throwable paramThrowable) {
super(paramString);
}
public final Throwable getCause() {
return this.m_throwable;
}
}

View File

@@ -0,0 +1,49 @@
package org.apache.commons.collections;
import java.util.Map;
public class DefaultMapEntry implements Map.Entry {
private Object key;
private Object value;
public DefaultMapEntry() {}
public DefaultMapEntry(Object paramObject1, Object paramObject2) {
this.key = paramObject1;
this.value = paramObject2;
}
public boolean equals(Object paramObject) {
if (paramObject == null)
return false;
if (paramObject == this)
return true;
if (!(paramObject instanceof Map.Entry))
return false;
Map.Entry entry = (Map.Entry)paramObject;
return !(!((getKey() == null) ? (entry.getKey() == null) : getKey().equals(entry.getKey())) || !((getValue() == null) ? (entry.getValue() == null) : getValue().equals(entry.getValue())));
}
public Object getKey() {
return this.key;
}
public Object getValue() {
return this.value;
}
public int hashCode() {
return ((getKey() == null) ? 0 : getKey().hashCode()) ^ ((getValue() == null) ? 0 : getValue().hashCode());
}
public void setKey(Object paramObject) {
this.key = paramObject;
}
public Object setValue(Object paramObject) {
Object object = this.value;
this.value = paramObject;
return object;
}
}

View File

@@ -0,0 +1,455 @@
package org.apache.commons.collections;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class FastHashMap extends HashMap {
protected HashMap map = null;
protected boolean fast = false;
public FastHashMap() {
this.map = new HashMap();
}
public FastHashMap(int paramInt) {
this.map = new HashMap(paramInt);
}
public FastHashMap(int paramInt, float paramFloat) {
this.map = new HashMap(paramInt, paramFloat);
}
public FastHashMap(Map paramMap) {
this.map = new HashMap(paramMap);
}
public void clear() {
if (this.fast) {
synchronized (this) {
HashMap hashMap = (HashMap)this.map.clone();
hashMap.clear();
this.map = hashMap;
}
} else {
synchronized (this.map) {
this.map.clear();
}
}
}
public Object clone() {
FastHashMap fastHashMap = null;
if (this.fast) {
fastHashMap = new FastHashMap(this.map);
} else {
synchronized (this.map) {
fastHashMap = new FastHashMap(this.map);
}
}
fastHashMap.setFast(getFast());
return fastHashMap;
}
public boolean containsKey(Object paramObject) {
if (this.fast)
return this.map.containsKey(paramObject);
synchronized (this.map) {
return this.map.containsKey(paramObject);
}
}
public boolean containsValue(Object paramObject) {
if (this.fast)
return this.map.containsValue(paramObject);
synchronized (this.map) {
return this.map.containsValue(paramObject);
}
}
public Set entrySet() {
return new EntrySet(this);
}
public boolean equals(Object paramObject) {
if (paramObject == this)
return true;
if (!(paramObject instanceof Map))
return false;
Map map = (Map)paramObject;
if (this.fast) {
if (map.size() != this.map.size())
return false;
for (Map.Entry entry : this.map.entrySet()) {
Object object1 = entry.getKey();
Object object2 = entry.getValue();
if (object2 == null) {
if (map.get(object1) != null || !map.containsKey(object1))
return false;
continue;
}
if (!object2.equals(map.get(object1)))
return false;
}
return true;
}
synchronized (this.map) {
if (map.size() != this.map.size())
return false;
for (Map.Entry entry : this.map.entrySet()) {
Object object1 = entry.getKey();
Object object2 = entry.getValue();
if (object2 == null) {
if (map.get(object1) != null || !map.containsKey(object1))
return false;
continue;
}
if (!object2.equals(map.get(object1)))
return false;
}
return true;
}
}
public Object get(Object paramObject) {
if (this.fast)
return this.map.get(paramObject);
synchronized (this.map) {
return this.map.get(paramObject);
}
}
public boolean getFast() {
return this.fast;
}
public int hashCode() {
if (this.fast) {
int i = 0;
Iterator iterator = this.map.entrySet().iterator();
while (iterator.hasNext())
i += iterator.next().hashCode();
return i;
}
synchronized (this.map) {
int i = 0;
Iterator iterator = this.map.entrySet().iterator();
while (iterator.hasNext())
i += iterator.next().hashCode();
return i;
}
}
public boolean isEmpty() {
if (this.fast)
return this.map.isEmpty();
synchronized (this.map) {
return this.map.isEmpty();
}
}
public Set keySet() {
return new KeySet(this);
}
public Object put(Object paramObject1, Object paramObject2) {
if (this.fast)
synchronized (this) {
HashMap hashMap = (HashMap)this.map.clone();
Object object = hashMap.put(paramObject1, paramObject2);
this.map = hashMap;
return object;
}
synchronized (this.map) {
return this.map.put(paramObject1, paramObject2);
}
}
public void putAll(Map paramMap) {
if (this.fast) {
synchronized (this) {
HashMap hashMap = (HashMap)this.map.clone();
hashMap.putAll(paramMap);
this.map = hashMap;
}
} else {
synchronized (this.map) {
this.map.putAll(paramMap);
}
}
}
public Object remove(Object paramObject) {
if (this.fast)
synchronized (this) {
HashMap hashMap = (HashMap)this.map.clone();
Object object = hashMap.remove(paramObject);
this.map = hashMap;
return object;
}
synchronized (this.map) {
return this.map.remove(paramObject);
}
}
public void setFast(boolean paramBoolean) {
this.fast = paramBoolean;
}
public int size() {
if (this.fast)
return this.map.size();
synchronized (this.map) {
return this.map.size();
}
}
public Collection values() {
return new Values(this);
}
private abstract class CollectionView implements Collection {
private final FastHashMap this$0;
public CollectionView(FastHashMap this$0) {
this.this$0 = this$0;
}
public boolean add(Object param1Object) {
throw new UnsupportedOperationException();
}
public boolean addAll(Collection param1Collection) {
throw new UnsupportedOperationException();
}
public void clear() {
if (this.this$0.fast) {
synchronized (this.this$0) {
HashMap hashMap = (HashMap)this.this$0.map.clone();
get(hashMap).clear();
this.this$0.map = hashMap;
}
} else {
synchronized (this.this$0.map) {
get(this.this$0.map).clear();
}
}
}
public boolean contains(Object param1Object) {
if (this.this$0.fast)
return get(this.this$0.map).contains(param1Object);
synchronized (this.this$0.map) {
return get(this.this$0.map).contains(param1Object);
}
}
public boolean containsAll(Collection param1Collection) {
if (this.this$0.fast)
return get(this.this$0.map).containsAll(param1Collection);
synchronized (this.this$0.map) {
return get(this.this$0.map).containsAll(param1Collection);
}
}
public boolean equals(Object param1Object) {
if (param1Object == this)
return true;
if (this.this$0.fast)
return get(this.this$0.map).equals(param1Object);
synchronized (this.this$0.map) {
return get(this.this$0.map).equals(param1Object);
}
}
protected abstract Collection get(Map param1Map);
public int hashCode() {
if (this.this$0.fast)
return get(this.this$0.map).hashCode();
synchronized (this.this$0.map) {
return get(this.this$0.map).hashCode();
}
}
public boolean isEmpty() {
if (this.this$0.fast)
return get(this.this$0.map).isEmpty();
synchronized (this.this$0.map) {
return get(this.this$0.map).isEmpty();
}
}
public Iterator iterator() {
return new CollectionViewIterator(this);
}
protected abstract Object iteratorNext(Map.Entry param1Entry);
public boolean remove(Object param1Object) {
if (this.this$0.fast)
synchronized (this.this$0) {
HashMap hashMap = (HashMap)this.this$0.map.clone();
boolean bool = get(hashMap).remove(param1Object);
this.this$0.map = hashMap;
return bool;
}
synchronized (this.this$0.map) {
return get(this.this$0.map).remove(param1Object);
}
}
public boolean removeAll(Collection param1Collection) {
if (this.this$0.fast)
synchronized (this.this$0) {
HashMap hashMap = (HashMap)this.this$0.map.clone();
boolean bool = get(hashMap).removeAll(param1Collection);
this.this$0.map = hashMap;
return bool;
}
synchronized (this.this$0.map) {
return get(this.this$0.map).removeAll(param1Collection);
}
}
public boolean retainAll(Collection param1Collection) {
if (this.this$0.fast)
synchronized (this.this$0) {
HashMap hashMap = (HashMap)this.this$0.map.clone();
boolean bool = get(hashMap).retainAll(param1Collection);
this.this$0.map = hashMap;
return bool;
}
synchronized (this.this$0.map) {
return get(this.this$0.map).retainAll(param1Collection);
}
}
public int size() {
if (this.this$0.fast)
return get(this.this$0.map).size();
synchronized (this.this$0.map) {
return get(this.this$0.map).size();
}
}
public Object[] toArray() {
if (this.this$0.fast)
return get(this.this$0.map).toArray();
synchronized (this.this$0.map) {
return get(this.this$0.map).toArray();
}
}
public Object[] toArray(Object[] param1ArrayOfObject) {
if (this.this$0.fast)
return get(this.this$0.map).toArray(param1ArrayOfObject);
synchronized (this.this$0.map) {
return get(this.this$0.map).toArray(param1ArrayOfObject);
}
}
private class CollectionViewIterator implements Iterator {
private final FastHashMap.CollectionView this$1;
private Map expected;
private Map.Entry lastReturned;
private Iterator iterator;
public CollectionViewIterator(FastHashMap.CollectionView this$0) {
this.this$1 = this$0;
this.lastReturned = null;
this.expected = this$0.this$0.map;
this.iterator = this.expected.entrySet().iterator();
}
public boolean hasNext() {
if (this.expected != this.this$1.this$0.map)
throw new ConcurrentModificationException();
return this.iterator.hasNext();
}
public Object next() {
if (this.expected != this.this$1.this$0.map)
throw new ConcurrentModificationException();
this.lastReturned = this.iterator.next();
return this.this$1.iteratorNext(this.lastReturned);
}
public void remove() {
if (this.lastReturned == null)
throw new IllegalStateException();
if (this.this$1.this$0.fast) {
synchronized (this.this$1.this$0) {
if (this.expected != this.this$1.this$0.map)
throw new ConcurrentModificationException();
this.this$1.this$0.remove(this.lastReturned.getKey());
this.lastReturned = null;
this.expected = this.this$1.this$0.map;
}
} else {
this.iterator.remove();
this.lastReturned = null;
}
}
}
}
private class KeySet extends CollectionView implements Set {
private final FastHashMap this$0;
KeySet(FastHashMap this$0) {
super(this$0);
this.this$0 = this$0;
}
protected Collection get(Map param1Map) {
return param1Map.keySet();
}
protected Object iteratorNext(Map.Entry param1Entry) {
return param1Entry.getKey();
}
}
private class Values extends CollectionView {
private final FastHashMap this$0;
Values(FastHashMap this$0) {
super(this$0);
this.this$0 = this$0;
}
protected Collection get(Map param1Map) {
return param1Map.values();
}
protected Object iteratorNext(Map.Entry param1Entry) {
return param1Entry.getValue();
}
}
private class EntrySet extends CollectionView implements Set {
private final FastHashMap this$0;
EntrySet(FastHashMap this$0) {
super(this$0);
this.this$0 = this$0;
}
protected Collection get(Map param1Map) {
return param1Map.entrySet();
}
protected Object iteratorNext(Map.Entry param1Entry) {
return param1Entry;
}
}
}

View File

@@ -0,0 +1,563 @@
package org.apache.commons.collections;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
public class ReferenceMap extends AbstractMap {
private static final long serialVersionUID = -3370601314380922368L;
public static final int HARD = 0;
public static final int SOFT = 1;
public static final int WEAK = 2;
private int keyType;
private int valueType;
private float loadFactor;
private transient ReferenceQueue queue = new ReferenceQueue();
private transient Entry[] table;
private transient int size;
private transient int threshold;
private volatile transient int modCount;
private transient Set keySet;
private transient Set entrySet;
private transient Collection values;
public ReferenceMap() {
this(0, 1);
}
public ReferenceMap(int paramInt1, int paramInt2) {
this(paramInt1, paramInt2, 16, 0.75F);
}
public ReferenceMap(int paramInt1, int paramInt2, int paramInt3, float paramFloat) {
verify("keyType", paramInt1);
verify("valueType", paramInt2);
if (paramInt3 <= 0)
throw new IllegalArgumentException("capacity must be positive");
if (paramFloat <= 0.0F || paramFloat >= 1.0F)
throw new IllegalArgumentException("Load factor must be greater than 0 and less than 1.");
this.keyType = paramInt1;
this.valueType = paramInt2;
int i;
for (i = 1; i < paramInt3; i *= 2);
this.table = new Entry[i];
this.loadFactor = paramFloat;
this.threshold = (int)(i * paramFloat);
}
public void clear() {
Arrays.fill((Object[])this.table, (Object)null);
this.size = 0;
do {
} while (this.queue.poll() != null);
}
public boolean containsKey(Object paramObject) {
purge();
Entry entry = getEntry(paramObject);
return (entry == null) ? false : (!(entry.getValue() == null));
}
public Set entrySet() {
if (this.entrySet != null)
return this.entrySet;
this.entrySet = new AbstractSet(this) {
private final ReferenceMap this$0;
public void clear() {
this.this$0.clear();
}
public boolean contains(Object param1Object) {
if (param1Object == null)
return false;
if (!(param1Object instanceof Map.Entry))
return false;
Map.Entry entry = (Map.Entry)param1Object;
ReferenceMap.Entry entry1 = this.this$0.getEntry(entry.getKey());
return !(entry1 == null || !entry.equals(entry1));
}
public Iterator iterator() {
return new ReferenceMap.EntryIterator(this.this$0);
}
public boolean remove(Object param1Object) {
boolean bool = contains(param1Object);
if (bool) {
Map.Entry entry = (Map.Entry)param1Object;
this.this$0.remove(entry.getKey());
}
return bool;
}
public int size() {
return this.this$0.size();
}
public Object[] toArray() {
return toArray(new Object[0]);
}
public Object[] toArray(Object[] param1ArrayOfObject) {
ArrayList arrayList = new ArrayList();
for (ReferenceMap.Entry entry : this)
arrayList.add(new DefaultMapEntry(entry.getKey(), entry.getValue()));
return arrayList.toArray(param1ArrayOfObject);
}
};
return this.entrySet;
}
public Object get(Object paramObject) {
purge();
Entry entry = getEntry(paramObject);
return (entry == null) ? null : entry.getValue();
}
private Entry getEntry(Object paramObject) {
if (paramObject == null)
return null;
int i = paramObject.hashCode();
int j = indexFor(i);
for (Entry entry = this.table[j]; entry != null; entry = entry.next) {
if (entry.hash == i && paramObject.equals(entry.getKey()))
return entry;
}
return null;
}
private int indexFor(int paramInt) {
paramInt += paramInt << 15 ^ 0xFFFFFFFF;
paramInt ^= paramInt >>> 10;
paramInt += paramInt << 3;
paramInt ^= paramInt >>> 6;
paramInt += paramInt << 11 ^ 0xFFFFFFFF;
paramInt ^= paramInt >>> 16;
return paramInt & this.table.length - 1;
}
public boolean isEmpty() {
purge();
return !(this.size != 0);
}
public Set keySet() {
if (this.keySet != null)
return this.keySet;
this.keySet = new AbstractSet(this) {
private final ReferenceMap this$0;
public void clear() {
this.this$0.clear();
}
public boolean contains(Object param1Object) {
return this.this$0.containsKey(param1Object);
}
public Iterator iterator() {
return new ReferenceMap.KeyIterator(this.this$0);
}
public boolean remove(Object param1Object) {
Object object = this.this$0.remove(param1Object);
return !(object == null);
}
public int size() {
return this.this$0.size;
}
};
return this.keySet;
}
private void purge() {
for (Reference reference = this.queue.poll(); reference != null; reference = this.queue.poll())
purge(reference);
}
private void purge(Reference paramReference) {
int i = paramReference.hashCode();
int j = indexFor(i);
Entry entry1 = null;
for (Entry entry2 = this.table[j]; entry2 != null; entry2 = entry2.next) {
if (entry2.purge(paramReference)) {
if (entry1 == null) {
this.table[j] = entry2.next;
} else {
entry1.next = entry2.next;
}
this.size--;
return;
}
entry1 = entry2;
}
}
public Object put(Object paramObject1, Object paramObject2) {
if (paramObject1 == null)
throw new NullPointerException("null keys not allowed");
if (paramObject2 == null)
throw new NullPointerException("null values not allowed");
purge();
if (this.size + 1 > this.threshold)
resize();
int i = paramObject1.hashCode();
int j = indexFor(i);
for (Entry entry = this.table[j]; entry != null; entry = entry.next) {
if (i == entry.hash && paramObject1.equals(entry.getKey())) {
Object object = entry.getValue();
entry.setValue(paramObject2);
return object;
}
}
this.size++;
this.modCount++;
paramObject1 = toReference(this.keyType, paramObject1, i);
paramObject2 = toReference(this.valueType, paramObject2, i);
this.table[j] = new Entry(this, paramObject1, i, paramObject2, this.table[j]);
return null;
}
private void readObject(ObjectInputStream paramObjectInputStream) throws IOException, ClassNotFoundException {
paramObjectInputStream.defaultReadObject();
this.table = new Entry[paramObjectInputStream.readInt()];
this.threshold = (int)(this.table.length * this.loadFactor);
this.queue = new ReferenceQueue();
for (Object object = paramObjectInputStream.readObject(); object != null; object = paramObjectInputStream.readObject()) {
Object object1 = paramObjectInputStream.readObject();
put(object, object1);
}
}
public Object remove(Object paramObject) {
if (paramObject == null)
return null;
purge();
int i = paramObject.hashCode();
int j = indexFor(i);
Entry entry1 = null;
for (Entry entry2 = this.table[j]; entry2 != null; entry2 = entry2.next) {
if (i == entry2.hash && paramObject.equals(entry2.getKey())) {
if (entry1 == null) {
this.table[j] = entry2.next;
} else {
entry1.next = entry2.next;
}
this.size--;
this.modCount++;
return entry2.getValue();
}
entry1 = entry2;
}
return null;
}
private void resize() {
Entry[] arrayOfEntry = this.table;
this.table = new Entry[arrayOfEntry.length * 2];
for (byte b = 0; b < arrayOfEntry.length; b++) {
Entry entry = arrayOfEntry[b];
while (entry != null) {
Entry entry1 = entry;
entry = entry.next;
int i = indexFor(entry1.hash);
entry1.next = this.table[i];
this.table[i] = entry1;
}
arrayOfEntry[b] = null;
}
this.threshold = (int)(this.table.length * this.loadFactor);
}
public int size() {
purge();
return this.size;
}
private Object toReference(int paramInt1, Object paramObject, int paramInt2) {
switch (paramInt1) {
case 0:
return paramObject;
case 1:
return new SoftRef(paramInt2, paramObject, this.queue);
case 2:
return new WeakRef(paramInt2, paramObject, this.queue);
}
throw new Error();
}
public Collection values() {
if (this.values != null)
return this.values;
this.values = new AbstractCollection(this) {
private final ReferenceMap this$0;
public void clear() {
this.this$0.clear();
}
public Iterator iterator() {
return new ReferenceMap.ValueIterator(this.this$0);
}
public int size() {
return this.this$0.size;
}
};
return this.values;
}
private static void verify(String paramString, int paramInt) {
if (paramInt < 0 || paramInt > 2)
throw new IllegalArgumentException(String.valueOf(paramString) + " must be HARD, SOFT, WEAK.");
}
private void writeObject(ObjectOutputStream paramObjectOutputStream) throws IOException {
paramObjectOutputStream.defaultWriteObject();
paramObjectOutputStream.writeInt(this.table.length);
for (Map.Entry entry : entrySet()) {
paramObjectOutputStream.writeObject(entry.getKey());
paramObjectOutputStream.writeObject(entry.getValue());
}
paramObjectOutputStream.writeObject(null);
}
private class Entry implements Map.Entry {
private final ReferenceMap this$0;
Object key;
Object value;
int hash;
Entry next;
public Entry(ReferenceMap this$0, Object param1Object1, int param1Int, Object param1Object2, Entry param1Entry) {
this.this$0 = this$0;
this.key = param1Object1;
this.hash = param1Int;
this.value = param1Object2;
this.next = param1Entry;
}
public boolean equals(Object param1Object) {
if (param1Object == null)
return false;
if (param1Object == this)
return true;
if (!(param1Object instanceof Map.Entry))
return false;
Map.Entry entry = (Map.Entry)param1Object;
Object object1 = entry.getKey();
Object object2 = entry.getValue();
return (object1 == null || object2 == null) ? false : (!(!object1.equals(getKey()) || !object2.equals(getValue())));
}
public Object getKey() {
return (this.this$0.keyType > 0) ? ((Reference)this.key).get() : this.key;
}
public Object getValue() {
return (this.this$0.valueType > 0) ? ((Reference)this.value).get() : this.value;
}
public int hashCode() {
Object object = getValue();
return this.hash ^ ((object == null) ? 0 : object.hashCode());
}
boolean purge(Reference param1Reference) {
boolean bool = (this.this$0.keyType <= 0 || this.key != param1Reference) ? false : true;
bool = (!bool && (this.this$0.valueType <= 0 || this.value != param1Reference)) ? false : true;
if (bool) {
if (this.this$0.keyType > 0)
((Reference)this.key).clear();
if (this.this$0.valueType > 0)
((Reference)this.value).clear();
}
return bool;
}
public Object setValue(Object param1Object) {
Object object = getValue();
if (this.this$0.valueType > 0)
((Reference)this.value).clear();
this.value = this.this$0.toReference(this.this$0.valueType, param1Object, this.hash);
return object;
}
public String toString() {
return String.valueOf(String.valueOf(getKey())) + "=" + getValue();
}
}
private class EntryIterator implements Iterator {
private final ReferenceMap this$0;
int index;
ReferenceMap.Entry entry;
ReferenceMap.Entry previous;
Object nextKey;
Object nextValue;
Object currentKey;
Object currentValue;
int expectedModCount;
public EntryIterator(ReferenceMap this$0) {
this.this$0 = this$0;
this.index = (this$0.size() != 0) ? this$0.table.length : 0;
this.expectedModCount = this$0.modCount;
}
private void checkMod() {
if (this.this$0.modCount != this.expectedModCount)
throw new ConcurrentModificationException();
}
public boolean hasNext() {
checkMod();
while (nextNull()) {
ReferenceMap.Entry entry = this.entry;
int i = this.index;
while (entry == null && i > 0)
entry = this.this$0.table[--i];
this.entry = entry;
this.index = i;
if (entry == null) {
this.currentKey = null;
this.currentValue = null;
return false;
}
this.nextKey = entry.getKey();
this.nextValue = entry.getValue();
if (nextNull())
this.entry = this.entry.next;
}
return true;
}
public Object next() {
return nextEntry();
}
protected ReferenceMap.Entry nextEntry() {
checkMod();
if (nextNull() && !hasNext())
throw new NoSuchElementException();
this.previous = this.entry;
this.entry = this.entry.next;
this.currentKey = this.nextKey;
this.currentValue = this.nextValue;
this.nextKey = null;
this.nextValue = null;
return this.previous;
}
private boolean nextNull() {
return !(this.nextKey != null && this.nextValue != null);
}
public void remove() {
checkMod();
if (this.previous == null)
throw new IllegalStateException();
this.this$0.remove(this.currentKey);
this.previous = null;
this.currentKey = null;
this.currentValue = null;
this.expectedModCount = this.this$0.modCount;
}
}
private class ValueIterator extends EntryIterator {
private final ReferenceMap this$0;
ValueIterator(ReferenceMap this$0) {
super(this$0);
this.this$0 = this$0;
}
public Object next() {
return nextEntry().getValue();
}
}
private class KeyIterator extends EntryIterator {
private final ReferenceMap this$0;
KeyIterator(ReferenceMap this$0) {
super(this$0);
this.this$0 = this$0;
}
public Object next() {
return nextEntry().getKey();
}
}
private static class SoftRef extends SoftReference {
private int hash;
public SoftRef(int param1Int, Object param1Object, ReferenceQueue param1ReferenceQueue) {
super((T)param1Object, param1ReferenceQueue);
this.hash = param1Int;
}
public int hashCode() {
return this.hash;
}
}
private static class WeakRef extends WeakReference {
private int hash;
public WeakRef(int param1Int, Object param1Object, ReferenceQueue param1ReferenceQueue) {
super((T)param1Object, param1ReferenceQueue);
this.hash = param1Int;
}
public int hashCode() {
return this.hash;
}
}
}

View File

@@ -0,0 +1,476 @@
package org.apache.commons.collections;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.AbstractCollection;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
public class SequencedHashMap implements Map, Cloneable, Externalizable {
private Entry sentinel = createSentinel();
private HashMap entries = new HashMap();
private transient long modCount = 0L;
private static final int KEY = 0;
private static final int VALUE = 1;
private static final int ENTRY = 2;
private static final int REMOVED_MASK = -2147483648;
private static final long serialVersionUID = 3380552487888102930L;
public SequencedHashMap() {}
public SequencedHashMap(int paramInt) {}
public SequencedHashMap(int paramInt, float paramFloat) {}
public SequencedHashMap(Map paramMap) {
this();
putAll(paramMap);
}
public void clear() {
this.modCount++;
this.entries.clear();
this.sentinel.next = this.sentinel;
this.sentinel.prev = this.sentinel;
}
public Object clone() throws CloneNotSupportedException {
SequencedHashMap sequencedHashMap = (SequencedHashMap)super.clone();
sequencedHashMap.sentinel = createSentinel();
sequencedHashMap.entries = new HashMap();
sequencedHashMap.putAll(this);
return sequencedHashMap;
}
public boolean containsKey(Object paramObject) {
return this.entries.containsKey(paramObject);
}
public boolean containsValue(Object paramObject) {
if (paramObject == null) {
for (Entry entry = this.sentinel.next; entry != this.sentinel; entry = entry.next) {
if (entry.getValue() == null)
return true;
}
} else {
for (Entry entry = this.sentinel.next; entry != this.sentinel; entry = entry.next) {
if (paramObject.equals(entry.getValue()))
return true;
}
}
return false;
}
private static final Entry createSentinel() {
Entry entry = new Entry(null, null);
entry.prev = entry;
entry.next = entry;
return entry;
}
public Set entrySet() {
return new AbstractSet(this) {
private final SequencedHashMap this$0;
public void clear() {
this.this$0.clear();
}
public boolean contains(Object param1Object) {
return !(findEntry(param1Object) == null);
}
private SequencedHashMap.Entry findEntry(Object param1Object) {
if (param1Object == null)
return null;
if (!(param1Object instanceof Map.Entry))
return null;
Map.Entry entry = (Map.Entry)param1Object;
SequencedHashMap.Entry entry1 = (SequencedHashMap.Entry)this.this$0.entries.get(entry.getKey());
return (entry1 != null && entry1.equals(entry)) ? entry1 : null;
}
public boolean isEmpty() {
return this.this$0.isEmpty();
}
public Iterator iterator() {
return new SequencedHashMap.OrderedIterator(this.this$0, 2);
}
public boolean remove(Object param1Object) {
SequencedHashMap.Entry entry = findEntry(param1Object);
return (entry == null) ? false : (!(this.this$0.removeImpl(entry.getKey()) == null));
}
public int size() {
return this.this$0.size();
}
};
}
public boolean equals(Object paramObject) {
return (paramObject == null) ? false : ((paramObject == this) ? true : (!(paramObject instanceof Map) ? false : entrySet().equals(((Map)paramObject).entrySet())));
}
public Object get(int paramInt) {
return getEntry(paramInt).getKey();
}
public Object get(Object paramObject) {
Entry entry = (Entry)this.entries.get(paramObject);
return (entry == null) ? null : entry.getValue();
}
private Map.Entry getEntry(int paramInt) {
Entry entry = this.sentinel;
if (paramInt < 0)
throw new ArrayIndexOutOfBoundsException(String.valueOf(paramInt) + " < 0");
byte b = -1;
while (b < paramInt - 1 && entry.next != this.sentinel) {
b++;
entry = entry.next;
}
if (entry.next == this.sentinel)
throw new ArrayIndexOutOfBoundsException(String.valueOf(paramInt) + " >= " + (b + 1));
return entry.next;
}
public Map.Entry getFirst() {
return isEmpty() ? null : this.sentinel.next;
}
public Object getFirstKey() {
return this.sentinel.next.getKey();
}
public Object getFirstValue() {
return this.sentinel.next.getValue();
}
public Map.Entry getLast() {
return isEmpty() ? null : this.sentinel.prev;
}
public Object getLastKey() {
return this.sentinel.prev.getKey();
}
public Object getLastValue() {
return this.sentinel.prev.getValue();
}
public Object getValue(int paramInt) {
return getEntry(paramInt).getValue();
}
public int hashCode() {
return entrySet().hashCode();
}
public int indexOf(Object paramObject) {
Entry entry = (Entry)this.entries.get(paramObject);
byte b = 0;
while (entry.prev != this.sentinel) {
b++;
entry = entry.prev;
}
return b;
}
private void insertEntry(Entry paramEntry) {
paramEntry.next = this.sentinel;
paramEntry.prev = this.sentinel.prev;
this.sentinel.prev.next = paramEntry;
this.sentinel.prev = paramEntry;
}
public boolean isEmpty() {
return !(this.sentinel.next != this.sentinel);
}
public Iterator iterator() {
return keySet().iterator();
}
public Set keySet() {
return new AbstractSet(this) {
private final SequencedHashMap this$0;
public void clear() {
this.this$0.clear();
}
public boolean contains(Object param1Object) {
return this.this$0.containsKey(param1Object);
}
public boolean isEmpty() {
return this.this$0.isEmpty();
}
public Iterator iterator() {
return new SequencedHashMap.OrderedIterator(this.this$0, 0);
}
public boolean remove(Object param1Object) {
SequencedHashMap.Entry entry = this.this$0.removeImpl(param1Object);
return !(entry == null);
}
public int size() {
return this.this$0.size();
}
};
}
public int lastIndexOf(Object paramObject) {
return indexOf(paramObject);
}
public Object put(Object paramObject1, Object paramObject2) {
this.modCount++;
Object object = null;
Entry entry = (Entry)this.entries.get(paramObject1);
if (entry != null) {
removeEntry(entry);
object = entry.setValue(paramObject2);
} else {
entry = new Entry(paramObject1, paramObject2);
this.entries.put(paramObject1, entry);
}
insertEntry(entry);
return object;
}
public void putAll(Map paramMap) {
for (Map.Entry entry : paramMap.entrySet())
put(entry.getKey(), entry.getValue());
}
public void readExternal(ObjectInput paramObjectInput) throws IOException, ClassNotFoundException {
int i = paramObjectInput.readInt();
for (byte b = 0; b < i; b++) {
Object object1 = paramObjectInput.readObject();
Object object2 = paramObjectInput.readObject();
put(object1, object2);
}
}
public Object remove(int paramInt) {
return remove(get(paramInt));
}
public Object remove(Object paramObject) {
Entry entry = removeImpl(paramObject);
return (entry == null) ? null : entry.getValue();
}
private void removeEntry(Entry paramEntry) {
paramEntry.next.prev = paramEntry.prev;
paramEntry.prev.next = paramEntry.next;
}
private Entry removeImpl(Object paramObject) {
Entry entry = (Entry)this.entries.remove(paramObject);
if (entry == null)
return null;
this.modCount++;
removeEntry(entry);
return entry;
}
public List sequence() {
ArrayList arrayList = new ArrayList(size());
Iterator iterator = keySet().iterator();
while (iterator.hasNext())
arrayList.add(iterator.next());
return Collections.unmodifiableList(arrayList);
}
public int size() {
return this.entries.size();
}
public String toString() {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append('[');
for (Entry entry = this.sentinel.next; entry != this.sentinel; entry = entry.next) {
stringBuffer.append(entry.getKey());
stringBuffer.append('=');
stringBuffer.append(entry.getValue());
if (entry.next != this.sentinel)
stringBuffer.append(',');
}
stringBuffer.append(']');
return stringBuffer.toString();
}
public Collection values() {
return new AbstractCollection(this) {
private final SequencedHashMap this$0;
public void clear() {
this.this$0.clear();
}
public boolean contains(Object param1Object) {
return this.this$0.containsValue(param1Object);
}
public boolean isEmpty() {
return this.this$0.isEmpty();
}
public Iterator iterator() {
return new SequencedHashMap.OrderedIterator(this.this$0, 1);
}
public boolean remove(Object param1Object) {
if (param1Object == null) {
for (SequencedHashMap.Entry entry = this.this$0.sentinel.next; entry != this.this$0.sentinel; entry = entry.next) {
if (entry.getValue() == null) {
this.this$0.removeImpl(entry.getKey());
return true;
}
}
} else {
for (SequencedHashMap.Entry entry = this.this$0.sentinel.next; entry != this.this$0.sentinel; entry = entry.next) {
if (param1Object.equals(entry.getValue())) {
this.this$0.removeImpl(entry.getKey());
return true;
}
}
}
return false;
}
public int size() {
return this.this$0.size();
}
};
}
public void writeExternal(ObjectOutput paramObjectOutput) throws IOException {
paramObjectOutput.writeInt(size());
for (Entry entry = this.sentinel.next; entry != this.sentinel; entry = entry.next) {
paramObjectOutput.writeObject(entry.getKey());
paramObjectOutput.writeObject(entry.getValue());
}
}
private static class Entry implements Map.Entry {
private final Object key;
private Object value;
Entry next = null;
Entry prev = null;
public Entry(Object param1Object1, Object param1Object2) {
this.key = param1Object1;
this.value = param1Object2;
}
public boolean equals(Object param1Object) {
if (param1Object == null)
return false;
if (param1Object == this)
return true;
if (!(param1Object instanceof Map.Entry))
return false;
Map.Entry entry = (Map.Entry)param1Object;
return !(!((getKey() == null) ? (entry.getKey() == null) : getKey().equals(entry.getKey())) || !((getValue() == null) ? (entry.getValue() == null) : getValue().equals(entry.getValue())));
}
public Object getKey() {
return this.key;
}
public Object getValue() {
return this.value;
}
public int hashCode() {
return ((getKey() == null) ? 0 : getKey().hashCode()) ^ ((getValue() == null) ? 0 : getValue().hashCode());
}
public Object setValue(Object param1Object) {
Object object = this.value;
this.value = param1Object;
return object;
}
public String toString() {
return "[" + getKey() + "=" + getValue() + "]";
}
}
private class OrderedIterator implements Iterator {
private final SequencedHashMap this$0;
private int returnType;
private SequencedHashMap.Entry pos;
private transient long expectedModCount;
public OrderedIterator(SequencedHashMap this$0, int param1Int) {
this.this$0 = this$0;
this.pos = this.this$0.sentinel;
this.expectedModCount = this.this$0.modCount;
this.returnType = param1Int | Integer.MIN_VALUE;
}
public boolean hasNext() {
return !(this.pos.next == this.this$0.sentinel);
}
public Object next() {
if (this.this$0.modCount != this.expectedModCount)
throw new ConcurrentModificationException();
if (this.pos.next == this.this$0.sentinel)
throw new NoSuchElementException();
this.returnType &= Integer.MAX_VALUE;
this.pos = this.pos.next;
switch (this.returnType) {
case 0:
return this.pos.getKey();
case 1:
return this.pos.getValue();
case 2:
return this.pos;
}
throw new Error("bad iterator type: " + this.returnType);
}
public void remove() {
if ((this.returnType & Integer.MIN_VALUE) != 0)
throw new IllegalStateException("remove() must follow next()");
if (this.this$0.modCount != this.expectedModCount)
throw new ConcurrentModificationException();
this.this$0.removeImpl(this.pos.getKey());
this.expectedModCount++;
this.returnType |= Integer.MIN_VALUE;
}
}
}

View File

@@ -0,0 +1,36 @@
package org.apache.commons.collections.comparators;
import java.io.Serializable;
import java.util.Comparator;
public class ComparableComparator implements Comparator, Serializable {
private static final ComparableComparator instance = new ComparableComparator();
private static final long serialVersionUID = -291439688585137865L;
public int compare(Object paramObject1, Object paramObject2) {
if (paramObject1 == null || paramObject2 == null)
throw new ClassCastException("There were nulls in the arguments for this method: compare(" + paramObject1 + ", " + paramObject2 + ")");
if (paramObject1 instanceof Comparable) {
if (paramObject2 instanceof Comparable) {
int i = ((Comparable)paramObject1).compareTo(paramObject2);
int j = ((Comparable)paramObject2).compareTo(paramObject1);
if (i == 0 && j == 0)
return 0;
if (i < 0 && j > 0)
return i;
if (i > 0 && j < 0)
return i;
throw new ClassCastException("o1 not comparable to o2");
}
throw new ClassCastException("The first argument of this method was not a Comparable: " + paramObject2.getClass().getName());
}
if (paramObject2 instanceof Comparable)
throw new ClassCastException("The second argument of this method was not a Comparable: " + paramObject1.getClass().getName());
throw new ClassCastException("Both arguments of this method were not Comparables: " + paramObject1.getClass().getName() + " and " + paramObject2.getClass().getName());
}
public static ComparableComparator getInstance() {
return instance;
}
}

View File

@@ -0,0 +1,24 @@
package org.apache.commons.collections.comparators;
import java.io.Serializable;
import java.util.Comparator;
public class ReverseComparator implements Comparator, Serializable {
private Comparator comparator;
public ReverseComparator() {
this(null);
}
public ReverseComparator(Comparator paramComparator) {
if (paramComparator != null) {
this.comparator = paramComparator;
} else {
this.comparator = ComparableComparator.getInstance();
}
}
public int compare(Object paramObject1, Object paramObject2) {
return this.comparator.compare(paramObject2, paramObject1);
}
}

View File

@@ -0,0 +1,17 @@
package org.apache.commons.digester;
import org.xml.sax.Attributes;
public abstract class AbstractObjectCreationFactory implements ObjectCreationFactory {
protected Digester digester = null;
public abstract Object createObject(Attributes paramAttributes) throws Exception;
public Digester getDigester() {
return this.digester;
}
public void setDigester(Digester digester) {
this.digester = digester;
}
}

View File

@@ -0,0 +1,68 @@
package org.apache.commons.digester;
import java.beans.PropertyDescriptor;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.commons.beanutils.PropertyUtils;
public class BeanPropertySetterRule extends Rule {
protected String propertyName;
protected String bodyText;
public BeanPropertySetterRule(Digester digester, String propertyName) {
this(propertyName);
}
public BeanPropertySetterRule(Digester digester) {
this();
}
public BeanPropertySetterRule(String propertyName) {
this.propertyName = null;
this.bodyText = null;
this.propertyName = propertyName;
}
public BeanPropertySetterRule() {
this((String)null);
}
public void body(String namespace, String name, String text) throws Exception {
if (this.digester.log.isDebugEnabled())
this.digester.log.debug("[BeanPropertySetterRule]{" + this.digester.match + "} Called with text '" + text + "'");
this.bodyText = text.trim();
}
public void end(String namespace, String name) throws Exception {
String property = this.propertyName;
if (property == null)
property = name;
Object top = this.digester.peek();
if (this.digester.log.isDebugEnabled())
this.digester.log.debug("[BeanPropertySetterRule]{" + this.digester.match + "} Set " + top.getClass().getName() + " property " + property + " with text " + this.bodyText);
if (top instanceof DynaBean) {
DynaProperty desc = ((DynaBean)top).getDynaClass().getDynaProperty(property);
if (desc == null)
throw new NoSuchMethodException("Bean has no property named " + property);
} else {
PropertyDescriptor desc = PropertyUtils.getPropertyDescriptor(top, property);
if (desc == null)
throw new NoSuchMethodException("Bean has no property named " + property);
}
BeanUtils.setProperty(top, property, this.bodyText);
}
public void finish() throws Exception {
this.bodyText = null;
}
public String toString() {
StringBuffer sb = new StringBuffer("BeanPropertySetterRule[");
sb.append("propertyName=");
sb.append(this.propertyName);
sb.append("]");
return sb.toString();
}
}

View File

@@ -0,0 +1,217 @@
package org.apache.commons.digester;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.MethodUtils;
import org.xml.sax.Attributes;
public class CallMethodRule extends Rule {
protected String bodyText;
protected String methodName;
protected int paramCount;
protected Class[] paramTypes;
private String[] paramClassNames;
protected boolean useExactMatch;
public CallMethodRule(Digester digester, String methodName, int paramCount) {
this(methodName, paramCount);
}
public CallMethodRule(Digester digester, String methodName, int paramCount, String[] paramTypes) {
this(methodName, paramCount, paramTypes);
}
public CallMethodRule(Digester digester, String methodName, int paramCount, Class[] paramTypes) {
this(methodName, paramCount, paramTypes);
}
public CallMethodRule(String methodName, int paramCount) {
this.bodyText = null;
this.methodName = null;
this.paramCount = 0;
this.paramTypes = null;
this.paramClassNames = null;
this.useExactMatch = false;
this.methodName = methodName;
this.paramCount = paramCount;
if (paramCount == 0) {
this.paramTypes = new Class[] { String.class };
} else {
this.paramTypes = new Class[paramCount];
for (int i = 0; i < this.paramTypes.length; i++)
this.paramTypes[i] = String.class;
}
}
public CallMethodRule(String methodName) {
this(methodName, 0, (Class[])null);
}
public CallMethodRule(String methodName, int paramCount, String[] paramTypes) {
this.bodyText = null;
this.methodName = null;
this.paramCount = 0;
this.paramTypes = null;
this.paramClassNames = null;
this.useExactMatch = false;
this.methodName = methodName;
this.paramCount = paramCount;
if (paramTypes == null) {
this.paramTypes = new Class[paramCount];
for (int i = 0; i < this.paramTypes.length; i++)
this.paramTypes[i] = "abc".getClass();
} else {
this.paramClassNames = new String[paramTypes.length];
for (int i = 0; i < this.paramClassNames.length; i++)
this.paramClassNames[i] = paramTypes[i];
}
}
public CallMethodRule(String methodName, int paramCount, Class[] paramTypes) {
this.bodyText = null;
this.methodName = null;
this.paramCount = 0;
this.paramTypes = null;
this.paramClassNames = null;
this.useExactMatch = false;
this.methodName = methodName;
this.paramCount = paramCount;
if (paramTypes == null) {
this.paramTypes = new Class[paramCount];
for (int i = 0; i < this.paramTypes.length; i++)
this.paramTypes[i] = "abc".getClass();
} else {
this.paramTypes = new Class[paramTypes.length];
for (int i = 0; i < this.paramTypes.length; i++)
this.paramTypes[i] = paramTypes[i];
}
}
public boolean getUseExactMatch() {
return this.useExactMatch;
}
public void setUseExactMatch(boolean useExactMatch) {
this.useExactMatch = useExactMatch;
}
public void setDigester(Digester digester) {
super.setDigester(digester);
if (this.paramClassNames != null) {
this.paramTypes = new Class[this.paramClassNames.length];
for (int i = 0; i < this.paramClassNames.length; i++) {
try {
this.paramTypes[i] = digester.getClassLoader().loadClass(this.paramClassNames[i]);
} catch (ClassNotFoundException e) {
digester.getLogger().error("(CallMethodRule) Cannot load class " + this.paramClassNames[i], e);
this.paramTypes[i] = null;
}
}
}
}
public void begin(Attributes attributes) throws Exception {
if (this.paramCount > 0) {
Object[] parameters = new Object[this.paramCount];
for (int i = 0; i < parameters.length; i++)
parameters[i] = null;
this.digester.pushParams(parameters);
}
}
public void body(String bodyText) throws Exception {
if (this.paramCount == 0)
this.bodyText = bodyText.trim();
}
public void end() throws Exception {
Object[] parameters = null;
if (this.paramCount > 0) {
parameters = (Object[])this.digester.popParams();
if (this.digester.log.isTraceEnabled())
for (int j = 0, size = parameters.length; j < size; j++)
this.digester.log.trace("[CallMethodRule](" + j + ")" + parameters[j]);
if (this.paramCount == 1 && parameters[0] == null)
return;
} else if (this.paramTypes != null && this.paramTypes.length != 0) {
if (this.bodyText == null)
return;
parameters = new Object[1];
parameters[0] = this.bodyText;
if (this.paramTypes.length == 0) {
this.paramTypes = new Class[1];
this.paramTypes[0] = "abc".getClass();
}
}
Object[] paramValues = new Object[this.paramTypes.length];
for (int i = 0; i < this.paramTypes.length; i++) {
if (parameters[i] == null || (parameters[i] instanceof String && !String.class.isAssignableFrom(this.paramTypes[i]))) {
paramValues[i] = ConvertUtils.convert((String)parameters[i], this.paramTypes[i]);
} else {
paramValues[i] = parameters[i];
}
}
Object top = this.digester.peek();
if (this.digester.log.isDebugEnabled()) {
StringBuffer sb = new StringBuffer("[CallMethodRule]{");
sb.append(this.digester.match);
sb.append("} Call ");
if (top == null) {
sb.append("[NULL TOP]");
} else {
sb.append(top.getClass().getName());
}
sb.append(".");
sb.append(this.methodName);
sb.append("(");
for (int j = 0; j < paramValues.length; j++) {
if (j > 0)
sb.append(",");
if (paramValues[j] == null) {
sb.append("null");
} else {
sb.append(paramValues[j].toString());
}
sb.append("/");
if (this.paramTypes[j] == null) {
sb.append("null");
} else {
sb.append(this.paramTypes[j].getName());
}
}
sb.append(")");
this.digester.log.debug(sb.toString());
}
if (this.useExactMatch) {
MethodUtils.invokeExactMethod(top, this.methodName, paramValues, this.paramTypes);
} else {
MethodUtils.invokeMethod(top, this.methodName, paramValues, this.paramTypes);
}
}
public void finish() throws Exception {
this.bodyText = null;
}
public String toString() {
StringBuffer sb = new StringBuffer("CallMethodRule[");
sb.append("methodName=");
sb.append(this.methodName);
sb.append(", paramCount=");
sb.append(this.paramCount);
sb.append(", paramTypes={");
if (this.paramTypes != null)
for (int i = 0; i < this.paramTypes.length; i++) {
if (i > 0)
sb.append(", ");
sb.append(this.paramTypes[i].getName());
}
sb.append("}");
sb.append("]");
return sb.toString();
}
}

View File

@@ -0,0 +1,103 @@
package org.apache.commons.digester;
import org.apache.commons.collections.ArrayStack;
import org.xml.sax.Attributes;
public class CallParamRule extends Rule {
protected String attributeName;
protected int paramIndex;
protected boolean fromStack;
protected int stackIndex;
protected ArrayStack bodyTextStack;
public CallParamRule(Digester digester, int paramIndex) {
this(paramIndex);
}
public CallParamRule(Digester digester, int paramIndex, String attributeName) {
this(paramIndex, attributeName);
}
public CallParamRule(int paramIndex) {
this(paramIndex, (String)null);
}
public CallParamRule(int paramIndex, String attributeName) {
this.attributeName = null;
this.paramIndex = 0;
this.fromStack = false;
this.stackIndex = 0;
this.paramIndex = paramIndex;
this.attributeName = attributeName;
}
public CallParamRule(int paramIndex, boolean fromStack) {
this.attributeName = null;
this.paramIndex = 0;
this.fromStack = false;
this.stackIndex = 0;
this.paramIndex = paramIndex;
this.fromStack = fromStack;
}
public CallParamRule(int paramIndex, int stackIndex) {
this.attributeName = null;
this.paramIndex = 0;
this.fromStack = false;
this.stackIndex = 0;
this.paramIndex = paramIndex;
this.fromStack = true;
this.stackIndex = stackIndex;
}
public void begin(Attributes attributes) throws Exception {
Object param = null;
if (this.attributeName != null) {
param = attributes.getValue(this.attributeName);
} else if (this.fromStack) {
param = this.digester.peek(this.stackIndex);
if (this.digester.log.isDebugEnabled()) {
StringBuffer sb = new StringBuffer("[CallParamRule]{");
sb.append(this.digester.match);
sb.append("} Save from stack; from stack?").append(this.fromStack);
sb.append("; object=").append(param);
this.digester.log.debug(sb.toString());
}
}
if (param != null) {
Object[] parameters = (Object[])this.digester.peekParams();
parameters[this.paramIndex] = param;
}
}
public void body(String bodyText) throws Exception {
if (this.attributeName == null && !this.fromStack) {
if (this.bodyTextStack == null)
this.bodyTextStack = new ArrayStack();
this.bodyTextStack.push(bodyText.trim());
}
}
public void end(String namespace, String name) {
if (this.bodyTextStack != null && !this.bodyTextStack.empty()) {
Object[] parameters = (Object[])this.digester.peekParams();
parameters[this.paramIndex] = this.bodyTextStack.pop();
}
}
public String toString() {
StringBuffer sb = new StringBuffer("CallParamRule[");
sb.append("paramIndex=");
sb.append(this.paramIndex);
sb.append(", attributeName=");
sb.append(this.attributeName);
sb.append(", from stack=");
sb.append(this.fromStack);
sb.append("]");
return sb.toString();
}
}

View File

@@ -0,0 +1,874 @@
package org.apache.commons.digester;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.InvocationTargetException;
import java.util.EmptyStackException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.commons.collections.ArrayStack;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.Attributes;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
public class Digester extends DefaultHandler {
public Digester() {}
public Digester(SAXParser parser) {
this.parser = parser;
}
public Digester(XMLReader reader) {
this.reader = reader;
}
protected StringBuffer bodyText = new StringBuffer();
protected ArrayStack bodyTexts = new ArrayStack();
protected ClassLoader classLoader = null;
protected boolean configured = false;
protected EntityResolver entityResolver;
protected HashMap entityValidator = new HashMap();
protected ErrorHandler errorHandler = null;
protected SAXParserFactory factory = null;
private static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
protected String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
protected Locator locator = null;
protected String match = "";
protected boolean namespaceAware = false;
protected HashMap namespaces = new HashMap();
protected ArrayStack params = new ArrayStack();
protected SAXParser parser = null;
protected String publicId = null;
protected XMLReader reader = null;
protected Object root = null;
protected Rules rules = null;
protected String schemaLanguage = "http://www.w3.org/2001/XMLSchema";
protected String schemaLocation = null;
protected ArrayStack stack = new ArrayStack();
protected boolean useContextClassLoader = false;
protected boolean validating = false;
protected Log log = LogFactory.getLog("org.apache.commons.digester.Digester");
protected Log saxLog = LogFactory.getLog("org.apache.commons.digester.Digester.sax");
protected static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
public String findNamespaceURI(String prefix) {
ArrayStack stack = (ArrayStack)this.namespaces.get(prefix);
if (stack == null)
return null;
try {
return (String)stack.peek();
} catch (EmptyStackException e) {
return null;
}
}
public ClassLoader getClassLoader() {
if (this.classLoader != null)
return this.classLoader;
if (this.useContextClassLoader) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader != null)
return classLoader;
}
return getClass().getClassLoader();
}
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
public int getCount() {
return this.stack.size();
}
public String getCurrentElementName() {
String elementName = this.match;
int lastSlash = elementName.lastIndexOf('/');
if (lastSlash >= 0)
elementName = elementName.substring(lastSlash + 1);
return elementName;
}
public int getDebug() {
return 0;
}
public void setDebug(int debug) {}
public ErrorHandler getErrorHandler() {
return this.errorHandler;
}
public void setErrorHandler(ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
public SAXParserFactory getFactory() {
if (this.factory == null) {
this.factory = SAXParserFactory.newInstance();
this.factory.setNamespaceAware(this.namespaceAware);
this.factory.setValidating(this.validating);
}
return this.factory;
}
public boolean getFeature(String feature) throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException {
return getFactory().getFeature(feature);
}
public void setFeature(String feature, boolean value) throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException {
getFactory().setFeature(feature, value);
}
public Log getLogger() {
return this.log;
}
public void setLogger(Log log) {
this.log = log;
}
public String getMatch() {
return this.match;
}
public boolean getNamespaceAware() {
return this.namespaceAware;
}
public void setNamespaceAware(boolean namespaceAware) {
this.namespaceAware = namespaceAware;
}
public void setPublicId(String publicId) {
this.publicId = publicId;
}
public String getPublicId() {
return this.publicId;
}
public String getRuleNamespaceURI() {
return getRules().getNamespaceURI();
}
public void setRuleNamespaceURI(String ruleNamespaceURI) {
getRules().setNamespaceURI(ruleNamespaceURI);
}
public SAXParser getParser() {
if (this.parser != null)
return this.parser;
try {
this.parser = getFactory().newSAXParser();
} catch (Exception e) {
this.log.error("Digester.getParser: ", e);
return null;
}
try {
if (this.schemaLocation != null) {
setProperty(this.JAXP_SCHEMA_LANGUAGE, this.schemaLanguage);
setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", this.schemaLocation);
}
} catch (Exception e) {
this.log.warn("" + e);
}
return this.parser;
}
public Object getProperty(String property) throws SAXNotRecognizedException, SAXNotSupportedException {
return getParser().getProperty(property);
}
public void setProperty(String property, Object value) throws SAXNotRecognizedException, SAXNotSupportedException {
getParser().setProperty(property, value);
}
public XMLReader getReader() {
try {
return getXMLReader();
} catch (SAXException e) {
this.log.error("Cannot get XMLReader", e);
return null;
}
}
public Rules getRules() {
if (this.rules == null) {
this.rules = new RulesBase();
this.rules.setDigester(this);
}
return this.rules;
}
public void setRules(Rules rules) {
this.rules = rules;
this.rules.setDigester(this);
}
public String getSchema() {
return this.schemaLocation;
}
public void setSchema(String schemaLocation) {
this.schemaLocation = schemaLocation;
}
public String getSchemaLanguage() {
return this.schemaLanguage;
}
public void setSchemaLanguage(String schemaLanguage) {
this.schemaLanguage = schemaLanguage;
}
public boolean getUseContextClassLoader() {
return this.useContextClassLoader;
}
public void setUseContextClassLoader(boolean use) {
this.useContextClassLoader = use;
}
public boolean getValidating() {
return this.validating;
}
public void setValidating(boolean validating) {
this.validating = validating;
}
public XMLReader getXMLReader() throws SAXException {
if (this.reader == null)
this.reader = getParser().getXMLReader();
this.reader.setDTDHandler(this);
this.reader.setContentHandler(this);
if (this.entityResolver == null) {
this.reader.setEntityResolver(this);
} else {
this.reader.setEntityResolver(this.entityResolver);
}
this.reader.setErrorHandler(this);
return this.reader;
}
public void characters(char[] buffer, int start, int length) throws SAXException {
if (this.saxLog.isDebugEnabled())
this.saxLog.debug("characters(" + new String(buffer, start, length) + ")");
this.bodyText.append(buffer, start, length);
}
public void endDocument() throws SAXException {
if (this.saxLog.isDebugEnabled())
if (getCount() > 1) {
this.saxLog.debug("endDocument(): " + getCount() + " elements left");
} else {
this.saxLog.debug("endDocument()");
}
while (getCount() > 1)
pop();
Iterator rules = getRules().rules().iterator();
while (rules.hasNext()) {
Rule rule = rules.next();
try {
rule.finish();
} catch (Exception e) {
this.log.error("Finish event threw exception", e);
throw createSAXException(e);
} catch (Error e) {
this.log.error("Finish event threw error", e);
throw e;
}
}
clear();
}
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
boolean debug = this.log.isDebugEnabled();
if (debug) {
if (this.saxLog.isDebugEnabled())
this.saxLog.debug("endElement(" + namespaceURI + "," + localName + "," + qName + ")");
this.log.debug(" match='" + this.match + "'");
this.log.debug(" bodyText='" + this.bodyText + "'");
}
String name = localName;
if (name == null || name.length() < 1)
name = qName;
List rules = getRules().match(namespaceURI, this.match);
if (rules != null && rules.size() > 0) {
String bodyText = this.bodyText.toString();
for (int i = 0; i < rules.size(); i++) {
try {
Rule rule = rules.get(i);
if (debug)
this.log.debug(" Fire body() for " + rule);
rule.body(namespaceURI, name, bodyText);
} catch (Exception e) {
this.log.error("Body event threw exception", e);
throw createSAXException(e);
} catch (Error e) {
this.log.error("Body event threw error", e);
throw e;
}
}
} else if (debug) {
this.log.debug(" No rules found matching '" + this.match + "'.");
}
this.bodyText = (StringBuffer)this.bodyTexts.pop();
if (debug)
this.log.debug(" Popping body text '" + this.bodyText.toString() + "'");
if (rules != null)
for (int i = 0; i < rules.size(); i++) {
int j = rules.size() - i - 1;
try {
Rule rule = rules.get(j);
if (debug)
this.log.debug(" Fire end() for " + rule);
rule.end(namespaceURI, name);
} catch (Exception e) {
this.log.error("End event threw exception", e);
throw createSAXException(e);
} catch (Error e) {
this.log.error("End event threw error", e);
throw e;
}
}
int slash = this.match.lastIndexOf('/');
if (slash >= 0) {
this.match = this.match.substring(0, slash);
} else {
this.match = "";
}
}
public void endPrefixMapping(String prefix) throws SAXException {
if (this.saxLog.isDebugEnabled())
this.saxLog.debug("endPrefixMapping(" + prefix + ")");
ArrayStack stack = (ArrayStack)this.namespaces.get(prefix);
if (stack == null)
return;
try {
stack.pop();
if (stack.empty())
this.namespaces.remove(prefix);
} catch (EmptyStackException e) {
throw createSAXException("endPrefixMapping popped too many times");
}
}
public void ignorableWhitespace(char[] buffer, int start, int len) throws SAXException {
if (this.saxLog.isDebugEnabled())
this.saxLog.debug("ignorableWhitespace(" + new String(buffer, start, len) + ")");
}
public void processingInstruction(String target, String data) throws SAXException {
if (this.saxLog.isDebugEnabled())
this.saxLog.debug("processingInstruction('" + target + "','" + data + "')");
}
public Locator getDocumentLocator() {
return this.locator;
}
public void setDocumentLocator(Locator locator) {
if (this.saxLog.isDebugEnabled())
this.saxLog.debug("setDocumentLocator(" + locator + ")");
this.locator = locator;
}
public void skippedEntity(String name) throws SAXException {
if (this.saxLog.isDebugEnabled())
this.saxLog.debug("skippedEntity(" + name + ")");
}
public void startDocument() throws SAXException {
if (this.saxLog.isDebugEnabled())
this.saxLog.debug("startDocument()");
configure();
}
public void startElement(String namespaceURI, String localName, String qName, Attributes list) throws SAXException {
boolean debug = this.log.isDebugEnabled();
if (this.saxLog.isDebugEnabled())
this.saxLog.debug("startElement(" + namespaceURI + "," + localName + "," + qName + ")");
this.bodyTexts.push(this.bodyText);
if (debug)
this.log.debug(" Pushing body text '" + this.bodyText.toString() + "'");
this.bodyText = new StringBuffer();
String name = localName;
if (name == null || name.length() < 1)
name = qName;
StringBuffer sb = new StringBuffer(this.match);
if (this.match.length() > 0)
sb.append('/');
sb.append(name);
this.match = sb.toString();
if (debug)
this.log.debug(" New match='" + this.match + "'");
List rules = getRules().match(namespaceURI, this.match);
if (rules != null && rules.size() > 0) {
String bodyText = this.bodyText.toString();
for (int i = 0; i < rules.size(); i++) {
try {
Rule rule = rules.get(i);
if (debug)
this.log.debug(" Fire begin() for " + rule);
rule.begin(namespaceURI, name, list);
} catch (Exception e) {
this.log.error("Begin event threw exception", e);
throw createSAXException(e);
} catch (Error e) {
this.log.error("Begin event threw error", e);
throw e;
}
}
} else if (debug) {
this.log.debug(" No rules found matching '" + this.match + "'.");
}
}
public void startPrefixMapping(String prefix, String namespaceURI) throws SAXException {
if (this.saxLog.isDebugEnabled())
this.saxLog.debug("startPrefixMapping(" + prefix + "," + namespaceURI + ")");
ArrayStack stack = (ArrayStack)this.namespaces.get(prefix);
if (stack == null) {
stack = new ArrayStack();
this.namespaces.put(prefix, stack);
}
stack.push(namespaceURI);
}
public void notationDecl(String name, String publicId, String systemId) {
if (this.saxLog.isDebugEnabled())
this.saxLog.debug("notationDecl(" + name + "," + publicId + "," + systemId + ")");
}
public void unparsedEntityDecl(String name, String publicId, String systemId, String notation) {
if (this.saxLog.isDebugEnabled())
this.saxLog.debug("unparsedEntityDecl(" + name + "," + publicId + "," + systemId + "," + notation + ")");
}
public void setEntityResolver(EntityResolver entityResolver) {
this.entityResolver = entityResolver;
}
public EntityResolver getEntityResolver() {
return this.entityResolver;
}
public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
boolean debug = this.log.isDebugEnabled();
if (this.saxLog.isDebugEnabled())
this.saxLog.debug("resolveEntity('" + publicId + "', '" + systemId + "')");
if (publicId != null)
this.publicId = publicId;
String entityURL = null;
if (publicId != null)
entityURL = (String)this.entityValidator.get(publicId);
if (this.schemaLocation != null && entityURL == null && systemId != null)
entityURL = (String)this.entityValidator.get(systemId);
if (entityURL == null)
return null;
if (debug)
this.log.debug(" Resolving to alternate DTD '" + entityURL + "'");
try {
return new InputSource(entityURL);
} catch (Exception e) {
throw createSAXException(e);
}
}
public void error(SAXParseException exception) throws SAXException {
this.log.error("Parse Error at line " + exception.getLineNumber() + " column " + exception.getColumnNumber() + ": " + exception.getMessage(), exception);
if (this.errorHandler != null)
this.errorHandler.error(exception);
}
public void fatalError(SAXParseException exception) throws SAXException {
this.log.error("Parse Fatal Error at line " + exception.getLineNumber() + " column " + exception.getColumnNumber() + ": " + exception.getMessage(), exception);
if (this.errorHandler != null)
this.errorHandler.fatalError(exception);
}
public void warning(SAXParseException exception) throws SAXException {
if (this.errorHandler != null) {
this.log.warn("Parse Warning Error at line " + exception.getLineNumber() + " column " + exception.getColumnNumber() + ": " + exception.getMessage(), exception);
this.errorHandler.warning(exception);
}
}
public void log(String message) {
this.log.info(message);
}
public void log(String message, Throwable exception) {
this.log.error(message, exception);
}
public Object parse(File file) throws IOException, SAXException {
configure();
InputSource input = new InputSource(new FileInputStream(file));
input.setSystemId("file://" + file.getAbsolutePath());
getXMLReader().parse(input);
return this.root;
}
public Object parse(InputSource input) throws IOException, SAXException {
configure();
getXMLReader().parse(input);
return this.root;
}
public Object parse(InputStream input) throws IOException, SAXException {
configure();
InputSource is = new InputSource(input);
getXMLReader().parse(is);
return this.root;
}
public Object parse(Reader reader) throws IOException, SAXException {
configure();
InputSource is = new InputSource(reader);
getXMLReader().parse(is);
return this.root;
}
public Object parse(String uri) throws IOException, SAXException {
configure();
InputSource is = new InputSource(uri);
getXMLReader().parse(is);
return this.root;
}
public void register(String publicId, String entityURL) {
if (this.log.isDebugEnabled())
this.log.debug("register('" + publicId + "', '" + entityURL + "'");
this.entityValidator.put(publicId, entityURL);
}
public void addRule(String pattern, Rule rule) {
rule.setDigester(this);
getRules().add(pattern, rule);
}
public void addRuleSet(RuleSet ruleSet) {
String oldNamespaceURI = getRuleNamespaceURI();
String newNamespaceURI = ruleSet.getNamespaceURI();
if (this.log.isDebugEnabled())
if (newNamespaceURI == null) {
this.log.debug("addRuleSet() with no namespace URI");
} else {
this.log.debug("addRuleSet() with namespace URI " + newNamespaceURI);
}
setRuleNamespaceURI(newNamespaceURI);
ruleSet.addRuleInstances(this);
setRuleNamespaceURI(oldNamespaceURI);
}
public void addBeanPropertySetter(String pattern) {
addRule(pattern, new BeanPropertySetterRule());
}
public void addBeanPropertySetter(String pattern, String propertyName) {
addRule(pattern, new BeanPropertySetterRule(propertyName));
}
public void addCallMethod(String pattern, String methodName) {
addRule(pattern, new CallMethodRule(methodName));
}
public void addCallMethod(String pattern, String methodName, int paramCount) {
addRule(pattern, new CallMethodRule(methodName, paramCount));
}
public void addCallMethod(String pattern, String methodName, int paramCount, String[] paramTypes) {
addRule(pattern, new CallMethodRule(methodName, paramCount, paramTypes));
}
public void addCallMethod(String pattern, String methodName, int paramCount, Class[] paramTypes) {
addRule(pattern, new CallMethodRule(methodName, paramCount, paramTypes));
}
public void addCallParam(String pattern, int paramIndex) {
addRule(pattern, new CallParamRule(paramIndex));
}
public void addCallParam(String pattern, int paramIndex, String attributeName) {
addRule(pattern, new CallParamRule(paramIndex, attributeName));
}
public void addCallParam(String pattern, int paramIndex, boolean fromStack) {
addRule(pattern, new CallParamRule(paramIndex, fromStack));
}
public void addCallParam(String pattern, int paramIndex, int stackIndex) {
addRule(pattern, new CallParamRule(paramIndex, stackIndex));
}
public void addFactoryCreate(String pattern, String className) {
addFactoryCreate(pattern, className, false);
}
public void addFactoryCreate(String pattern, Class clazz) {
addFactoryCreate(pattern, clazz, false);
}
public void addFactoryCreate(String pattern, String className, String attributeName) {
addFactoryCreate(pattern, className, attributeName, false);
}
public void addFactoryCreate(String pattern, Class clazz, String attributeName) {
addFactoryCreate(pattern, clazz, attributeName, false);
}
public void addFactoryCreate(String pattern, ObjectCreationFactory creationFactory) {
addFactoryCreate(pattern, creationFactory, false);
}
public void addFactoryCreate(String pattern, String className, boolean ignoreCreateExceptions) {
addRule(pattern, new FactoryCreateRule(className, ignoreCreateExceptions));
}
public void addFactoryCreate(String pattern, Class clazz, boolean ignoreCreateExceptions) {
addRule(pattern, new FactoryCreateRule(clazz, ignoreCreateExceptions));
}
public void addFactoryCreate(String pattern, String className, String attributeName, boolean ignoreCreateExceptions) {
addRule(pattern, new FactoryCreateRule(className, attributeName, ignoreCreateExceptions));
}
public void addFactoryCreate(String pattern, Class clazz, String attributeName, boolean ignoreCreateExceptions) {
addRule(pattern, new FactoryCreateRule(clazz, attributeName, ignoreCreateExceptions));
}
public void addFactoryCreate(String pattern, ObjectCreationFactory creationFactory, boolean ignoreCreateExceptions) {
creationFactory.setDigester(this);
addRule(pattern, new FactoryCreateRule(creationFactory, ignoreCreateExceptions));
}
public void addObjectCreate(String pattern, String className) {
addRule(pattern, new ObjectCreateRule(className));
}
public void addObjectCreate(String pattern, Class clazz) {
addRule(pattern, new ObjectCreateRule(clazz));
}
public void addObjectCreate(String pattern, String className, String attributeName) {
addRule(pattern, new ObjectCreateRule(className, attributeName));
}
public void addObjectCreate(String pattern, String attributeName, Class clazz) {
addRule(pattern, new ObjectCreateRule(attributeName, clazz));
}
public void addSetNext(String pattern, String methodName) {
addRule(pattern, new SetNextRule(methodName));
}
public void addSetNext(String pattern, String methodName, String paramType) {
addRule(pattern, new SetNextRule(methodName, paramType));
}
public void addSetRoot(String pattern, String methodName) {
addRule(pattern, new SetRootRule(methodName));
}
public void addSetRoot(String pattern, String methodName, String paramType) {
addRule(pattern, new SetRootRule(methodName, paramType));
}
public void addSetProperties(String pattern) {
addRule(pattern, new SetPropertiesRule());
}
public void addSetProperties(String pattern, String attributeName, String propertyName) {
addRule(pattern, new SetPropertiesRule(attributeName, propertyName));
}
public void addSetProperties(String pattern, String[] attributeNames, String[] propertyNames) {
addRule(pattern, new SetPropertiesRule(attributeNames, propertyNames));
}
public void addSetProperty(String pattern, String name, String value) {
addRule(pattern, new SetPropertyRule(name, value));
}
public void addSetTop(String pattern, String methodName) {
addRule(pattern, new SetTopRule(methodName));
}
public void addSetTop(String pattern, String methodName, String paramType) {
addRule(pattern, new SetTopRule(methodName, paramType));
}
public void clear() {
this.match = "";
this.bodyTexts.clear();
this.params.clear();
this.publicId = null;
this.stack.clear();
}
public Object peek() {
try {
return this.stack.peek();
} catch (EmptyStackException e) {
this.log.warn("Empty stack (returning null)");
return null;
}
}
public Object peek(int n) {
try {
return this.stack.peek(n);
} catch (EmptyStackException e) {
this.log.warn("Empty stack (returning null)");
return null;
}
}
public Object pop() {
try {
return this.stack.pop();
} catch (EmptyStackException e) {
this.log.warn("Empty stack (returning null)");
return null;
}
}
public void push(Object object) {
if (this.stack.size() == 0)
this.root = object;
this.stack.push(object);
}
public Object getRoot() {
return this.root;
}
protected void configure() {
if (this.configured)
return;
this.configured = true;
}
Map getRegistrations() {
return this.entityValidator;
}
List getRules(String match) {
return getRules().match(match);
}
Object peekParams() {
try {
return this.params.peek();
} catch (EmptyStackException e) {
this.log.warn("Empty stack (returning null)");
return null;
}
}
Object peekParams(int n) {
try {
return this.params.peek(n);
} catch (EmptyStackException e) {
this.log.warn("Empty stack (returning null)");
return null;
}
}
Object popParams() {
try {
if (this.log.isTraceEnabled())
this.log.trace("Popping params");
return this.params.pop();
} catch (EmptyStackException e) {
this.log.warn("Empty stack (returning null)");
return null;
}
}
void pushParams(Object object) {
if (this.log.isTraceEnabled())
this.log.trace("Pushing params");
this.params.push(object);
}
protected SAXException createSAXException(String message, Exception e) {
if (e != null && e instanceof InvocationTargetException) {
Throwable t = ((InvocationTargetException)e).getTargetException();
if (t != null && t instanceof Exception)
e = (Exception)t;
}
if (this.locator != null) {
String error = "Error at (" + this.locator.getLineNumber() + ", " + this.locator.getColumnNumber() + ": " + message;
if (e != null)
return new SAXParseException(error, this.locator, e);
return new SAXParseException(error, this.locator);
}
this.log.error("No Locator!");
if (e != null)
return new SAXException(message, e);
return new SAXException(message);
}
protected SAXException createSAXException(Exception e) {
if (e instanceof InvocationTargetException) {
Throwable t = ((InvocationTargetException)e).getTargetException();
if (t != null && t instanceof Exception)
e = (Exception)t;
}
return createSAXException(e.getMessage(), e);
}
protected SAXException createSAXException(String message) {
return createSAXException(message, null);
}
}

View File

@@ -0,0 +1,159 @@
package org.apache.commons.digester;
import org.apache.commons.collections.ArrayStack;
import org.xml.sax.Attributes;
public class FactoryCreateRule extends Rule {
private boolean ignoreCreateExceptions;
private ArrayStack exceptionIgnoredStack;
protected String attributeName;
protected String className;
protected ObjectCreationFactory creationFactory;
public FactoryCreateRule(Digester digester, String className) {
this(className);
}
public FactoryCreateRule(Digester digester, Class clazz) {
this(clazz);
}
public FactoryCreateRule(Digester digester, String className, String attributeName) {
this(className, attributeName);
}
public FactoryCreateRule(Digester digester, Class clazz, String attributeName) {
this(clazz, attributeName);
}
public FactoryCreateRule(Digester digester, ObjectCreationFactory creationFactory) {
this(creationFactory);
}
public FactoryCreateRule(String className) {
this(className, false);
}
public FactoryCreateRule(Class clazz) {
this(clazz, false);
}
public FactoryCreateRule(String className, String attributeName) {
this(className, attributeName, false);
}
public FactoryCreateRule(Class clazz, String attributeName) {
this(clazz, attributeName, false);
}
public FactoryCreateRule(ObjectCreationFactory creationFactory) {
this(creationFactory, false);
}
public FactoryCreateRule(String className, boolean ignoreCreateExceptions) {
this(className, (String)null, ignoreCreateExceptions);
}
public FactoryCreateRule(Class clazz, boolean ignoreCreateExceptions) {
this(clazz, (String)null, ignoreCreateExceptions);
}
public FactoryCreateRule(String className, String attributeName, boolean ignoreCreateExceptions) {
this.attributeName = null;
this.className = null;
this.creationFactory = null;
this.className = className;
this.attributeName = attributeName;
this.ignoreCreateExceptions = ignoreCreateExceptions;
}
public FactoryCreateRule(Class clazz, String attributeName, boolean ignoreCreateExceptions) {
this(clazz.getName(), attributeName, ignoreCreateExceptions);
}
public FactoryCreateRule(ObjectCreationFactory creationFactory, boolean ignoreCreateExceptions) {
this.attributeName = null;
this.className = null;
this.creationFactory = null;
this.creationFactory = creationFactory;
this.ignoreCreateExceptions = ignoreCreateExceptions;
}
public void begin(String namespace, String name, Attributes attributes) throws Exception {
if (this.ignoreCreateExceptions) {
if (this.exceptionIgnoredStack == null)
this.exceptionIgnoredStack = new ArrayStack();
try {
Object instance = getFactory(attributes).createObject(attributes);
if (this.digester.log.isDebugEnabled())
this.digester.log.debug("[FactoryCreateRule]{" + this.digester.match + "} New " + instance.getClass().getName());
this.digester.push(instance);
this.exceptionIgnoredStack.push(Boolean.FALSE);
} catch (Exception e) {
if (this.digester.log.isInfoEnabled()) {
this.digester.log.info("[FactoryCreateRule] Create exception ignored: " + ((e.getMessage() == null) ? e.getClass().getName() : e.getMessage()));
if (this.digester.log.isDebugEnabled())
this.digester.log.debug("[FactoryCreateRule] Ignored exception:", e);
}
this.exceptionIgnoredStack.push(Boolean.TRUE);
}
} else {
Object instance = getFactory(attributes).createObject(attributes);
if (this.digester.log.isDebugEnabled())
this.digester.log.debug("[FactoryCreateRule]{" + this.digester.match + "} New " + instance.getClass().getName());
this.digester.push(instance);
}
}
public void end(String namespace, String name) throws Exception {
if (this.ignoreCreateExceptions && this.exceptionIgnoredStack != null && !this.exceptionIgnoredStack.empty())
if (((Boolean)this.exceptionIgnoredStack.pop()).booleanValue()) {
if (this.digester.log.isTraceEnabled())
this.digester.log.trace("[FactoryCreateRule] No creation so no push so no pop");
return;
}
Object top = this.digester.pop();
if (this.digester.log.isDebugEnabled())
this.digester.log.debug("[FactoryCreateRule]{" + this.digester.match + "} Pop " + top.getClass().getName());
}
public void finish() throws Exception {
if (this.attributeName != null)
this.creationFactory = null;
}
public String toString() {
StringBuffer sb = new StringBuffer("FactoryCreateRule[");
sb.append("className=");
sb.append(this.className);
sb.append(", attributeName=");
sb.append(this.attributeName);
if (this.creationFactory != null) {
sb.append(", creationFactory=");
sb.append(this.creationFactory);
}
sb.append("]");
return sb.toString();
}
protected ObjectCreationFactory getFactory(Attributes attributes) throws Exception {
if (this.creationFactory == null) {
String realClassName = this.className;
if (this.attributeName != null) {
String value = attributes.getValue(this.attributeName);
if (value != null)
realClassName = value;
}
if (this.digester.log.isDebugEnabled())
this.digester.log.debug("[FactoryCreateRule]{" + this.digester.match + "} New factory " + realClassName);
Class clazz = this.digester.getClassLoader().loadClass(realClassName);
this.creationFactory = (ObjectCreationFactory)clazz.newInstance();
this.creationFactory.setDigester(this.digester);
}
return this.creationFactory;
}
}

View File

@@ -0,0 +1,74 @@
package org.apache.commons.digester;
import org.xml.sax.Attributes;
public class ObjectCreateRule extends Rule {
protected String attributeName;
protected String className;
public ObjectCreateRule(Digester digester, String className) {
this(className);
}
public ObjectCreateRule(Digester digester, Class clazz) {
this(clazz);
}
public ObjectCreateRule(Digester digester, String className, String attributeName) {
this(className, attributeName);
}
public ObjectCreateRule(Digester digester, String attributeName, Class clazz) {
this(attributeName, clazz);
}
public ObjectCreateRule(String className) {
this(className, (String)null);
}
public ObjectCreateRule(Class clazz) {
this(clazz.getName(), (String)null);
}
public ObjectCreateRule(String className, String attributeName) {
this.attributeName = null;
this.className = null;
this.className = className;
this.attributeName = attributeName;
}
public ObjectCreateRule(String attributeName, Class clazz) {
this(clazz.getName(), attributeName);
}
public void begin(Attributes attributes) throws Exception {
String realClassName = this.className;
if (this.attributeName != null) {
String value = attributes.getValue(this.attributeName);
if (value != null)
realClassName = value;
}
if (this.digester.log.isDebugEnabled())
this.digester.log.debug("[ObjectCreateRule]{" + this.digester.match + "}New " + realClassName);
Class clazz = this.digester.getClassLoader().loadClass(realClassName);
Object instance = clazz.newInstance();
this.digester.push(instance);
}
public void end() throws Exception {
Object top = this.digester.pop();
if (this.digester.log.isDebugEnabled())
this.digester.log.debug("[ObjectCreateRule]{" + this.digester.match + "} Pop " + top.getClass().getName());
}
public String toString() {
StringBuffer sb = new StringBuffer("ObjectCreateRule[");
sb.append("className=");
sb.append(this.className);
sb.append(", attributeName=");
sb.append(this.attributeName);
sb.append("]");
return sb.toString();
}
}

View File

@@ -0,0 +1,11 @@
package org.apache.commons.digester;
import org.xml.sax.Attributes;
public interface ObjectCreationFactory {
Object createObject(Attributes paramAttributes) throws Exception;
Digester getDigester();
void setDigester(Digester paramDigester);
}

View File

@@ -0,0 +1,56 @@
package org.apache.commons.digester;
import org.xml.sax.Attributes;
public abstract class Rule {
protected Digester digester;
protected String namespaceURI;
public Rule(Digester digester) {
this.digester = null;
this.namespaceURI = null;
setDigester(digester);
}
public Rule() {
this.digester = null;
this.namespaceURI = null;
}
public Digester getDigester() {
return this.digester;
}
public void setDigester(Digester digester) {
this.digester = digester;
}
public String getNamespaceURI() {
return this.namespaceURI;
}
public void setNamespaceURI(String namespaceURI) {
this.namespaceURI = namespaceURI;
}
public void begin(Attributes attributes) throws Exception {}
public void begin(String namespace, String name, Attributes attributes) throws Exception {
begin(attributes);
}
public void body(String text) throws Exception {}
public void body(String namespace, String name, String text) throws Exception {
body(text);
}
public void end() throws Exception {}
public void end(String namespace, String name) throws Exception {
end();
}
public void finish() throws Exception {}
}

View File

@@ -0,0 +1,7 @@
package org.apache.commons.digester;
public interface RuleSet {
String getNamespaceURI();
void addRuleInstances(Digester paramDigester);
}

View File

@@ -0,0 +1,11 @@
package org.apache.commons.digester;
public abstract class RuleSetBase implements RuleSet {
protected String namespaceURI = null;
public String getNamespaceURI() {
return this.namespaceURI;
}
public abstract void addRuleInstances(Digester paramDigester);
}

View File

@@ -0,0 +1,23 @@
package org.apache.commons.digester;
import java.util.List;
public interface Rules {
Digester getDigester();
void setDigester(Digester paramDigester);
String getNamespaceURI();
void setNamespaceURI(String paramString);
void add(String paramString, Rule paramRule);
void clear();
List match(String paramString);
List match(String paramString1, String paramString2);
List rules();
}

View File

@@ -0,0 +1,100 @@
package org.apache.commons.digester;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
public class RulesBase implements Rules {
protected HashMap cache = new HashMap();
protected Digester digester = null;
protected String namespaceURI = null;
protected ArrayList rules = new ArrayList();
public Digester getDigester() {
return this.digester;
}
public void setDigester(Digester digester) {
this.digester = digester;
Iterator items = this.rules.iterator();
while (items.hasNext()) {
Rule item = items.next();
item.setDigester(digester);
}
}
public String getNamespaceURI() {
return this.namespaceURI;
}
public void setNamespaceURI(String namespaceURI) {
this.namespaceURI = namespaceURI;
}
public void add(String pattern, Rule rule) {
List list = (List)this.cache.get(pattern);
if (list == null) {
list = new ArrayList();
this.cache.put(pattern, list);
}
list.add(rule);
this.rules.add(rule);
if (this.digester != null)
rule.setDigester(this.digester);
if (this.namespaceURI != null)
rule.setNamespaceURI(this.namespaceURI);
}
public void clear() {
this.cache.clear();
this.rules.clear();
}
public List match(String pattern) {
return match(null, pattern);
}
public List match(String namespaceURI, String pattern) {
List rulesList = lookup(namespaceURI, pattern);
if (rulesList == null || rulesList.size() < 1) {
String longKey = "";
Iterator keys = this.cache.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
if (key.startsWith("*/") && (
pattern.equals(key.substring(2)) || pattern.endsWith(key.substring(1))))
if (key.length() > longKey.length()) {
rulesList = lookup(namespaceURI, key);
longKey = key;
}
}
}
if (rulesList == null)
rulesList = new ArrayList();
return rulesList;
}
public List rules() {
return this.rules;
}
protected List lookup(String namespaceURI, String pattern) {
List list = (List)this.cache.get(pattern);
if (list == null)
return null;
if (namespaceURI == null || namespaceURI.length() == 0)
return list;
ArrayList results = new ArrayList();
Iterator items = list.iterator();
while (items.hasNext()) {
Rule item = items.next();
if (namespaceURI.equals(item.getNamespaceURI()) || item.getNamespaceURI() == null)
results.add(item);
}
return results;
}
}

View File

@@ -0,0 +1,71 @@
package org.apache.commons.digester;
import org.apache.commons.beanutils.MethodUtils;
public class SetNextRule extends Rule {
protected String methodName;
protected String paramType;
protected boolean useExactMatch;
public SetNextRule(Digester digester, String methodName) {
this(methodName);
}
public SetNextRule(Digester digester, String methodName, String paramType) {
this(methodName, paramType);
}
public SetNextRule(String methodName) {
this(methodName, (String)null);
}
public SetNextRule(String methodName, String paramType) {
this.methodName = null;
this.paramType = null;
this.useExactMatch = false;
this.methodName = methodName;
this.paramType = paramType;
}
public boolean isExactMatch() {
return this.useExactMatch;
}
public void setExactMatch(boolean useExactMatch) {
this.useExactMatch = useExactMatch;
}
public void end() throws Exception {
Object child = this.digester.peek(0);
Object parent = this.digester.peek(1);
if (this.digester.log.isDebugEnabled())
if (parent == null) {
this.digester.log.debug("[SetNextRule]{" + this.digester.match + "} Call [NULL PARENT]." + this.methodName + "(" + child + ")");
} else {
this.digester.log.debug("[SetNextRule]{" + this.digester.match + "} Call " + parent.getClass().getName() + "." + this.methodName + "(" + child + ")");
}
Class[] paramTypes = new Class[1];
if (this.paramType != null) {
paramTypes[0] = this.digester.getClassLoader().loadClass(this.paramType);
} else {
paramTypes[0] = child.getClass();
}
if (this.useExactMatch) {
MethodUtils.invokeExactMethod(parent, this.methodName, new Object[] { child }, paramTypes);
} else {
MethodUtils.invokeMethod(parent, this.methodName, new Object[] { child }, paramTypes);
}
}
public String toString() {
StringBuffer sb = new StringBuffer("SetNextRule[");
sb.append("methodName=");
sb.append(this.methodName);
sb.append(", paramType=");
sb.append(this.paramType);
sb.append("]");
return sb.toString();
}
}

View File

@@ -0,0 +1,94 @@
package org.apache.commons.digester;
import java.util.HashMap;
import org.apache.commons.beanutils.BeanUtils;
import org.xml.sax.Attributes;
public class SetPropertiesRule extends Rule {
private String[] attributeNames;
private String[] propertyNames;
public SetPropertiesRule(Digester digester) {
this();
}
public SetPropertiesRule() {}
public SetPropertiesRule(String attributeName, String propertyName) {
this.attributeNames = new String[1];
this.attributeNames[0] = attributeName;
this.propertyNames = new String[1];
this.propertyNames[0] = propertyName;
}
public SetPropertiesRule(String[] attributeNames, String[] propertyNames) {
this.attributeNames = new String[attributeNames.length];
for (int i = 0, size = attributeNames.length; i < size; i++)
this.attributeNames[i] = attributeNames[i];
this.propertyNames = new String[propertyNames.length];
for (int j = 0, k = propertyNames.length; j < k; j++)
this.propertyNames[j] = propertyNames[j];
}
public void begin(Attributes attributes) throws Exception {
HashMap values = new HashMap();
int attNamesLength = 0;
if (this.attributeNames != null)
attNamesLength = this.attributeNames.length;
int propNamesLength = 0;
if (this.propertyNames != null)
propNamesLength = this.propertyNames.length;
for (int i = 0; i < attributes.getLength(); i++) {
String name = attributes.getLocalName(i);
if ("".equals(name))
name = attributes.getQName(i);
String value = attributes.getValue(i);
for (int n = 0; n < attNamesLength; n++) {
if (name.equals(this.attributeNames[n])) {
if (n < propNamesLength) {
name = this.propertyNames[n];
break;
}
name = null;
break;
}
}
if (this.digester.log.isDebugEnabled())
this.digester.log.debug("[SetPropertiesRule]{" + this.digester.match + "} Setting property '" + name + "' to '" + value + "'");
if (name != null)
values.put(name, value);
}
Object top = this.digester.peek();
if (this.digester.log.isDebugEnabled())
this.digester.log.debug("[SetPropertiesRule]{" + this.digester.match + "} Set " + top.getClass().getName() + " properties");
BeanUtils.populate(top, values);
}
public void addAlias(String attributeName, String propertyName) {
if (this.attributeNames == null) {
this.attributeNames = new String[1];
this.attributeNames[0] = attributeName;
this.propertyNames = new String[1];
this.propertyNames[0] = propertyName;
} else {
int length = this.attributeNames.length;
String[] tempAttributes = new String[length + 1];
for (int i = 0; i < length; i++)
tempAttributes[i] = this.attributeNames[i];
tempAttributes[length] = attributeName;
String[] tempProperties = new String[length + 1];
for (int j = 0; j < length && j < this.propertyNames.length; j++)
tempProperties[j] = this.propertyNames[j];
tempProperties[length] = propertyName;
this.propertyNames = tempProperties;
this.attributeNames = tempAttributes;
}
}
public String toString() {
StringBuffer sb = new StringBuffer("SetPropertiesRule[");
sb.append("]");
return sb.toString();
}
}

View File

@@ -0,0 +1,64 @@
package org.apache.commons.digester;
import java.beans.PropertyDescriptor;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.commons.beanutils.PropertyUtils;
import org.xml.sax.Attributes;
public class SetPropertyRule extends Rule {
protected String name;
protected String value;
public SetPropertyRule(Digester digester, String name, String value) {
this(name, value);
}
public SetPropertyRule(String name, String value) {
this.name = null;
this.value = null;
this.name = name;
this.value = value;
}
public void begin(Attributes attributes) throws Exception {
String actualName = null;
String actualValue = null;
for (int i = 0; i < attributes.getLength(); i++) {
String name = attributes.getLocalName(i);
if ("".equals(name))
name = attributes.getQName(i);
String value = attributes.getValue(i);
if (name.equals(this.name)) {
actualName = value;
} else if (name.equals(this.value)) {
actualValue = value;
}
}
Object top = this.digester.peek();
if (this.digester.log.isDebugEnabled())
this.digester.log.debug("[SetPropertyRule]{" + this.digester.match + "} Set " + top.getClass().getName() + " property " + actualName + " to " + actualValue);
if (top instanceof DynaBean) {
DynaProperty desc = ((DynaBean)top).getDynaClass().getDynaProperty(actualName);
if (desc == null)
throw new NoSuchMethodException("Bean has no property named " + actualName);
} else {
PropertyDescriptor desc = PropertyUtils.getPropertyDescriptor(top, actualName);
if (desc == null)
throw new NoSuchMethodException("Bean has no property named " + actualName);
}
BeanUtils.setProperty(top, actualName, actualValue);
}
public String toString() {
StringBuffer sb = new StringBuffer("SetPropertyRule[");
sb.append("name=");
sb.append(this.name);
sb.append(", value=");
sb.append(this.value);
sb.append("]");
return sb.toString();
}
}

View File

@@ -0,0 +1,71 @@
package org.apache.commons.digester;
import org.apache.commons.beanutils.MethodUtils;
public class SetRootRule extends Rule {
protected String methodName;
protected String paramType;
protected boolean useExactMatch;
public SetRootRule(Digester digester, String methodName) {
this(methodName);
}
public SetRootRule(Digester digester, String methodName, String paramType) {
this(methodName, paramType);
}
public SetRootRule(String methodName) {
this(methodName, (String)null);
}
public SetRootRule(String methodName, String paramType) {
this.methodName = null;
this.paramType = null;
this.useExactMatch = false;
this.methodName = methodName;
this.paramType = paramType;
}
public boolean isExactMatch() {
return this.useExactMatch;
}
public void setExactMatch(boolean useExactMatch) {
this.useExactMatch = useExactMatch;
}
public void end() throws Exception {
Object child = this.digester.peek(0);
Object parent = this.digester.root;
if (this.digester.log.isDebugEnabled())
if (parent == null) {
this.digester.log.debug("[SetRootRule]{" + this.digester.match + "} Call [NULL ROOT]." + this.methodName + "(" + child + ")");
} else {
this.digester.log.debug("[SetRootRule]{" + this.digester.match + "} Call " + parent.getClass().getName() + "." + this.methodName + "(" + child + ")");
}
Class[] paramTypes = new Class[1];
if (this.paramType != null) {
paramTypes[0] = this.digester.getClassLoader().loadClass(this.paramType);
} else {
paramTypes[0] = child.getClass();
}
if (this.useExactMatch) {
MethodUtils.invokeExactMethod(parent, this.methodName, new Object[] { child }, paramTypes);
} else {
MethodUtils.invokeMethod(parent, this.methodName, new Object[] { child }, paramTypes);
}
}
public String toString() {
StringBuffer sb = new StringBuffer("SetRootRule[");
sb.append("methodName=");
sb.append(this.methodName);
sb.append(", paramType=");
sb.append(this.paramType);
sb.append("]");
return sb.toString();
}
}

View File

@@ -0,0 +1,71 @@
package org.apache.commons.digester;
import org.apache.commons.beanutils.MethodUtils;
public class SetTopRule extends Rule {
protected String methodName;
protected String paramType;
protected boolean useExactMatch;
public SetTopRule(Digester digester, String methodName) {
this(methodName);
}
public SetTopRule(Digester digester, String methodName, String paramType) {
this(methodName, paramType);
}
public SetTopRule(String methodName) {
this(methodName, (String)null);
}
public SetTopRule(String methodName, String paramType) {
this.methodName = null;
this.paramType = null;
this.useExactMatch = false;
this.methodName = methodName;
this.paramType = paramType;
}
public boolean isExactMatch() {
return this.useExactMatch;
}
public void setExactMatch(boolean useExactMatch) {
this.useExactMatch = useExactMatch;
}
public void end() throws Exception {
Object child = this.digester.peek(0);
Object parent = this.digester.peek(1);
if (this.digester.log.isDebugEnabled())
if (child == null) {
this.digester.log.debug("[SetTopRule]{" + this.digester.match + "} Call [NULL CHILD]." + this.methodName + "(" + parent + ")");
} else {
this.digester.log.debug("[SetTopRule]{" + this.digester.match + "} Call " + child.getClass().getName() + "." + this.methodName + "(" + parent + ")");
}
Class[] paramTypes = new Class[1];
if (this.paramType != null) {
paramTypes[0] = this.digester.getClassLoader().loadClass(this.paramType);
} else {
paramTypes[0] = parent.getClass();
}
if (this.useExactMatch) {
MethodUtils.invokeExactMethod(child, this.methodName, new Object[] { parent }, paramTypes);
} else {
MethodUtils.invokeMethod(child, this.methodName, new Object[] { parent }, paramTypes);
}
}
public String toString() {
StringBuffer sb = new StringBuffer("SetTopRule[");
sb.append("methodName=");
sb.append(this.methodName);
sb.append(", paramType=");
sb.append(this.paramType);
sb.append("]");
return sb.toString();
}
}

View File

@@ -0,0 +1,39 @@
package org.apache.commons.logging;
public interface Log {
boolean isDebugEnabled();
boolean isErrorEnabled();
boolean isFatalEnabled();
boolean isInfoEnabled();
boolean isTraceEnabled();
boolean isWarnEnabled();
void trace(Object paramObject);
void trace(Object paramObject, Throwable paramThrowable);
void debug(Object paramObject);
void debug(Object paramObject, Throwable paramThrowable);
void info(Object paramObject);
void info(Object paramObject, Throwable paramThrowable);
void warn(Object paramObject);
void warn(Object paramObject, Throwable paramThrowable);
void error(Object paramObject);
void error(Object paramObject, Throwable paramThrowable);
void fatal(Object paramObject);
void fatal(Object paramObject, Throwable paramThrowable);
}

View File

@@ -0,0 +1,24 @@
package org.apache.commons.logging;
public class LogConfigurationException extends RuntimeException {
public LogConfigurationException() {}
public LogConfigurationException(String message) {
super(message);
}
public LogConfigurationException(Throwable cause) {
this((cause == null) ? null : cause.toString(), cause);
}
public LogConfigurationException(String message, Throwable cause) {
super(message);
this.cause = cause;
}
protected Throwable cause = null;
public Throwable getCause() {
return this.cause;
}
}

View File

@@ -0,0 +1,207 @@
package org.apache.commons.logging;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
public abstract class LogFactory {
public static final String FACTORY_PROPERTY = "org.apache.commons.logging.LogFactory";
public static final String FACTORY_DEFAULT = "org.apache.commons.logging.impl.LogFactoryImpl";
public static final String FACTORY_PROPERTIES = "commons-logging.properties";
protected static final String SERVICE_ID = "META-INF/services/org.apache.commons.logging.LogFactory";
protected static Hashtable factories = new Hashtable();
public static LogFactory getFactory() throws LogConfigurationException {
ClassLoader contextClassLoader = AccessController.<ClassLoader>doPrivileged(new PrivilegedAction() {
public Object run() {
return LogFactory.getContextClassLoader();
}
});
LogFactory factory = getCachedFactory(contextClassLoader);
if (factory != null)
return factory;
Properties props = null;
try {
InputStream stream = getResourceAsStream(contextClassLoader, "commons-logging.properties");
if (stream != null) {
props = new Properties();
props.load(stream);
stream.close();
}
} catch (IOException e) {
} catch (SecurityException e) {}
try {
String factoryClass = System.getProperty("org.apache.commons.logging.LogFactory");
if (factoryClass != null)
factory = newFactory(factoryClass, contextClassLoader);
} catch (SecurityException e) {}
if (factory == null)
try {
InputStream is = getResourceAsStream(contextClassLoader, "META-INF/services/org.apache.commons.logging.LogFactory");
if (is != null) {
BufferedReader bufferedReader;
try {
bufferedReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
} catch (UnsupportedEncodingException e) {
bufferedReader = new BufferedReader(new InputStreamReader(is));
}
String factoryClassName = bufferedReader.readLine();
bufferedReader.close();
if (factoryClassName != null && !"".equals(factoryClassName))
factory = newFactory(factoryClassName, contextClassLoader);
}
} catch (Exception ex) {}
if (factory == null && props != null) {
String factoryClass = props.getProperty("org.apache.commons.logging.LogFactory");
if (factoryClass != null)
factory = newFactory(factoryClass, contextClassLoader);
}
if (factory == null)
factory = newFactory("org.apache.commons.logging.impl.LogFactoryImpl", LogFactory.class.getClassLoader());
if (factory != null) {
cacheFactory(contextClassLoader, factory);
if (props != null) {
Enumeration names = props.propertyNames();
while (names.hasMoreElements()) {
String name = (String)names.nextElement();
String value = props.getProperty(name);
factory.setAttribute(name, value);
}
}
}
return factory;
}
public static Log getLog(Class clazz) throws LogConfigurationException {
return getFactory().getInstance(clazz);
}
public static Log getLog(String name) throws LogConfigurationException {
return getFactory().getInstance(name);
}
public static void release(ClassLoader classLoader) {
synchronized (factories) {
LogFactory factory = (LogFactory)factories.get(classLoader);
if (factory != null) {
factory.release();
factories.remove(classLoader);
}
}
}
public static void releaseAll() {
synchronized (factories) {
Enumeration elements = factories.elements();
while (elements.hasMoreElements()) {
LogFactory element = elements.nextElement();
element.release();
}
factories.clear();
}
}
protected static ClassLoader getContextClassLoader() throws LogConfigurationException {
ClassLoader classLoader = null;
try {
Method method = Thread.class.getMethod("getContextClassLoader", null);
try {
classLoader = (ClassLoader)method.invoke(Thread.currentThread(), null);
} catch (IllegalAccessException e) {
throw new LogConfigurationException("Unexpected IllegalAccessException", e);
} catch (InvocationTargetException e) {
if (!(e.getTargetException() instanceof SecurityException))
throw new LogConfigurationException("Unexpected InvocationTargetException", e.getTargetException());
}
} catch (NoSuchMethodException e) {
classLoader = LogFactory.class.getClassLoader();
}
return classLoader;
}
private static LogFactory getCachedFactory(ClassLoader contextClassLoader) {
LogFactory factory = null;
if (contextClassLoader != null)
factory = (LogFactory)factories.get(contextClassLoader);
return factory;
}
private static void cacheFactory(ClassLoader classLoader, LogFactory factory) {
if (classLoader != null && factory != null)
factories.put(classLoader, factory);
}
protected static LogFactory newFactory(String factoryClass, ClassLoader classLoader) throws LogConfigurationException {
Object result = AccessController.doPrivileged(new PrivilegedAction(classLoader, factoryClass) {
private final ClassLoader val$classLoader;
private final String val$factoryClass;
public Object run() {
try {
if (this.val$classLoader != null)
try {
return this.val$classLoader.loadClass(this.val$factoryClass).newInstance();
} catch (ClassNotFoundException ex) {
if (this.val$classLoader == ((LogFactory.class$org$apache$commons$logging$LogFactory == null) ? (LogFactory.class$org$apache$commons$logging$LogFactory = LogFactory.class$("org.apache.commons.logging.LogFactory")) : LogFactory.class$org$apache$commons$logging$LogFactory).getClassLoader())
throw ex;
} catch (NoClassDefFoundError e) {
if (this.val$classLoader == ((LogFactory.class$org$apache$commons$logging$LogFactory == null) ? (LogFactory.class$org$apache$commons$logging$LogFactory = LogFactory.class$("org.apache.commons.logging.LogFactory")) : LogFactory.class$org$apache$commons$logging$LogFactory).getClassLoader())
throw e;
} catch (ClassCastException e) {
if (this.val$classLoader == ((LogFactory.class$org$apache$commons$logging$LogFactory == null) ? (LogFactory.class$org$apache$commons$logging$LogFactory = LogFactory.class$("org.apache.commons.logging.LogFactory")) : LogFactory.class$org$apache$commons$logging$LogFactory).getClassLoader())
throw e;
}
return Class.forName(this.val$factoryClass).newInstance();
} catch (Exception e) {
return new LogConfigurationException(e);
}
}
});
if (result instanceof LogConfigurationException)
throw (LogConfigurationException)result;
return (LogFactory)result;
}
private static InputStream getResourceAsStream(ClassLoader loader, String name) {
return AccessController.<InputStream>doPrivileged(new PrivilegedAction(loader, name) {
private final ClassLoader val$loader;
private final String val$name;
public Object run() {
if (this.val$loader != null)
return this.val$loader.getResourceAsStream(this.val$name);
return ClassLoader.getSystemResourceAsStream(this.val$name);
}
});
}
public abstract Object getAttribute(String paramString);
public abstract String[] getAttributeNames();
public abstract Log getInstance(Class paramClass) throws LogConfigurationException;
public abstract Log getInstance(String paramString) throws LogConfigurationException;
public abstract void release();
public abstract void removeAttribute(String paramString);
public abstract void setAttribute(String paramString, Object paramObject);
}

View File

@@ -0,0 +1,169 @@
package org.apache.struts.action;
import java.io.IOException;
import java.util.Locale;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.RequestUtils;
import org.apache.struts.util.TokenProcessor;
public class Action {
public static final String ACTION_SERVLET_KEY = "org.apache.struts.action.ACTION_SERVLET";
public static final String APPLICATION_KEY = "org.apache.struts.action.MODULE";
public static final String DATA_SOURCE_KEY = "org.apache.struts.action.DATA_SOURCE";
public static final String ERROR_KEY = "org.apache.struts.action.ERROR";
public static final String EXCEPTION_KEY = "org.apache.struts.action.EXCEPTION";
public static final String FORM_BEANS_KEY = "org.apache.struts.action.FORM_BEANS";
public static final String FORWARDS_KEY = "org.apache.struts.action.FORWARDS";
public static final String LOCALE_KEY = "org.apache.struts.action.LOCALE";
public static final String MAPPING_KEY = "org.apache.struts.action.mapping.instance";
public static final String MAPPINGS_KEY = "org.apache.struts.action.MAPPINGS";
public static final String MESSAGE_KEY = "org.apache.struts.action.ACTION_MESSAGE";
public static final String MESSAGES_KEY = "org.apache.struts.action.MESSAGE";
public static final String MULTIPART_KEY = "org.apache.struts.action.mapping.multipartclass";
public static final String PLUG_INS_KEY = "org.apache.struts.action.PLUG_INS";
public static final String REQUEST_PROCESSOR_KEY = "org.apache.struts.action.REQUEST_PROCESSOR";
public static final String SERVLET_KEY = "org.apache.struts.action.SERVLET_MAPPING";
public static final String TRANSACTION_TOKEN_KEY = "org.apache.struts.action.TOKEN";
private static TokenProcessor token = TokenProcessor.getInstance();
protected static Locale defaultLocale = Locale.getDefault();
protected ActionServlet servlet = null;
public ActionServlet getServlet() {
return this.servlet;
}
public void setServlet(ActionServlet servlet) {
this.servlet = servlet;
}
public ActionForward execute(ActionMapping mapping, ActionForm form, ServletRequest request, ServletResponse response) throws Exception {
return perform(mapping, form, request, response);
}
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
return perform(mapping, form, request, response);
}
public ActionForward perform(ActionMapping mapping, ActionForm form, ServletRequest request, ServletResponse response) throws IOException, ServletException {
try {
return perform(mapping, form, (HttpServletRequest)request, (HttpServletResponse)response);
} catch (ClassCastException e) {
return null;
}
}
public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
return null;
}
protected String generateToken(HttpServletRequest request) {
return token.generateToken(request);
}
protected DataSource getDataSource(HttpServletRequest request) {
return getDataSource(request, "org.apache.struts.action.DATA_SOURCE");
}
protected DataSource getDataSource(HttpServletRequest request, String key) {
ServletContext context = getServlet().getServletContext();
ModuleConfig moduleConfig = RequestUtils.getModuleConfig(request, context);
return (DataSource)context.getAttribute(key + moduleConfig.getPrefix());
}
protected Locale getLocale(HttpServletRequest request) {
HttpSession session = request.getSession();
Locale locale = (Locale)session.getAttribute("org.apache.struts.action.LOCALE");
if (locale == null)
locale = defaultLocale;
return locale;
}
protected MessageResources getResources() {
return (MessageResources)this.servlet.getServletContext().getAttribute("org.apache.struts.action.MESSAGE");
}
protected MessageResources getResources(HttpServletRequest request) {
return (MessageResources)request.getAttribute("org.apache.struts.action.MESSAGE");
}
protected MessageResources getResources(HttpServletRequest request, String key) {
ServletContext context = getServlet().getServletContext();
ModuleConfig moduleConfig = RequestUtils.getModuleConfig(request, context);
return (MessageResources)context.getAttribute(key + moduleConfig.getPrefix());
}
protected boolean isCancelled(HttpServletRequest request) {
return (request.getAttribute("org.apache.struts.action.CANCEL") != null);
}
protected boolean isTokenValid(HttpServletRequest request) {
return token.isTokenValid(request, false);
}
protected boolean isTokenValid(HttpServletRequest request, boolean reset) {
return token.isTokenValid(request, reset);
}
protected void resetToken(HttpServletRequest request) {
token.resetToken(request);
}
protected void saveErrors(HttpServletRequest request, ActionErrors errors) {
if (errors == null || errors.isEmpty()) {
request.removeAttribute("org.apache.struts.action.ERROR");
return;
}
request.setAttribute("org.apache.struts.action.ERROR", errors);
}
protected void saveMessages(HttpServletRequest request, ActionMessages messages) {
if (messages == null || messages.isEmpty()) {
request.removeAttribute("org.apache.struts.action.ACTION_MESSAGE");
return;
}
request.setAttribute("org.apache.struts.action.ACTION_MESSAGE", messages);
}
protected void saveToken(HttpServletRequest request) {
token.saveToken(request);
}
protected void setLocale(HttpServletRequest request, Locale locale) {
HttpSession session = request.getSession();
if (locale == null)
locale = defaultLocale;
session.setAttribute("org.apache.struts.action.LOCALE", locale);
}
protected String toHex(byte[] buffer) {
return token.toHex(buffer);
}
}

View File

@@ -0,0 +1,29 @@
package org.apache.struts.action;
import java.io.Serializable;
public class ActionError extends ActionMessage implements Serializable {
public ActionError(String key) {
super(key);
}
public ActionError(String key, Object value0) {
super(key, value0);
}
public ActionError(String key, Object value0, Object value1) {
super(key, value0, value1);
}
public ActionError(String key, Object value0, Object value1, Object value2) {
super(key, value0, value1, value2);
}
public ActionError(String key, Object value0, Object value1, Object value2, Object value3) {
super(key, value0, value1, value2, value3);
}
public ActionError(String key, Object[] values) {
super(key, values);
}
}

View File

@@ -0,0 +1,17 @@
package org.apache.struts.action;
import java.io.Serializable;
public class ActionErrors extends ActionMessages implements Serializable {
public static final String GLOBAL_ERROR = "org.apache.struts.action.GLOBAL_ERROR";
public ActionErrors() {}
public ActionErrors(ActionErrors messages) {
super(messages);
}
public void add(String property, ActionError error) {
add(property, error);
}
}

View File

@@ -0,0 +1,52 @@
package org.apache.struts.action;
import java.io.Serializable;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.upload.MultipartRequestHandler;
public abstract class ActionForm implements Serializable {
protected transient ActionServlet servlet = null;
protected transient MultipartRequestHandler multipartRequestHandler;
protected ActionServlet getServlet() {
return this.servlet;
}
public ActionServletWrapper getServletWrapper() {
return new ActionServletWrapper(getServlet());
}
public MultipartRequestHandler getMultipartRequestHandler() {
return this.multipartRequestHandler;
}
public void setServlet(ActionServlet servlet) {
this.servlet = servlet;
}
public void setMultipartRequestHandler(MultipartRequestHandler multipartRequestHandler) {
this.multipartRequestHandler = multipartRequestHandler;
}
public void reset(ActionMapping mapping, ServletRequest request) {
try {
reset(mapping, (HttpServletRequest)request);
} catch (ClassCastException e) {}
}
public void reset(ActionMapping mapping, HttpServletRequest request) {}
public ActionErrors validate(ActionMapping mapping, ServletRequest request) {
try {
return validate(mapping, (HttpServletRequest)request);
} catch (ClassCastException e) {
return null;
}
}
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
return null;
}
}

View File

@@ -0,0 +1,12 @@
package org.apache.struts.action;
import org.apache.struts.config.FormBeanConfig;
public class ActionFormBean extends FormBeanConfig {
public ActionFormBean() {}
public ActionFormBean(String name, String type) {
setName(name);
setType(type);
}
}

View File

@@ -0,0 +1,32 @@
package org.apache.struts.action;
import java.io.Serializable;
import org.apache.commons.collections.FastHashMap;
public class ActionFormBeans implements Serializable {
protected FastHashMap formBeans = new FastHashMap();
public boolean getFast() {
return this.formBeans.getFast();
}
public void setFast(boolean fast) {
this.formBeans.setFast(fast);
}
public void addFormBean(ActionFormBean formBean) {
this.formBeans.put(formBean.getName(), formBean);
}
public ActionFormBean findFormBean(String name) {
return (ActionFormBean)this.formBeans.get(name);
}
public String[] findFormBeans() {
return (String[])this.formBeans.keySet().toArray((Object[])new String[this.formBeans.size()]);
}
public void removeFormBean(ActionFormBean formBean) {
this.formBeans.remove(formBean.getName());
}
}

View File

@@ -0,0 +1,32 @@
package org.apache.struts.action;
import org.apache.struts.config.ForwardConfig;
public class ActionForward extends ForwardConfig {
public ActionForward() {
this((String)null, false);
}
public ActionForward(String path) {
this(path, false);
}
public ActionForward(String path, boolean redirect) {
setName(null);
setPath(path);
setRedirect(redirect);
}
public ActionForward(String name, String path, boolean redirect) {
setName(name);
setPath(path);
setRedirect(redirect);
}
public ActionForward(String name, String path, boolean redirect, boolean contextRelative) {
setName(name);
setPath(path);
setRedirect(redirect);
setContextRelative(contextRelative);
}
}

View File

@@ -0,0 +1,32 @@
package org.apache.struts.action;
import java.io.Serializable;
import org.apache.commons.collections.FastHashMap;
public class ActionForwards implements Serializable {
private FastHashMap forwards = new FastHashMap();
public boolean getFast() {
return this.forwards.getFast();
}
public void setFast(boolean fast) {
this.forwards.setFast(fast);
}
public void addForward(ActionForward forward) {
this.forwards.put(forward.getName(), forward);
}
public ActionForward findForward(String name) {
return (ActionForward)this.forwards.get(name);
}
public String[] findForwards() {
return (String[])this.forwards.keySet().toArray((Object[])new String[this.forwards.size()]);
}
public void removeForward(ActionForward forward) {
this.forwards.remove(forward.getName());
}
}

View File

@@ -0,0 +1,44 @@
package org.apache.struts.action;
import java.util.ArrayList;
import org.apache.struts.config.ActionConfig;
import org.apache.struts.config.ExceptionConfig;
import org.apache.struts.config.ForwardConfig;
public class ActionMapping extends ActionConfig {
public ExceptionConfig findException(Class type) {
ExceptionConfig config = null;
do {
String name = type.getName();
config = findExceptionConfig(name);
if (config != null)
return config;
config = getModuleConfig().findExceptionConfig(name);
if (config != null)
return config;
type = type.getSuperclass();
} while (type != null);
return null;
}
public ActionForward findForward(String name) {
ForwardConfig config = findForwardConfig(name);
if (config == null)
config = getModuleConfig().findForwardConfig(name);
return (ActionForward)config;
}
public String[] findForwards() {
ArrayList results = new ArrayList();
ForwardConfig[] fcs = findForwardConfigs();
for (int i = 0; i < fcs.length; i++)
results.add(fcs[i].getName());
return results.<String>toArray(new String[results.size()]);
}
public ActionForward getInputForward() {
if (getModuleConfig().getControllerConfig().getInputForward())
return findForward(getInput());
return new ActionForward(getInput());
}
}

View File

@@ -0,0 +1,64 @@
package org.apache.struts.action;
import java.io.Serializable;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections.FastHashMap;
public class ActionMappings implements Serializable {
protected FastHashMap mappings = new FastHashMap();
protected transient ActionServlet servlet = null;
protected ActionMapping unknown = null;
public boolean getFast() {
return this.mappings.getFast();
}
public void setFast(boolean fast) {
this.mappings.setFast(fast);
}
public ActionMapping getUnknown(ServletRequest request) {
return getUnknown((HttpServletRequest)request);
}
public ActionMapping getUnknown(HttpServletRequest request) {
if (this.unknown != null)
return this.unknown;
String[] paths = findMappings();
for (int i = 0; i < paths.length; i++) {
ActionMapping mapping = findMapping(paths[i]);
if (mapping.getUnknown()) {
this.unknown = mapping;
return mapping;
}
}
return null;
}
public ActionServlet getServlet() {
return this.servlet;
}
public void setServlet(ActionServlet servlet) {
this.servlet = servlet;
}
public void addMapping(ActionMapping mapping) {
this.mappings.put(mapping.getPath(), mapping);
}
public ActionMapping findMapping(String path) {
return (ActionMapping)this.mappings.get(path);
}
public String[] findMappings() {
return (String[])this.mappings.keySet().toArray((Object[])new String[this.mappings.size()]);
}
public void removeMapping(ActionMapping mapping) {
this.mappings.remove(mapping.getPath());
}
}

View File

@@ -0,0 +1,59 @@
package org.apache.struts.action;
import java.io.Serializable;
public class ActionMessage implements Serializable {
protected String key;
protected Object[] values;
public ActionMessage(String key) {
this.key = null;
this.values = null;
this.key = key;
this.values = null;
}
public ActionMessage(String key, Object value0) {
this.key = null;
this.values = null;
this.key = key;
this.values = new Object[] { value0 };
}
public ActionMessage(String key, Object value0, Object value1) {
this.key = null;
this.values = null;
this.key = key;
this.values = new Object[] { value0, value1 };
}
public ActionMessage(String key, Object value0, Object value1, Object value2) {
this.key = null;
this.values = null;
this.key = key;
this.values = new Object[] { value0, value1, value2 };
}
public ActionMessage(String key, Object value0, Object value1, Object value2, Object value3) {
this.key = null;
this.values = null;
this.key = key;
this.values = new Object[] { value0, value1, value2, value3 };
}
public ActionMessage(String key, Object[] values) {
this.key = null;
this.values = null;
this.key = key;
this.values = values;
}
public String getKey() {
return this.key;
}
public Object[] getValues() {
return this.values;
}
}

View File

@@ -0,0 +1,143 @@
package org.apache.struts.action;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
public class ActionMessages implements Serializable {
public static final String GLOBAL_MESSAGE = "org.apache.struts.action.GLOBAL_MESSAGE";
protected HashMap messages = new HashMap();
protected int iCount = 0;
public ActionMessages() {}
public ActionMessages(ActionMessages messages) {
add(messages);
}
public void add(String property, ActionMessage message) {
ActionMessageItem item = (ActionMessageItem)this.messages.get(property);
List list = null;
if (item == null) {
list = new ArrayList();
item = new ActionMessageItem(this, list, this.iCount++);
this.messages.put(property, item);
} else {
list = item.getList();
}
list.add(message);
}
public void add(ActionMessages messages) {
if (messages == null)
return;
Iterator props = messages.properties();
while (props.hasNext()) {
String property = props.next();
Iterator msgs = messages.get(property);
while (msgs.hasNext()) {
ActionMessage msg = msgs.next();
add(property, msg);
}
}
}
public void clear() {
this.messages.clear();
}
public boolean empty() {
return isEmpty();
}
public boolean isEmpty() {
return this.messages.isEmpty();
}
public Iterator get() {
if (this.messages.isEmpty())
return Collections.EMPTY_LIST.iterator();
ArrayList results = new ArrayList();
ArrayList actionItems = new ArrayList();
for (Iterator i = this.messages.values().iterator(); i.hasNext();)
actionItems.add(i.next());
Collections.sort(actionItems, new Comparator(this) {
private final ActionMessages this$0;
public int compare(Object o1, Object o2) {
return ((ActionMessages.ActionMessageItem)o1).getOrder() - ((ActionMessages.ActionMessageItem)o2).getOrder();
}
});
for (Iterator iterator = actionItems.iterator(); iterator.hasNext(); ) {
ActionMessageItem ami = (ActionMessageItem)iterator.next();
for (Iterator messages = ami.getList().iterator(); messages.hasNext();)
results.add(messages.next());
}
return results.iterator();
}
public Iterator get(String property) {
ActionMessageItem item = (ActionMessageItem)this.messages.get(property);
if (item == null)
return Collections.EMPTY_LIST.iterator();
return item.getList().iterator();
}
public Iterator properties() {
return this.messages.keySet().iterator();
}
public int size() {
int total = 0;
for (Iterator i = this.messages.values().iterator(); i.hasNext(); ) {
ActionMessageItem ami = i.next();
total += ami.getList().size();
}
return total;
}
public int size(String property) {
ActionMessageItem ami = (ActionMessageItem)this.messages.get(property);
if (ami == null)
return 0;
return ami.getList().size();
}
protected class ActionMessageItem implements Serializable {
protected List list;
protected int iOrder;
private final ActionMessages this$0;
public ActionMessageItem(ActionMessages this$0, List list, int iOrder) {
this.this$0 = this$0;
this.list = null;
this.iOrder = 0;
this.list = list;
this.iOrder = iOrder;
}
public List getList() {
return this.list;
}
public void setList(List list) {
this.list = list;
}
public int getOrder() {
return this.iOrder;
}
public void setOrder(int iOrder) {
this.iOrder = iOrder;
}
}
}

View File

@@ -0,0 +1,646 @@
package org.apache.struts.action;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.MissingResourceException;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.converters.BigDecimalConverter;
import org.apache.commons.beanutils.converters.BigIntegerConverter;
import org.apache.commons.beanutils.converters.BooleanConverter;
import org.apache.commons.beanutils.converters.ByteConverter;
import org.apache.commons.beanutils.converters.CharacterConverter;
import org.apache.commons.beanutils.converters.DoubleConverter;
import org.apache.commons.beanutils.converters.FloatConverter;
import org.apache.commons.beanutils.converters.IntegerConverter;
import org.apache.commons.beanutils.converters.LongConverter;
import org.apache.commons.beanutils.converters.ShortConverter;
import org.apache.commons.collections.FastHashMap;
import org.apache.commons.digester.Digester;
import org.apache.commons.digester.RuleSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.config.ActionConfig;
import org.apache.struts.config.ApplicationConfig;
import org.apache.struts.config.ConfigRuleSet;
import org.apache.struts.config.ControllerConfig;
import org.apache.struts.config.DataSourceConfig;
import org.apache.struts.config.FormBeanConfig;
import org.apache.struts.config.ForwardConfig;
import org.apache.struts.config.MessageResourcesConfig;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.config.ModuleConfigFactory;
import org.apache.struts.config.PlugInConfig;
import org.apache.struts.config.impl.ModuleConfigImpl;
import org.apache.struts.util.GenericDataSource;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.MessageResourcesFactory;
import org.apache.struts.util.RequestUtils;
import org.apache.struts.util.ServletContextWriter;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class ActionServlet extends HttpServlet {
protected String config = "/WEB-INF/struts-config.xml";
protected Digester configDigester = null;
protected boolean convertNull = false;
protected FastHashMap dataSources = new FastHashMap();
protected int debug = 0;
protected MessageResources internal = null;
protected String internalName = "org.apache.struts.action.ActionResources";
protected static Log log = LogFactory.getLog(ActionServlet.class);
protected RequestProcessor processor = null;
protected String[] registrations = new String[] { "-//Apache Software Foundation//DTD Struts Configuration 1.0//EN", "/org/apache/struts/resources/struts-config_1_0.dtd", "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN", "/org/apache/struts/resources/struts-config_1_1.dtd", "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN", "/org/apache/struts/resources/web-app_2_2.dtd", "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN", "/org/apache/struts/resources/web-app_2_3.dtd" };
protected String servletMapping = null;
protected String servletName = null;
public void destroy() {
if (log.isDebugEnabled())
log.debug(this.internal.getMessage("finalizing"));
destroyModules();
destroyDataSources();
destroyInternal();
getServletContext().removeAttribute("org.apache.struts.action.ACTION_SERVLET");
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null)
classLoader = ActionServlet.class.getClassLoader();
try {
LogFactory.release(classLoader);
} catch (Throwable t) {}
}
public void init() throws ServletException {
initInternal();
initOther();
initServlet();
getServletContext().setAttribute("org.apache.struts.action.ACTION_SERVLET", this);
ModuleConfig moduleConfig = initModuleConfig("", this.config);
initModuleMessageResources(moduleConfig);
initModuleDataSources(moduleConfig);
initModulePlugIns(moduleConfig);
moduleConfig.freeze();
Enumeration names = getServletConfig().getInitParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
if (!name.startsWith("config/"))
continue;
String prefix = name.substring(6);
moduleConfig = initModuleConfig(prefix, getServletConfig().getInitParameter(name));
initModuleMessageResources(moduleConfig);
initModuleDataSources(moduleConfig);
initModulePlugIns(moduleConfig);
moduleConfig.freeze();
}
destroyConfigDigester();
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
process(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
process(request, response);
}
public void addServletMapping(String servletName, String urlPattern) {
if (log.isDebugEnabled())
log.debug("Process servletName=" + servletName + ", urlPattern=" + urlPattern);
if (servletName == null)
return;
if (servletName.equals(this.servletName))
this.servletMapping = urlPattern;
}
public DataSource findDataSource(String key) {
if (key == null)
return (DataSource)this.dataSources.get("org.apache.struts.action.DATA_SOURCE");
return (DataSource)this.dataSources.get(key);
}
public ActionFormBean findFormBean(String name) {
ActionFormBeans afb = (ActionFormBeans)getServletContext().getAttribute("org.apache.struts.action.FORM_BEANS");
if (afb == null)
return null;
return afb.findFormBean(name);
}
public ActionForward findForward(String name) {
ActionForwards af = (ActionForwards)getServletContext().getAttribute("org.apache.struts.action.FORWARDS");
if (af == null)
return null;
return af.findForward(name);
}
public ActionMapping findMapping(String path) {
ActionMappings am = (ActionMappings)getServletContext().getAttribute("org.apache.struts.action.MAPPINGS");
if (am == null)
return null;
return am.findMapping(path);
}
public int getDebug() {
return this.debug;
}
public MessageResources getInternal() {
return this.internal;
}
public MessageResources getResources() {
return (MessageResources)getServletContext().getAttribute("org.apache.struts.action.MESSAGE");
}
public void log(String message, int level) {
if (this.debug >= level)
log(message);
}
protected void destroyApplications() {
destroyModules();
}
protected void destroyModules() {
ArrayList values = new ArrayList();
Enumeration names = getServletContext().getAttributeNames();
while (names.hasMoreElements())
values.add(names.nextElement());
Iterator keys = values.iterator();
while (keys.hasNext()) {
String name = keys.next();
Object value = getServletContext().getAttribute(name);
if (value instanceof ModuleConfig) {
ModuleConfig config = (ModuleConfig)value;
try {
getRequestProcessor(config).destroy();
} catch (ServletException e) {
log.error(e);
}
getServletContext().removeAttribute(name);
PlugIn[] plugIns = (PlugIn[])getServletContext().getAttribute("org.apache.struts.action.PLUG_INS" + config.getPrefix());
if (plugIns != null) {
for (int i = 0; i < plugIns.length; i++) {
int j = plugIns.length - i + 1;
plugIns[j].destroy();
}
getServletContext().removeAttribute("org.apache.struts.action.PLUG_INS" + config.getPrefix());
}
}
}
}
protected void destroyConfigDigester() {
this.configDigester = null;
}
protected void destroyDataSources() {
synchronized (this.dataSources) {
Iterator keys = this.dataSources.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
getServletContext().removeAttribute(key);
DataSource dataSource = findDataSource(key);
if (dataSource instanceof GenericDataSource) {
if (log.isDebugEnabled())
log.debug(this.internal.getMessage("dataSource.destroy", key));
try {
((GenericDataSource)dataSource).close();
} catch (SQLException e) {
log.error(this.internal.getMessage("destroyDataSource", key), e);
}
}
}
this.dataSources.clear();
}
}
protected void destroyInternal() {
this.internal = null;
}
protected ApplicationConfig getApplicationConfig(HttpServletRequest request) {
return new ApplicationConfig((ModuleConfigImpl)getModuleConfig(request));
}
protected ModuleConfig getModuleConfig(HttpServletRequest request) {
ModuleConfig config = (ModuleConfig)request.getAttribute("org.apache.struts.action.MODULE");
if (config == null)
config = (ModuleConfig)getServletContext().getAttribute("org.apache.struts.action.MODULE");
return config;
}
protected synchronized RequestProcessor getRequestProcessor(ModuleConfig config) throws ServletException {
String key = "org.apache.struts.action.REQUEST_PROCESSOR" + config.getPrefix();
RequestProcessor processor = (RequestProcessor)getServletContext().getAttribute(key);
if (processor == null) {
try {
processor = (RequestProcessor)RequestUtils.applicationInstance(config.getControllerConfig().getProcessorClass());
} catch (Exception e) {
throw new UnavailableException("Cannot initialize RequestProcessor of class " + config.getControllerConfig().getProcessorClass() + ": " + e);
}
processor.init(this, config);
getServletContext().setAttribute(key, processor);
}
return processor;
}
protected ApplicationConfig initApplicationConfig(String prefix, String path) throws ServletException {
return new ApplicationConfig((ModuleConfigImpl)initModuleConfig(prefix, path));
}
protected ModuleConfig initModuleConfig(String prefix, String paths) throws ServletException {
if (log.isDebugEnabled())
log.debug("Initializing module path '" + prefix + "' configuration from '" + paths + "'");
ModuleConfigFactory factoryObject = ModuleConfigFactory.createFactory();
ModuleConfig config = factoryObject.createModuleConfig(prefix);
String mapping = getServletConfig().getInitParameter("mapping");
if (mapping != null)
config.setActionMappingClass(mapping);
Digester digester = initConfigDigester();
while (paths.length() > 0) {
digester.push(config);
String path = null;
int comma = paths.indexOf(',');
if (comma >= 0) {
path = paths.substring(0, comma).trim();
paths = paths.substring(comma + 1);
} else {
path = paths.trim();
paths = "";
}
if (path.length() < 1)
break;
parseModuleConfigFile(prefix, paths, config, digester, path);
}
FormBeanConfig[] fbs = config.findFormBeanConfigs();
for (int i = 0; i < fbs.length; i++) {
if (fbs[i].getDynamic())
DynaActionFormClass.createDynaActionFormClass(fbs[i]);
}
if (prefix.length() < 1) {
defaultControllerConfig(config);
defaultMessageResourcesConfig(config);
defaultFormBeansConfig(config);
defaultForwardsConfig(config);
defaultMappingsConfig(config);
}
return config;
}
private void parseModuleConfigFile(String prefix, String paths, ModuleConfig config, Digester digester, String path) throws UnavailableException {
InputStream input = null;
try {
URL url = getServletContext().getResource(path);
InputSource is = new InputSource(url.toExternalForm());
input = getServletContext().getResourceAsStream(path);
is.setByteStream(input);
digester.parse(is);
getServletContext().setAttribute("org.apache.struts.action.MODULE" + prefix, config);
} catch (MalformedURLException e) {
handleConfigException(paths, e);
} catch (IOException e) {
handleConfigException(paths, e);
} catch (SAXException e) {
handleConfigException(paths, e);
} finally {
if (input != null)
try {
input.close();
} catch (IOException e) {
throw new UnavailableException(e.getMessage());
}
}
}
private void handleConfigException(String paths, Exception e) throws UnavailableException {
log.error(this.internal.getMessage("configParse", paths), e);
throw new UnavailableException(this.internal.getMessage("configParse", paths));
}
protected void initApplicationDataSources(ModuleConfig config) throws ServletException {
initModuleDataSources(config);
}
protected void initModuleDataSources(ModuleConfig config) throws ServletException {
if (log.isDebugEnabled())
log.debug("Initializing module path '" + config.getPrefix() + "' data sources");
ServletContextWriter scw = new ServletContextWriter(getServletContext());
DataSourceConfig[] dscs = config.findDataSourceConfigs();
if (dscs == null)
dscs = new DataSourceConfig[0];
this.dataSources.setFast(false);
for (int i = 0; i < dscs.length; i++) {
if (log.isDebugEnabled())
log.debug("Initializing module path '" + config.getPrefix() + "' data source '" + dscs[i].getKey() + "'");
DataSource ds = null;
try {
ds = (DataSource)RequestUtils.applicationInstance(dscs[i].getType());
BeanUtils.populate(ds, dscs[i].getProperties());
if (ds instanceof GenericDataSource)
((GenericDataSource)ds).open();
ds.setLogWriter((PrintWriter)scw);
} catch (Exception e) {
log.error(this.internal.getMessage("dataSource.init", dscs[i].getKey()), e);
throw new UnavailableException(this.internal.getMessage("dataSource.init", dscs[i].getKey()));
}
getServletContext().setAttribute(dscs[i].getKey() + config.getPrefix(), ds);
this.dataSources.put(dscs[i].getKey(), ds);
}
this.dataSources.setFast(true);
if ("".equals(config.getPrefix()))
initDataSources();
}
protected void initApplicationPlugIns(ModuleConfig config) throws ServletException {
initModulePlugIns(config);
}
protected void initModulePlugIns(ModuleConfig config) throws ServletException {
if (log.isDebugEnabled())
log.debug("Initializing module path '" + config.getPrefix() + "' plug ins");
PlugInConfig[] plugInConfigs = config.findPlugInConfigs();
PlugIn[] plugIns = new PlugIn[plugInConfigs.length];
getServletContext().setAttribute("org.apache.struts.action.PLUG_INS" + config.getPrefix(), plugIns);
for (int i = 0; i < plugIns.length; i++) {
try {
plugIns[i] = (PlugIn)RequestUtils.applicationInstance(plugInConfigs[i].getClassName());
BeanUtils.populate(plugIns[i], plugInConfigs[i].getProperties());
try {
PropertyUtils.setProperty(plugIns[i], "currentPlugInConfigObject", plugInConfigs[i]);
} catch (Exception e) {}
plugIns[i].init(this, config);
} catch (ServletException e) {
throw e;
} catch (Exception e) {
String errMsg = this.internal.getMessage("plugIn.init", plugInConfigs[i].getClassName());
log(errMsg, e);
throw new UnavailableException(errMsg);
}
}
}
protected void initApplicationMessageResources(ModuleConfig config) throws ServletException {
initModuleMessageResources(config);
}
protected void initModuleMessageResources(ModuleConfig config) throws ServletException {
MessageResourcesConfig[] mrcs = config.findMessageResourcesConfigs();
for (int i = 0; i < mrcs.length; i++) {
if (mrcs[i].getFactory() != null && mrcs[i].getParameter() != null) {
if (log.isDebugEnabled())
log.debug("Initializing module path '" + config.getPrefix() + "' message resources from '" + mrcs[i].getParameter() + "'");
String factory = mrcs[i].getFactory();
MessageResourcesFactory.setFactoryClass(factory);
MessageResourcesFactory factoryObject = MessageResourcesFactory.createFactory();
MessageResources resources = factoryObject.createResources(mrcs[i].getParameter());
resources.setReturnNull(mrcs[i].getNull());
getServletContext().setAttribute(mrcs[i].getKey() + config.getPrefix(), resources);
}
}
}
protected Digester initConfigDigester() throws ServletException {
if (this.configDigester != null)
return this.configDigester;
boolean validating = true;
String value = getServletConfig().getInitParameter("validating");
if ("false".equalsIgnoreCase(value) || "no".equalsIgnoreCase(value) || "n".equalsIgnoreCase(value) || "0".equalsIgnoreCase(value))
validating = false;
this.configDigester = new Digester();
this.configDigester.setNamespaceAware(true);
this.configDigester.setValidating(validating);
this.configDigester.setUseContextClassLoader(true);
this.configDigester.addRuleSet((RuleSet)new ConfigRuleSet());
for (int i = 0; i < this.registrations.length; i += 2) {
URL url = getClass().getResource(this.registrations[i + 1]);
if (url != null)
this.configDigester.register(this.registrations[i], url.toString());
}
String rulesets = getServletConfig().getInitParameter("rulesets");
if (rulesets == null)
rulesets = "";
rulesets = rulesets.trim();
String ruleset = null;
while (rulesets.length() > 0) {
int comma = rulesets.indexOf(",");
if (comma < 0) {
ruleset = rulesets.trim();
rulesets = "";
} else {
ruleset = rulesets.substring(0, comma).trim();
rulesets = rulesets.substring(comma + 1).trim();
}
if (log.isDebugEnabled())
log.debug("Configuring custom Digester Ruleset of type " + ruleset);
try {
RuleSet instance = (RuleSet)RequestUtils.applicationInstance(ruleset);
this.configDigester.addRuleSet(instance);
} catch (Exception e) {
log.error("Exception configuring custom Digester RuleSet", e);
throw new ServletException(e);
}
}
return this.configDigester;
}
protected void initDataSources() throws ServletException {}
protected void initInternal() throws ServletException {
try {
this.internal = MessageResources.getMessageResources(this.internalName);
} catch (MissingResourceException e) {
log.error("Cannot load internal resources from '" + this.internalName + "'", e);
throw new UnavailableException("Cannot load internal resources from '" + this.internalName + "'");
}
}
protected void initOther() throws ServletException {
String value = null;
value = getServletConfig().getInitParameter("config");
if (value != null)
this.config = value;
value = getServletConfig().getInitParameter("debug");
if (value != null)
try {
this.debug = Integer.parseInt(value);
} catch (NumberFormatException e) {
this.debug = 0;
}
value = getServletConfig().getInitParameter("convertNull");
if ("true".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value) || "y".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value))
this.convertNull = true;
if (this.convertNull) {
ConvertUtils.deregister();
ConvertUtils.register((Converter)new BigDecimalConverter(null), BigDecimal.class);
ConvertUtils.register((Converter)new BigIntegerConverter(null), BigInteger.class);
ConvertUtils.register((Converter)new BooleanConverter(null), Boolean.class);
ConvertUtils.register((Converter)new ByteConverter(null), Byte.class);
ConvertUtils.register((Converter)new CharacterConverter(null), Character.class);
ConvertUtils.register((Converter)new DoubleConverter(null), Double.class);
ConvertUtils.register((Converter)new FloatConverter(null), Float.class);
ConvertUtils.register((Converter)new IntegerConverter(null), Integer.class);
ConvertUtils.register((Converter)new LongConverter(null), Long.class);
ConvertUtils.register((Converter)new ShortConverter(null), Short.class);
}
}
protected void initServlet() throws ServletException {
this.servletName = getServletConfig().getServletName();
Digester digester = new Digester();
digester.push(this);
digester.setNamespaceAware(true);
digester.setValidating(false);
for (int i = 0; i < this.registrations.length; i += 2) {
URL url = getClass().getResource(this.registrations[i + 1]);
if (url != null)
digester.register(this.registrations[i], url.toString());
}
digester.addCallMethod("web-app/servlet-mapping", "addServletMapping", 2);
digester.addCallParam("web-app/servlet-mapping/servlet-name", 0);
digester.addCallParam("web-app/servlet-mapping/url-pattern", 1);
if (log.isDebugEnabled())
log.debug("Scanning web.xml for controller servlet mapping");
InputStream input = getServletContext().getResourceAsStream("/WEB-INF/web.xml");
try {
digester.parse(input);
} catch (IOException e) {
log.error(this.internal.getMessage("configWebXml"), e);
throw new ServletException(e);
} catch (SAXException e) {
log.error(this.internal.getMessage("configWebXml"), e);
throw new ServletException(e);
} finally {
if (input != null)
try {
input.close();
} catch (IOException e) {
log.error(this.internal.getMessage("configWebXml"), e);
throw new ServletException(e);
}
}
if (log.isDebugEnabled())
log.debug("Mapping for servlet '" + this.servletName + "' = '" + this.servletMapping + "'");
if (this.servletMapping != null)
getServletContext().setAttribute("org.apache.struts.action.SERVLET_MAPPING", this.servletMapping);
}
protected void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
RequestUtils.selectModule(request, getServletContext());
getRequestProcessor(getModuleConfig(request)).process(request, response);
}
private void defaultControllerConfig(ModuleConfig config) {
String value = null;
ControllerConfig cc = config.getControllerConfig();
value = getServletConfig().getInitParameter("bufferSize");
if (value != null)
cc.setBufferSize(Integer.parseInt(value));
value = getServletConfig().getInitParameter("content");
if (value != null)
cc.setContentType(value);
value = getServletConfig().getInitParameter("locale");
if (value != null)
if ("true".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value)) {
cc.setLocale(true);
} else {
cc.setLocale(false);
}
value = getServletConfig().getInitParameter("maxFileSize");
if (value != null)
cc.setMaxFileSize(value);
value = getServletConfig().getInitParameter("nocache");
if (value != null)
if ("true".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value)) {
cc.setNocache(true);
} else {
cc.setNocache(false);
}
value = getServletConfig().getInitParameter("multipartClass");
if (value != null)
cc.setMultipartClass(value);
value = getServletConfig().getInitParameter("tempDir");
if (value != null)
cc.setTempDir(value);
}
private void defaultFormBeansConfig(ModuleConfig config) {
FormBeanConfig[] fbcs = config.findFormBeanConfigs();
ActionFormBeans afb = new ActionFormBeans();
afb.setFast(false);
for (int i = 0; i < fbcs.length; i++)
afb.addFormBean((ActionFormBean)fbcs[i]);
afb.setFast(true);
getServletContext().setAttribute("org.apache.struts.action.FORM_BEANS", afb);
}
private void defaultForwardsConfig(ModuleConfig config) {
ForwardConfig[] fcs = config.findForwardConfigs();
ActionForwards af = new ActionForwards();
af.setFast(false);
for (int i = 0; i < fcs.length; i++)
af.addForward((ActionForward)fcs[i]);
af.setFast(true);
getServletContext().setAttribute("org.apache.struts.action.FORWARDS", af);
}
private void defaultMappingsConfig(ModuleConfig config) {
ActionConfig[] acs = config.findActionConfigs();
ActionMappings am = new ActionMappings();
am.setServlet(this);
am.setFast(false);
for (int i = 0; i < acs.length; i++)
am.addMapping((ActionMapping)acs[i]);
am.setFast(true);
getServletContext().setAttribute("org.apache.struts.action.MAPPINGS", am);
}
private void defaultMessageResourcesConfig(ModuleConfig config) {
String value = null;
MessageResourcesConfig mrc = config.findMessageResourcesConfig("org.apache.struts.action.MESSAGE");
if (mrc == null) {
mrc = new MessageResourcesConfig();
mrc.setKey("org.apache.struts.action.MESSAGE");
config.addMessageResourcesConfig(mrc);
}
value = getServletConfig().getInitParameter("application");
if (value != null)
mrc.setParameter(value);
value = getServletConfig().getInitParameter("factory");
if (value != null)
mrc.setFactory(value);
value = getServletConfig().getInitParameter("null");
if (value != null)
if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes")) {
mrc.setNull(true);
} else {
mrc.setNull(false);
}
}
}

View File

@@ -0,0 +1,23 @@
package org.apache.struts.action;
import org.apache.struts.upload.MultipartRequestHandler;
public class ActionServletWrapper {
protected transient ActionServlet servlet = null;
public void log(String message, int level) {
this.servlet.log(message, level);
}
public void log(String message) {
this.servlet.log(message);
}
public void setServletFor(MultipartRequestHandler object) {
object.setServlet(this.servlet);
}
public ActionServletWrapper(ActionServlet servlet) {
this.servlet = servlet;
}
}

View File

@@ -0,0 +1,228 @@
package org.apache.struts.action;
import java.lang.reflect.Array;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaClass;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.struts.config.FormBeanConfig;
import org.apache.struts.config.FormPropertyConfig;
public class DynaActionForm extends ActionForm implements DynaBean {
protected DynaActionFormClass dynaClass = null;
protected HashMap dynaValues = new HashMap();
public void initialize(ActionMapping mapping) {
String name = mapping.getName();
if (name == null)
return;
FormBeanConfig config = mapping.getModuleConfig().findFormBeanConfig(name);
if (config == null)
return;
FormPropertyConfig[] props = config.findFormPropertyConfigs();
for (int i = 0; i < props.length; i++)
set(props[i].getName(), props[i].initial());
}
public void reset(ActionMapping mapping, ServletRequest request) {
try {
reset(mapping, (HttpServletRequest)request);
} catch (ClassCastException e) {}
}
public void reset(ActionMapping mapping, HttpServletRequest request) {}
public boolean contains(String name, String key) {
Object value = this.dynaValues.get(name);
if (value == null)
throw new NullPointerException("No mapped value for '" + name + "(" + key + ")'");
if (value instanceof Map)
return ((Map)value).containsKey(key);
throw new IllegalArgumentException("Non-mapped property for '" + name + "(" + key + ")'");
}
public Object get(String name) {
Object value = this.dynaValues.get(name);
if (value != null)
return value;
Class type = getDynaProperty(name).getType();
if (type == null)
throw new NullPointerException("The type for property " + name + " is invalid");
if (!type.isPrimitive())
return value;
if (type == boolean.class)
return Boolean.FALSE;
if (type == byte.class)
return new Byte((byte)0);
if (type == char.class)
return new Character(false);
if (type == double.class)
return new Double(0.0D);
if (type == float.class)
return new Float(0.0F);
if (type == int.class)
return new Integer(0);
if (type == long.class)
return new Long(0L);
if (type == short.class)
return new Short((short)0);
return null;
}
public Object get(String name, int index) {
Object value = this.dynaValues.get(name);
if (value == null)
throw new NullPointerException("No indexed value for '" + name + "[" + index + "]'");
if (value.getClass().isArray())
return Array.get(value, index);
if (value instanceof List)
return ((List)value).get(index);
throw new IllegalArgumentException("Non-indexed property for '" + name + "[" + index + "]'");
}
public Object get(String name, String key) {
Object value = this.dynaValues.get(name);
if (value == null)
throw new NullPointerException("No mapped value for '" + name + "(" + key + ")'");
if (value instanceof Map)
return ((Map)value).get(key);
throw new IllegalArgumentException("Non-mapped property for '" + name + "(" + key + ")'");
}
public DynaClass getDynaClass() {
return this.dynaClass;
}
public Map getMap() {
return this.dynaValues;
}
public void remove(String name, String key) {
Object value = this.dynaValues.get(name);
if (value == null)
throw new NullPointerException("No mapped value for '" + name + "(" + key + ")'");
if (value instanceof Map) {
((Map)value).remove(key);
} else {
throw new IllegalArgumentException("Non-mapped property for '" + name + "(" + key + ")'");
}
}
public void set(String name, Object value) {
DynaProperty descriptor = getDynaProperty(name);
if (descriptor.getType() == null)
throw new NullPointerException("The type for property " + name + " is invalid");
if (value == null) {
if (descriptor.getType().isPrimitive())
throw new NullPointerException("Primitive value for '" + name + "'");
} else if (!isDynaAssignable(descriptor.getType(), value.getClass())) {
throw new ConversionException("Cannot assign value of type '" + value.getClass().getName() + "' to property '" + name + "' of type '" + descriptor.getType().getName() + "'");
}
this.dynaValues.put(name, value);
}
public void set(String name, int index, Object value) {
Object prop = this.dynaValues.get(name);
if (prop == null)
throw new NullPointerException("No indexed value for '" + name + "[" + index + "]'");
if (prop.getClass().isArray()) {
Array.set(prop, index, value);
} else if (prop instanceof List) {
try {
((List)prop).set(index, value);
} catch (ClassCastException e) {
throw new ConversionException(e.getMessage());
}
} else {
throw new IllegalArgumentException("Non-indexed property for '" + name + "[" + index + "]'");
}
}
public void set(String name, String key, Object value) {
Object prop = this.dynaValues.get(name);
if (prop == null)
throw new NullPointerException("No mapped value for '" + name + "(" + key + ")'");
if (prop instanceof Map) {
((Map)prop).put(key, value);
} else {
throw new IllegalArgumentException("Non-mapped property for '" + name + "(" + key + ")'");
}
}
public String toString() {
StringBuffer sb = new StringBuffer("DynaActionForm[dynaClass=");
sb.append(getDynaClass().getName());
DynaProperty[] props = getDynaClass().getDynaProperties();
if (props == null)
props = new DynaProperty[0];
for (int i = 0; i < props.length; i++) {
sb.append(',');
sb.append(props[i].getName());
sb.append('=');
Object value = get(props[i].getName());
if (value == null) {
sb.append("<NULL>");
} else if (value.getClass().isArray()) {
int n = Array.getLength(value);
sb.append("{");
for (int j = 0; j < n; j++) {
if (j > 0)
sb.append(',');
sb.append(Array.get(value, j));
}
sb.append("}");
} else if (value instanceof List) {
int n = ((List)value).size();
sb.append("{");
for (int j = 0; j < n; j++) {
if (j > 0)
sb.append(',');
sb.append(((List)value).get(j));
}
sb.append("}");
} else if (value instanceof Map) {
int n = 0;
Iterator keys = ((Map)value).keySet().iterator();
sb.append("{");
while (keys.hasNext()) {
if (n > 0)
sb.append(',');
n++;
String key = keys.next();
sb.append(key);
sb.append('=');
sb.append(((Map)value).get(key));
}
sb.append("}");
} else {
sb.append(value);
}
}
sb.append("]");
return sb.toString();
}
void setDynaActionFormClass(DynaActionFormClass dynaClass) {
this.dynaClass = dynaClass;
}
protected DynaProperty getDynaProperty(String name) {
DynaProperty descriptor = getDynaClass().getDynaProperty(name);
if (descriptor == null)
throw new IllegalArgumentException("Invalid property name '" + name + "'");
return descriptor;
}
protected boolean isDynaAssignable(Class dest, Class source) {
if (dest.isAssignableFrom(source) || (dest == boolean.class && source == Boolean.class) || (dest == byte.class && source == Byte.class) || (dest == char.class && source == Character.class) || (dest == double.class && source == Double.class) || (dest == float.class && source == Float.class) || (dest == int.class && source == Integer.class) || (dest == long.class && source == Long.class) || (dest == short.class && source == Short.class))
return true;
return false;
}
}

View File

@@ -0,0 +1,126 @@
package org.apache.struts.action;
import java.io.Serializable;
import java.util.HashMap;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaClass;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.struts.config.FormBeanConfig;
import org.apache.struts.config.FormPropertyConfig;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.util.RequestUtils;
public class DynaActionFormClass implements DynaClass, Serializable {
protected transient Class beanClass;
protected FormBeanConfig config;
protected String name;
protected DynaProperty[] properties;
protected HashMap propertiesMap;
private DynaActionFormClass(FormBeanConfig config) {
this.beanClass = null;
this.config = null;
this.name = null;
this.properties = null;
this.propertiesMap = new HashMap();
introspect(config);
}
protected static transient HashMap dynaClasses = new HashMap();
protected static String lock = "";
public String getName() {
return this.name;
}
public DynaProperty getDynaProperty(String name) {
if (name == null)
throw new IllegalArgumentException("No property name specified");
return (DynaProperty)this.propertiesMap.get(name);
}
public DynaProperty[] getDynaProperties() {
return this.properties;
}
public DynaBean newInstance() throws IllegalAccessException, InstantiationException {
DynaActionForm dynaBean = getBeanClass().newInstance();
dynaBean.setDynaActionFormClass(this);
FormPropertyConfig[] props = this.config.findFormPropertyConfigs();
for (int i = 0; i < props.length; i++)
dynaBean.set(props[i].getName(), props[i].initial());
return dynaBean;
}
public String toString() {
StringBuffer sb = new StringBuffer("DynaActionFormBean[name=");
sb.append(this.name);
DynaProperty[] props = getDynaProperties();
if (props == null)
props = new DynaProperty[0];
for (int i = 0; i < props.length; i++) {
sb.append(',');
sb.append(props[i].getName());
sb.append('/');
sb.append(props[i].getType());
}
sb.append("]");
return sb.toString();
}
public static void clear() {
synchronized (lock) {
if (dynaClasses == null)
dynaClasses = new HashMap();
dynaClasses.clear();
}
}
public static DynaActionFormClass createDynaActionFormClass(FormBeanConfig config) {
synchronized (lock) {
if (dynaClasses == null)
dynaClasses = new HashMap();
ModuleConfig moduleConfig = config.getModuleConfig();
String key = config.getName();
if (moduleConfig != null)
key = key + moduleConfig.getPrefix();
DynaActionFormClass dynaClass = (DynaActionFormClass)dynaClasses.get(key);
if (dynaClass == null) {
dynaClass = new DynaActionFormClass(config);
dynaClasses.put(key, dynaClass);
}
return dynaClass;
}
}
protected Class getBeanClass() {
if (this.beanClass == null)
introspect(this.config);
return this.beanClass;
}
protected void introspect(FormBeanConfig config) {
this.config = config;
try {
this.beanClass = RequestUtils.applicationClass(config.getType());
} catch (Throwable t) {
throw new IllegalArgumentException("Cannot instantiate ActionFormBean class '" + config.getType() + "': " + t);
}
if (!DynaActionForm.class.isAssignableFrom(this.beanClass))
throw new IllegalArgumentException("Class '" + config.getType() + "' is not a subclass of " + "'org.apache.struts.action.DynaActionForm'");
this.name = config.getName();
FormPropertyConfig[] descriptors = config.findFormPropertyConfigs();
if (descriptors == null)
descriptors = new FormPropertyConfig[0];
this.properties = new DynaProperty[descriptors.length];
for (int i = 0; i < descriptors.length; i++) {
this.properties[i] = new DynaProperty(descriptors[i].getName(), descriptors[i].getTypeClass());
this.propertiesMap.put(this.properties[i].getName(), this.properties[i]);
}
}
}

View File

@@ -0,0 +1,40 @@
package org.apache.struts.action;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.config.ExceptionConfig;
import org.apache.struts.util.ModuleException;
public class ExceptionHandler {
public ActionForward execute(Exception ex, ExceptionConfig ae, ActionMapping mapping, ActionForm formInstance, HttpServletRequest request, HttpServletResponse response) throws ServletException {
ActionForward forward = null;
ActionError error = null;
String property = null;
if (ae.getPath() != null) {
forward = new ActionForward(ae.getPath());
} else {
forward = mapping.getInputForward();
}
if (ex instanceof ModuleException) {
error = ((ModuleException)ex).getError();
property = ((ModuleException)ex).getProperty();
} else {
error = new ActionError(ae.getKey(), ex.getMessage());
property = error.getKey();
}
request.setAttribute("org.apache.struts.action.EXCEPTION", ex);
storeException(request, property, error, forward, ae.getScope());
return forward;
}
protected void storeException(HttpServletRequest request, String property, ActionError error, ActionForward forward, String scope) {
ActionErrors errors = new ActionErrors();
errors.add(property, error);
if ("request".equals(scope)) {
request.setAttribute("org.apache.struts.action.ERROR", errors);
} else {
request.getSession().setAttribute("org.apache.struts.action.ERROR", errors);
}
}
}

View File

@@ -0,0 +1,10 @@
package org.apache.struts.action;
import javax.servlet.ServletException;
import org.apache.struts.config.ModuleConfig;
public interface PlugIn {
void destroy();
void init(ActionServlet paramActionServlet, ModuleConfig paramModuleConfig) throws ServletException;
}

View File

@@ -0,0 +1,414 @@
package org.apache.struts.action;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.config.ActionConfig;
import org.apache.struts.config.ExceptionConfig;
import org.apache.struts.config.ForwardConfig;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.upload.MultipartRequestWrapper;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.RequestUtils;
public class RequestProcessor {
public static final String INCLUDE_PATH_INFO = "javax.servlet.include.path_info";
public static final String INCLUDE_SERVLET_PATH = "javax.servlet.include.servlet_path";
protected HashMap actions = new HashMap();
protected ModuleConfig appConfig = null;
protected ModuleConfig moduleConfig = null;
protected static Log log = LogFactory.getLog(RequestProcessor.class);
protected ActionServlet servlet = null;
public void destroy() {
synchronized (this.actions) {
Iterator actions = this.actions.values().iterator();
while (actions.hasNext()) {
Action action = actions.next();
action.setServlet(null);
}
this.actions.clear();
}
this.servlet = null;
}
public void init(ActionServlet servlet, ModuleConfig moduleConfig) throws ServletException {
synchronized (this.actions) {
this.actions.clear();
}
this.servlet = servlet;
this.appConfig = moduleConfig;
this.moduleConfig = moduleConfig;
}
public void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
request = processMultipart(request);
String path = processPath(request, response);
if (path == null)
return;
if (log.isDebugEnabled())
log.debug("Processing a '" + request.getMethod() + "' for path '" + path + "'");
processLocale(request, response);
processContent(request, response);
processNoCache(request, response);
if (!processPreprocess(request, response))
return;
ActionMapping mapping = processMapping(request, response, path);
if (mapping == null)
return;
if (!processRoles(request, response, mapping))
return;
ActionForm form = processActionForm(request, response, mapping);
processPopulate(request, response, form, mapping);
if (!processValidate(request, response, form, mapping))
return;
if (!processForward(request, response, mapping))
return;
if (!processInclude(request, response, mapping))
return;
Action action = processActionCreate(request, response, mapping);
if (action == null)
return;
ActionForward forward = processActionPerform(request, response, action, form, mapping);
processForwardConfig(request, response, forward);
}
protected Action processActionCreate(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) throws IOException {
String className = mapping.getType();
if (log.isDebugEnabled())
log.debug(" Looking for Action instance for class " + className);
Action instance = null;
synchronized (this.actions) {
instance = (Action)this.actions.get(className);
if (instance != null) {
if (log.isTraceEnabled())
log.trace(" Returning existing Action instance");
return instance;
}
if (log.isTraceEnabled())
log.trace(" Creating new Action instance");
try {
instance = (Action)RequestUtils.applicationInstance(className);
} catch (Exception e) {
log.error(getInternal().getMessage("actionCreate", mapping.getPath()), e);
response.sendError(500, getInternal().getMessage("actionCreate", mapping.getPath()));
return null;
}
instance.setServlet(this.servlet);
this.actions.put(className, instance);
}
return instance;
}
protected ActionForm processActionForm(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) {
ActionForm instance = RequestUtils.createActionForm(request, mapping, this.moduleConfig, this.servlet);
if (instance == null)
return null;
if (log.isDebugEnabled())
log.debug(" Storing ActionForm bean instance in scope '" + mapping.getScope() + "' under attribute key '" + mapping.getAttribute() + "'");
if ("request".equals(mapping.getScope())) {
request.setAttribute(mapping.getAttribute(), instance);
} else {
HttpSession session = request.getSession();
session.setAttribute(mapping.getAttribute(), instance);
}
return instance;
}
protected void processActionForward(HttpServletRequest request, HttpServletResponse response, ActionForward forward) throws IOException, ServletException {
processForwardConfig(request, response, forward);
}
protected void processForwardConfig(HttpServletRequest request, HttpServletResponse response, ForwardConfig forward) throws IOException, ServletException {
if (forward == null)
return;
if (log.isDebugEnabled())
log.debug("processForwardConfig(" + forward + ")");
String forwardPath = forward.getPath();
String uri = null;
if (forwardPath.startsWith("/")) {
uri = RequestUtils.forwardURL(request, forward);
} else {
uri = forwardPath;
}
if (forward.getRedirect()) {
if (uri.startsWith("/"))
uri = request.getContextPath() + uri;
response.sendRedirect(response.encodeRedirectURL(uri));
} else {
doForward(uri, request, response);
}
}
protected ActionForward processActionPerform(HttpServletRequest request, HttpServletResponse response, Action action, ActionForm form, ActionMapping mapping) throws IOException, ServletException {
try {
return action.execute(mapping, form, request, response);
} catch (Exception e) {
return processException(request, response, e, form, mapping);
}
}
protected void processContent(HttpServletRequest request, HttpServletResponse response) {
String contentType = this.moduleConfig.getControllerConfig().getContentType();
if (contentType != null)
response.setContentType(contentType);
}
protected ActionForward processException(HttpServletRequest request, HttpServletResponse response, Exception exception, ActionForm form, ActionMapping mapping) throws IOException, ServletException {
ExceptionConfig config = mapping.findException(exception.getClass());
if (config == null) {
log.warn(getInternal().getMessage("unhandledException", exception.getClass()));
if (exception instanceof IOException)
throw (IOException)exception;
if (exception instanceof ServletException)
throw (ServletException)exception;
throw new ServletException(exception);
}
try {
ExceptionHandler handler = (ExceptionHandler)RequestUtils.applicationInstance(config.getHandler());
return handler.execute(exception, config, mapping, form, request, response);
} catch (Exception e) {
throw new ServletException(e);
}
}
protected boolean processForward(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) throws IOException, ServletException {
String forward = mapping.getForward();
if (forward == null)
return true;
internalModuleRelativeForward(forward, request, response);
return false;
}
protected boolean processInclude(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) throws IOException, ServletException {
String include = mapping.getInclude();
if (include == null)
return true;
internalModuleRelativeInclude(include, request, response);
return false;
}
protected void processLocale(HttpServletRequest request, HttpServletResponse response) {
if (!this.moduleConfig.getControllerConfig().getLocale())
return;
HttpSession session = request.getSession();
if (session.getAttribute("org.apache.struts.action.LOCALE") != null)
return;
Locale locale = request.getLocale();
if (locale != null) {
if (log.isDebugEnabled())
log.debug(" Setting user locale '" + locale + "'");
session.setAttribute("org.apache.struts.action.LOCALE", locale);
}
}
protected ActionMapping processMapping(HttpServletRequest request, HttpServletResponse response, String path) throws IOException {
ActionMapping mapping = (ActionMapping)this.moduleConfig.findActionConfig(path);
if (mapping != null) {
request.setAttribute("org.apache.struts.action.mapping.instance", mapping);
return mapping;
}
ActionConfig[] configs = this.moduleConfig.findActionConfigs();
for (int i = 0; i < configs.length; i++) {
if (configs[i].getUnknown()) {
mapping = (ActionMapping)configs[i];
request.setAttribute("org.apache.struts.action.mapping.instance", mapping);
return mapping;
}
}
log.error(getInternal().getMessage("processInvalid", path));
response.sendError(400, getInternal().getMessage("processInvalid", path));
return null;
}
protected HttpServletRequest processMultipart(HttpServletRequest request) {
if (!"POST".equalsIgnoreCase(request.getMethod()))
return request;
String contentType = request.getContentType();
if (contentType != null && contentType.startsWith("multipart/form-data"))
return (HttpServletRequest)new MultipartRequestWrapper(request);
return request;
}
protected void processNoCache(HttpServletRequest request, HttpServletResponse response) {
if (this.moduleConfig.getControllerConfig().getNocache()) {
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 1L);
}
}
protected String processPath(HttpServletRequest request, HttpServletResponse response) throws IOException {
String path = null;
path = (String)request.getAttribute("javax.servlet.include.path_info");
if (path == null)
path = request.getPathInfo();
if (path != null && path.length() > 0)
return path;
path = (String)request.getAttribute("javax.servlet.include.servlet_path");
if (path == null)
path = request.getServletPath();
String prefix = this.moduleConfig.getPrefix();
if (!path.startsWith(prefix)) {
log.error(getInternal().getMessage("processPath", request.getRequestURI()));
response.sendError(400, getInternal().getMessage("processPath", request.getRequestURI()));
return null;
}
path = path.substring(prefix.length());
int slash = path.lastIndexOf("/");
int period = path.lastIndexOf(".");
if (period >= 0 && period > slash)
path = path.substring(0, period);
return path;
}
protected void processPopulate(HttpServletRequest request, HttpServletResponse response, ActionForm form, ActionMapping mapping) throws ServletException {
if (form == null)
return;
if (log.isDebugEnabled())
log.debug(" Populating bean properties from this request");
form.setServlet(this.servlet);
form.reset(mapping, request);
if (mapping.getMultipartClass() != null)
request.setAttribute("org.apache.struts.action.mapping.multipartclass", mapping.getMultipartClass());
RequestUtils.populate(form, mapping.getPrefix(), mapping.getSuffix(), request);
if (request.getParameter("org.apache.struts.taglib.html.CANCEL") != null || request.getParameter("org.apache.struts.taglib.html.CANCEL.x") != null)
request.setAttribute("org.apache.struts.action.CANCEL", Boolean.TRUE);
}
protected boolean processPreprocess(HttpServletRequest request, HttpServletResponse response) {
return true;
}
protected boolean processRoles(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) throws IOException, ServletException {
String[] roles = mapping.getRoleNames();
if (roles == null || roles.length < 1)
return true;
for (int i = 0; i < roles.length; i++) {
if (request.isUserInRole(roles[i])) {
if (log.isDebugEnabled())
log.debug(" User '" + request.getRemoteUser() + "' has role '" + roles[i] + "', granting access");
return true;
}
}
if (log.isDebugEnabled())
log.debug(" User '" + request.getRemoteUser() + "' does not have any required role, denying access");
response.sendError(400, getInternal().getMessage("notAuthorized", mapping.getPath()));
return false;
}
protected boolean processValidate(HttpServletRequest request, HttpServletResponse response, ActionForm form, ActionMapping mapping) throws IOException, ServletException {
if (form == null)
return true;
if (request.getAttribute("org.apache.struts.action.CANCEL") != null) {
if (log.isDebugEnabled())
log.debug(" Cancelled transaction, skipping validation");
return true;
}
if (!mapping.getValidate())
return true;
if (log.isDebugEnabled())
log.debug(" Validating input form properties");
ActionErrors errors = form.validate(mapping, request);
if (errors == null || errors.isEmpty()) {
if (log.isTraceEnabled())
log.trace(" No errors detected, accepting input");
return true;
}
if (form.getMultipartRequestHandler() != null) {
if (log.isTraceEnabled())
log.trace(" Rolling back multipart request");
form.getMultipartRequestHandler().rollback();
}
String input = mapping.getInput();
if (input == null) {
if (log.isTraceEnabled())
log.trace(" Validation failed but no input form available");
response.sendError(500, getInternal().getMessage("noInput", mapping.getPath()));
return false;
}
if (log.isDebugEnabled())
log.debug(" Validation failed, returning to '" + input + "'");
request.setAttribute("org.apache.struts.action.ERROR", errors);
if (this.moduleConfig.getControllerConfig().getInputForward()) {
ForwardConfig forward = mapping.findForward(input);
processForwardConfig(request, response, forward);
} else {
internalModuleRelativeForward(input, request, response);
}
return false;
}
protected void internalModuleRelativeForward(String uri, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
uri = this.moduleConfig.getPrefix() + uri;
if (log.isDebugEnabled())
log.debug(" Delegating via forward to '" + uri + "'");
doForward(uri, request, response);
}
protected void internalModuleRelativeInclude(String uri, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
uri = this.moduleConfig.getPrefix() + uri;
if (log.isDebugEnabled())
log.debug(" Delegating via include to '" + uri + "'");
doInclude(uri, request, response);
}
protected void doForward(String uri, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
if (request instanceof MultipartRequestWrapper)
request = ((MultipartRequestWrapper)request).getRequest();
RequestDispatcher rd = getServletContext().getRequestDispatcher(uri);
if (rd == null) {
response.sendError(500, getInternal().getMessage("requestDispatcher", uri));
return;
}
rd.forward((ServletRequest)request, (ServletResponse)response);
}
protected void doInclude(String uri, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
if (request instanceof MultipartRequestWrapper)
request = ((MultipartRequestWrapper)request).getRequest();
RequestDispatcher rd = getServletContext().getRequestDispatcher(uri);
if (rd == null) {
response.sendError(500, getInternal().getMessage("requestDispatcher", uri));
return;
}
rd.include((ServletRequest)request, (ServletResponse)response);
}
public int getDebug() {
return this.servlet.getDebug();
}
protected MessageResources getInternal() {
return this.servlet.getInternal();
}
protected ServletContext getServletContext() {
return this.servlet.getServletContext();
}
protected void log(String message) {
this.servlet.log(message);
}
protected void log(String message, Throwable exception) {
this.servlet.log(message, exception);
}
}

View File

@@ -0,0 +1,344 @@
package org.apache.struts.config;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
public class ActionConfig implements Serializable {
protected boolean configured = false;
protected HashMap exceptions = new HashMap();
protected HashMap forwards = new HashMap();
protected ModuleConfig moduleConfig = null;
public ModuleConfig getApplicationConfig() {
return getModuleConfig();
}
public ModuleConfig getModuleConfig() {
return this.moduleConfig;
}
public void setApplicationConfig(ModuleConfig moduleConfig) {
setModuleConfig(moduleConfig);
}
public void setModuleConfig(ModuleConfig moduleConfig) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.moduleConfig = moduleConfig;
}
protected String attribute = null;
public String getAttribute() {
if (this.attribute == null)
return this.name;
return this.attribute;
}
public void setAttribute(String attribute) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.attribute = attribute;
}
protected String forward = null;
public String getForward() {
return this.forward;
}
public void setForward(String forward) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.forward = forward;
}
protected String include = null;
public String getInclude() {
return this.include;
}
public void setInclude(String include) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.include = include;
}
protected String input = null;
public String getInput() {
return this.input;
}
public void setInput(String input) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.input = input;
}
protected String multipartClass = null;
public String getMultipartClass() {
return this.multipartClass;
}
public void setMultipartClass(String multipartClass) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.multipartClass = multipartClass;
}
protected String name = null;
public String getName() {
return this.name;
}
public void setName(String name) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.name = name;
}
protected String parameter = null;
public String getParameter() {
return this.parameter;
}
public void setParameter(String parameter) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.parameter = parameter;
}
protected String path = null;
public String getPath() {
return this.path;
}
public void setPath(String path) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.path = path;
}
protected String prefix = null;
public String getPrefix() {
return this.prefix;
}
public void setPrefix(String prefix) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.prefix = prefix;
}
protected String roles = null;
public String getRoles() {
return this.roles;
}
public void setRoles(String roles) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.roles = roles;
if (roles == null) {
this.roleNames = new String[0];
return;
}
ArrayList list = new ArrayList();
while (true) {
int comma = roles.indexOf(',');
if (comma < 0)
break;
list.add(roles.substring(0, comma).trim());
roles = roles.substring(comma + 1);
}
roles = roles.trim();
if (roles.length() > 0)
list.add(roles);
this.roleNames = list.<String>toArray(new String[list.size()]);
}
protected String[] roleNames = new String[0];
public String[] getRoleNames() {
return this.roleNames;
}
protected String scope = "session";
public String getScope() {
return this.scope;
}
public void setScope(String scope) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.scope = scope;
}
protected String suffix = null;
public String getSuffix() {
return this.suffix;
}
public void setSuffix(String suffix) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.suffix = suffix;
}
protected String type = null;
public String getType() {
return this.type;
}
public void setType(String type) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.type = type;
}
protected boolean unknown = false;
public boolean getUnknown() {
return this.unknown;
}
public void setUnknown(boolean unknown) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.unknown = unknown;
}
protected boolean validate = true;
public boolean getValidate() {
return this.validate;
}
public void setValidate(boolean validate) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.validate = validate;
}
public void addExceptionConfig(ExceptionConfig config) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.exceptions.put(config.getType(), config);
}
public void addForwardConfig(ForwardConfig config) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.forwards.put(config.getName(), config);
}
public ExceptionConfig findExceptionConfig(String type) {
return (ExceptionConfig)this.exceptions.get(type);
}
public ExceptionConfig[] findExceptionConfigs() {
ExceptionConfig[] results = new ExceptionConfig[this.exceptions.size()];
return (ExceptionConfig[])this.exceptions.values().toArray((Object[])results);
}
public ForwardConfig findForwardConfig(String name) {
return (ForwardConfig)this.forwards.get(name);
}
public ForwardConfig[] findForwardConfigs() {
ForwardConfig[] results = new ForwardConfig[this.forwards.size()];
return (ForwardConfig[])this.forwards.values().toArray((Object[])results);
}
public void freeze() {
this.configured = true;
ExceptionConfig[] econfigs = findExceptionConfigs();
for (int i = 0; i < econfigs.length; i++)
econfigs[i].freeze();
ForwardConfig[] fconfigs = findForwardConfigs();
for (int j = 0; j < fconfigs.length; j++)
fconfigs[j].freeze();
}
public void removeExceptionConfig(ExceptionConfig config) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.exceptions.remove(config.getType());
}
public void removeForwardConfig(ForwardConfig config) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.forwards.remove(config.getName());
}
public String toString() {
StringBuffer sb = new StringBuffer("ActionConfig[");
sb.append("path=");
sb.append(this.path);
if (this.attribute != null) {
sb.append(",attribute=");
sb.append(this.attribute);
}
if (this.forward != null) {
sb.append(",forward=");
sb.append(this.forward);
}
if (this.include != null) {
sb.append(",include=");
sb.append(this.include);
}
if (this.input != null) {
sb.append(",input=");
sb.append(this.input);
}
if (this.multipartClass != null) {
sb.append(",multipartClass=");
sb.append(this.multipartClass);
}
if (this.name != null) {
sb.append(",name=");
sb.append(this.name);
}
if (this.parameter != null) {
sb.append(",parameter=");
sb.append(this.parameter);
}
if (this.prefix != null) {
sb.append(",prefix=");
sb.append(this.prefix);
}
if (this.roles != null) {
sb.append(",roles=");
sb.append(this.roles);
}
if (this.scope != null) {
sb.append(",scope=");
sb.append(this.scope);
}
if (this.suffix != null) {
sb.append(",suffix=");
sb.append(this.suffix);
}
if (this.type != null) {
sb.append(",type=");
sb.append(this.type);
}
return sb.toString();
}
}

View File

@@ -0,0 +1,22 @@
package org.apache.struts.config;
import org.apache.commons.digester.AbstractObjectCreationFactory;
import org.apache.struts.util.RequestUtils;
import org.xml.sax.Attributes;
final class ActionMappingFactory extends AbstractObjectCreationFactory {
public Object createObject(Attributes attributes) {
String className = attributes.getValue("className");
if (className == null) {
ModuleConfig mc = (ModuleConfig)this.digester.peek();
className = mc.getActionMappingClass();
}
Object actionMapping = null;
try {
actionMapping = RequestUtils.applicationInstance(className);
} catch (Exception e) {
this.digester.getLogger().error("ActionMappingFactory.createObject: ", e);
}
return actionMapping;
}
}

View File

@@ -0,0 +1,11 @@
package org.apache.struts.config;
import org.apache.commons.digester.Rule;
import org.xml.sax.Attributes;
final class AddDataSourcePropertyRule extends Rule {
public void begin(Attributes attributes) throws Exception {
DataSourceConfig dsc = (DataSourceConfig)this.digester.peek();
dsc.addProperty(attributes.getValue("property"), attributes.getValue("value"));
}
}

View File

@@ -0,0 +1,14 @@
package org.apache.struts.config;
import org.apache.struts.config.impl.ModuleConfigImpl;
public class ApplicationConfig extends ModuleConfigImpl {
public ApplicationConfig(String prefix) {
super(prefix);
this.prefix = prefix;
}
public ApplicationConfig(ModuleConfigImpl moduleConfig) {
super(moduleConfig);
}
}

View File

@@ -0,0 +1,55 @@
package org.apache.struts.config;
import org.apache.commons.digester.Digester;
import org.apache.commons.digester.ObjectCreationFactory;
import org.apache.commons.digester.RuleSetBase;
public class ConfigRuleSet extends RuleSetBase {
public void addRuleInstances(Digester digester) {
digester.addObjectCreate("struts-config/data-sources/data-source", "org.apache.struts.config.DataSourceConfig", "className");
digester.addSetProperties("struts-config/data-sources/data-source");
digester.addSetNext("struts-config/data-sources/data-source", "addDataSourceConfig", "org.apache.struts.config.DataSourceConfig");
digester.addRule("struts-config/data-sources/data-source/set-property", new AddDataSourcePropertyRule());
digester.addRule("struts-config/action-mappings", new SetActionMappingClassRule());
digester.addFactoryCreate("struts-config/action-mappings/action", (ObjectCreationFactory)new ActionMappingFactory());
digester.addSetProperties("struts-config/action-mappings/action");
digester.addSetNext("struts-config/action-mappings/action", "addActionConfig", "org.apache.struts.config.ActionConfig");
digester.addSetProperty("struts-config/action-mappings/action/set-property", "property", "value");
digester.addObjectCreate("struts-config/action-mappings/action/exception", "org.apache.struts.config.ExceptionConfig", "className");
digester.addSetProperties("struts-config/action-mappings/action/exception");
digester.addSetNext("struts-config/action-mappings/action/exception", "addExceptionConfig", "org.apache.struts.config.ExceptionConfig");
digester.addSetProperty("struts-config/action-mappings/action/exception/set-property", "property", "value");
digester.addObjectCreate("struts-config/action-mappings/action/forward", "org.apache.struts.action.ActionForward", "className");
digester.addSetProperties("struts-config/action-mappings/action/forward");
digester.addSetNext("struts-config/action-mappings/action/forward", "addForwardConfig", "org.apache.struts.config.ForwardConfig");
digester.addSetProperty("struts-config/action-mappings/action/forward/set-property", "property", "value");
digester.addObjectCreate("struts-config/controller", "org.apache.struts.config.ControllerConfig", "className");
digester.addSetProperties("struts-config/controller");
digester.addSetNext("struts-config/controller", "setControllerConfig", "org.apache.struts.config.ControllerConfig");
digester.addSetProperty("struts-config/controller/set-property", "property", "value");
digester.addObjectCreate("struts-config/form-beans/form-bean", "org.apache.struts.action.ActionFormBean", "className");
digester.addSetProperties("struts-config/form-beans/form-bean");
digester.addSetNext("struts-config/form-beans/form-bean", "addFormBeanConfig", "org.apache.struts.config.FormBeanConfig");
digester.addObjectCreate("struts-config/form-beans/form-bean/form-property", "org.apache.struts.config.FormPropertyConfig", "className");
digester.addSetProperties("struts-config/form-beans/form-bean/form-property");
digester.addSetNext("struts-config/form-beans/form-bean/form-property", "addFormPropertyConfig", "org.apache.struts.config.FormPropertyConfig");
digester.addSetProperty("struts-config/form-beans/form-bean/form-property/set-property", "property", "value");
digester.addSetProperty("struts-config/form-beans/form-bean/set-property", "property", "value");
digester.addObjectCreate("struts-config/global-exceptions/exception", "org.apache.struts.config.ExceptionConfig", "className");
digester.addSetProperties("struts-config/global-exceptions/exception");
digester.addSetNext("struts-config/global-exceptions/exception", "addExceptionConfig", "org.apache.struts.config.ExceptionConfig");
digester.addSetProperty("struts-config/global-exceptions/exception/set-property", "property", "value");
digester.addObjectCreate("struts-config/global-forwards/forward", "org.apache.struts.action.ActionForward", "className");
digester.addSetProperties("struts-config/global-forwards/forward");
digester.addSetNext("struts-config/global-forwards/forward", "addForwardConfig", "org.apache.struts.config.ForwardConfig");
digester.addSetProperty("struts-config/global-forwards/forward/set-property", "property", "value");
digester.addObjectCreate("struts-config/message-resources", "org.apache.struts.config.MessageResourcesConfig", "className");
digester.addSetProperties("struts-config/message-resources");
digester.addSetNext("struts-config/message-resources", "addMessageResourcesConfig", "org.apache.struts.config.MessageResourcesConfig");
digester.addSetProperty("struts-config/message-resources/set-property", "property", "value");
digester.addObjectCreate("struts-config/plug-in", "org.apache.struts.config.PlugInConfig");
digester.addSetProperties("struts-config/plug-in");
digester.addSetNext("struts-config/plug-in", "addPlugInConfig", "org.apache.struts.config.PlugInConfig");
digester.addRule("struts-config/plug-in/set-property", new PlugInSetPropertyRule());
}
}

View File

@@ -0,0 +1,203 @@
package org.apache.struts.config;
import java.io.Serializable;
public class ControllerConfig implements Serializable {
protected boolean configured = false;
protected int bufferSize = 4096;
public int getBufferSize() {
return this.bufferSize;
}
public void setBufferSize(int bufferSize) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.bufferSize = bufferSize;
}
protected String contentType = "text/html";
public String getContentType() {
return this.contentType;
}
public void setContentType(String contentType) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.contentType = contentType;
}
protected int debug = 0;
public int getDebug() {
return this.debug;
}
public void setDebug(int debug) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.debug = debug;
}
protected String forwardPattern = null;
public String getForwardPattern() {
return this.forwardPattern;
}
public void setForwardPattern(String forwardPattern) {
this.forwardPattern = forwardPattern;
}
protected boolean inputForward = false;
public boolean getInputForward() {
return this.inputForward;
}
public void setInputForward(boolean inputForward) {
this.inputForward = inputForward;
}
protected boolean locale = true;
public boolean getLocale() {
return this.locale;
}
public void setLocale(boolean locale) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.locale = locale;
}
protected String maxFileSize = "250M";
public String getMaxFileSize() {
return this.maxFileSize;
}
public void setMaxFileSize(String maxFileSize) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.maxFileSize = maxFileSize;
}
protected String memFileSize = "256K";
public String getMemFileSize() {
return this.memFileSize;
}
public void setMemFileSize(String memFileSize) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.memFileSize = memFileSize;
}
protected String multipartClass = "org.apache.struts.upload.CommonsMultipartRequestHandler";
public String getMultipartClass() {
return this.multipartClass;
}
public void setMultipartClass(String multipartClass) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.multipartClass = multipartClass;
}
protected boolean nocache = false;
public boolean getNocache() {
return this.nocache;
}
public void setNocache(boolean nocache) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.nocache = nocache;
}
protected String pagePattern = null;
public String getPagePattern() {
return this.pagePattern;
}
public void setPagePattern(String pagePattern) {
this.pagePattern = pagePattern;
}
protected String processorClass = "org.apache.struts.action.RequestProcessor";
public String getProcessorClass() {
return this.processorClass;
}
public void setProcessorClass(String processorClass) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.processorClass = processorClass;
}
protected String tempDir = null;
public String getTempDir() {
return this.tempDir;
}
public void setTempDir(String tempDir) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.tempDir = tempDir;
}
public void freeze() {
this.configured = true;
}
public String toString() {
StringBuffer sb = new StringBuffer("ControllerConfig[");
sb.append("bufferSize=");
sb.append(this.bufferSize);
if (this.contentType != null) {
sb.append(",contentType=");
sb.append(this.contentType);
}
if (this.forwardPattern != null) {
sb.append(",forwardPattern=");
sb.append(this.forwardPattern);
}
sb.append(",inputForward=");
sb.append(this.inputForward);
sb.append(",locale=");
sb.append(this.locale);
if (this.maxFileSize != null) {
sb.append(",maxFileSize=");
sb.append(this.maxFileSize);
}
if (this.memFileSize != null) {
sb.append(",memFileSize=");
sb.append(this.memFileSize);
}
sb.append(",multipartClass=");
sb.append(this.multipartClass);
sb.append(",nocache=");
sb.append(this.nocache);
if (this.pagePattern != null) {
sb.append(",pagePattern=");
sb.append(this.pagePattern);
}
sb.append(",processorClass=");
sb.append(this.processorClass);
if (this.tempDir != null) {
sb.append(",tempDir=");
sb.append(this.tempDir);
}
sb.append("]");
return sb.toString();
}
}

View File

@@ -0,0 +1,69 @@
package org.apache.struts.config;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class DataSourceConfig implements Serializable {
protected boolean configured = false;
protected String key = "org.apache.struts.action.DATA_SOURCE";
public String getKey() {
return this.key;
}
public void setKey(String key) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.key = key;
}
protected HashMap properties = new HashMap();
public Map getProperties() {
return this.properties;
}
protected String type = "org.apache.struts.util.GenericDataSource";
public String getType() {
return this.type;
}
public void setType(String type) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.type = type;
}
public void addProperty(String name, String value) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.properties.put(name, value);
}
public void freeze() {
this.configured = true;
}
public String toString() {
StringBuffer sb = new StringBuffer("DataSourceConfig[");
sb.append("key=");
sb.append(this.key);
sb.append(",type=");
sb.append(this.type);
Iterator names = this.properties.keySet().iterator();
while (names.hasNext()) {
String name = names.next();
String value = (String)this.properties.get(name);
sb.append(',');
sb.append(name);
sb.append('=');
sb.append(value);
}
sb.append("]");
return sb.toString();
}
}

View File

@@ -0,0 +1,101 @@
package org.apache.struts.config;
import java.io.Serializable;
public class ExceptionConfig implements Serializable {
protected boolean configured = false;
protected String bundle = null;
public String getBundle() {
return this.bundle;
}
public void setBundle(String bundle) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.bundle = bundle;
}
protected String handler = "org.apache.struts.action.ExceptionHandler";
public String getHandler() {
return this.handler;
}
public void setHandler(String handler) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.handler = handler;
}
protected String key = null;
public String getKey() {
return this.key;
}
public void setKey(String key) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.key = key;
}
protected String path = null;
public String getPath() {
return this.path;
}
public void setPath(String path) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.path = path;
}
protected String scope = "request";
public String getScope() {
return this.scope;
}
public void setScope(String scope) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.scope = scope;
}
protected String type = null;
public String getType() {
return this.type;
}
public void setType(String type) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.type = type;
}
public void freeze() {
this.configured = true;
}
public String toString() {
StringBuffer sb = new StringBuffer("ExceptionConfig[");
sb.append("type=");
sb.append(this.type);
if (this.bundle != null) {
sb.append(",bundle=");
sb.append(this.bundle);
}
sb.append(",key=");
sb.append(this.key);
sb.append(",path=");
sb.append(this.path);
sb.append(",scope=");
sb.append(this.scope);
sb.append("]");
return sb.toString();
}
}

View File

@@ -0,0 +1,120 @@
package org.apache.struts.config;
import java.io.Serializable;
import java.util.HashMap;
import org.apache.struts.action.DynaActionForm;
public class FormBeanConfig implements Serializable {
protected boolean configured = false;
protected HashMap formProperties = new HashMap();
protected boolean dynamic = false;
public boolean getDynamic() {
return this.dynamic;
}
public void setDynamic(boolean dynamic) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
}
protected ModuleConfig moduleConfig = null;
public ModuleConfig getModuleConfig() {
return this.moduleConfig;
}
public void setModuleConfig(ModuleConfig moduleConfig) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.moduleConfig = moduleConfig;
}
protected String name = null;
public String getName() {
return this.name;
}
public void setName(String name) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.name = name;
}
protected String type = null;
public String getType() {
return this.type;
}
public void setType(String type) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.type = type;
Class dynaBeanClass = DynaActionForm.class;
Class formBeanClass = formBeanClass();
if (formBeanClass != null) {
if (dynaBeanClass.isAssignableFrom(formBeanClass)) {
this.dynamic = true;
} else {
this.dynamic = false;
}
} else {
this.dynamic = false;
}
}
public void addFormPropertyConfig(FormPropertyConfig config) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
if (this.formProperties.containsKey(config.getName()))
throw new IllegalArgumentException("Property " + config.getName() + " already defined");
this.formProperties.put(config.getName(), config);
}
public FormPropertyConfig findFormPropertyConfig(String name) {
return (FormPropertyConfig)this.formProperties.get(name);
}
public FormPropertyConfig[] findFormPropertyConfigs() {
FormPropertyConfig[] results = new FormPropertyConfig[this.formProperties.size()];
return (FormPropertyConfig[])this.formProperties.values().toArray((Object[])results);
}
public void freeze() {
this.configured = true;
FormPropertyConfig[] fpconfigs = findFormPropertyConfigs();
for (int i = 0; i < fpconfigs.length; i++)
fpconfigs[i].freeze();
}
public void removeFormPropertyConfig(FormPropertyConfig config) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.formProperties.remove(config.getName());
}
public String toString() {
StringBuffer sb = new StringBuffer("FormBeanConfig[");
sb.append("name=");
sb.append(this.name);
sb.append(",type=");
sb.append(this.type);
sb.append("]");
return sb.toString();
}
protected Class formBeanClass() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null)
classLoader = getClass().getClassLoader();
try {
return classLoader.loadClass(getType());
} catch (Exception e) {
return null;
}
}
}

View File

@@ -0,0 +1,153 @@
package org.apache.struts.config;
import java.io.Serializable;
import java.lang.reflect.Array;
import org.apache.commons.beanutils.ConvertUtils;
public class FormPropertyConfig implements Serializable {
public FormPropertyConfig() {}
public FormPropertyConfig(String name, String type, String initial) {
this(name, type, initial, 0);
}
public FormPropertyConfig(String name, String type, String initial, int size) {
setName(name);
setType(type);
setInitial(initial);
setSize(size);
}
protected boolean configured = false;
protected String initial = null;
public String getInitial() {
return this.initial;
}
public void setInitial(String initial) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.initial = initial;
}
protected String name = null;
public String getName() {
return this.name;
}
public void setName(String name) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.name = name;
}
protected int size = 0;
public int getSize() {
return this.size;
}
public void setSize(int size) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
if (size < 0)
throw new IllegalArgumentException("size < 0");
this.size = size;
}
protected String type = null;
public String getType() {
return this.type;
}
public void setType(String type) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.type = type;
}
public Class getTypeClass() {
String baseType = getType();
boolean indexed = false;
if (baseType.endsWith("[]")) {
baseType = baseType.substring(0, baseType.length() - 2);
indexed = true;
}
Class baseClass = null;
if ("boolean".equals(baseType)) {
baseClass = boolean.class;
} else if ("byte".equals(baseType)) {
Class clazz = byte.class;
} else if ("char".equals(baseType)) {
Class clazz = char.class;
} else if ("double".equals(baseType)) {
Class clazz = double.class;
} else if ("float".equals(baseType)) {
Class clazz = float.class;
} else if ("int".equals(baseType)) {
Class clazz = int.class;
} else if ("long".equals(baseType)) {
Class clazz = long.class;
} else if ("short".equals(baseType)) {
Class clazz = short.class;
} else {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null)
classLoader = getClass().getClassLoader();
try {
baseClass = (Class)classLoader.loadClass(baseType);
} catch (Throwable t) {
baseClass = null;
}
}
if (indexed)
return Array.newInstance(baseClass, 0).getClass();
return baseClass;
}
public Object initial() {
Object initialValue = null;
try {
Class clazz = getTypeClass();
if (clazz.isArray()) {
if (this.initial != null) {
initialValue = ConvertUtils.convert(this.initial, clazz);
} else {
initialValue = Array.newInstance(clazz.getComponentType(), this.size);
for (int i = 0; i < this.size; i++) {
try {
Array.set(initialValue, i, clazz.getComponentType().newInstance());
} catch (Throwable t) {}
}
}
} else if (this.initial != null) {
initialValue = ConvertUtils.convert(this.initial, clazz);
} else {
initialValue = clazz.newInstance();
}
} catch (Throwable t) {
initialValue = null;
}
return initialValue;
}
public void freeze() {
this.configured = true;
}
public String toString() {
StringBuffer sb = new StringBuffer("FormPropertyConfig[");
sb.append("name=");
sb.append(this.name);
sb.append(",type=");
sb.append(this.type);
sb.append(",initial=");
sb.append(this.initial);
sb.append("]");
return sb.toString();
}
}

View File

@@ -0,0 +1,88 @@
package org.apache.struts.config;
import java.io.Serializable;
public class ForwardConfig implements Serializable {
public ForwardConfig() {}
public ForwardConfig(String name, String path, boolean redirect) {
setName(name);
setPath(path);
setRedirect(redirect);
}
public ForwardConfig(String name, String path, boolean redirect, boolean contextRelative) {
setName(name);
setPath(path);
setRedirect(redirect);
setContextRelative(contextRelative);
}
protected boolean configured = false;
protected boolean contextRelative = false;
public boolean getContextRelative() {
return this.contextRelative;
}
public void setContextRelative(boolean contextRelative) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.contextRelative = contextRelative;
}
protected String name = null;
public String getName() {
return this.name;
}
public void setName(String name) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.name = name;
}
protected String path = null;
public String getPath() {
return this.path;
}
public void setPath(String path) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.path = path;
}
protected boolean redirect = false;
public boolean getRedirect() {
return this.redirect;
}
public void setRedirect(boolean redirect) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.redirect = redirect;
}
public void freeze() {
this.configured = true;
}
public String toString() {
StringBuffer sb = new StringBuffer("ForwardConfig[");
sb.append("name=");
sb.append(this.name);
sb.append(",path=");
sb.append(this.path);
sb.append(",redirect=");
sb.append(this.redirect);
sb.append(",contextRelative=");
sb.append(this.contextRelative);
sb.append("]");
return sb.toString();
}
}

View File

@@ -0,0 +1,71 @@
package org.apache.struts.config;
import java.io.Serializable;
public class MessageResourcesConfig implements Serializable {
protected boolean configured = false;
protected String factory = "org.apache.struts.util.PropertyMessageResourcesFactory";
public String getFactory() {
return this.factory;
}
public void setFactory(String factory) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.factory = factory;
}
protected String key = "org.apache.struts.action.MESSAGE";
public String getKey() {
return this.key;
}
public void setKey(String key) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.key = key;
}
protected boolean nullValue = true;
public boolean getNull() {
return this.nullValue;
}
public void setNull(boolean nullValue) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.nullValue = nullValue;
}
protected String parameter = null;
public String getParameter() {
return this.parameter;
}
public void setParameter(String parameter) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.parameter = parameter;
}
public void freeze() {
this.configured = true;
}
public String toString() {
StringBuffer sb = new StringBuffer("MessageResourcesConfig[");
sb.append("factory=");
sb.append(this.factory);
sb.append(",null=");
sb.append(this.nullValue);
sb.append(",parameter=");
sb.append(this.parameter);
sb.append("]");
return sb.toString();
}
}

View File

@@ -0,0 +1,71 @@
package org.apache.struts.config;
public interface ModuleConfig {
boolean getConfigured();
ControllerConfig getControllerConfig();
void setControllerConfig(ControllerConfig paramControllerConfig);
String getPrefix();
void setPrefix(String paramString);
String getActionMappingClass();
void setActionMappingClass(String paramString);
void addActionConfig(ActionConfig paramActionConfig);
void addDataSourceConfig(DataSourceConfig paramDataSourceConfig);
void addExceptionConfig(ExceptionConfig paramExceptionConfig);
void addFormBeanConfig(FormBeanConfig paramFormBeanConfig);
void addForwardConfig(ForwardConfig paramForwardConfig);
void addMessageResourcesConfig(MessageResourcesConfig paramMessageResourcesConfig);
void addPlugInConfig(PlugInConfig paramPlugInConfig);
ActionConfig findActionConfig(String paramString);
ActionConfig[] findActionConfigs();
DataSourceConfig findDataSourceConfig(String paramString);
DataSourceConfig[] findDataSourceConfigs();
ExceptionConfig findExceptionConfig(String paramString);
ExceptionConfig[] findExceptionConfigs();
FormBeanConfig findFormBeanConfig(String paramString);
FormBeanConfig[] findFormBeanConfigs();
ForwardConfig findForwardConfig(String paramString);
ForwardConfig[] findForwardConfigs();
MessageResourcesConfig findMessageResourcesConfig(String paramString);
MessageResourcesConfig[] findMessageResourcesConfigs();
PlugInConfig[] findPlugInConfigs();
void freeze();
void removeActionConfig(ActionConfig paramActionConfig);
void removeExceptionConfig(ExceptionConfig paramExceptionConfig);
void removeDataSourceConfig(DataSourceConfig paramDataSourceConfig);
void removeFormBeanConfig(FormBeanConfig paramFormBeanConfig);
void removeForwardConfig(ForwardConfig paramForwardConfig);
void removeMessageResourcesConfig(MessageResourcesConfig paramMessageResourcesConfig);
}

View File

@@ -0,0 +1,36 @@
package org.apache.struts.config;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.util.RequestUtils;
public abstract class ModuleConfigFactory {
public abstract ModuleConfig createModuleConfig(String paramString);
public static String getFactoryClass() {
return factoryClass;
}
public static void setFactoryClass(String factoryClass) {
ModuleConfigFactory.factoryClass = factoryClass;
clazz = null;
}
public static ModuleConfigFactory createFactory() {
try {
if (clazz == null)
clazz = RequestUtils.applicationClass(factoryClass);
ModuleConfigFactory factory = clazz.newInstance();
return factory;
} catch (Throwable t) {
LOG.error("ModuleConfigFactory.createFactory", t);
return null;
}
}
protected static Class clazz = null;
private static Log LOG = LogFactory.getLog(ModuleConfigFactory.class);
protected static String factoryClass = "org.apache.struts.config.impl.DefaultModuleConfigFactory";
}

View File

@@ -0,0 +1,35 @@
package org.apache.struts.config;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
public class PlugInConfig implements Serializable {
protected boolean configured = false;
protected Map properties = new HashMap();
protected String className = null;
public String getClassName() {
return this.className;
}
public void setClassName(String className) {
this.className = className;
}
public void addProperty(String name, String value) {
if (this.configured)
throw new IllegalStateException("Configuration is frozen");
this.properties.put(name, value);
}
public void freeze() {
this.configured = true;
}
public Map getProperties() {
return this.properties;
}
}

View File

@@ -0,0 +1,11 @@
package org.apache.struts.config;
import org.apache.commons.digester.Rule;
import org.xml.sax.Attributes;
final class PlugInSetPropertyRule extends Rule {
public void begin(Attributes attributes) throws Exception {
PlugInConfig plugInConfig = (PlugInConfig)this.digester.peek();
plugInConfig.addProperty(attributes.getValue("property"), attributes.getValue("value"));
}
}

Some files were not shown because too many files have changed in this diff Show More