mirror of
https://github.com/haraldk/TwelveMonkeys.git
synced 2026-04-05 00:00:01 -04:00
Clean-up of sandbox, rearranging everything.
Added a couple of files that was never commited.
This commit is contained in:
1757
sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/DebugUtil.java
Executable file
1757
sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/DebugUtil.java
Executable file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,456 @@
|
||||
/*
|
||||
* Copyright (c) 2009, Harald Kuhr
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name "TwelveMonkeys" nor the
|
||||
* names of its contributors may be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
package com.twelvemonkeys.util;
|
||||
|
||||
import java.beans.BeanInfo;
|
||||
import java.beans.IntrospectionException;
|
||||
import java.beans.Introspector;
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.io.ObjectStreamException;
|
||||
import java.io.Serializable;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* MappedBeanFactory
|
||||
*
|
||||
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
|
||||
* @author last modified by $Author: haku $
|
||||
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-sandbox/src/main/java/com/twelvemonkeys/sandbox/MappedBeanFactory.java#1 $
|
||||
*/
|
||||
public final class MappedBeanFactory {
|
||||
|
||||
// TODO: Map<String, ?> getMap(Object pProxy)
|
||||
|
||||
// TODO: Consider a @NotNull annotation that will allow for throwing IllegalArgumentExceptions
|
||||
// - Or a more general validator approach for custom fields...
|
||||
|
||||
// NOTE: Specifying default values does not make much sense, as it would be possible to just add values to the map
|
||||
// in the first place
|
||||
|
||||
// TODO: Replace Converter varargs with new class a PropertyConverterConfiguration
|
||||
// - setPropertyConverter(String propertyName, Converter from, Converter to)
|
||||
// - setDefaultConverter(Class from, Class to, Converter)
|
||||
// TODO: Validators? Allows for more than just NotNull checking
|
||||
// TODO: Mixin support for other methods, and we are on the way to full-blown AOP.. ;-)
|
||||
// TODO: Delegate for behaviour?
|
||||
|
||||
// TODO: Consider being fail-fast for primitives without default values?
|
||||
// Or have default values be the same as they would have been if class members (false/0/null)
|
||||
// NOTE: There's a difference between a map with a null value for a key, and no presence of that key at all
|
||||
|
||||
// TODO: ProperyChange support!
|
||||
|
||||
private MappedBeanFactory() {
|
||||
}
|
||||
|
||||
static <T> T as(final Class<T> pClass, final Converter... pConverters) {
|
||||
// TODO: Add neccessary default initializer stuff here.
|
||||
return as(pClass, new LinkedHashMap<String, Object>(), pConverters);
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked"})
|
||||
static <T> T as(final Class<T> pClass, final Map<String, ?> pMap, final Converter... pConverters) {
|
||||
return asImpl(pClass, (Map<String, Object>) pMap, pConverters);
|
||||
}
|
||||
|
||||
static <T> T asImpl(final Class<T> pClass, final Map<String, Object> pMap, final Converter[] pConverters) {
|
||||
// TODO: Report clashing? Named converters?
|
||||
final Map<ConverterKey, Converter> converters = new HashMap<ConverterKey, Converter>() {
|
||||
@Override
|
||||
public Converter get(Object key) {
|
||||
Converter converter = super.get(key);
|
||||
return converter != null ? converter : Converter.NULL;
|
||||
}
|
||||
};
|
||||
|
||||
for (Converter converter : pConverters) {
|
||||
converters.put(new ConverterKey(converter.getFromType(), converter.getToType()), converter);
|
||||
}
|
||||
|
||||
return pClass.cast(
|
||||
Proxy.newProxyInstance(
|
||||
pClass.getClassLoader(),
|
||||
new Class<?>[]{pClass, Serializable.class}, // TODO: Maybe Serializable should be specified by pClass?
|
||||
new MappedBeanInvocationHandler(pClass, pMap, converters)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
private static class ConverterKey {
|
||||
private Class<?> to;
|
||||
private Class<?> from;
|
||||
|
||||
ConverterKey(Class<?> pFrom, Class<?> pTo) {
|
||||
to = pTo;
|
||||
from = pFrom;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object pOther) {
|
||||
if (this == pOther) {
|
||||
return true;
|
||||
}
|
||||
if (pOther == null || getClass() != pOther.getClass()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
ConverterKey that = (ConverterKey) pOther;
|
||||
|
||||
return from == that.from && to == that.to;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = to != null ? to.hashCode() : 0;
|
||||
result = 31 * result + (from != null ? from.hashCode() : 0);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("%s->%s", from, to);
|
||||
}
|
||||
}
|
||||
|
||||
public static interface Converter<F, T> {
|
||||
|
||||
Converter NULL = new Converter() {
|
||||
public Class<?> getFromType() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Class<?> getToType() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Object convert(Object value, Object old) {
|
||||
if (value == null) {
|
||||
return value;
|
||||
}
|
||||
throw new ClassCastException(value.getClass().getName());
|
||||
}
|
||||
};
|
||||
|
||||
Class<F> getFromType();
|
||||
|
||||
Class<T> getToType();
|
||||
|
||||
T convert(F value, T old);
|
||||
}
|
||||
|
||||
// Add guards for null values by throwing IllegalArgumentExceptions for parameters
|
||||
// TODO: Throw IllegalArgumentException at CREATION time, if value in map is null for a method with @NotNull return type
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD})
|
||||
static @interface NotNull {
|
||||
}
|
||||
|
||||
// For setter methods to have automatic property change support
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
// TODO: Consider field as well?
|
||||
static @interface Observable {
|
||||
}
|
||||
|
||||
// TODO: Decide on default value annotation
|
||||
// Alternate default value annotation
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
static @interface DefaultValue {
|
||||
boolean booleanValue() default false;
|
||||
byte byteValue() default 0;
|
||||
char charValue() default 0;
|
||||
short shortValue() default 0;
|
||||
int intValue() default 0;
|
||||
float floatValue() default 0f;
|
||||
long longValue() default 0l;
|
||||
double doubleValue() default 0d;
|
||||
}
|
||||
|
||||
|
||||
// Default values for primitive types
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
static @interface DefaultBooleanValue {
|
||||
boolean value() default false;
|
||||
}
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
static @interface DefaultByteValue {
|
||||
byte value() default 0;
|
||||
}
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
static @interface DefaultCharValue {
|
||||
char value() default 0;
|
||||
}
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
static @interface DefaultShortValue {
|
||||
short value() default 0;
|
||||
}
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
static @interface DefaultIntValue {
|
||||
int value() default 0;
|
||||
}
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
static @interface DefaultFloatValue {
|
||||
float value() default 0;
|
||||
}
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
static @interface DefaultLongValue {
|
||||
long value() default 0;
|
||||
}
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
static @interface DefaultDouleValue {
|
||||
double value() default 0;
|
||||
}
|
||||
|
||||
// TODO: Does it make sense to NOT just put the value in the map?
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
private static @interface DefaultStringValue {
|
||||
String value(); // TODO: Do we want a default empty string?
|
||||
}
|
||||
|
||||
private static class MappedBeanInvocationHandler implements InvocationHandler, Serializable {
|
||||
|
||||
private static final Method OBJECT_TO_STRING = getObjectMethod("toString");
|
||||
private static final Method OBJECT_HASH_CODE = getObjectMethod("hashCode");
|
||||
private static final Method OBJECT_EQUALS = getObjectMethod("equals", Object.class);
|
||||
private static final Method OBJECT_CLONE = getObjectMethod("clone");
|
||||
|
||||
private final Class<?> mClass;
|
||||
private final Map<String, Object> mMap;
|
||||
private final Map<ConverterKey, Converter> mConverters;
|
||||
|
||||
private transient Map<Method, String> mReadMethods = new HashMap<Method, String>();
|
||||
private transient Map<Method, String> mWriteMethods = new HashMap<Method, String>();
|
||||
|
||||
private static Method getObjectMethod(final String pMethodName, final Class<?>... pParams) {
|
||||
try {
|
||||
return Object.class.getDeclaredMethod(pMethodName, pParams);
|
||||
}
|
||||
catch (NoSuchMethodException e) {
|
||||
throw new Error(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private Object readResolve() throws ObjectStreamException {
|
||||
mReadMethods = new HashMap<Method, String>();
|
||||
mWriteMethods = new HashMap<Method, String>();
|
||||
|
||||
introspectBean(mClass, mReadMethods, mWriteMethods);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public MappedBeanInvocationHandler(Class<?> pClass, Map<String, Object> pMap, Map<ConverterKey, Converter> pConverters) {
|
||||
mClass = pClass;
|
||||
mMap = pMap;
|
||||
mConverters = pConverters;
|
||||
|
||||
introspectBean(mClass, mReadMethods, mWriteMethods);
|
||||
}
|
||||
|
||||
private void introspectBean(Class<?> pClass, Map<Method, String> pReadMethods, Map<Method, String> pWriteMethods) {
|
||||
try {
|
||||
BeanInfo info = Introspector.getBeanInfo(pClass);
|
||||
PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
|
||||
for (PropertyDescriptor descriptor : descriptors) {
|
||||
String name = descriptor.getName();
|
||||
|
||||
Method read = descriptor.getReadMethod();
|
||||
if (read != null) {
|
||||
pReadMethods.put(read, name);
|
||||
}
|
||||
|
||||
Method write = descriptor.getWriteMethod();
|
||||
if (write != null) {
|
||||
pWriteMethods.put(write, name);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (IntrospectionException e) {
|
||||
throw new IllegalArgumentException(String.format("Class %s not introspectable: %s", pClass, e.getMessage()) , e);
|
||||
}
|
||||
}
|
||||
|
||||
public Object invoke(final Object pProxy, final Method pMethod, final Object[] pArguments) throws Throwable {
|
||||
String property = mReadMethods.get(pMethod);
|
||||
if (property != null) {
|
||||
if (pArguments == null || pArguments.length == 0) {
|
||||
Object value = mMap.get(property);
|
||||
Class<?> type = pMethod.getReturnType();
|
||||
|
||||
if (!isCompatible(value, type)) {
|
||||
return mConverters.get(new ConverterKey(value != null ? value.getClass() : Void.class, unBoxType(type))).convert(value, null);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException("Unknown parameters for " + pMethod + ": " + Arrays.toString(pArguments));
|
||||
}
|
||||
}
|
||||
|
||||
property = mWriteMethods.get(pMethod);
|
||||
if (property != null) {
|
||||
if (pArguments.length == 1) {
|
||||
Object value = pArguments[0];
|
||||
|
||||
// Make sure we don't accidentally overwrite a value that looks like ours...
|
||||
Object oldValue = mMap.get(property);
|
||||
Class<?> type = pMethod.getParameterTypes()[0];
|
||||
if (oldValue != null && !isCompatible(oldValue, type)) {
|
||||
value = mConverters.get(new ConverterKey(type, oldValue.getClass())).convert(value, oldValue);
|
||||
}
|
||||
return mMap.put(property, value);
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException("Unknown parameters for " + pMethod + ": " + Arrays.toString(pArguments));
|
||||
}
|
||||
}
|
||||
|
||||
if (pMethod.equals(OBJECT_TO_STRING)) {
|
||||
return proxyToString();
|
||||
}
|
||||
if (pMethod.equals(OBJECT_EQUALS)) {
|
||||
return proxyEquals(pProxy, pArguments[0]);
|
||||
}
|
||||
if (pMethod.equals(OBJECT_HASH_CODE)) {
|
||||
return proxyHashCode();
|
||||
}
|
||||
if (pMethod.getName().equals(OBJECT_CLONE.getName())
|
||||
&& Arrays.equals(pMethod.getParameterTypes(), OBJECT_CLONE.getParameterTypes())
|
||||
&& OBJECT_CLONE.getReturnType().isAssignableFrom(pMethod.getReturnType())) {
|
||||
return proxyClone();
|
||||
}
|
||||
|
||||
// Other methods not handled (for now)
|
||||
throw new AbstractMethodError(pMethod.getName());
|
||||
}
|
||||
|
||||
private boolean isCompatible(final Object pValue, final Class<?> pType) {
|
||||
return pValue == null && !pType.isPrimitive() || unBoxType(pType).isInstance(pValue);
|
||||
}
|
||||
|
||||
private Class<?> unBoxType(final Class<?> pType) {
|
||||
if (pType.isPrimitive()) {
|
||||
if (pType == boolean.class) {
|
||||
return Boolean.class;
|
||||
}
|
||||
if (pType == byte.class) {
|
||||
return Byte.class;
|
||||
}
|
||||
if (pType == char.class) {
|
||||
return Character.class;
|
||||
}
|
||||
if (pType == short.class) {
|
||||
return Short.class;
|
||||
}
|
||||
if (pType == int.class) {
|
||||
return Integer.class;
|
||||
}
|
||||
if (pType == float.class) {
|
||||
return Float.class;
|
||||
}
|
||||
if (pType == long.class) {
|
||||
return Long.class;
|
||||
}
|
||||
if (pType == double.class) {
|
||||
return Double.class;
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("Unknown type: " + pType);
|
||||
}
|
||||
return pType;
|
||||
}
|
||||
|
||||
private int proxyHashCode() {
|
||||
// NOTE: Implies mMap instance must follow Map.equals contract
|
||||
return mMap.hashCode();
|
||||
}
|
||||
|
||||
private boolean proxyEquals(final Object pThisProxy, final Object pThat) {
|
||||
if (pThisProxy == pThat) {
|
||||
return true;
|
||||
}
|
||||
if (pThat == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// TODO: Document that subclasses are considered equal (if no extra properties)
|
||||
if (!mClass.isInstance(pThat)) {
|
||||
return false;
|
||||
}
|
||||
if (!Proxy.isProxyClass(pThat.getClass())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// NOTE: This implies that we should put default values in map at creation time
|
||||
// NOTE: Implies mMap instance must follow Map.equals contract
|
||||
InvocationHandler handler = Proxy.getInvocationHandler(pThat);
|
||||
return handler.getClass() == getClass() && mMap.equals(((MappedBeanInvocationHandler) handler).mMap);
|
||||
|
||||
}
|
||||
|
||||
private Object proxyClone() throws CloneNotSupportedException {
|
||||
return as(
|
||||
mClass,
|
||||
new LinkedHashMap<String, Object>(mMap),
|
||||
mConverters.values().toArray(new Converter[mConverters.values().size()])
|
||||
);
|
||||
}
|
||||
|
||||
private String proxyToString() {
|
||||
return String.format("%s$MapProxy@%s: %s", mClass.getName(), System.identityHashCode(this), mMap);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* Copyright (c) 2009, Harald Kuhr
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright notice,
|
||||
* this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
* * Neither the name "TwelveMonkeys" nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software
|
||||
* without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
package com.twelvemonkeys.util;
|
||||
|
||||
/**
|
||||
* PersistentMap
|
||||
*
|
||||
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
|
||||
* @author last modified by $Author: haraldk$
|
||||
* @version $Id: PersistentMap.java,v 1.0 May 13, 2009 2:31:29 PM haraldk Exp$
|
||||
*/
|
||||
public class PersistentMap {
|
||||
// TODO: Implement Map
|
||||
// TODO: Delta synchronization (db?)
|
||||
}
|
||||
|
||||
/*
|
||||
Persistent format
|
||||
|
||||
Header
|
||||
File ID 4-8 bytes
|
||||
Size
|
||||
|
||||
Entry pointer array block
|
||||
Size
|
||||
Next entry pointer block address
|
||||
Entry 1 address
|
||||
...
|
||||
Entry n address
|
||||
|
||||
Entry 1
|
||||
...
|
||||
Entry n
|
||||
|
||||
*/
|
||||
1287
sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/XMLProperties.java
Executable file
1287
sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/XMLProperties.java
Executable file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,398 @@
|
||||
/*
|
||||
* Copyright (c) 2008, Harald Kuhr
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name "TwelveMonkeys" nor the
|
||||
* names of its contributors may be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
package com.twelvemonkeys.util.regex;
|
||||
|
||||
import com.twelvemonkeys.util.DebugUtil;
|
||||
|
||||
import java.io.PrintStream;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.regex.PatternSyntaxException;
|
||||
|
||||
/**
|
||||
* This class parses arbitrary strings against a wildcard string mask provided.
|
||||
* The wildcard characters are '*' and '?'.
|
||||
* <p>
|
||||
* The string masks provided are treated as case sensitive.<br>
|
||||
* Null-valued string masks as well as null valued strings to be parsed, will lead to rejection.
|
||||
*
|
||||
* <p><hr style="height=1"><p>
|
||||
*
|
||||
* This task is performed based on regular expression techniques.
|
||||
* The possibilities of string generation with the well-known wildcard characters stated above,
|
||||
* represent a subset of the possibilities of string generation with regular expressions.<br>
|
||||
* The '*' corresponds to ([Union of all characters in the alphabet])*<br>
|
||||
* The '?' corresponds to ([Union of all characters in the alphabet])<br>
|
||||
* <small>These expressions are not suited for textual representation at all, I must say. Is there any math tags included in HTML?</small>
|
||||
*
|
||||
* <p>
|
||||
*
|
||||
* This class uses the Regexp package from Apache's Jakarta Project, links below.
|
||||
*
|
||||
* <p><hr style="height=1"><p>
|
||||
*
|
||||
* Examples of usage:<br>
|
||||
* This example will return "Accepted!".
|
||||
* <pre>
|
||||
* REWildcardStringParser parser = new REWildcardStringParser("*_28????.jp*");
|
||||
* if (parser.parseString("gupu_280915.jpg")) {
|
||||
* System.out.println("Accepted!");
|
||||
* } else {
|
||||
* System.out.println("Not accepted!");
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* <p><hr style="height=1"><p>
|
||||
*
|
||||
* @author <a href="mailto:eirik.torske@iconmedialab.no">Eirik Torske</a>
|
||||
* @see <a href="http://jakarta.apache.org/regexp/">Jakarta Regexp</a>
|
||||
* @see <a href="http://jakarta.apache.org/regexp/apidocs/org/apache/regexp/RE.html">{@code org.apache.regexp.RE}</a>
|
||||
* @see com.twelvemonkeys.util.regex.WildcardStringParser
|
||||
*
|
||||
* @todo Rewrite to use this regex package, and not Jakarta directly!
|
||||
*/
|
||||
public class REWildcardStringParser /*extends EntityObject*/ {
|
||||
|
||||
// Constants
|
||||
|
||||
/** Field ALPHABET */
|
||||
public static final char[] ALPHABET = {
|
||||
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'æ',
|
||||
'ø', 'å', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'N', 'M', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
|
||||
'Z', 'Æ', 'Ø', 'Å', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '_', '-'
|
||||
};
|
||||
|
||||
/** Field FREE_RANGE_CHARACTER */
|
||||
public static final char FREE_RANGE_CHARACTER = '*';
|
||||
|
||||
/** Field FREE_PASS_CHARACTER */
|
||||
public static final char FREE_PASS_CHARACTER = '?';
|
||||
|
||||
// Members
|
||||
Pattern mRegexpParser;
|
||||
String mStringMask;
|
||||
boolean mInitialized = false;
|
||||
int mTotalNumberOfStringsParsed;
|
||||
boolean mDebugging;
|
||||
PrintStream out;
|
||||
|
||||
// Properties
|
||||
// Constructors
|
||||
|
||||
/**
|
||||
* Creates a wildcard string parser.
|
||||
* <p>
|
||||
* @param pStringMask the wildcard string mask.
|
||||
*/
|
||||
public REWildcardStringParser(final String pStringMask) {
|
||||
this(pStringMask, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a wildcard string parser.
|
||||
* <p>
|
||||
* @param pStringMask the wildcard string mask.
|
||||
* @param pDebugging {@code true} will cause debug messages to be emitted to {@code System.out}.
|
||||
*/
|
||||
public REWildcardStringParser(final String pStringMask, final boolean pDebugging) {
|
||||
this(pStringMask, pDebugging, System.out);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a wildcard string parser.
|
||||
* <p>
|
||||
* @param pStringMask the wildcard string mask.
|
||||
* @param pDebugging {@code true} will cause debug messages to be emitted.
|
||||
* @param pDebuggingPrintStream the {@code java.io.PrintStream} to which the debug messages will be emitted.
|
||||
*/
|
||||
public REWildcardStringParser(final String pStringMask, final boolean pDebugging, final PrintStream pDebuggingPrintStream) {
|
||||
|
||||
this.mStringMask = pStringMask;
|
||||
this.mDebugging = pDebugging;
|
||||
this.out = pDebuggingPrintStream;
|
||||
mInitialized = buildRegexpParser();
|
||||
}
|
||||
|
||||
// Methods
|
||||
|
||||
/**
|
||||
* Converts wildcard string mask to regular expression.
|
||||
* This method should reside in som utility class, but I don't know how proprietary the regular expression format is...
|
||||
* @return the corresponding regular expression or {@code null} if an error occurred.
|
||||
*/
|
||||
private String convertWildcardExpressionToRegularExpression(final String pWildcardExpression) {
|
||||
|
||||
if (pWildcardExpression == null) {
|
||||
if (mDebugging) {
|
||||
out.println(DebugUtil.getPrefixDebugMessage(this) + "wildcard expression is null - also returning null as regexp!");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
StringBuilder regexpBuffer = new StringBuilder();
|
||||
boolean convertingError = false;
|
||||
|
||||
for (int i = 0; i < pWildcardExpression.length(); i++) {
|
||||
if (convertingError) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Free-range character '*'
|
||||
char stringMaskChar = pWildcardExpression.charAt(i);
|
||||
|
||||
if (isFreeRangeCharacter(stringMaskChar)) {
|
||||
regexpBuffer.append("(([a-åA-Å0-9]|.|_|-)*)");
|
||||
}
|
||||
|
||||
// Free-pass character '?'
|
||||
else if (isFreePassCharacter(stringMaskChar)) {
|
||||
regexpBuffer.append("([a-åA_Å0-9]|.|_|-)");
|
||||
}
|
||||
|
||||
// Valid characters
|
||||
else if (isInAlphabet(stringMaskChar)) {
|
||||
regexpBuffer.append(stringMaskChar);
|
||||
}
|
||||
|
||||
// Invalid character - aborting
|
||||
else {
|
||||
if (mDebugging) {
|
||||
out.println(DebugUtil.getPrefixDebugMessage(this)
|
||||
+ "one or more characters in string mask are not legal characters - returning null as regexp!");
|
||||
}
|
||||
convertingError = true;
|
||||
}
|
||||
}
|
||||
return regexpBuffer.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the regexp parser.
|
||||
*/
|
||||
private boolean buildRegexpParser() {
|
||||
|
||||
// Convert wildcard string mask to regular expression
|
||||
String regexp = convertWildcardExpressionToRegularExpression(mStringMask);
|
||||
|
||||
if (regexp == null) {
|
||||
out.println(DebugUtil.getPrefixErrorMessage(this)
|
||||
+ "irregularity in regexp conversion - now not able to parse any strings, all strings will be rejected!");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Instantiate a regular expression parser
|
||||
try {
|
||||
mRegexpParser = Pattern.compile(regexp);
|
||||
}
|
||||
catch (PatternSyntaxException e) {
|
||||
if (mDebugging) {
|
||||
out.println(DebugUtil.getPrefixErrorMessage(this) + "RESyntaxException \"" + e.getMessage()
|
||||
+ "\" caught - now not able to parse any strings, all strings will be rejected!");
|
||||
}
|
||||
if (mDebugging) {
|
||||
e.printStackTrace(System.err);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (mDebugging) {
|
||||
out.println(DebugUtil.getPrefixDebugMessage(this) + "regular expression parser from regular expression " + regexp
|
||||
+ " extracted from wildcard string mask " + mStringMask + ".");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple check of the string to be parsed.
|
||||
*/
|
||||
private boolean checkStringToBeParsed(final String pStringToBeParsed) {
|
||||
|
||||
// Check for nullness
|
||||
if (pStringToBeParsed == null) {
|
||||
if (mDebugging) {
|
||||
out.println(DebugUtil.getPrefixDebugMessage(this) + "string to be parsed is null - rejection!");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if valid character (element in alphabet)
|
||||
for (int i = 0; i < pStringToBeParsed.length(); i++) {
|
||||
if (!isInAlphabet(pStringToBeParsed.charAt(i))) {
|
||||
if (mDebugging) {
|
||||
out.println(DebugUtil.getPrefixDebugMessage(this)
|
||||
+ "one or more characters in string to be parsed are not legal characters - rejection!");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a certain character is a valid character in the alphabet that is applying for this automaton.
|
||||
*/
|
||||
public static boolean isInAlphabet(final char pCharToCheck) {
|
||||
|
||||
for (int i = 0; i < ALPHABET.length; i++) {
|
||||
if (pCharToCheck == ALPHABET[i]) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a certain character is the designated "free-range" character ('*').
|
||||
*/
|
||||
public static boolean isFreeRangeCharacter(final char pCharToCheck) {
|
||||
return pCharToCheck == FREE_RANGE_CHARACTER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a certain character is the designated "free-pass" character ('?').
|
||||
*/
|
||||
public static boolean isFreePassCharacter(final char pCharToCheck) {
|
||||
return pCharToCheck == FREE_PASS_CHARACTER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if a certain character is a wildcard character ('*' or '?').
|
||||
*/
|
||||
public static boolean isWildcardCharacter(final char pCharToCheck) {
|
||||
return ((isFreeRangeCharacter(pCharToCheck)) || (isFreePassCharacter(pCharToCheck)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the string mask that was used when building the parser atomaton.
|
||||
* <p>
|
||||
* @return the string mask used for building the parser automaton.
|
||||
*/
|
||||
public String getStringMask() {
|
||||
return mStringMask;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a string.
|
||||
* <p>
|
||||
*
|
||||
* @param pStringToBeParsed
|
||||
* @return {@code true} if and only if the string are accepted by the parser.
|
||||
*/
|
||||
public boolean parseString(final String pStringToBeParsed) {
|
||||
|
||||
if (mDebugging) {
|
||||
out.println();
|
||||
}
|
||||
if (mDebugging) {
|
||||
out.println(DebugUtil.getPrefixDebugMessage(this) + "parsing \"" + pStringToBeParsed + "\"...");
|
||||
}
|
||||
|
||||
// Update statistics
|
||||
mTotalNumberOfStringsParsed++;
|
||||
|
||||
// Check string to be parsed
|
||||
if (!checkStringToBeParsed(pStringToBeParsed)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Perform parsing and return accetance/rejection flag
|
||||
if (mInitialized) {
|
||||
return mRegexpParser.matcher(pStringToBeParsed).matches();
|
||||
} else {
|
||||
out.println(DebugUtil.getPrefixErrorMessage(this) + "trying to use non-initialized parser - string rejected!");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* Overriding mandatory methods from EntityObject's.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Method toString
|
||||
*
|
||||
*
|
||||
* @return
|
||||
*
|
||||
*/
|
||||
public String toString() {
|
||||
|
||||
StringBuilder buffer = new StringBuilder();
|
||||
|
||||
buffer.append(DebugUtil.getClassName(this));
|
||||
buffer.append(": String mask ");
|
||||
buffer.append(mStringMask);
|
||||
buffer.append("\n");
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
// Just taking the lazy, easy and dangerous way out
|
||||
|
||||
/**
|
||||
* Method equals
|
||||
*
|
||||
*
|
||||
* @param pObject
|
||||
*
|
||||
* @return
|
||||
*
|
||||
*/
|
||||
public boolean equals(Object pObject) {
|
||||
|
||||
if (pObject instanceof REWildcardStringParser) {
|
||||
REWildcardStringParser externalParser = (REWildcardStringParser) pObject;
|
||||
|
||||
return (externalParser.mStringMask == this.mStringMask);
|
||||
}
|
||||
return ((Object) this).equals(pObject);
|
||||
}
|
||||
|
||||
// Just taking the lazy, easy and dangerous way out
|
||||
|
||||
/**
|
||||
* Method hashCode
|
||||
*
|
||||
*
|
||||
* @return
|
||||
*
|
||||
*/
|
||||
public int hashCode() {
|
||||
return ((Object) this).hashCode();
|
||||
}
|
||||
|
||||
protected Object clone() throws CloneNotSupportedException {
|
||||
return new REWildcardStringParser(mStringMask);
|
||||
}
|
||||
|
||||
// Just taking the lazy, easy and dangerous way out
|
||||
protected void finalize() throws Throwable {}
|
||||
}
|
||||
|
||||
|
||||
/*--- Formatted in Sun Java Convention Style on ma, des 1, '03 ---*/
|
||||
|
||||
|
||||
/*------ Formatted by Jindent 3.23 Basic 1.0 --- http://www.jindent.de ------*/
|
||||
Reference in New Issue
Block a user