You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by dw...@apache.org on 2002/01/06 06:08:44 UTC
cvs commit: jakarta-commons/validator/src/share/org/apache/commons/validator Arg.java Constant.java DefaultValidatorLog.java Field.java Form.java FormSet.java GenericValidator.java Msg.java Validator.java ValidatorAction.java ValidatorException.java ValidatorLog.java ValidatorResources.java ValidatorResourcesInitializer.java ValidatorUtil.java Var.java
dwinterfeldt 02/01/05 21:08:44
Added: validator/src/share/org/apache/commons/validator Arg.java
Constant.java DefaultValidatorLog.java Field.java
Form.java FormSet.java GenericValidator.java
Msg.java Validator.java ValidatorAction.java
ValidatorException.java ValidatorLog.java
ValidatorResources.java
ValidatorResourcesInitializer.java
ValidatorUtil.java Var.java
Log:
Initial check in for Commons Validator. Need to switch logging to commons logging package.
Revision Changes Path
1.1 jakarta-commons/validator/src/share/org/apache/commons/validator/Arg.java
Index: Arg.java
===================================================================
/*
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.validator;
/**
* <p>This class stores the replacement arguments for a message resource.</p>
*
* <ul><li>See /WEB-INF/validation.xml for validation rules.</li></ul>
*
* @author David Winterfeldt
*/
public class Arg implements Cloneable, java.io.Serializable {
/**
* The name dependency that this argument goes with (optional).
*/
protected String name = null;
/**
* The key or value of the argument.
*/
protected String key = null;
/**
* Whether or not the key is a message resource (optional). Defaults to true.
* If it is 'true', the value will try to be resolved as a message resource.
*/
protected String resource = "true";
/**
* Gets the name of the dependency.
*/
public String getName() {
return name;
}
/**
* Sets the name of the dependency.
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the key/value.
*/
public String getKey() {
return key;
}
/**
* Sets the key/value.
*/
public void setKey(String key) {
this.key = key;
}
/**
* Gets whether or not the key is a resource.
*/
public String getResource() {
return resource;
}
/**
* Sets whether or not the key is a resource.
*/
public void setResource(String resource) {
this.resource = resource;
}
public Object clone() {
try {
Arg arg = (Arg)super.clone();
if (name != null)
arg.name = new String(name);
if (key != null)
arg.key = new String(key);
if (resource != null)
arg.resource = new String(resource);
return arg;
} catch (CloneNotSupportedException e) {
throw new InternalError(e.toString());
}
}
public String toString() {
StringBuffer results = new StringBuffer();
results.append("Arg: name=");
results.append(name);
results.append(" key=");
results.append(key);
results.append(" resource=");
results.append(resource);
results.append("\n");
return results.toString();
}
}
1.1 jakarta-commons/validator/src/share/org/apache/commons/validator/Constant.java
Index: Constant.java
===================================================================
/*
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.validator;
/**
* <p>Used in the Validation framework for creating a constant. A constant can be
* used to define a global or locale level constant that can be used to replace
* some values in the <code>Field</code> class.<BR>
* ex: <constant name="zip" value="^\d{5}$" /><BR>
* mask="${zip}" </p>
*
* <ul><li>See /WEB-INF/validation.xml for validation rules.</li></ul>
*
* @author David Winterfeldt
*/
public class Constant implements java.io.Serializable {
/**
* The name of the constant.
*/
private String name = null;
/**
* The name of the constant.
*/
private String value = null;
/**
* Gets the name of the constant.
*/
public String getName() {
return name;
}
/**
* Sets the name of the constant.
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the value of the constant.
*/
public String getValue() {
return value;
}
/**
* Sets the value of the constant.
*/
public void setValue(String value) {
this.value = value;
}
public String toString() {
StringBuffer results = new StringBuffer();
results.append("Constant: name=");
results.append(name);
results.append(" value=");
results.append(value);
results.append("\n");
return results.toString();
}
}
1.1 jakarta-commons/validator/src/share/org/apache/commons/validator/DefaultValidatorLog.java
Index: DefaultValidatorLog.java
===================================================================
/*
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.validator;
import java.io.CharArrayWriter;
import java.io.PrintWriter;
import java.io.Serializable;
/**
* <p>Default logging that writes to System.out.</p>
*
* <ul><li>See /WEB-INF/validation.xml for validation rules.</li></ul>
*
* @author David Winterfeldt
*/
public class DefaultValidatorLog implements ValidatorLog, Serializable {
/**
* Gets the debugging detail level for this resource.
*/
protected int debug = 0;
/**
* Debug Level if off by default.
*/
public DefaultValidatorLog(){}
/**
* Set the debug level.
*/
public DefaultValidatorLog(int debug){
this.debug = debug;
}
/**
* Gets the debugging detail level for this resource.
*/
public int getDebug() {
return debug;
}
/**
* Sets the debugging detail level for this resource.
*/
public void setDebug(int debug) {
this.debug = debug;
}
/**
* Writes the specified message to the log output.
*/
public void log(String message) {
System.out.println(message);
}
/**
* Writes the specified message and stack trace to the log output.
*/
public void log(String message, Throwable t) {
CharArrayWriter buf = new CharArrayWriter();
PrintWriter writer = new PrintWriter(buf);
writer.println(message);
t.printStackTrace(writer);
System.out.println(buf.toString());
}
/**
* Writes the specified message to the log output if the debug level is
* greater than zero.
*/
public void info(String message) {
if (debug > 0)
System.out.println(message);
}
/**
* Writes the specified message and stack trace to the log output
* if the debug level is greater than zero.
*/
public void info(String message, Throwable t) {
if (debug > 0) {
CharArrayWriter buf = new CharArrayWriter();
PrintWriter writer = new PrintWriter(buf);
writer.println(message);
t.printStackTrace(writer);
System.out.println(buf.toString());
}
}
}
1.1 jakarta-commons/validator/src/share/org/apache/commons/validator/Field.java
Index: Field.java
===================================================================
/*
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.validator;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.commons.collections.FastHashMap;
/**
* <p>Used in the Validation framework.</p>
*
* <ul><li>See /WEB-INF/validation.xml for validation rules.</li></ul>
*
* @author David Winterfeldt
* @see org.apache.commons.validator.Form
*/
public class Field implements Cloneable, Serializable {
/**
* This is the value that will be used as a key if the <code>Arg</code>
* name field has no value.
*/
public final static String ARG_DEFAULT = "org.apache.commons.validator.Field.DEFAULT";
public final static String TOKEN_INDEXED = "[]";
protected final static String TOKEN_START = "${";
protected final static String TOKEN_END = "}";
protected final static String TOKEN_VAR = "var:";
protected String property = null;
protected String indexedProperty = null;
protected String indexedListProperty = null;
protected String key = null;
protected String depends = null;
protected int page = 0;
protected int fieldOrder = 0;
protected FastHashMap hDependencies = new FastHashMap();
protected FastHashMap hVars = new FastHashMap();
protected FastHashMap hMsgs = new FastHashMap();
protected FastHashMap hArg0 = new FastHashMap();
protected FastHashMap hArg1 = new FastHashMap();
protected FastHashMap hArg2 = new FastHashMap();
protected FastHashMap hArg3 = new FastHashMap();
/**
* Gets the page value that the Field is associated with for
* validation.
*/
public int getPage() {
return page;
}
/**
* Sets the page value that the Field is associated with for
* validation.
*/
public void setPage(int page) {
this.page = page;
}
/**
* Gets the position of the <code>Field</code> in the validation list.
*/
public int getFieldOrder() {
return fieldOrder;
}
/**
* Sets the position of the <code>Field</code> in the validation list.
*/
public void setFieldOrder(int fieldOrder) {
this.fieldOrder = fieldOrder;
}
/**
* Gets the property name of the field.
*/
public String getProperty() {
return property;
}
/**
* Sets the property name of the field.
*/
public void setProperty(String property) {
this.property = property;
}
/**
* Gets the indexed property name of the field. This
* is the method name that can take an <code>int</code> as
* a parameter for indexed property value retrieval.
*/
public String getIndexedProperty() {
return indexedProperty;
}
/**
* Sets the indexed property name of the field.
*/
public void setIndexedProperty(String indexedProperty) {
this.indexedProperty = indexedProperty;
}
/**
* Gets the indexed property name of the field. This
* is the method name that will return an array or a
* <code>Collection</code> used to retrieve the
* list and then loop through the list performing the specified
* validations.
*/
public String getIndexedListProperty() {
return indexedListProperty;
}
/**
* Sets the indexed property name of the field.
*/
public void setIndexedListProperty(String indexedListProperty) {
this.indexedListProperty = indexedListProperty;
}
/**
* Gets the validation rules for this field.
*/
public String getDepends() {
return depends;
}
/**
* Sets the validation rules for this field.
*/
public void setDepends(String depends) {
this.depends = depends;
}
/**
* Add a <code>Msg</code> to the <code>Field</code>.
*/
public void addMsg(Msg msg) {
if (msg != null && msg.getKey() != null && msg.getKey().length() > 0 &&
msg.getName() != null && msg.getName().length() > 0)
hMsgs.put(msg.getName(), msg.getKey());
}
/**
* Retrieve a message value.
*/
public String getMsg(String key) {
return (String)hMsgs.get(key);
}
/**
* Add a <code>Arg</code> to the arg0 list.
*/
public void addArg0(Arg arg) {
if (arg != null && arg.getKey() != null && arg.getKey().length() > 0) {
if (arg.getName() != null && arg.getName().length() > 0)
hArg0.put(arg.getName(), arg);
else
hArg0.put(ARG_DEFAULT, arg);
}
}
/**
* Gets the default arg0 <code>Arg</code> object.
*/
public Arg getArg0() {
return (Arg)hArg0.get(ARG_DEFAULT);
}
/**
* Gets the arg0 <code>Arg</code> object based on the key passed in. If the key
* finds a <code>null</code> value then the default value will try to be retrieved.
*/
public Arg getArg0(String key) {
Object o = hArg0.get(key);
if (o != null)
return (Arg)o;
else
return getArg0();
}
/**
* Add a <code>Arg</code> to the arg1 list.
*/
public void addArg1(Arg arg) {
if (arg != null && arg.getKey() != null && arg.getKey().length() > 0) {
if (arg.getName() != null && arg.getName().length() > 0)
hArg1.put(arg.getName(), arg);
else
hArg1.put(ARG_DEFAULT, arg);
}
}
/**
* Gets the default arg1 <code>Arg</code> object.
*/
public Arg getArg1() {
return (Arg)hArg1.get(ARG_DEFAULT);
}
/**
* Gets the arg1 <code>Arg</code> object based on the key passed in. If the key
* finds a <code>null</code> value then the default value will try to be retrieved.
*/
public Arg getArg1(String key) {
Object o = hArg1.get(key);
if (o != null)
return (Arg)o;
else
return getArg1();
}
/**
* Add a <code>Arg</code> to the arg2 list.
*/
public void addArg2(Arg arg) {
if (arg != null && arg.getKey() != null && arg.getKey().length() > 0) {
if (arg.getName() != null && arg.getName().length() > 0)
hArg2.put(arg.getName(), arg);
else
hArg2.put(ARG_DEFAULT, arg);
}
}
/**
* Gets the default arg2 <code>Arg</code> object.
*/
public Arg getArg2() {
return (Arg)hArg2.get(ARG_DEFAULT);
}
/**
* Gets the arg2 <code>Arg</code> object based on the key passed in. If the key
* finds a <code>null</code> value then the default value will try to be retrieved.
*/
public Arg getArg2(String key) {
Object o = hArg2.get(key);
if (o != null)
return (Arg)o;
else
return getArg2();
}
/**
* Add a <code>Arg</code> to the arg3 list.
*/
public void addArg3(Arg arg) {
if (arg != null && arg.getKey() != null && arg.getKey().length() > 0) {
if (arg.getName() != null && arg.getName().length() > 0)
hArg3.put(arg.getName(), arg);
else
hArg3.put(ARG_DEFAULT, arg);
}
}
/**
* Gets the default arg3 <code>Arg</code> object.
*/
public Arg getArg3() {
return (Arg)hArg3.get(ARG_DEFAULT);
}
/**
* Gets the arg3 <code>Arg</code> object based on the key passed in. If the key
* finds a <code>null</code> value then the default value will try to be retrieved.
*/
public Arg getArg3(String key) {
Object o = hArg3.get(key);
if (o != null)
return (Arg)o;
else
return getArg3();
}
/**
* Add a <code>Var</code> to the <code>Field</code>.
*/
public void addVar(Var v) {
if (v != null && v.getName() != null && v.getName().length() > 0 && v.getValue() != null)
hVars.put(v.getName(), v);
}
/**
* Add a <code>Var</code>, based on the values passed in, to the <code>Field</code>.
*/
public void addVarParam(String name, String value, String jsType) {
if (name != null && name.length() > 0 && value != null)
hVars.put(name, new Var(name, value, jsType));
}
/**
* Retrieve a variable.
*/
public Var getVar(String mainKey) {
return (Var)hVars.get(mainKey);
}
/**
* Retrieve a variable's value.
*/
public String getVarValue(String mainKey) {
String value = null;
Object o = hVars.get(mainKey);
if (o != null && o instanceof Var) {
Var v = (Var)o;
value = v.getValue();
}
return value;
}
/**
* The <code>Field</code>'s variables are returned as an
* unmodifiable <code>Map</code>.
*/
public Map getVars() {
return Collections.unmodifiableMap(hVars);
}
/**
* Gets a unique key based on the property and indexedProperty fields.
*/
public String getKey() {
if (key == null)
generateKey();
return key;
}
/**
* Sets a unique key for the field. This can be used to change
* the key temporarily to have a unique key for an indexed field.
*/
public void setKey(String key) {
this.key = key;
}
/**
* If there is a value specified for the indexedProperty field then
* <code>true</code> will be returned. Otherwise it will be <code>false</code>.
*/
public boolean isIndexed() {
if ((indexedProperty != null && indexedProperty.length() > 0) &&
(indexedListProperty != null && indexedListProperty.length() > 0))
return true;
else
return false;
}
/**
* Generate correct <code>key</code> value.
*/
public void generateKey() {
if (isIndexed())
key = indexedProperty + TOKEN_INDEXED + "." + property;
else
key = property;
}
/**
* Replace constants with values in fields and process the depends field
* to create the dependency <code>Map</code>.
*/
public void process(Map globalConstants, Map constants) {
hMsgs.setFast(true);
hArg0.setFast(true);
hArg1.setFast(true);
hArg2.setFast(true);
hArg3.setFast(true);
hVars.setFast(true);
generateKey();
// Process FormSet Constants
for (Iterator i = constants.keySet().iterator(); i.hasNext(); ) {
String key = (String)i.next();
String key2 = TOKEN_START + key + TOKEN_END;
String replaceValue = (String)constants.get(key);
property = ValidatorUtil.replace(property, key2, replaceValue);
processVars(key2, replaceValue);
processMessageComponents(key2, replaceValue);
}
// Process Global Constants
for (Iterator i = globalConstants.keySet().iterator(); i.hasNext(); ) {
String key = (String)i.next();
String key2 = TOKEN_START + key + TOKEN_END;
String replaceValue = (String)globalConstants.get(key);
property = ValidatorUtil.replace(property, key2, replaceValue);
processVars(key2, replaceValue);
processMessageComponents(key2, replaceValue);
}
// Process Var Constant Replacement
for (Iterator i = hVars.keySet().iterator(); i.hasNext(); ) {
String key = (String)i.next();
String key2 = TOKEN_START + TOKEN_VAR + key + TOKEN_END;
Var var = (Var)hVars.get(key);
String replaceValue = var.getValue();
processMessageComponents(key2, replaceValue);
}
if (getDepends() != null) {
StringTokenizer st = new StringTokenizer(getDepends(), ",");
String value = "";
while (st.hasMoreTokens()) {
String depend = st.nextToken().trim();
if (depend != null && depend.length() > 0)
hDependencies.put(depend, value);
}
hDependencies.setFast(true);
}
}
/**
* Replace the vars value with the key/value pairs passed in.
*/
private void processVars(String key, String replaceValue) {
for (Iterator i = hVars.keySet().iterator(); i.hasNext(); ) {
String varKey = (String)i.next();
Var var = (Var)hVars.get(varKey);
var.setValue(ValidatorUtil.replace(var.getValue(), key, replaceValue));
}
}
/**
* Replace the args key value with the key/value pairs passed in.
*/
public void processMessageComponents(String key, String replaceValue) {
String varKey = TOKEN_START + TOKEN_VAR;
// Process Messages
if (key != null && !key.startsWith(varKey)) {
for (Iterator i = hMsgs.keySet().iterator(); i.hasNext(); ) {
String msgKey = (String)i.next();
String value = (String)hMsgs.get(msgKey);
hMsgs.put(msgKey, ValidatorUtil.replace(value, key, replaceValue));
}
}
processArg(hArg0, key, replaceValue);
processArg(hArg1, key, replaceValue);
processArg(hArg2, key, replaceValue);
processArg(hArg3, key, replaceValue);
}
/**
* Replace the arg <code>Collection</code> key value with the key/value pairs passed in.
*/
private void processArg(Map hArgs, String key, String replaceValue) {
for (Iterator i = hArgs.values().iterator(); i.hasNext(); ) {
Arg arg = (Arg)i.next();
if (arg != null)
arg.setKey(ValidatorUtil.replace(arg.getKey(), key, replaceValue));
}
}
/**
* Checks if the key is listed as a dependency.
*/
public boolean isDependency(String key) {
if (hDependencies != null)
return hDependencies.containsKey(key);
else
return false;
}
/**
* Gets an unmodifiable <code>Set</code> of the dependencies.
*/
public Collection getDependencies() {
return Collections.unmodifiableMap(hDependencies).keySet();
}
public Object clone() {
try {
Field field = (Field)super.clone();
if (key != null)
field.setKey(new String(key));
if (property != null)
field.setProperty(new String(property));
if (indexedProperty != null)
field.setIndexedProperty(new String(indexedProperty));
if (indexedListProperty != null)
field.setIndexedListProperty(new String(indexedListProperty));
if (depends != null)
field.setDepends(new String(depends));
// page & fieldOrder should be taken care of by clone method
field.hDependencies = copyFastHashMap(hDependencies);
field.hVars = copyFastHashMap(hVars);
field.hMsgs = copyFastHashMap(hMsgs);
field.hArg0 = copyFastHashMap(hArg0);
field.hArg1 = copyFastHashMap(hArg1);
field.hArg2 = copyFastHashMap(hArg2);
field.hArg3 = copyFastHashMap(hArg3);
return field;
} catch (CloneNotSupportedException e) {
throw new InternalError(e.toString());
}
}
/**
* Makes a deep copy of a <code>FastHashMap</code> if the values
* are <code>String</code>, <code>Msg</code>, <code>Arg</code>,
* or <code>Var</code>. Otherwise it is a shallow copy.
*/
public FastHashMap copyFastHashMap(FastHashMap map) {
FastHashMap hResults = new FastHashMap();
for (Iterator i = map.keySet().iterator(); i.hasNext(); ) {
String key = (String)i.next();
Object value = map.get(key);
if (value instanceof String) {
hResults.put(key, new String((String)value));
} else if (value instanceof Msg) {
hResults.put(key, ((Msg)value).clone());
} else if (value instanceof Arg) {
hResults.put(key, ((Arg)value).clone());
} else if (value instanceof Var) {
hResults.put(key, ((Var)value).clone());
} else {
hResults.put(key, value);
}
}
hResults.setFast(true);
return hResults;
}
public String toString() {
StringBuffer results = new StringBuffer();
results.append("\t\tkey= " + key + "\n");
results.append("\t\tproperty= " + property + "\n");
results.append("\t\tindexedProperty= " + indexedProperty + "\n");
results.append("\t\tindexedListProperty= " + indexedListProperty + "\n");
results.append("\t\tdepends= " + depends + "\n");
results.append("\t\tpage= " + page + "\n");
results.append("\t\tfieldOrder= " + fieldOrder + "\n");
if (hVars != null) {
results.append("\t\tVars:\n");
for (Iterator i = hVars.keySet().iterator(); i.hasNext(); ) {
Object key = i.next();
results.append("\t\t\t");
results.append(key);
results.append("=");
results.append(hVars.get(key));
results.append("\n");
}
}
return results.toString();
}
}
1.1 jakarta-commons/validator/src/share/org/apache/commons/validator/Form.java
Index: Form.java
===================================================================
/*
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.validator;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.FastHashMap;
/**
* <p>Used in the Validation framework.</p>
*
* <ul><li>See /WEB-INF/validation.xml for validation rules.</li></ul>
*
* @author David Winterfeldt
*/
public class Form implements Serializable {
/**
* The name of the form should match the form name in the action configuration
* in the struts-config.xml file.
*/
protected String name = null;
/**
* List of <code>Field</code>s. Used to maintain the order they were added in.
*/
protected List lFields = new ArrayList();
/**
* Map of <code>Field</code>s keyed on their property value.
*/
protected FastHashMap hFields = new FastHashMap();
/**
* Gets the name of the form. It should match the form name in
* the action configuration in the struts-config.xml file.
*/
public String getName() {
return name;
}
/**
* Sets the name of the form. It should match the form name in
* the action configuration in the struts-config.xml file.
*/
public void setName(String name) {
this.name = name;
}
/**
* Add a <code>Field</code> to the <code>Form</code>.
*/
public void addField(Field f) {
if (f != null && f.getProperty() != null && f.getProperty().length() > 0) {
lFields.add(f);
hFields.put(f.getKey(), f);
}
}
/**
* A <code>List</code> of <code>Field</code>s is returned as an
* unmodifiable <code>List</code>.
*/
public List getFields() {
return Collections.unmodifiableList(lFields);
}
/**
* A <code>Map</code> of <code>Field</code>s is returned as an
* unmodifiable <code>List</code>.
*/
public Map getFieldMap() {
return Collections.unmodifiableMap(hFields);
}
/**
* Processes all of the <code>Form</code>'s <code>Field</code>s.
*/
public void process(Map globalConstants, Map constants) {
hFields.setFast(true);
for (Iterator i = lFields.iterator(); i.hasNext(); ) {
Field f = (Field)i.next();
f.process(globalConstants, constants);
}
}
public String toString() {
StringBuffer results = new StringBuffer();
results.append("Form: ");
results.append(name);
results.append("\n");
for (Iterator i = lFields.iterator(); i.hasNext(); ) {
results.append("\tField: \n");
results.append(i.next());
results.append("\n");
}
return results.toString();
}
}
1.1 jakarta-commons/validator/src/share/org/apache/commons/validator/FormSet.java
Index: FormSet.java
===================================================================
/*
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.validator;
import java.io.Serializable;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.collections.FastHashMap;
/**
* <p>Used in the Validation framework. It holds a set of <code>Form</code>s
* stored associated with a <code>Locale</code>.</p>
*
* <ul><li>See /WEB-INF/validation.xml for validation rules.</li></ul>
*
* @author David Winterfeldt
*/
public class FormSet implements Serializable {
/**
* Whether or not the this <code>FormSet</code> was processed
* for replacing variables in strings with their values.
*/
private boolean bProcessed = false;
/**
* Language component of <code>Locale</code> (required).
*/
private String language = null;
/**
* Country component of <code>Locale</code> (optional).
*/
private String country = null;
/**
* Variant component of <code>Locale</code> (optional).
*/
private String variant = null;
private FastHashMap hForms = new FastHashMap();
/**
* Constants
*/
private FastHashMap hConstants = new FastHashMap();
/**
* Whether or not the this <code>FormSet</code> was processed
* for replacing variables in strings with their values.
*/
public boolean isProcessed() {
return bProcessed;
}
/**
* Gets the equivalent of the language component of <code>Locale</code>.
*/
public String getLanguage() {
return language;
}
/**
* Sets the equivalent of the language component of <code>Locale</code>.
*/
public void setLanguage(String language) {
this.language = language;
}
/**
* Gets the equivalent of the country component of <code>Locale</code>.
*/
public String getCountry() {
return country;
}
/**
* Sets the equivalent of the country component of <code>Locale</code>.
*/
public void setCountry(String country) {
this.country = country;
}
/**
* Gets the equivalent of the variant component of <code>Locale</code>.
*/
public String getVariant() {
return variant;
}
/**
* Sets the equivalent of the variant component of <code>Locale</code>.
*/
public void setVariant(String variant) {
this.variant = variant;
}
/**
* Add a <code>Constant</code> (locale level).
*/
public void addConstant(Constant c) {
if (c.getName() != null && c.getName().length() > 0 &&
c.getValue() != null && c.getValue().length() > 0)
hConstants.put(c.getName(), c.getValue());
//System.out.println("Add Constant: " + c.getName() + "," + c.getValue());
}
/**
* Add a <code>Form</code> to the <code>FormSet</code>.
*/
public void addForm(Form f) {
hForms.put(f.getName(), f);
//System.out.println("Add Form: " + f.getName());
}
/**
* Retrieve a <code>Form</code> based on the form name.
*/
public Form getForm(Object key) {
Form f = null;
Object o = hForms.get(key);
if (o != null)
f = (Form)o;
return f;
}
/**
* A <code>Map</code> of <code>Form</code>s is returned as an
* unmodifiable <code>Map</code> with the key based on the form name.
*/
public Map getForms() {
return Collections.unmodifiableMap(hForms);
}
/**
* Processes all of the <code>Form</code>s, set <code>FastHashMap</code>s
* to 'fast' mode.
*/
public synchronized void process(Map globalConstants) {
for (Iterator i = hForms.values().iterator(); i.hasNext(); ) {
Form f = (Form)i.next();
f.process(globalConstants, hConstants);
}
hForms.setFast(true);
hConstants.setFast(true);
bProcessed = true;
}
public String toString() {
StringBuffer results = new StringBuffer();
results.append("FormSet: language=");
results.append(language);
results.append(" country=");
results.append(country);
results.append(" variant=");
results.append(variant);
results.append("\n");
for (Iterator i = getForms().values().iterator(); i.hasNext(); ) {
results.append(" ");
results.append(i.next());
results.append("\n");
}
return results.toString();
}
}
1.1 jakarta-commons/validator/src/share/org/apache/commons/validator/GenericValidator.java
Index: GenericValidator.java
===================================================================
/*
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.validator;
import java.io.Serializable;
import java.util.Date;
import java.util.Locale;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import org.apache.regexp.RE;
import org.apache.regexp.RESyntaxException;
/**
* <p>This class performs validations.</p>
*
* @author David Winterfeldt
*/
public class GenericValidator implements Serializable {
/**
* <p>Checks if the field isn't null and length of the field is greater than zero not
* including whitespace.</p>
*
* @param value The value validation is being performed on.
*/
public static boolean isBlankOrNull(String value) {
if (value == null || value.trim().length() == 0)
return true;
else
return false;
}
/**
* <p>Checks if the value matches the regular expression.</p>
*
* @param value The value validation is being performed on.
* @param regexp The regular expression.
*/
public static boolean matchRegexp(String value, String regexp) throws RESyntaxException {
if (regexp != null && regexp.length() > 0) {
RE r = new RE(regexp);
boolean match = r.match(value);
return match;
} else {
return false;
}
}
/**
* <p>Checks if the value can safely be converted to a byte primitive.</p>
*
* @param value The value validation is being performed on.
*/
public static boolean isByte(String value) {
try {
Byte.parseByte(value);
} catch (Exception e) {
return false;
}
return true;
}
/**
* <p>Checks if the value can safely be converted to a short primitive.</p>
*
* @param value The value validation is being performed on.
*/
public static boolean isShort(String value) {
try {
Short.parseShort(value);
} catch (Exception e) {
return false;
}
return true;
}
/**
* <p>Checks if the value can safely be converted to a int primitive.</p>
*
* @param value The value validation is being performed on.
*/
public static boolean isInt(String value) {
try {
Integer.parseInt(value);
} catch (Exception e) {
return false;
}
return true;
}
/**
* <p>Checks if the value can safely be converted to a long primitive.</p>
*
* @param value The value validation is being performed on.
*/
public static boolean isLong(String value) {
try {
Long.parseLong(value);
} catch (Exception e) {
return false;
}
return true;
}
/**
* <p>Checks if the value can safely be converted to a float primitive.</p>
*
* @param value The value validation is being performed on.
*/
public static boolean isFloat(String value) {
try {
Float.parseFloat(value);
} catch (Exception e) {
return false;
}
return true;
}
/**
* <p>Checks if the value can safely be converted to a double primitive.</p>
*
* @param value The value validation is being performed on.
*/
public static boolean isDouble(String value) {
try {
Double.parseDouble(value);
} catch (Exception e) {
return false;
}
return true;
}
/**
* <p>Checks if the field is a valid date. The <code>Locale</code> is
* used with <code>java.text.DateFormat</code>. The setLenient method
* is set to <code>false</code> for all.</p>
*
* @param value The value validation is being performed on.
* @param datePattern The pattern passed to <code>SimpleDateFormat</code>.
*/
public static boolean isDate(String value, Locale locale) {
boolean bValid = true;
if (value != null) {
try {
DateFormat formatter = null;
if (locale != null)
formatter = DateFormat.getDateInstance(DateFormat.SHORT, locale);
else
formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
formatter.setLenient(false);
Date date = formatter.parse(value);
} catch (ParseException e) {
bValid = false;
}
} else {
bValid = false;
}
return bValid;
}
/**
* <p>Checks if the field is a valid date. The pattern is used with
* <code>java.text.SimpleDateFormat</code>. If strict is true, then the
* length will be checked so '2/12/1999' will not pass validation with
* the format 'MM/dd/yyyy' because the month isn't two digits.
* The setLenient method is set to <code>false</code> for all.</p>
*
* @param value The value validation is being performed on.
* @param datePattern The pattern passed to <code>SimpleDateFormat</code>.
* @param strict Whether or not to have an exact match of the datePattern.
*/
public static boolean isDate(String value, String datePattern, boolean strict) {
boolean bValid = true;
if (value != null && datePattern != null && datePattern.length() > 0) {
try {
SimpleDateFormat formatter = new SimpleDateFormat(datePattern);
formatter.setLenient(false);
Date date = formatter.parse(value);
if (strict) {
if (datePattern.length() != value.length())
bValid = false;
}
} catch (ParseException e) {
bValid = false;
}
} else {
bValid = false;
}
return bValid;
}
/**
* <p>Checks if a value is within a range (min & max specified
* in the vars attribute).</p>
*
* @param value The value validation is being performed on.
* @param min The minimum value of the range.
* @param max The maximum value of the range.
*/
public static boolean isInRange(int value, int min, int max) {
if (!(value >= min && value <= max))
return false;
else
return true;
}
/**
* <p>Checks if the field is a valid credit card number.</p>
* <p>Translated to Java by Ted Husted (<a href="mailto:husted@apache.org">husted@apache.org</a>).<br>
* Reference Sean M. Burke's script at http://www.ling.nwu.edu/~sburke/pub/luhn_lib.pl</p>
*
* @param value The value validation is being performed on.
*/
public static boolean isCreditCard(String value) {
if (!(validateCreditCardLuhnCheck(value) && validateCreditCardPrefixCheck(value)))
return false;
else
return true;
}
/**
* <p>Checks for a valid credit card number.</p>
* <p>Translated to Java by Ted Husted (<a href="mailto:husted@apache.org">husted@apache.org</a>).<br>
* Reference Sean M. Burke's script at http://www.ling.nwu.edu/~sburke/pub/luhn_lib.pl</p>
*
* @param cardNumber Credit Card Number
*/
protected static boolean validateCreditCardLuhnCheck(String cardNumber) {
// number must be validated as 0..9 numeric first!!
int no_digit = cardNumber.length();
int oddoeven = no_digit & 1;
long sum = 0;
for (int count = 0; count < no_digit; count++) {
int digit = 0;
try {
digit = Integer.parseInt(String.valueOf(cardNumber.charAt(count)));
} catch (NumberFormatException e) {
return false;
}
if (((count & 1) ^ oddoeven) == 0) { // not
digit *= 2;
if (digit > 9) digit -= 9;
}
sum += digit;
}
if (sum == 0) return false;
if (sum % 10 == 0) return true;
return false;
}
/**
* <p>Checks for a valid credit card number.</p>
* <p>Translated to Java by Ted Husted (<a href="mailto:husted@apache.org">husted@apache.org</a>).<br>
* Reference Sean M. Burke's script at http://www.ling.nwu.edu/~sburke/pub/luhn_lib.pl</p>
*
* @param cardNumber Credit Card Number
*/
protected static boolean validateCreditCardPrefixCheck(String cardNumber) {
final String AX_PREFIX = "34,37,";
final String VS_PREFIX = "4";
final String MC_PREFIX = "51,52,53,54,55,";
final String DS_PREFIX = "6011";
int length = cardNumber.length();
if (length < 13) return false;
boolean valid = false;
int cardType = 0;
String prefix2 = cardNumber.substring(0,2) + ",";
if (AX_PREFIX.indexOf(prefix2) != -1)
cardType = 3;
if (cardNumber.substring(0,1).equals(VS_PREFIX))
cardType = 4;
if (MC_PREFIX.indexOf(prefix2) != -1)
cardType = 5;
if (cardNumber.substring(0,4).equals(DS_PREFIX))
cardType = 6;
if ((cardType==3) && (length==15))
valid = true;
if ((cardType==4) && ((length==13) || (length==16)))
valid = true;
if ((cardType==5) && (length==16))
valid = true;
if ((cardType==6) && (length==16))
valid = true;
return valid;
}
/**
* <p>Checks if a field has a valid e-mail address.</p>
* <p>Based on a script by Sandeep V. Tamhankar (stamhankar@hotmail.com),
* http://javascript.internet.com</p>
*
* @param value The value validation is being performed on.
*/
public static boolean isEmail(String value) {
boolean bValid = true;
try {
RE emailPat = new RE("^(.+)@(.+)$");
String specialChars = "\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
// ??? '/' character was removed before '[' and ']'
// I'm not sure if that was the right thing to do.
String validChars = "[^\\s" + specialChars + "]";
String quotedUser = "(\"[^\"]*\")";
//RE ipDomainPat = new RE("^\\[(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\]$");
RE ipDomainPat = new RE("^(\\d{1,3})[.](\\d{1,3})[.](\\d{1,3})[.](\\d{1,3})$");
String atom = validChars + '+';
String word = "(" + atom + "|" + quotedUser + ")";
RE userPat = new RE("^" + word + "(\\." + word + ")*$");
RE domainPat = new RE("^" + atom + "(\\." + atom +")*$");
boolean matchEmailPat = emailPat.match(value);
if (!matchEmailPat)
bValid = false;
if (bValid) {
if (matchEmailPat) {
String user = emailPat.getParen(1);
// See if "user" is valid
if (!userPat.match(user))
bValid = false;
} else {
bValid = false;
}
}
String domain = emailPat.getParen(2);
if (bValid) {
if (ipDomainPat.match(domain)) {
// this is an IP address
for (int i = 1; i <= 4; i++) {
String ipSegment = ipDomainPat.getParen(i);
if (ipSegment != null && ipSegment.length() > 0) {
int iIpSegment = 0;
try {
iIpSegment = Integer.parseInt(ipSegment);
} catch (Exception e) {
bValid = false;
}
if (iIpSegment > 255)
bValid = false;
} else {
bValid = false;
}
}
} else {
if (bValid) {
// Domain is symbolic name
if (!domainPat.match(domain))
bValid = false;
}
if (bValid) {
RE atomPat = new RE("(" + atom + ")");
boolean match = true;
int pos = 0;
int i = 0;
String[] domainSegment = new String[10];
while (match) {
match = atomPat.match(domain, pos);
if (match) {
domainSegment[i] = atomPat.getParen(1);
pos += domainSegment[i].length() + 1;
i++;
} else {
}
}
int len = i;
if (domainSegment[len - 1].length() < 2 || domainSegment[len - 1].length() > 3)
bValid = false;
// Make sure there's a host name preceding the domain.
if (len < 2)
bValid = false;
}
}
}
} catch (RESyntaxException e) {
bValid = false;
} catch (Exception e) {
bValid = false;
}
return bValid;
}
/**
* <p>Checks if the value's length is less than or equal to the max.</p>
*
* @param value The value validation is being performed on.
* @param max The maximum length.
*/
public static boolean maxLength(String value, int max) {
if (value.length() <= max)
return true;
else
return false;
}
/**
* <p>Checks if the value's length is greater than or equal to the min.</p>
*
* @param value The value validation is being performed on.
* @param min The minimum length.
*/
public static boolean minLength(String value, int min) {
if (value.length() >= min)
return true;
else
return false;
}
}
1.1 jakarta-commons/validator/src/share/org/apache/commons/validator/Msg.java
Index: Msg.java
===================================================================
/*
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.validator;
/**
* <p>This class can be used to supply an alternative message for a pluggable validator.</p>
*
* <ul><li>See /WEB-INF/validation.xml for validation rules.</li></ul>
*
* @author David Winterfeldt
*/
public class Msg implements Cloneable, java.io.Serializable {
/**
* The name dependency that this argument goes with (optional).
*/
protected String name = null;
/**
* The key or value of the argument.
*/
protected String key = null;
/**
* Gets the name of the dependency.
*/
public String getName() {
return name;
}
/**
* Sets the name of the dependency.
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the key/value.
*/
public String getKey() {
return key;
}
/**
* Sets the key/value.
*/
public void setKey(String key) {
this.key = key;
}
public Object clone() {
try {
Msg msg = (Msg)super.clone();
if (key != null)
msg.name = new String(name);
if (key != null)
msg.key = new String(key);
return msg;
} catch (CloneNotSupportedException e) {
throw new InternalError(e.toString());
}
}
public String toString() {
StringBuffer results = new StringBuffer();
results.append("Msg: name=");
results.append(name);
results.append(" key=");
results.append(key);
results.append("\n");
return results.toString();
}
}
1.1 jakarta-commons/validator/src/share/org/apache/commons/validator/Validator.java
Index: Validator.java
===================================================================
/*
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.validator;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import org.apache.commons.beanutils.PropertyUtils;
/**
* <p>This class performs validations. The methods are can be configured to be
* used in the framework in the validation.xml file. (See example webapp)</p>
*
* @author David Winterfeldt
*/
public class Validator implements Serializable {
public static String SERVLET_CONTEXT_KEY = "javax.servlet.ServletContext";
public static String HTTP_SERVLET_REQUEST_KEY = "javax.servlet.http.HttpServletRequest";
public static String MESSAGE_RESOURCES_KEY = "org.apache.struts.util.MessageResources";
public static String LOCALE_KEY = "java.util.Locale";
public static String BEAN_KEY = "java.lang.Object";
public static String ACTION_ERRORS_KEY = "org.apache.struts.action.ActionErrors";
public static String VALIDATOR_ACTION_KEY = "org.apache.commons.validator.ValidatorAction";
public static String FIELD_KEY = "org.apache.commons.validator.Field";
protected ValidatorResources resources = null;
protected ValidatorLog logger = null;
protected String formName = null;
protected HashMap hResources = new HashMap();
protected int page = 0;
public Validator(ValidatorResources resources, String formName) {
this.resources = resources;
this.logger = resources.getLogger();
this.formName = formName;
}
public void addResource(String key, Object value) {
hResources.put(key, value);
}
public void setPage(int page) {
this.page = page;
}
public int getPage() {
return page;
}
public void validate() throws ValidatorException {
Locale locale = null;
if (hResources.containsKey(LOCALE_KEY))
locale = (Locale)hResources.get(LOCALE_KEY);
if (locale == null)
locale = Locale.getDefault();
Form form = null;
if ((form = resources.get(locale, formName)) != null) {
Map hActions = resources.getValidatorActions();
List lActions = new ArrayList();
Map hActionsRun = new HashMap();
boolean bMoreActions = true;
boolean bErrors = false;
for (Iterator actions = hActions.values().iterator(); actions.hasNext(); )
lActions.add(actions.next());
while (bMoreActions) {
ValidatorAction va = null;
int iErrorCount = 0;
// FIX ME - These sorts will not work for all variations.
// Sort by number dependencies
Collections.sort(lActions, new DependencyComparator());
// Sort by number of dependencies successfully run
Collections.sort(lActions, new DependencySuccessComparator(hActionsRun));
if (lActions.size() > 0)
va = (ValidatorAction)lActions.get(0);
if (va != null && va.getDepends() != null && va.getDepends().length() > 0) {
StringTokenizer st = new StringTokenizer(va.getDepends(), ",");
while (st.hasMoreTokens()) {
String depend = st.nextToken().trim();
Object o = hActionsRun.get(depend);
//if (logger.getDebug() > 10)
// logger.info("***### Validator main - " + va.getName() + " - " + va.getDepends());
if (o == null) {
//if (logger.getDebug() > 10)
// logger.info("***### Validator o==null - " + va.getName() + " - " + va.getDepends());
lActions.clear();
va = null;
bMoreActions = false;
break;
} else {
boolean bContinue = ((Boolean)o).booleanValue();
//if (logger.getDebug() > 10)
// logger.info("***### Validator - " + va.getName() + " depend=" + depend + " bContinue=" + bContinue);
if (!bContinue) {
lActions.clear();
va = null;
bMoreActions = false;
break;
}
}
}
}
// For debug
/**if (logger.getDebug() > 10) {
logger.info("***Order ******************************");
for (Iterator actions = lActions.iterator(); actions.hasNext(); ) {
ValidatorAction tmp = (ValidatorAction)actions.next();
logger.info("***Order - " + tmp.getName() + " " + tmp.getDepends());
}
logger.info("***Order End ******************************");
}*/
if (va != null) {
for (Iterator i = form.getFields().iterator(); i.hasNext(); ) {
Field field = (Field)i.next();
if (field.getPage() <= page && (field.getDepends() != null && field.isDependency(va.getName()))) {
try {
// Add these two Objects to the resources since they reference
// the current validator action and field
hResources.put(VALIDATOR_ACTION_KEY, va);
hResources.put(FIELD_KEY, field);
Class c = Class.forName(va.getClassname(), true, this.getClass().getClassLoader());
List lParams = va.getMethodParamsList();
int size = lParams.size();
int beanIndexPos = -1;
int fieldIndexPos = -1;
Class[] paramClass = new Class[size];
Object[] paramValue = new Object[size];
for (int x = 0; x < size; x++) {
String paramKey = (String)lParams.get(x);
if (BEAN_KEY.equals(paramKey))
beanIndexPos = x;
if (FIELD_KEY.equals(paramKey))
fieldIndexPos = x;
// There were problems calling getClass on paramValue[]
paramClass[x] = Class.forName(paramKey, true, this.getClass().getClassLoader());
paramValue[x] = hResources.get(paramKey);
}
Method m = c.getMethod(va.getMethod(), paramClass);
// If the method is static we don't need an instance of the class
// to call the method. If it isn't, we do.
if (!Modifier.isStatic(m.getModifiers())) {
try {
if (va.getClassnameInstance() == null) {
va.setClassnameInstance(c.newInstance());
}
} catch (Exception ex) {
logger.log("Validator::validate - Couldn't load instance " +
"of class " + va.getClassname() + ". " + ex.getMessage());
}
}
Object result = null;
if (field.isIndexed()) {
Object oIndexed = PropertyUtils.getProperty(hResources.get(BEAN_KEY), field.getIndexedListProperty());
Object indexedList[] = new Object[0];
if (oIndexed instanceof Collection)
indexedList = ((Collection)oIndexed).toArray();
else if(oIndexed.getClass().isArray())
indexedList = (Object[])oIndexed;
for (int pos = 0; pos < indexedList.length; pos++) {
// Set current iteration object to the parameter array
paramValue[beanIndexPos] = indexedList[pos];
// Set field clone with the key modified to represent
// the current field
Field indexedField = (Field)field.clone();
indexedField.setKey(ValidatorUtil.replace(indexedField.getKey(), Field.TOKEN_INDEXED, "[" + pos + "]"));
paramValue[fieldIndexPos] = indexedField;
result = m.invoke(va.getClassnameInstance(), paramValue);
if (result instanceof Boolean) {
Boolean valid = (Boolean)result;
if (!valid.booleanValue())
iErrorCount++;
}
}
} else {
result = m.invoke(va.getClassnameInstance(), paramValue);
if (result instanceof Boolean) {
Boolean valid = (Boolean)result;
if (!valid.booleanValue())
iErrorCount++;
}
}
} catch (Exception e) {
bErrors = true;
logger.log("Validator::validate() reflection - " + e.getMessage());
if (e instanceof ValidatorException)
throw ((ValidatorException)e);
}
}
}
if (iErrorCount == 0) {
hActionsRun.put(va.getName(), new Boolean(true));
} else {
hActionsRun.put(va.getName(), new Boolean(false));
}
if (logger.getDebug() > 10)
logger.info("*** Validator - " + va.getName() + " size=" + lActions.size());
if (lActions.size() > 0)
lActions.remove(0);
if (logger.getDebug() > 10)
logger.info("*** Validator - after remove - " + va.getName() + " size=" + lActions.size());
}
if (lActions.size() == 0)
bMoreActions = false;
}
}
}
/**
* Sort by number dependencies.
*/
protected class DependencyComparator implements Comparator {
public int compare(Object o1, Object o2) {
ValidatorAction va1 = (ValidatorAction)o1;
ValidatorAction va2 = (ValidatorAction)o2;
if ((va1.getDepends() == null || va1.getDepends().length() == 0) &&
(va2.getDepends() == null || va2.getDepends().length() == 0)) {
return 0;
} else if ((va1.getDepends() != null && va1.getDepends().length() > 0) &&
(va2.getDepends() == null || va2.getDepends().length() == 0)) {
return 1;
} else if ((va1.getDepends() == null || va1.getDepends().length() == 0) &&
(va2.getDepends() != null && va2.getDepends().length() > 0)) {
return -1;
} else {
return va1.getDependencies().size() - va2.getDependencies().size();
}
}
}
/**
* Sort by number of dependencies successfully run.
*/
protected class DependencySuccessComparator implements Comparator {
Map hActionsRun = null;
public DependencySuccessComparator(Map hActionsRun) {
this.hActionsRun = hActionsRun;
}
public int compare(Object o1, Object o2) {
ValidatorAction va1 = (ValidatorAction)o1;
ValidatorAction va2 = (ValidatorAction)o2;
if ((va1.getDepends() == null || va1.getDepends().length() == 0) &&
(va2.getDepends() == null || va2.getDepends().length() == 0)) {
return 0;
} else if ((va1.getDepends() != null && va1.getDepends().length() > 0) &&
(va2.getDepends() == null || va2.getDepends().length() == 0)) {
return 1;
} else if ((va1.getDepends() == null || va1.getDepends().length() == 0) &&
(va2.getDepends() != null && va2.getDepends().length() > 0)) {
return -1;
} else {
int iVA1 = 0;
int iVA2 = 0;
for (Iterator i = va1.getDependencies().iterator(); i.hasNext(); ) {
String depend = ((String)i.next()).trim();
Object o = hActionsRun.get(depend);
if (o != null) {
if (((Boolean)o).booleanValue())
iVA1++;
}
}
for (Iterator i = va2.getDependencies().iterator(); i.hasNext(); ) {
String depend = ((String)i.next()).trim();
Object o = hActionsRun.get(depend);
if (o != null) {
if (((Boolean)o).booleanValue())
iVA2++;
}
}
return iVA1 - iVA2;
}
}
}
}
1.1 jakarta-commons/validator/src/share/org/apache/commons/validator/ValidatorAction.java
Index: ValidatorAction.java
===================================================================
/*
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.validator;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.commons.collections.FastHashMap;
/**
* <p>Used in the Validation framework. Reference to the class and method to perform
* a validation. Used to dynamically instantiate and run a validation method defined
* in the validation.xml file.<BR>
* Note: The validation method is assumed to be thread safe.</p>
*
* <ul><li>See /WEB-INF/validation.xml for validation rules.</li></ul>
*
* @author David Winterfeldt
*/
public class ValidatorAction implements Serializable {
/**
* The name of the validation.
*/
private String name = null;
private String classname = null;
private String method = null;
// Default for Struts
private String methodParams = Validator.BEAN_KEY + "," +
Validator.VALIDATOR_ACTION_KEY + "," +
Validator.FIELD_KEY + "," +
Validator.ACTION_ERRORS_KEY + "," +
Validator.HTTP_SERVLET_REQUEST_KEY + "," +
Validator.SERVLET_CONTEXT_KEY;
private String depends = null;
private String msg = null;
private String jsFunctionName = null;
private String javascript = null;
private Object instance = null;
private FastHashMap hDependencies = new FastHashMap();
private List lMethodParams = new ArrayList();
/**
* Gets the name of the validator action.
*/
public String getName() {
return name;
}
/**
* Sets the name of the validator action.
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the class of the validator action.
*/
public String getClassname() {
return classname;
}
/**
* Sets the class of the validator action.
*/
public void setClassname(String classname) {
this.classname = classname;
}
/**
* Gets the name of method being called for the validator action.
*/
public String getMethod() {
return method;
}
/**
* Sets the name of method being called for the validator action.
*/
public void setMethod(String method) {
this.method = method;
}
/**
* Gets the method parameters for the method.
*/
public String getMethodParams() {
return methodParams;
}
/**
* Sets the method parameters for the method.
*/
public void setMethodParams(String methodParams) {
this.methodParams = methodParams;
}
/**
* Gets the method parameters for the method.
*/
public List getMethodParamsList() {
return Collections.unmodifiableList(lMethodParams);
}
/**
* Gets the dependencies of the validator action.
*/
public String getDepends() {
return depends;
}
/**
* Sets the dependencies of the validator action.
*/
public void setDepends(String depends) {
this.depends = depends;
}
/**
* Gets the resource message associated with the validator action.
*/
public String getMsg() {
return msg;
}
/**
* Sets the resource message associated with the validator action.
*/
public void setMsg(String msg) {
this.msg = msg;
}
/**
* Gets the Javascript function name. This is optional and will
* be used instead of validator action name for the name of the
* Javascript function/object.
*/
public String getJsFunctionName() {
return jsFunctionName;
}
/**
* Sets the Javascript function name. This is optional and will
* be used instead of validator action name for the name of the
* Javascript function/object.
*/
public void setJsFunctionName(String jsFunctionName) {
this.jsFunctionName = jsFunctionName;
}
/**
* Gets the Javascript equivalent of the java class and method
* associated with this action.
*/
public String getJavascript() {
return javascript;
}
/**
* Sets the Javascript equivalent of the java class and method
* associated with this action.
*/
public void setJavascript(String javascript) {
this.javascript = javascript;
}
/**
* Gets an instance based on the validator action's classname.
*/
public Object getClassnameInstance() {
return instance;
}
/**
* Sets an instance based on the validator action's classname.
*/
public void setClassnameInstance(Object instance) {
this.instance = instance;
}
/**
* Creates a <code>FastHashMap</code> for the isDependency method
* based on depends.
*/
public synchronized void process(Map globalConstants) {
// Create FastHashMap for isDependency method
if (getDepends() != null) {
if (hDependencies == null)
hDependencies = new FastHashMap();
StringTokenizer st = new StringTokenizer(getDepends(), ",");
String value = "";
while (st.hasMoreTokens()) {
String depend = st.nextToken().trim();
if (depend != null && depend.length() > 0)
hDependencies.put(depend, value);
}
hDependencies.setFast(true);
}
// Create List for methodParams
if (getMethodParams() != null) {
if (lMethodParams == null)
lMethodParams = new ArrayList();
StringTokenizer st = new StringTokenizer(getMethodParams(), ",");
while (st.hasMoreTokens()) {
String value = st.nextToken().trim();
if (value != null && value.length() > 0)
lMethodParams.add(value);
}
}
}
/**
* Checks whether or not the value passed in is in the depends field.
*/
public boolean isDependency(String key) {
if (hDependencies != null)
return hDependencies.containsKey(key);
else
return false;
}
/**
* Gets the dependencies as a <code>Collection</code>.
*/
public Collection getDependencies() {
return Collections.unmodifiableMap(hDependencies).keySet();
}
public String toString() {
StringBuffer results = new StringBuffer();
results.append("ValidatorAction: ");
results.append(name);
results.append("\n");
return results.toString();
}
}
1.1 jakarta-commons/validator/src/share/org/apache/commons/validator/ValidatorException.java
Index: ValidatorException.java
===================================================================
/*
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.validator;
import java.io.Serializable;
/**
* <p>Exception for the Validator Framework.</p>
*
* @author David Winterfeldt
*/
public class ValidatorException extends Exception implements Serializable{
public ValidatorException() {}
public ValidatorException(String message) {
super(message);
}
}
1.1 jakarta-commons/validator/src/share/org/apache/commons/validator/ValidatorLog.java
Index: ValidatorLog.java
===================================================================
/*
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.validator;
/**
* <p>Generic interface for logging.</p>
*
* @author David Winterfeldt
*/
public interface ValidatorLog {
/**
* Gets the debugging detail level for this resource.
*/
public int getDebug();
/**
* Sets the debugging detail level for this resource.
*/
public void setDebug(int debug);
/**
* Writes the specified message to the log output.
*/
public void log(String message);
/**
* Writes the specified message and stack trace to the log output.
*/
public void log(String message, Throwable t);
/**
* Writes the specified message to the log output if the debug level is
* greater than zero.
*/
public void info(String message);
/**
* Writes the specified message and stack trace to the log output
* if the debug level is greater than zero.
*/
public void info(String message, Throwable t);
}
1.1 jakarta-commons/validator/src/share/org/apache/commons/validator/ValidatorResources.java
Index: ValidatorResources.java
===================================================================
/*
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.validator;
import java.io.Serializable;
import java.util.Collections;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.collections.FastHashMap;
/**
* <p>General purpose class for storing <code>FormSet</code> objects based
* on their associated <code>Locale</code>.</p>
*
* <p><strong>IMPLEMENTATION NOTE</strong> - Classes that extend this class
* must be Serializable so that instances may be used in distributable
* application server environments.</p>
*
* @author David Winterfeldt
*/
public class ValidatorResources implements Serializable {
/**
* Logging interface.
*/
protected ValidatorLog logger = null;
/**
* <code>FastHashMap</code> of <code>FormSet</code>s stored under
* a <code>Locale</code> key.
*/
protected FastHashMap hFormSets = new FastHashMap();
/**
* <code>FastHashMap</code> of global constant values with
* the name of the constant as the key.
*/
protected FastHashMap hConstants = new FastHashMap();
/**
* <code>FastHashMap</code> of <code>ValidatorAction</code>s with
* the name of the <code>ValidatorAction</code> as the key.
*/
protected FastHashMap hActions = new FastHashMap();
/**
* The default locale on our server.
*/
protected static Locale defaultLocale = Locale.getDefault();
public ValidatorResources(ValidatorLog logger) {
this.logger = logger;
}
/**
* Gets the logger.
*/
public ValidatorLog getLogger() {
return logger;
}
/**
* Sets the logger.
*/
public void setLogger(ValidatorLog logger) {
this.logger = logger;
}
/**
* Add a <code>FormSet</code> to this <code>ValidatorResources</code>
* object. It will be associated with the <code>Locale</code> of the
* <code>FormSet</code>.
*/
public void put(FormSet fs) {
if (fs != null) {
hFormSets.put(buildKey(fs), fs);
//if (!fs.isProcessed())
// fs.process(hConstants);
logger.info(fs.toString());
}
}
/**
* Add a global constant to the resource.
*/
public void addConstant(Constant c) {
if (c != null &&
c.getName() != null && c.getName().length() > 0 &&
c.getValue() != null && c.getValue().length() > 0)
hConstants.put(c.getName(), c.getValue());
logger.info("Add Global Constant: " + c.getName() + "," + c.getValue());
}
/**
* <p>Add a <code>ValidatorAction</code> to the resource. It also creates an instance
* of the class based on the <code>ValidatorAction</code>s classname and retrieves
* the <code>Method</code> instance and sets them in the <code>ValidatorAction</code>.</p>
*/
public void addValidatorAction(ValidatorAction va) {
if (va != null &&
va.getName() != null && va.getName().length() > 0 &&
va.getClassname() != null && va.getClassname().length() > 0 &&
va.getMethod() != null && va.getMethod().length() > 0) {
va.process(hConstants);
hActions.put(va.getName(), va);
logger.info("Add ValidatorAction: " + va.getName() + "," + va.getClassname());
}
}
/**
* Get a <code>ValidatorAction</code> based on it's name.
*/
public ValidatorAction getValidatorAction(String key) {
return (ValidatorAction)hActions.get(key);
}
/**
* Get an unmodifiable <code>Map</code> of the <code>ValidatorAction</code>s.
*/
public Map getValidatorActions() {
return Collections.unmodifiableMap(hActions);
}
/**
* Builds a key to store the <code>FormSet</code> under based on it's language, country,
* and variant values.
*/
protected String buildKey(FormSet fs) {
String key = ((fs.getLanguage() != null && fs.getLanguage().length() > 0) ? fs.getLanguage() : "") +
((fs.getCountry() != null && fs.getCountry().length() > 0) ? "_" + fs.getCountry() : "") +
((fs.getVariant() != null && fs.getVariant().length() > 0) ? "_" + fs.getVariant() : "");
if (key.length() == 0)
key = defaultLocale.toString();
return key;
}
/**
* <p>Gets a <code>Form</code> based on the name of the form and the <code>Locale</code> that
* most closely matches the <code>Locale</code> passed in. The order of <code>Locale</code>
* matching is:</p>
* <ol>
* <li>language + country + variant</li>
* <li>language + country</li>
* <li>language</li>
* <li>default locale</li>
* </ol>
*/
public Form get(Locale locale, Object formKey) {
return get(locale.getLanguage(), locale.getCountry(), locale.getVariant(), formKey);
}
/**
* <p>Gets a <code>Form</code> based on the name of the form and the <code>Locale</code> that
* most closely matches the <code>Locale</code> passed in. The order of <code>Locale</code>
* matching is:</p>
* <ol>
* <li>language + country + variant</li>
* <li>language + country</li>
* <li>language</li>
* <li>default locale</li>
* </ol>
*/
public Form get(String language, String country, String variant, Object formKey) {
FormSet fs = null;
Form f = null;
String key = null;
Object o = null;
key = ((language != null && language.length() > 0) ? language : "") +
((country != null && country.length() > 0) ? "_" + country : "") +
((variant != null && variant.length() > 0) ? "_" + variant : "");
//System.out.println("ValidatorResources::get #1 - locale=" + locale.toString() + " key=" + key);
o = hFormSets.get(key);
if (o != null) {
fs = (FormSet)o;
if (fs != null)
f = fs.getForm(formKey);
}
if (f == null) {
key = ((language != null && language.length() > 0) ? language : "") +
((country != null && country.length() > 0) ? "_" + country : "");
//System.out.println("ValidatorResources::get #2 - locale=" + locale.toString() + " key=" + key);
o = hFormSets.get(key);
if (o != null) {
fs = (FormSet)o;
if (fs != null)
f = fs.getForm(formKey);
}
}
if (f == null) {
key = ((language != null && language.length() > 0) ? language : "");
//System.out.println("ValidatorResources::get #3 - locale=" + locale.toString() + " key=" + key);
o = hFormSets.get(key);
if (o != null) {
fs = (FormSet)o;
if (fs != null)
f = fs.getForm(formKey);
}
}
if (f == null) {
key = Locale.getDefault().toString();
//System.out.println("ValidatorResources::get #4 - locale=" + locale.toString() + " key=" + key);
o = hFormSets.get(key);
if (o != null) {
fs = (FormSet)o;
if (fs != null)
f = fs.getForm(formKey);
}
}
return f;
}
/**
* Gets the debugging detail level for this resource.
*/
public int getDebug() {
return logger.getDebug();
}
/**
* Sets the debugging detail level for this resource.
*/
public void setDebug(int debug) {
logger.setDebug(debug);
}
// Commented out for now because it should really try all the different locale combinations
// like the get method does.
//public boolean containsKey(Locale locale, Object key) {
// FormSet fs = null;
// Object o = hFormSets.get(locale.toString());
// if (o != null)
// fs = (FormSet)o;
//
// if (fs != null && fs.getForm(key) != null)
// return true;
//
// return false;
//}
/**
* <p>Process the <code>ValidatorResources</code> object. </p>
*
* <p>Currently sets the <code>FastHashMap</code>s to the 'fast' mode.</p>
*/
public void process() {
hFormSets.setFast(true);
hConstants.setFast(true);
hActions.setFast(true);
processForms();
}
/**
* <p>Process the <code>Form</code> objects. This clones the <code>Field</code>s
* that don't exist in a <code>FormSet</code> compared to the default
* <code>FormSet</code>.</p>
*/
public void processForms() {
//hFormSets.put(buildKey(fs), fs);
String defaultKey = defaultLocale.toString();
// Loop through FormSets
for (Iterator i = hFormSets.keySet().iterator(); i.hasNext(); ) {
String key = (String)i.next();
FormSet fs = (FormSet)hFormSets.get(key);
// Skip default FormSet
if (key.equals(defaultKey))
continue;
// Loop through Forms and copy/clone fields from default locale
for (Iterator x = fs.getForms().keySet().iterator(); x.hasNext(); ) {
String formKey = (String)x.next();
Form form = (Form)fs.getForms().get(formKey);
// Create a new Form object so the order from the default is
// maintained (very noticable in the JavaScript).
Form newForm = new Form();
newForm.setName(form.getName());
// Loop through the default locale form's fields
// If they don't exist in the current locale's form, then clone them.
Form defaultForm = get(defaultLocale, formKey);
for (Iterator defaultFields = defaultForm.getFields().iterator(); defaultFields.hasNext(); ) {
Field defaultField = (Field)defaultFields.next();
String fieldKey = defaultField.getKey();
if (form.getFieldMap().containsKey(fieldKey)) {
newForm.addField((Field)form.getFieldMap().get(fieldKey));
} else {
Field field = getClosestLocaleField(fs, formKey, fieldKey);
newForm.addField((Field)field.clone());
}
}
fs.addForm(newForm);
}
}
// Process Fully Constructed FormSets
for (Iterator i = hFormSets.values().iterator(); i.hasNext(); ) {
FormSet fs = (FormSet)i.next();
if (!fs.isProcessed())
fs.process(hConstants);
}
}
protected Field getClosestLocaleField(FormSet fs, String formKey, String fieldKey) {
Field field = null;
String language = fs.getLanguage();
String country = fs.getCountry();
String variant = fs.getVariant();
if (!GenericValidator.isBlankOrNull(language) &&
!GenericValidator.isBlankOrNull(country) &&
!GenericValidator.isBlankOrNull(variant)) {
Form form = get(language, country, null, formKey);
if (form.getFieldMap().containsKey(fieldKey))
field = (Field)form.getFieldMap().get(fieldKey);
}
if (field == null) {
if (!GenericValidator.isBlankOrNull(language) &&
!GenericValidator.isBlankOrNull(country)) {
Form form = get(language, null, null, formKey);
if (form.getFieldMap().containsKey(fieldKey))
field = (Field)form.getFieldMap().get(fieldKey);
}
}
if (field == null) {
Form form = get(defaultLocale, formKey);
if (form.getFieldMap().containsKey(fieldKey))
field = (Field)form.getFieldMap().get(fieldKey);
}
return field;
}
}
1.1 jakarta-commons/validator/src/share/org/apache/commons/validator/ValidatorResourcesInitializer.java
Index: ValidatorResourcesInitializer.java
===================================================================
/*
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.validator;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.digester.Digester;
import org.xml.sax.SAXException;
/**
* <p>Maps an xml file to <code>ValidatorResources</code>.</p>
*
* @author David Winterfeldt
*/
public class ValidatorResourcesInitializer {
/**
* Initializes a <code>ValidatorResources</code> based on a
* file path.
*
* @param fileName The file path for the xml resource.
*/
public static ValidatorResources initialize(String fileName)
throws IOException {
return initialize(fileName, 0);
}
/**
* Initializes a <code>ValidatorResources</code> based on an
* <code>InputStream</code>.
*
* @param in <code>InputStream</code> for the xml resource.
*/
public static ValidatorResources initialize(InputStream in)
throws IOException {
return initialize(in, 0);
}
/**
* Initializes a <code>ValidatorResources</code> based on a
* file path and the debug level.
*
* @param fileName The file path for the xml resource.
* @param debug The debug level
*/
public static ValidatorResources initialize(String fileName, int debug)
throws IOException {
BufferedInputStream in = new BufferedInputStream(new FileInputStream(fileName));
return initialize(new DefaultValidatorLog(), in, debug);
}
/**
* Initializes a <code>ValidatorResources</code> based on an
* <code>InputStream</code> and the debug level.
*
* @param in <code>InputStream</code> for the xml resource.
* @param debug The debug level
*/
public static ValidatorResources initialize(InputStream in, int debug)
throws IOException {
return initialize(new DefaultValidatorLog(), in, debug);
}
/**
* Initializes a <code>ValidatorResources</code> based on an
* <code>ValidatorLog</code>, <code>InputStream</code>, and the debug level.
*
* @param logger Used for logging.
* @param in <code>InputStream</code> for the xml resource.
* @param debug The debug level
*/
public static ValidatorResources initialize(ValidatorLog logger, InputStream in, int debug)
throws IOException {
logger.setDebug(debug);
ValidatorResources resources = new ValidatorResources(logger);
Digester digester = new Digester();
digester.push(resources);
digester.setDebug(debug);
digester.setNamespaceAware(true);
digester.setValidating(false);
// Create Global Constant objects
digester.addObjectCreate("form-validation/global/constant",
"org.apache.commons.validator.Constant", "className");
digester.addSetProperties("form-validation/global/constant");
digester.addSetNext("form-validation/global/constant", "addConstant",
"org.apache.commons.validator.Constant");
// Create Global ValidatorAction objects
digester.addObjectCreate("form-validation/global/validator",
"org.apache.commons.validator.ValidatorAction", "className");
digester.addSetProperties("form-validation/global/validator");
digester.addSetNext("form-validation/global/validator", "addValidatorAction",
"org.apache.commons.validator.ValidatorAction");
// Add the body of a javascript element to the Validatoraction
digester.addCallMethod("form-validation/global/validator",
"setJavascript", 1);
digester.addCallParam("form-validation/global/validator/javascript", 0);
// Create FormSet objects
digester.addObjectCreate("form-validation/formset", "org.apache.commons.validator.FormSet",
"className");
digester.addSetProperties("form-validation/formset");
digester.addSetNext("form-validation/formset", "put",
"org.apache.commons.validator.FormSet");
// Create Constant objects
digester.addObjectCreate("form-validation/formset/constant",
"org.apache.commons.validator.Constant", "className");
digester.addSetProperties("form-validation/formset/constant");
digester.addSetNext("form-validation/formset/constant", "addConstant",
"org.apache.commons.validator.Constant");
// Create Form objects
digester.addObjectCreate("form-validation/formset/form",
"org.apache.commons.validator.Form", "className");
digester.addSetProperties("form-validation/formset/form");
digester.addSetNext("form-validation/formset/form", "addForm",
"org.apache.commons.validator.Form");
// Create Field objects
digester.addObjectCreate("form-validation/formset/form/field",
"org.apache.commons.validator.Field", "className");
digester.addSetProperties("form-validation/formset/form/field");
digester.addSetNext("form-validation/formset/form/field", "addField",
"org.apache.commons.validator.Field");
// Create Var objects
digester.addCallMethod("form-validation/formset/form/field/var",
"addVarParam", 3);
digester.addCallParam("form-validation/formset/form/field/var/var-name", 0);
digester.addCallParam("form-validation/formset/form/field/var/var-value", 1);
digester.addCallParam("form-validation/formset/form/field/var/var-jstype", 2);
// Create Msg object
digester.addObjectCreate("form-validation/formset/form/field/msg",
"org.apache.commons.validator.Msg", "className");
digester.addSetProperties("form-validation/formset/form/field/msg");
digester.addSetNext("form-validation/formset/form/field/msg", "addMsg",
"org.apache.commons.validator.Msg");
// Create Arg objects
// Arg0
digester.addObjectCreate("form-validation/formset/form/field/arg0",
"org.apache.commons.validator.Arg", "className");
digester.addSetProperties("form-validation/formset/form/field/arg0");
digester.addSetNext("form-validation/formset/form/field/arg0", "addArg0",
"org.apache.commons.validator.Arg");
// Arg1
digester.addObjectCreate("form-validation/formset/form/field/arg1",
"org.apache.commons.validator.Arg", "className");
digester.addSetProperties("form-validation/formset/form/field/arg1");
digester.addSetNext("form-validation/formset/form/field/arg1", "addArg1",
"org.apache.commons.validator.Arg");
// Arg2
digester.addObjectCreate("form-validation/formset/form/field/arg2",
"org.apache.commons.validator.Arg", "className");
digester.addSetProperties("form-validation/formset/form/field/arg2");
digester.addSetNext("form-validation/formset/form/field/arg2", "addArg2",
"org.apache.commons.validator.Arg");
// Arg3
digester.addObjectCreate("form-validation/formset/form/field/arg3",
"org.apache.commons.validator.Arg", "className");
digester.addSetProperties("form-validation/formset/form/field/arg3");
digester.addSetNext("form-validation/formset/form/field/arg3", "addArg3",
"org.apache.commons.validator.Arg");
try {
// Parse the input stream to initialize our database
digester.parse(in);
in.close();
} catch (SAXException e) {
logger.log("ValidatorResourcesInitializer::initialize - SAXException: " + e.getMessage(), e);
} finally {
if (in != null)
try {in.close(); } catch (Exception e) {}
}
resources.process();
return resources;
}
}
1.1 jakarta-commons/validator/src/share/org/apache/commons/validator/ValidatorUtil.java
Index: ValidatorUtil.java
===================================================================
/*
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.validator;
import org.apache.commons.beanutils.PropertyUtils;
/**
* <p>This class helps provides some useful methods for retrieving objects
* from different scopes of the application.</p>
*
* @author David Winterfeldt
*/
public class ValidatorUtil {
/**
* <p>Replace part of a <code>String</code> with another value.</p>
*
* @param value <code>String</code> to perform the replacement on.
* @param key The name of the constant.
* @param replaceValue The value of the constant.
*/
public static String replace(String value, String key, String replaceValue) {
if (value != null && key != null && replaceValue != null) {
int pos = value.indexOf(key);
if (pos >= 0) {
int length = value.length();
int start = pos;
int end = pos + key.length();
if (length == key.length()) {
value = replaceValue;
} else if (end == length) {
value = value.substring(0, start) + replaceValue; //+ value.substring(end);
} else {
value = value.substring(0, start) + replaceValue + replace(value.substring(end), key, replaceValue);
}
}
}
return value;
}
/**
* Convenience method for getting a value from a bean property as a <code>String</code>.
*/
public static String getValueAsString(Object bean, String property) {
Object value = null;
try {
value = PropertyUtils.getProperty(bean, property);
} catch (Exception e) {
//log("ValidatorUtil::getValueAsString() - " + e.getMessage(), e);
}
return (value != null ? value.toString() : null);
}
}
1.1 jakarta-commons/validator/src/share/org/apache/commons/validator/Var.java
Index: Var.java
===================================================================
/*
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.validator;
/**
* <p>Used in the Validation framework for creating a variable. A variable
* can be used to pass in values on a field level for a validation method.</p>
*
* <ul><li>See /WEB-INF/validation.xml for validation rules.</li></ul>
*
* @author David Winterfeldt
*/
public class Var implements Cloneable, java.io.Serializable {
/**
* Int Constant for JavaScript type. This is used when generating the JavaScript objects
* for use in client side validation.
*/
public final static String JSTYPE_INT = "int";
/**
* String Constant for JavaScript type. This is used when generating the JavaScript objects
* for use in client side validation.
*/
public final static String JSTYPE_STRING = "string";
/**
* Regular Expression Constant for JavaScript type. This is used when generating the JavaScript objects
* for use in client side validation.
*/
public final static String JSTYPE_REGEXP = "regexp";
/**
* The name of the variable.
*/
private String name = null;
/**
* The name of the value.
*/
private String value = null;
/**
* The JavaScript type of the variable.
*/
private String jsType = null;
public Var() {}
public Var(String name, String value, String jsType) {
this.name = name;
this.value = value;
this.jsType = jsType;
}
/**
* Gets the name of the variable.
*/
public String getName() {
return name;
}
/**
* Sets the name of the variable.
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the value of the variable.
*/
public String getValue() {
return value;
}
/**
* Sets the value of the variable.
*/
public void setValue(String value) {
this.value = value;
}
/**
* Gets the JavaScript type of the variable.
*/
public String getJsType() {
return jsType;
}
/**
* Sets the JavaScript type of the variable.
*/
public void setJsType(String jsType) {
this.jsType = jsType;
}
public Object clone() {
try {
Var var = (Var)super.clone();
if (name != null)
var.name = new String(name);
if (value != null)
var.value = new String(value);
if (jsType != null)
var.jsType = new String(jsType);
return var;
} catch (CloneNotSupportedException e) {
throw new InternalError(e.toString());
}
}
public String toString() {
StringBuffer results = new StringBuffer();
results.append("Var: name=");
results.append(name);
results.append(" value=");
results.append(value);
results.append(" jsType=");
results.append(jsType);
results.append("\n");
return results.toString();
}
}
--
To unsubscribe, e-mail: <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>
Re: cvs
commit:jakarta-commons/validator/src/share/org/apache/commons/validator
Arg.javaConstant.java DefaultValidatorLog.java Field.java Form.java
FormSet.javaGenericValidator.java Msg.java Validator.java
ValidatorAction.javaValidatorException.java ValidatorLog.java
ValidatorResources.javaValidatorResourcesInitializer.java
ValidatorUtil.java Var.java
Posted by Ted Husted <hu...@apache.org>.
There was a long discussion on General, where we realized that we were
drifting away from the standard conventions. So some of us, like Jon and
I, are volunteering to nag people when we notice anything awry.
The preferred style is to always enclose if-else blocks in braces, to
avoid problems when another statement is added later. I'm forever
forgetting to do this myself. Both Sun and The Elements of Java Style
advocate this.
-Ted.
Jon Scott Stevens wrote:
>
> Sigh. We just went over this...
>
> <http://jakarta.apache.org/site/source.html>
>
> -jon
>
> on 1/6/02 12:45 PM, "David Winterfeldt" <dw...@yahoo.com> wrote:
>
> > What would the preferred style be?
> >
> > David
> >
> > --- Jon Scott Stevens <jo...@latchkey.com> wrote:
> >> on 1/5/02 9:08 PM, "dwinterfeldt@apache.org"
> >> <dw...@apache.org>
> >> wrote:
> >>
> >>> if (indexedListProperty != null)
> >>> field.setIndexedListProperty(new
> >> String(indexedListProperty));
> >>
> >> Bad coding style.
> >>
> >> -jon
--
To unsubscribe, e-mail: <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>
Re: cvs commit:
jakarta-commons/validator/src/share/org/apache/commons/validator Arg.java
Constant.java DefaultValidatorLog.java Field.java Form.java FormSet.java
GenericValidator.java Msg.java Validator.java ValidatorAction.java
ValidatorException.java ValidatorLog.java ValidatorResources.java
ValidatorResourcesInitializer.java ValidatorUtil.java Var.java
Posted by Jon Scott Stevens <jo...@latchkey.com>.
Sigh. We just went over this...
<http://jakarta.apache.org/site/source.html>
-jon
on 1/6/02 12:45 PM, "David Winterfeldt" <dw...@yahoo.com> wrote:
> What would the preferred style be?
>
> David
>
> --- Jon Scott Stevens <jo...@latchkey.com> wrote:
>> on 1/5/02 9:08 PM, "dwinterfeldt@apache.org"
>> <dw...@apache.org>
>> wrote:
>>
>>> if (indexedListProperty != null)
>>> field.setIndexedListProperty(new
>> String(indexedListProperty));
>>
>> Bad coding style.
>>
>> -jon
--
To unsubscribe, e-mail: <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>
Re: cvs commit: jakarta-commons/validator/src/share/org/apache/commons/validator Arg.java Constant.java DefaultValidatorLog.java Field.java Form.java FormSet.java GenericValidator.java Msg.java Validator.java ValidatorAction.java ValidatorException.java ValidatorLog.java ValidatorResources.java ValidatorResourcesInitializer.java ValidatorUtil.java Var.java
Posted by David Winterfeldt <dw...@yahoo.com>.
What would the preferred style be?
David
--- Jon Scott Stevens <jo...@latchkey.com> wrote:
> on 1/5/02 9:08 PM, "dwinterfeldt@apache.org"
> <dw...@apache.org>
> wrote:
>
> > if (indexedListProperty != null)
> > field.setIndexedListProperty(new
> String(indexedListProperty));
>
> Bad coding style.
>
> -jon
>
>
> --
> To unsubscribe, e-mail:
> <ma...@jakarta.apache.org>
> For additional commands, e-mail:
> <ma...@jakarta.apache.org>
>
__________________________________________________
Do You Yahoo!?
Send FREE video emails in Yahoo! Mail!
http://promo.yahoo.com/videomail/
--
To unsubscribe, e-mail: <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>
Re: cvs commit:
jakarta-commons/validator/src/share/org/apache/commons/validator Arg.java
Constant.java DefaultValidatorLog.java Field.java Form.java FormSet.java
GenericValidator.java Msg.java Validator.java ValidatorAction.java
ValidatorException.java ValidatorLog.java ValidatorResources.java
ValidatorResourcesInitializer.java ValidatorUtil.java Var.java
Posted by Jon Scott Stevens <jo...@latchkey.com>.
on 1/5/02 9:08 PM, "dwinterfeldt@apache.org" <dw...@apache.org>
wrote:
> if (indexedListProperty != null)
> field.setIndexedListProperty(new String(indexedListProperty));
Bad coding style.
-jon
--
To unsubscribe, e-mail: <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>