haul 2003/08/15 08:53:20
Modified: src/java/org/apache/cocoon/acting
AbstractValidatorAction.java
FormValidatorAction.java
SessionValidatorAction.java
src/blocks/session-fw/java/org/apache/cocoon/webapps/session/acting
SessionFormAction.java
Log:
Refactor validation actions and move common code to abstract validator action.
Revision Changes Path
1.2 +525 -189
cocoon-2.1/src/java/org/apache/cocoon/acting/AbstractValidatorAction.java
Index: AbstractValidatorAction.java
===================================================================
RCS file:
/home/cvs/cocoon-2.1/src/java/org/apache/cocoon/acting/AbstractValidatorAction.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- AbstractValidatorAction.java 9 Mar 2003 00:08:38 -0000 1.1
+++ AbstractValidatorAction.java 15 Aug 2003 15:53:20 -0000 1.2
@@ -53,10 +53,24 @@
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
+import org.apache.avalon.framework.parameters.Parameters;
+
+import org.apache.cocoon.Constants;
+import org.apache.cocoon.environment.SourceResolver;
+import org.apache.cocoon.environment.ObjectModelHelper;
+import org.apache.cocoon.environment.Redirector;
+import org.apache.cocoon.util.Tokenizer;
+
import org.apache.regexp.RE;
import org.apache.regexp.RESyntaxException;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
import java.util.Map;
+import java.util.Set;
+import java.util.Vector;
/**
* Abstract implementation of action that needs to perform validation of
@@ -67,6 +81,53 @@
* explicitely specify which parameters to validate - through a sitemap
* parameter.
*
+ * <h3>Variant 1</h3>
+ * <pre>
+ * <map:act type="validator">
+ * <parameter name="descriptor"
value="context://descriptor.xml">
+ * <parameter name="validate" value="username,password">
+ * </map:act>
+ * </pre>
+ *
+ * <p>The list of parameters to be validated is specified as a comma
+ * separated list of their names. descriptor.xml can therefore be used
+ * among many various actions. If the list contains only of <code>*</code>,
+ * all parameters in the file will be validated.</p>
+ *
+ * <h3>Variant 2</h3>
+ * <pre>
+ * <map:act type="validator">
+ * <parameter name="descriptor"
value="context://descriptor.xml">
+ * <parameter name="validate-set" value="is-logged-in">
+ * </map:act>
+ * </pre>
+ *
+ * <p>The parameter "validate-set" tells to take a given
+ * "constraint-set" from description file and test all parameters
+ * against given criteria. This variant is more powerful, more aspect
+ * oriented and more flexibile than the previous one, because it
+ * allows comparsion constructs, etc. See AbstractValidatorAction
+ * documentation.</p>
+ *
+ * <p>For even more powerful validation, constraints can be grouped
+ * and used independently of the parameter name. If a validate element
+ * has a <code>rule</code> attribute, it uses the parameter with that
+ * name as a rule template and validates the parameter from the
+ * <code>name</code> attribute with that rule.</p>
+ *
+ * <p>This action returns null when validation fails, otherwise it
+ * provides all validated parameters to the sitemap via {name}
+ * expression.</p>
+ *
+ * <p>In addition a request attribute
+ * <code>org.apache.cocoon.acting.FormValidatorAction.results</code>
+ * contains the validation results in both cases and make it available
+ * to XSPs. The special parameter "*" contains either the validation
+ * result "OK", if all parameters were validated successfully, or
+ * "ERROR" otherwise. Mind you that redirections create new request
+ * objects and thus the result is not available for the target
+ * page.</p>
+ *
* <pre>
* <root>
* <parameter name="username" type="string" nullable="no"/>
@@ -93,6 +154,12 @@
* <validate name="renewpassword"
* equals-to-param="newpass"/>
* </constraint-set>
+ *
+ * <constraint-set name="all">
+ * <include name="is-logged-in"/>
+ * <include name="is-in-admin-role"/>
+ * <include name="new-passwords-match"/>
+ * </constraint-set>
* </root>
* </pre>
*
@@ -155,9 +222,72 @@
* @version CVS $Id$
*/
public abstract class AbstractValidatorAction
-extends AbstractComplementaryConfigurableAction
-implements Configurable
-{
+ extends AbstractComplementaryConfigurableAction
+ implements Configurable {
+
+ /**
+ * Reads parameter values for all parameters that are contained in the
active
+ * constraint list. If a parameter has multiple values, all are stored
in the
+ * resulting map.
+ *
+ * @param objectModel the object model
+ * @param set a collection of parameter names
+ * @return
+ */
+ abstract protected HashMap createMapOfParameters(Map objectModel,
Collection set);
+
+ /**
+ * Are parameters encoded as strings?
+ * @return
+ */
+ abstract boolean isStringEncoded();
+
+ /*
+ * main method
+ */
+ public Map act(
+ Redirector redirector,
+ SourceResolver resolver,
+ Map objectModel,
+ String src,
+ Parameters parameters) {
+
+ Configuration conf = this.getDescriptor(resolver, objectModel,
parameters);
+ if (conf == null)
+ return null;
+
+ String valstr =
+ parameters.getParameter("validate", (String)
settings.get("validate", "")).trim();
+ String valsetstr =
+ parameters
+ .getParameter("validate-set", (String)
settings.get("validate-set", ""))
+ .trim();
+ Map desc = this.indexConfiguration(conf.getChildren("parameter"));
+
+ Map actionMap = new HashMap();
+ Map resultMap = new HashMap();
+ Collection params = null;
+ boolean allOK = false;
+
+ if (!"".equals(valstr)) {
+ if (getLogger().isDebugEnabled())
+ getLogger().debug(
+ "Validating parameters " + "as specified via 'validate'
parameter");
+ params = this.getSetOfParameterNamesFromSitemap(valstr, desc);
+
+ } else if (!"".equals(valsetstr)) {
+ if (getLogger().isDebugEnabled())
+ getLogger().debug(
+ "Validating parameters " + "from given constraint-set "
+ valsetstr);
+ Map csets =
this.indexConfiguration(conf.getChildren("constraint-set"));
+ params = this.resolveConstraints(valsetstr, csets);
+ }
+ HashMap values = this.createMapOfParameters(objectModel, params);
+ allOK = this.validateSetOfParameters(desc, actionMap, resultMap,
params, values, this.isStringEncoded());
+
+ return this.setResult(objectModel, actionMap, resultMap, allOK);
+ }
+
/**
* Try to validate given parameter.
* @param name The name of the parameter to validate.
@@ -172,8 +302,12 @@
* etc.
* @return The validated parameter.
*/
- public ValidatorActionHelper validateParameter(String name,
Configuration constraints,
- Configuration[] conf, Map params, boolean isString) {
+ public ValidatorActionHelper validateParameter(
+ String name,
+ Configuration constraints,
+ Map conf,
+ Map params,
+ boolean isString) {
return validateParameter(name, name, constraints, conf, params,
isString);
}
@@ -194,76 +328,85 @@
* etc.
* @return The validated parameter.
*/
- public ValidatorActionHelper validateParameter(String name, String rule,
Configuration constraints,
- Configuration[] conf, Map params, boolean isString) {
+ public ValidatorActionHelper validateParameter(
+ String name,
+ String rule,
+ Configuration constraints,
+ Map conf,
+ Map params,
+ boolean isString) {
String type = null;
int i = 0;
if (getLogger().isDebugEnabled())
- getLogger().debug ("Validating parameter: " + name + " using
rule: "+rule);
+ getLogger().debug("Validating parameter: " + name + " using
rule: " + rule);
/* try to find matching param description in conf tree */
try {
boolean found = false;
- for (i = 0; i < conf.length; i ++) {
- if (rule.equals (conf[i].getAttribute ("name"))) {
- found = true;
- break;
- }
- }
+ Configuration theConf = (Configuration) conf.get(rule);
+ type = theConf.getAttribute("type");
- if (!found) {
- if (getLogger().isDebugEnabled())
- getLogger().debug("Description for parameter "
- + name + " / " + rule + " not found");
- return null;
- }
+ return validateValue(name, constraints, theConf, params,
isString, type);
- /* check parameter's type */
- type = conf[i].getAttribute ("type");
} catch (Exception e) {
if (getLogger().isDebugEnabled())
getLogger().debug("No type specified for parameter " + name);
return null;
}
+ }
- /*
- * Validation phase
- */
+ /**
+ * Validate a single parameter value.
+ *
+ * @param name String holding the name of the parameter
+ * @param constraints Configuration holding the constraint set
configuration for the parameter
+ * @param conf Configuration holding the parameter configuration
+ * @param params Map of parameter values to be validated
+ * @param isString boolean indicating if the value is string encoded
+ * @param type string holding the name of the datatype to validate value
+ * @return
+ */
+ protected ValidatorActionHelper validateValue(
+ String name,
+ Configuration constraints,
+ Configuration conf,
+ Map params,
+ boolean isString,
+ String type) {
Object value = params.get(name);
-
- if (value!=null && value.getClass().isArray()) {
+
+ if (value != null && value.getClass().isArray()) {
Object[] values = (Object[]) value;
ValidatorActionHelper vaH = null;
ValidatorActionResult vaR = ValidatorActionResult.OK;
- for (int j=0; j<values.length; j++) {
+ for (int j = 0; j < values.length; j++) {
value = values[j];
- if ("string".equals (type)) {
- vaH = validateString(name, constraints, conf[i], params,
value);
- } else if ("long".equals (type)) {
- vaH = validateLong(name, constraints, conf[i], params,
isString, value);
- } else if ("double".equals (type)) {
- vaH = validateDouble(name, constraints, conf[i], params,
isString, value);
+ if ("string".equals(type)) {
+ vaH = validateString(name, constraints, conf, params,
value);
+ } else if ("long".equals(type)) {
+ vaH = validateLong(name, constraints, conf, params,
isString, value);
+ } else if ("double".equals(type)) {
+ vaH = validateDouble(name, constraints, conf, params,
isString, value);
} else {
if (getLogger().isDebugEnabled())
- getLogger().debug ("Unknown type " + type
- + " specified for parameter " +
name);
+ getLogger().debug(
+ "Unknown type " + type + " specified for
parameter " + name);
return null;
}
- vaR = (vaR.getPos() < vaH.getResult().getPos() ?
vaH.getResult() : vaR );
+ vaR = (vaR.getPos() < vaH.getResult().getPos() ?
vaH.getResult() : vaR);
}
return new ValidatorActionHelper(vaH.getObject(), vaR);
} else {
- if ("string".equals (type)) {
- return validateString(name, constraints, conf[i], params,
value);
- } else if ("long".equals (type)) {
- return validateLong(name, constraints, conf[i], params,
isString, value);
- } else if ("double".equals (type)) {
- return validateDouble(name, constraints, conf[i], params,
isString, value);
+ if ("string".equals(type)) {
+ return validateString(name, constraints, conf, params,
value);
+ } else if ("long".equals(type)) {
+ return validateLong(name, constraints, conf, params,
isString, value);
+ } else if ("double".equals(type)) {
+ return validateDouble(name, constraints, conf, params,
isString, value);
} else {
if (getLogger().isDebugEnabled())
- getLogger().debug ("Unknown type " + type
- + " specified for parameter " + name);
+ getLogger().debug("Unknown type " + type + " specified
for parameter " + name);
}
return null;
}
@@ -273,15 +416,19 @@
* Validates nullability and default value for given parameter. If given
* constraints are not null they are validated as well.
*/
- private ValidatorActionHelper validateString(String name, Configuration
constraints,
- Configuration conf, Map params, Object param) {
+ private ValidatorActionHelper validateString(
+ String name,
+ Configuration constraints,
+ Configuration conf,
+ Map params,
+ Object param) {
String value = null;
String dflt = getDefault(conf, constraints);
boolean nullable = getNullable(conf, constraints);
if (getLogger().isDebugEnabled())
- getLogger().debug ("Validating string parameter " + name);
+ getLogger().debug("Validating string parameter " + name);
try {
value = getStringValue(param);
} catch (Exception e) {
@@ -290,7 +437,7 @@
}
if (value == null) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("String parameter " + name + " is null");
+ getLogger().debug("String parameter " + name + " is null");
if (!nullable) {
return new ValidatorActionHelper(value,
ValidatorActionResult.ISNULL);
} else {
@@ -298,118 +445,122 @@
}
}
if (constraints != null) {
- String eq = constraints.getAttribute ("equals-to", "");
- eq = conf.getAttribute ("equals-to", eq);
+ String eq = constraints.getAttribute("equals-to", "");
+ eq = conf.getAttribute("equals-to", eq);
- String eqp = constraints.getAttribute ("equals-to-param", "");
- eqp = conf.getAttribute ("equals-to-param", eqp);
+ String eqp = constraints.getAttribute("equals-to-param", "");
+ eqp = conf.getAttribute("equals-to-param", eqp);
- String regex = conf.getAttribute ("matches-regex", "");
- regex = constraints.getAttribute ( "matches-regex", regex);
+ String regex = conf.getAttribute("matches-regex", "");
+ regex = constraints.getAttribute("matches-regex", regex);
- String oneOf = conf.getAttribute ("one-of", "");
- oneOf = constraints.getAttribute ( "one-of", oneOf);
+ String oneOf = conf.getAttribute("one-of", "");
+ oneOf = constraints.getAttribute("one-of", oneOf);
- Long minlen = getAttributeAsLong (conf, "min-len", null);
- minlen = getAttributeAsLong (constraints, "min-len", minlen);
+ Long minlen = getAttributeAsLong(conf, "min-len", null);
+ minlen = getAttributeAsLong(constraints, "min-len", minlen);
- Long maxlen = getAttributeAsLong (conf, "max-len", null);
- maxlen = getAttributeAsLong (constraints, "max-len", maxlen);
+ Long maxlen = getAttributeAsLong(conf, "max-len", null);
+ maxlen = getAttributeAsLong(constraints, "max-len", maxlen);
// Validate whether param is equal to constant
- if (!"".equals (eq)) {
+ if (!"".equals(eq)) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("String parameter "
- + name + " should be equal to " + eq);
- if (!value.equals (eq)) {
+ getLogger().debug("String parameter " + name + " should
be equal to " + eq);
+ if (!value.equals(eq)) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("and it is not");
- return new ValidatorActionHelper ( value,
ValidatorActionResult.NOMATCH);
+ getLogger().debug("and it is not");
+ return new ValidatorActionHelper(value,
ValidatorActionResult.NOMATCH);
}
}
// Validate whether param is equal to another param
// FIXME: take default value of param being compared with into
// account?
- if (!"".equals (eqp)) {
+ if (!"".equals(eqp)) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("String parameter "
- + name + " should be equal to " +
params.get (eqp));
- if (!value.equals (params.get (eqp))) {
+ getLogger().debug(
+ "String parameter " + name + " should be equal to "
+ params.get(eqp));
+ if (!value.equals(params.get(eqp))) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("and it is not");
- return new ValidatorActionHelper ( value,
ValidatorActionResult.NOMATCH);
+ getLogger().debug("and it is not");
+ return new ValidatorActionHelper(value,
ValidatorActionResult.NOMATCH);
}
}
// Validate whether param length is at least of minimum length
if (minlen != null) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("String parameter "
- + name + " should be at least " +
minlen + " characters long");
- if ( value.length() < minlen.longValue() ) {
- if (getLogger().isDebugEnabled())
- getLogger().debug ("and it is shorter (" +
- value.length() + ")" );
- return new ValidatorActionHelper ( value,
ValidatorActionResult.TOOSMALL);
+ getLogger().debug(
+ "String parameter "
+ + name
+ + " should be at least "
+ + minlen
+ + " characters long");
+ if (value.length() < minlen.longValue()) {
+ if (getLogger().isDebugEnabled())
+ getLogger().debug("and it is shorter (" +
value.length() + ")");
+ return new ValidatorActionHelper(value,
ValidatorActionResult.TOOSMALL);
}
}
// Validate whether param length is at most of maximum length
if (maxlen != null) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("String parameter "
- + name + " should be at most " +
maxlen + " characters long");
+ getLogger().debug(
+ "String parameter "
+ + name
+ + " should be at most "
+ + maxlen
+ + " characters long");
- if ( value.length() > maxlen.longValue() ) {
+ if (value.length() > maxlen.longValue()) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("and it is longer (" +
- value.length() + ")" );
- return new ValidatorActionHelper ( value,
ValidatorActionResult.TOOLARGE);
+ getLogger().debug("and it is longer (" +
value.length() + ")");
+ return new ValidatorActionHelper(value,
ValidatorActionResult.TOOLARGE);
}
}
// Validate wheter param matches regular expression
- if (!"".equals (regex)) {
+ if (!"".equals(regex)) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("String parameter " + name +
- " should match regexp \"" + regex +
"\"" );
+ getLogger().debug(
+ "String parameter " + name + " should match regexp
\"" + regex + "\"");
try {
- RE r = new RE ( regex );
- if ( !r.match(value) ) {
+ RE r = new RE(regex);
+ if (!r.match(value)) {
if (getLogger().isDebugEnabled())
getLogger().debug("and it does not match");
- return new ValidatorActionHelper ( value,
ValidatorActionResult.NOMATCH);
+ return new ValidatorActionHelper(value,
ValidatorActionResult.NOMATCH);
};
- } catch ( RESyntaxException rese ) {
+ } catch (RESyntaxException rese) {
if (getLogger().isDebugEnabled())
- getLogger().error ("String parameter " + name +
- " regex error ", rese);
- return new ValidatorActionHelper ( value,
ValidatorActionResult.NOMATCH);
+ getLogger().error("String parameter " + name + "
regex error ", rese);
+ return new ValidatorActionHelper(value,
ValidatorActionResult.NOMATCH);
}
}
-
+
// Validates against a set of possibilities
- if (!"".equals(oneOf)){
+ if (!"".equals(oneOf)) {
if (getLogger().isDebugEnabled())
- getLogger().debug("String parameter " + name +
- " should be one of \"" + oneOf +"\"" );
+ getLogger().debug(
+ "String parameter " + name + " should be one of \""
+ oneOf + "\"");
if (!oneOf.startsWith("|"))
- oneOf="|"+oneOf;
+ oneOf = "|" + oneOf;
if (!oneOf.endsWith("|"))
- oneOf=oneOf+"|";
- if (value.indexOf("|") != -1){
+ oneOf = oneOf + "|";
+ if (value.indexOf("|") != -1) {
if (getLogger().isDebugEnabled())
- getLogger().debug("String parameter " + name +
- "contains \"|\" - can't validate
that." );
+ getLogger().debug(
+ "String parameter " + name + "contains \"|\" -
can't validate that.");
return new ValidatorActionHelper(value,
ValidatorActionResult.ERROR);
}
- if (oneOf.indexOf("|"+value+"|") == -1) {
+ if (oneOf.indexOf("|" + value + "|") == -1) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("and it is not" );
- return new ValidatorActionHelper ( value,
ValidatorActionResult.NOMATCH);
+ getLogger().debug("and it is not");
+ return new ValidatorActionHelper(value,
ValidatorActionResult.NOMATCH);
}
- return new ValidatorActionHelper ( value,
ValidatorActionResult.OK);
+ return new ValidatorActionHelper(value,
ValidatorActionResult.OK);
}
@@ -421,16 +572,21 @@
* Validates nullability and default value for given parameter. If given
* constraints are not null they are validated as well.
*/
- private ValidatorActionHelper validateLong(String name, Configuration
constraints,
- Configuration conf, Map params, boolean is_string, Object param)
{
+ private ValidatorActionHelper validateLong(
+ String name,
+ Configuration constraints,
+ Configuration conf,
+ Map params,
+ boolean is_string,
+ Object param) {
- boolean nullable = getNullable (conf, constraints);
+ boolean nullable = getNullable(conf, constraints);
Long value = null;
Long dflt = getLongValue(getDefault(conf, constraints), true);
if (getLogger().isDebugEnabled())
- getLogger().debug ("Validating long parameter "
- + name + " (encoded in a string: " +
is_string + ")");
+ getLogger().debug(
+ "Validating long parameter " + name + " (encoded in a
string: " + is_string + ")");
try {
value = getLongValue(param, is_string);
} catch (Exception e) {
@@ -439,7 +595,7 @@
}
if (value == null) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("Long parameter " + name + " is null");
+ getLogger().debug("Long parameter " + name + " is null");
if (!nullable) {
return new ValidatorActionHelper(value,
ValidatorActionResult.ISNULL);
} else {
@@ -447,47 +603,48 @@
}
}
if (constraints != null) {
- Long eq = getAttributeAsLong (constraints, "equals-to", null);
- String eqp = constraints.getAttribute ("equals-to-param", "");
+ Long eq = getAttributeAsLong(constraints, "equals-to", null);
+ String eqp = constraints.getAttribute("equals-to-param", "");
- Long min = getAttributeAsLong (conf, "min", null);
- min = getAttributeAsLong ( constraints, "min", min);
+ Long min = getAttributeAsLong(conf, "min", null);
+ min = getAttributeAsLong(constraints, "min", min);
- Long max = getAttributeAsLong (conf, "max",null);
- max = getAttributeAsLong (constraints, "max", max);
+ Long max = getAttributeAsLong(conf, "max", null);
+ max = getAttributeAsLong(constraints, "max", max);
// Validate whether param is equal to constant
if (eq != null) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("Long parameter "
- + name + " should be equal to " + eq);
+ getLogger().debug("Long parameter " + name + " should be
equal to " + eq);
if (!value.equals(eq)) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("and it is not");
- return new ValidatorActionHelper ( value,
ValidatorActionResult.NOMATCH);
+ getLogger().debug("and it is not");
+ return new ValidatorActionHelper(value,
ValidatorActionResult.NOMATCH);
}
}
// Validate whether param is equal to another param
// FIXME: take default value of param being compared with into
// account?
- if (!"".equals (eqp)) {
+ if (!"".equals(eqp)) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("Long parameter "
- + name + " should be equal to " +
params.get (eqp));
+ getLogger().debug(
+ "Long parameter " + name + " should be equal to " +
params.get(eqp));
// Request parameter is stored as string.
// Need to convert it beforehand.
try {
- Long _eqp = new Long ( Long.parseLong((String)
params.get(eqp)) );
- if (!value.equals (_eqp)) {
+ Long _eqp = new Long(Long.parseLong((String)
params.get(eqp)));
+ if (!value.equals(_eqp)) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("and it is not");
+ getLogger().debug("and it is not");
return new ValidatorActionHelper(value,
ValidatorActionResult.NOMATCH);
}
- } catch ( NumberFormatException nfe ) {
+ } catch (NumberFormatException nfe) {
if (getLogger().isDebugEnabled())
- getLogger().debug("Long parameter "+ name +":
"+eqp+" is no long", nfe);
+ getLogger().debug(
+ "Long parameter " + name + ": " + eqp + " is no
long",
+ nfe);
return new ValidatorActionHelper(value,
ValidatorActionResult.NOMATCH);
}
}
@@ -495,25 +652,23 @@
// Validate wheter param is at least min
if (min != null) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("Long parameter "
- + name + " should be at least " +
min);
+ getLogger().debug("Long parameter " + name + " should be
at least " + min);
- if (min.compareTo(value)>0) {
+ if (min.compareTo(value) > 0) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("and it is not");
- return new ValidatorActionHelper ( value,
ValidatorActionResult.TOOSMALL);
+ getLogger().debug("and it is not");
+ return new ValidatorActionHelper(value,
ValidatorActionResult.TOOSMALL);
}
}
// Validate wheter param is at most max
if (max != null) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("Long parameter "
- + name + " should be at most " + max);
- if (max.compareTo(value)<0) {
+ getLogger().debug("Long parameter " + name + " should be
at most " + max);
+ if (max.compareTo(value) < 0) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("and it is not");
- return new ValidatorActionHelper ( value,
ValidatorActionResult.TOOLARGE);
+ getLogger().debug("and it is not");
+ return new ValidatorActionHelper(value,
ValidatorActionResult.TOOLARGE);
}
}
}
@@ -524,16 +679,25 @@
* Validates nullability and default value for given parameter. If given
* constraints are not null they are validated as well.
*/
- private ValidatorActionHelper validateDouble(String name, Configuration
constraints,
- Configuration conf, Map params, boolean is_string, Object param)
{
+ private ValidatorActionHelper validateDouble(
+ String name,
+ Configuration constraints,
+ Configuration conf,
+ Map params,
+ boolean is_string,
+ Object param) {
boolean nullable = getNullable(conf, constraints);
Double value = null;
Double dflt = getDoubleValue(getDefault(conf, constraints), true);
if (getLogger().isDebugEnabled())
- getLogger().debug ("Validating double parameter "
- + name + " (encoded in a string: " +
is_string + ")");
+ getLogger().debug(
+ "Validating double parameter "
+ + name
+ + " (encoded in a string: "
+ + is_string
+ + ")");
try {
value = getDoubleValue(param, is_string);
} catch (Exception e) {
@@ -542,7 +706,7 @@
}
if (value == null) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("double parameter " + name + " is null");
+ getLogger().debug("double parameter " + name + " is null");
if (!nullable) {
return new ValidatorActionHelper(value,
ValidatorActionResult.ISNULL);
} else {
@@ -550,72 +714,71 @@
}
}
if (constraints != null) {
- Double eq = getAttributeAsDouble (constraints, "equals-to",
null);
- String eqp = constraints.getAttribute ("equals-to-param", "");
+ Double eq = getAttributeAsDouble(constraints, "equals-to", null);
+ String eqp = constraints.getAttribute("equals-to-param", "");
- Double min = getAttributeAsDouble (conf, "min", null);
- min = getAttributeAsDouble ( constraints, "min", min);
+ Double min = getAttributeAsDouble(conf, "min", null);
+ min = getAttributeAsDouble(constraints, "min", min);
- Double max = getAttributeAsDouble (conf, "max", null);
- max = getAttributeAsDouble (constraints, "max", max);
+ Double max = getAttributeAsDouble(conf, "max", null);
+ max = getAttributeAsDouble(constraints, "max", max);
// Validate whether param is equal to constant
if (eq != null) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("Double parameter "
- + name + " should be equal to " + eq);
+ getLogger().debug("Double parameter " + name + " should
be equal to " + eq);
- if (!value.equals (eq)) {
+ if (!value.equals(eq)) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("and it is not");
- return new ValidatorActionHelper ( value,
ValidatorActionResult.NOMATCH);
+ getLogger().debug("and it is not");
+ return new ValidatorActionHelper(value,
ValidatorActionResult.NOMATCH);
}
}
// Validate whether param is equal to another param
// FIXME: take default value of param being compared with into
// account?
- if (!"".equals (eqp)) {
+ if (!"".equals(eqp)) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("Double parameter "
- + name + " should be equal to " +
params.get (eqp));
+ getLogger().debug(
+ "Double parameter " + name + " should be equal to "
+ params.get(eqp));
// Request parameter is stored as string.
// Need to convert it beforehand.
try {
- Double _eqp = new Double ( Double.parseDouble((String)
params.get(eqp)));
- if (!value.equals (_eqp)) {
+ Double _eqp = new Double(Double.parseDouble((String)
params.get(eqp)));
+ if (!value.equals(_eqp)) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("and it is not");
- return new ValidatorActionHelper ( value,
ValidatorActionResult.NOMATCH);
+ getLogger().debug("and it is not");
+ return new ValidatorActionHelper(value,
ValidatorActionResult.NOMATCH);
}
- } catch ( NumberFormatException nfe ) {
+ } catch (NumberFormatException nfe) {
if (getLogger().isDebugEnabled())
- getLogger().debug("Double parameter "+ name +":
"+eqp+" is no double", nfe);
- return new ValidatorActionHelper ( value,
ValidatorActionResult.NOMATCH);
+ getLogger().debug(
+ "Double parameter " + name + ": " + eqp + " is
no double",
+ nfe);
+ return new ValidatorActionHelper(value,
ValidatorActionResult.NOMATCH);
}
}
// Validate wheter param is at least min
if (min != null) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("Double parameter "
- + name + " should be at least " +
min);
+ getLogger().debug("Double parameter " + name + " should
be at least " + min);
if (0 > value.compareTo(min)) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("and it is not");
- return new ValidatorActionHelper (value,
ValidatorActionResult.TOOSMALL);
+ getLogger().debug("and it is not");
+ return new ValidatorActionHelper(value,
ValidatorActionResult.TOOSMALL);
}
}
// Validate wheter param is at most max
if (max != null) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("Double parameter "
- + name + " should be at most " + max);
- if (0<value.compareTo(max)) {
+ getLogger().debug("Double parameter " + name + " should
be at most " + max);
+ if (0 < value.compareTo(max)) {
if (getLogger().isDebugEnabled())
- getLogger().debug ("and it is not");
- return new ValidatorActionHelper (value,
ValidatorActionResult.TOOLARGE);
+ getLogger().debug("and it is not");
+ return new ValidatorActionHelper(value,
ValidatorActionResult.TOOLARGE);
}
}
}
@@ -625,8 +788,8 @@
/**
* Returns the parsed Double value.
*/
- private Double getDoubleValue (Object param, boolean is_string)
- throws ClassCastException, NumberFormatException {
+ private Double getDoubleValue(Object param, boolean is_string)
+ throws ClassCastException, NumberFormatException {
/* convert param to double */
if (is_string) {
@@ -636,15 +799,15 @@
}
return new Double(tmp);
} else {
- return (Double)param;
+ return (Double) param;
}
}
/**
* Returns the parsed Long value.
*/
- private Long getLongValue (Object param, boolean is_string)
- throws ClassCastException, NumberFormatException {
+ private Long getLongValue(Object param, boolean is_string)
+ throws ClassCastException, NumberFormatException {
/* convert param to long */
if (is_string) {
@@ -654,7 +817,7 @@
}
return Long.decode(tmp);
} else {
- return (Long)param;
+ return (Long) param;
}
}
@@ -665,7 +828,7 @@
private String getStringValue(Object param) throws ClassCastException {
/* convert param to string */
- String value = (String)param;
+ String value = (String) param;
if (value != null && "".equals(value.trim())) {
value = null;
}
@@ -684,7 +847,8 @@
return "yes".equals(tmp) || "true".equals(tmp);
} catch (Exception e) {
String tmp = "no";
- if (conf != null) tmp = conf.getAttribute("nullable", "no");
+ if (conf != null)
+ tmp = conf.getAttribute("nullable", "no");
return "yes".equals(tmp) || "true".equals(tmp);
}
}
@@ -723,7 +887,7 @@
* @throws NumberFormatException if conversion fails
*/
private Long getAttributeAsLong(Configuration conf, String name, Long
dflt)
- throws NumberFormatException {
+ throws NumberFormatException {
try {
return new Long(conf.getAttribute(name));
} catch (ConfigurationException e) {
@@ -744,11 +908,183 @@
* @throws NumberFormatException if conversion fails
*/
private Double getAttributeAsDouble(Configuration conf, String name,
Double dflt)
- throws NumberFormatException {
+ throws NumberFormatException {
try {
return new Double(conf.getAttribute(name));
} catch (ConfigurationException e) {
return dflt;
}
}
+
+ /**
+ * Create an index map to an array of configurations by their name
+ * attribute. An empty array results in an empty map.
+ *
+ * @param descriptor
+ * @return
+ */
+ protected Map indexConfiguration(Configuration[] descriptor) {
+ if (descriptor == null)
+ return new HashMap();
+ Map result = new HashMap((descriptor.length > 0) ? descriptor.length
* 2 : 5);
+ for (int i = descriptor.length - 1; i >= 0; i--) {
+ String name = descriptor[i].getAttribute("name", "");
+ result.put(name, descriptor[i]);
+ }
+ return result;
+ }
+
+ /**
+ * Recursively resolve constraint sets that may "include" other
constraint
+ * sets and return a collection of all parameters to validate.
+ *
+ * @param valsetstr
+ * @param consets
+ * @return
+ */
+ protected Collection resolveConstraints(String valsetstr, Map consets) {
+ /* get the list of params to be validated */
+ Vector rules = new Vector();
+ Configuration[] set = ((Configuration)
consets.get(valsetstr)).getChildren("validate");
+ for (int j = 0; j < set.length; j++) {
+ rules.add(set[j]);
+ }
+ set = ((Configuration)
consets.get(valsetstr)).getChildren("include");
+ for (int j = 0; j < set.length; j++) {
+ Collection tmp = resolveConstraints(set[j].getAttribute("name",
""), consets);
+ rules.addAll(tmp);
+ }
+ return rules;
+ }
+
+ /**
+ * Checks the default setting for reloading the descriptor file.
+ * @return
+ */
+ protected boolean isDescriptorReloadable() {
+ // read global parameter settings
+ boolean reloadable = Constants.DESCRIPTOR_RELOADABLE_DEFAULT;
+ if (this.settings.containsKey("reloadable")) {
+ reloadable = Boolean.valueOf((String)
this.settings.get("reloadable")).booleanValue();
+ }
+ return reloadable;
+ }
+
+ /**
+ * Get list of params to be validated from sitemap parameter and
+ * isolates the parameter names from the comma separated list.
+ *
+ */
+ protected Collection getSetOfParameterNamesFromSitemap(String valstr,
Map desc) {
+ String[] rparams = null;
+ Set set = new HashSet(20);
+ if (!"*".equals(valstr.trim())) {
+ rparams = Tokenizer.tokenize(valstr, ",", false);
+ if (rparams != null) {
+ for (int i = rparams.length - 1; i >= 0; i--) {
+ set.add(desc.get(rparams[i]));
+ }
+ }
+ } else {
+ // validate _all_ parameters
+ set = desc.entrySet();
+ }
+ return set;
+ }
+
+ /**
+ * Validate all parameters in the set with the constraints contained in
+ * desc and the values from params. Validation details are in resultMap
and
+ * successful validated parameters in resultMap.
+ *
+ * @param desc
+ * @param actionMap
+ * @param resultMap
+ * @param set
+ * @param params
+ * @param isString
+ * @return
+ */
+ protected boolean validateSetOfParameters(
+ Map desc,
+ Map actionMap,
+ Map resultMap,
+ Collection set,
+ Map params,
+ boolean isString) {
+
+ boolean allOK = true;
+ ValidatorActionHelper result;
+ String name;
+ String rule = null;
+ for (Iterator i = set.iterator(); i.hasNext();) {
+ Configuration constr = (Configuration) i.next();
+ name = constr.getAttribute("name", null);
+ rule = constr.getAttribute("rule", name);
+ result = validateParameter(name, rule, constr, desc, params,
isString);
+ if (!result.isOK()) {
+ if (getLogger().isDebugEnabled())
+ getLogger().debug("Validation failed for parameter " +
name);
+ allOK = false;
+ }
+ actionMap.put(name, result.getObject());
+ resultMap.put(name, result.getResult());
+ }
+ return allOK;
+ }
+
+ /**
+ * Add success indicator to resulting maps and clear actionMap if
unsuccessful.
+ * Results are stored as request attributes.
+ *
+ * @param objectModel the object model
+ * @param actionMap a Map containing validated parameters
+ * @param resultMap a Map containing validation results
+ * @param allOK a boolean indicating if all validations were successful
+ * @return actionMap if allOK or null otherwise
+ */
+ protected Map setResult(Map objectModel, Map actionMap, Map resultMap,
boolean allOK) {
+ if (!allOK) {
+ // if any validation failed return an empty map
+ actionMap = null;
+ resultMap.put("*", ValidatorActionResult.ERROR);
+ if (getLogger().isDebugEnabled())
+ getLogger().debug("All form params validated. An error
occurred.");
+ } else {
+ resultMap.put("*", ValidatorActionResult.OK);
+ if (getLogger().isDebugEnabled())
+ getLogger().debug("All form params successfully validated");
+ }
+ // store validation results in request attribute
+ ObjectModelHelper.getRequest(objectModel).setAttribute(
+ Constants.XSP_FORMVALIDATOR_PATH,
+ resultMap);
+ //return Collections.unmodifiableMap (actionMap);
+ return actionMap;
+ }
+
+ /**
+ * Load the descriptor containing the constraints.
+ * @param resolver
+ * @param parameters
+ * @return a Configuration containing the constraints or null if a
problem occurred.
+ */
+ protected Configuration getDescriptor(
+ SourceResolver resolver,
+ Map objectModel,
+ Parameters parameters) {
+ Configuration conf = null;
+ try {
+ conf =
+ this.getConfiguration(
+ parameters.getParameter("descriptor", (String)
this.settings.get("descriptor")),
+ resolver,
+ parameters.getParameterAsBoolean("reloadable",
isDescriptorReloadable()));
+ } catch (ConfigurationException e) {
+ if (this.getLogger().isWarnEnabled())
+ this.getLogger().warn("Exception reading descriptor: ", e);
+ }
+ return conf;
+ }
+
}
1.2 +42 -230
cocoon-2.1/src/java/org/apache/cocoon/acting/FormValidatorAction.java
Index: FormValidatorAction.java
===================================================================
RCS file:
/home/cvs/cocoon-2.1/src/java/org/apache/cocoon/acting/FormValidatorAction.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- FormValidatorAction.java 9 Mar 2003 00:08:38 -0000 1.1
+++ FormValidatorAction.java 15 Aug 2003 15:53:20 -0000 1.2
@@ -51,257 +51,69 @@
package org.apache.cocoon.acting;
import org.apache.avalon.framework.configuration.Configuration;
-import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.thread.ThreadSafe;
-import org.apache.cocoon.Constants;
+
import org.apache.cocoon.environment.ObjectModelHelper;
-import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.Request;
-import org.apache.cocoon.environment.SourceResolver;
-import org.apache.cocoon.util.Tokenizer;
+import java.util.Collection;
import java.util.HashMap;
+import java.util.Iterator;
import java.util.Map;
/**
* This is the action used to validate Request parameters.
* The parameters are described via the external xml
* file (its format is defined in AbstractValidatorAction).
- *
- * <h3>Variant 1</h3>
- * <pre>
- * <map:act type="form-validator">
- * <parameter name="descriptor"
value="context://descriptor.xml">
- * <parameter name="validate" value="username,password">
- * </map:act>
- * </pre>
- *
- * <p>The list of parameters to be validated is specified as a comma
- * separated list of their names. descriptor.xml can therefore be used
- * among many various actions. If the list contains only of <code>*</code>,
- * all parameters in the file will be validated.</p>
- *
- * <h3>Variant 2</h3>
- * <pre>
- * <map:act type="form-validator">
- * <parameter name="descriptor"
value="context://descriptor.xml">
- * <parameter name="validate-set" value="is-logged-in">
- * </map:act>
- * </pre>
- *
- * <p>The parameter "validate-set" tells to take a given
- * "constraint-set" from description file and test all parameters
- * against given criteria. This variant is more powerful, more aspect
- * oriented and more flexibile than the previous one, becuase it
- * allows the comparsion constructs, etc. See AbstractValidatorAction
- * documentation.</p>
- *
- * <p>For even more powerfull validation, constraints can be grouped
- * and used independently of the parameter name. If a validate element
- * has a <code>rule</code> attribute, it uses the parameter with that
- * name as a rule template and validates the parameter from the
- * <code>name</code> attribute with that rule.</p>
- *
- * <p>This action returns null when validation fails, otherwise it
- * provides all validated parameters to the sitemap via {name}
- * expression.</p>
- *
- * <p>In addition a request attribute
- * <code>org.apache.cocoon.acting.FormValidatorAction.results</code>
- * contains the validation results in both cases and make it available
- * to XSPs. The special parameter "*" contains either the validation
- * result "OK", if all parameters were validated successfully, or
- * "ERROR" otherwise. Mind you that redirections create new request
- * objects and thus the result is not available for the target
- * page.</p>
- *
- * <p>All values for a parameter are read through the
- * getParameterValues() method and validated seperately.</p>
+ * @see org.apache.cocoon.acting.AbstractValidatorAction
*
* @author <a href="mailto:[EMAIL PROTECTED]">Martin Man</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Christian Haul</a>
* @version CVS $Id$
*/
-public class FormValidatorAction extends AbstractValidatorAction implements
ThreadSafe
-{
+public class FormValidatorAction extends AbstractValidatorAction implements
ThreadSafe {
+
/**
- * Main invocation routine.
+ * Reads parameter values from request parameters for all parameters
+ * that are contained in the active constraint list. If a parameter
+ * has multiple values, all are stored in the resulting map.
+ *
+ * @param objectModel the object model
+ * @param set a collection of parameter names
+ * @return
*/
- public Map act (Redirector redirector, SourceResolver resolver, Map
objectModel, String src,
- Parameters parameters) throws Exception {
- Request req = ObjectModelHelper.getRequest(objectModel);
-
- /* check request validity */
- if (req == null) {
- if (getLogger().isDebugEnabled())
- getLogger().debug ("No request object");
- return null;
- }
-
- // read global parameter settings
- boolean reloadable = Constants.DESCRIPTOR_RELOADABLE_DEFAULT;
- if (this.settings.containsKey("reloadable")) {
- reloadable = Boolean.valueOf((String)
this.settings.get("reloadable")).booleanValue();
- }
-
- // read local settings
- try {
- Configuration conf = this.getConfiguration (
- parameters.getParameter ("descriptor", (String)
this.settings.get("descriptor")), resolver,
- parameters.getParameterAsBoolean("reloadable", reloadable));
- String valstr = parameters.getParameter ("validate", (String)
settings.get("validate",""));
- String valsetstr = parameters.getParameter ("validate-set",
(String) settings.get("validate-set",""));
- Configuration[] desc = conf.getChildren ("parameter");
- Configuration[] csets = conf.getChildren ("constraint-set");
- HashMap actionMap = new HashMap ();
- HashMap resultMap = new HashMap ();
- boolean allOK = true;
-
- /*
- * old obsoleted method
- */
- if (!"".equals (valstr.trim ())) {
- if (getLogger().isDebugEnabled())
- getLogger().debug ("Validating parameters "
- + "as specified via 'validate'
parameter");
- /* get list of params to be validated */
- String[] rparams = null;
- if (!"*".equals(valstr.trim())) {
- rparams = Tokenizer.tokenize (valstr, ",", false);
- } else {
- // validate _all_ parameters
- rparams = new String[desc.length];
- for (int i=0; i<desc.length; i++) {
- rparams[i] = desc[i].getAttribute("name","");
- if ("".equals(rparams[i])) {
- if (getLogger().isDebugEnabled())
- getLogger().debug ("Wrong syntax of the
'validate' parameter");
- return null;
- }
- }
- }
- /* perform actual validation */
- ValidatorActionHelper result = null;
- String name = null;
- HashMap params = new HashMap (rparams.length);
- /* put required params into hash */
- for (int i = 0; i < rparams.length; i ++) {
- name = rparams[i];
- if (name == null || "".equals (name.trim ())) {
- if (getLogger().isDebugEnabled())
- getLogger().debug ("Wrong syntax of the
'validate' parameter");
- return null;
- }
- name = name.trim ();
- params.put (name, req.getParameter (name));
- }
- for (int i = 0; i < rparams.length; i ++) {
- name = rparams[i].trim ();
- result = validateParameter (name, null, desc,
- params, true);
- if (!result.isOK()) {
- if (getLogger().isDebugEnabled())
- getLogger().debug ("Validation failed for
parameter " + name);
- allOK = false;
- }
- actionMap.put (name, result.getObject());
- resultMap.put (name, result.getResult());
- }
- }
- /*
- * new set-based method
- */
- if (!"".equals (valsetstr.trim ())) {
- if (getLogger().isDebugEnabled())
- getLogger().debug ("Validating parameters "
- + "from given constraint-set " +
valsetstr);
- // go over all constraint sets
- // untill the requested set is found
- // set number will be in j
- Configuration cset = null;
- String setname = null;
- int j = 0;
- boolean found = false;
- for (j = 0; j < csets.length; j ++) {
- setname = csets[j].getAttribute ("name", "");
- if (valsetstr.trim().equals (setname.trim ())) {
- found = true;
+ protected HashMap createMapOfParameters(Map objectModel, Collection set)
{
+ String name;
+ HashMap params = new HashMap(set.size());
+ // put required params into hash
+ Request request = ObjectModelHelper.getRequest(objectModel);
+ for (Iterator i = set.iterator(); i.hasNext();) {
+ name = ((Configuration) i.next()).getAttribute("name",
"").trim();
+ Object[] values = request.getParameterValues(name);
+ if (values != null) {
+ switch (values.length) {
+ case 0 :
+ params.put(name, null);
break;
- }
- }
- if (!found) {
- if (getLogger().isDebugEnabled())
- getLogger().debug ("Given set "
- + valsetstr
- + " does not exist in a
description file");
- return null;
- }
- cset = csets[j];
- /* get the list of params to be validated */
- Configuration[] set = cset.getChildren ("validate");
-
- /* perform actuall validation */
- ValidatorActionHelper result = null;
- String name = null;
- HashMap params = new HashMap (set.length);
- if (getLogger().isDebugEnabled())
- getLogger().debug ("Given set "
- + valsetstr
- + " contains " + set.length + "
rules");
- /* put required params into hash */
- for (int i = 0; i < set.length; i ++) {
- name = set[i].getAttribute ("name", "").trim();
- if ("".equals(name)) {
- if (getLogger().isDebugEnabled())
- getLogger().debug ("Wrong syntax "
- + " of 'validate' children
nr. " + i);
- return null;
- }
- Object[] values = req.getParameterValues(name);
- if (values != null) {
- switch (values.length) {
- case 0: params.put(name,null); break;
- case 1: params.put(name,values[0]); break;
- default: params.put(name,values);
- }
- } else {
- params.put(name,values);
- }
- }
- String rule = null;
- for (int i = 0; i < set.length; i ++) {
- name = set[i].getAttribute ("name", null);
- rule = set[i].getAttribute("rule",name);
- result = validateParameter (name, rule, set[i],
- desc, params, true);
- if (!result.isOK()) {
- if (getLogger().isDebugEnabled())
- getLogger().debug ("Validation failed for
parameter " + name);
- allOK = false;
- }
- actionMap.put (name, result.getObject());
- resultMap.put (name, result.getResult());
+ case 1 :
+ params.put(name, values[0]);
+ break;
+ default :
+ params.put(name, values);
}
- }
- if (!allOK) {
- // if any validation failed return an empty map
- actionMap = null;
- resultMap.put("*", ValidatorActionResult.ERROR);
- if (getLogger().isDebugEnabled())
- getLogger().debug ("All form params validated. An error
occurred.");
} else {
- resultMap.put("*", ValidatorActionResult.OK);
- if (getLogger().isDebugEnabled())
- getLogger().debug ("All form params successfully
validated");
+ params.put(name, values);
}
- // store validation results in request attribute
- req.setAttribute(Constants.XSP_FORMVALIDATOR_PATH, resultMap);
- //return Collections.unmodifiableMap (actionMap);
- return actionMap;
- } catch (Exception e) {
- if (getLogger().isDebugEnabled())
- getLogger().debug ("exception: ", e);
}
- return null;
+ return params;
}
+
+ /* (non-Javadoc)
+ * @see
org.apache.cocoon.acting.AbstractValidatorAction#isStringEncoded()
+ */
+ boolean isStringEncoded() {
+ return true;
+ }
+
+
}
1.2 +43 -187
cocoon-2.1/src/java/org/apache/cocoon/acting/SessionValidatorAction.java
Index: SessionValidatorAction.java
===================================================================
RCS file:
/home/cvs/cocoon-2.1/src/java/org/apache/cocoon/acting/SessionValidatorAction.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- SessionValidatorAction.java 9 Mar 2003 00:08:40 -0000 1.1
+++ SessionValidatorAction.java 15 Aug 2003 15:53:20 -0000 1.2
@@ -51,210 +51,66 @@
package org.apache.cocoon.acting;
import org.apache.avalon.framework.configuration.Configuration;
-import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.thread.ThreadSafe;
-import org.apache.cocoon.Constants;
+
import org.apache.cocoon.environment.ObjectModelHelper;
-import org.apache.cocoon.environment.Redirector;
-import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.Session;
-import org.apache.cocoon.environment.SourceResolver;
-import org.apache.cocoon.util.Tokenizer;
-import java.util.Collections;
+import java.util.Collection;
import java.util.HashMap;
+import java.util.Iterator;
import java.util.Map;
-
/**
* This is the action used to validate Session parameters (attributes).
* The parameters are described via the external xml
- * file (its format is defined in AbstractValidatorAction).
- *
- * <h3>Variant 1</h3>
- * <pre>
- * <map:act type="session-validator">
- * <parameter name="descriptor"
value="context://descriptor.xml">
- * <parameter name="validate" value="username,password">
- * </map:act>
- * </pre>
- * The list of parameters to be validated is specified as a comma separated
- * list of their names. descriptor.xml can therefore be used among many
- * various actions.
- *
- * <h3>Variant 2</h3>
- * <pre>
- * <pre>
- * <map:act type="session-validator">
- * <parameter name="descriptor"
value="context://descriptor.xml">
- * <parameter name="validate-set" value="is-logged-in">
- * </map:act>
- * </pre>
- *
- * The parameter "validate-set" tells to take a given "constraint-set"
- * from description
- * file and test all parameters against given criteria. This variant is more
- * powerful, more aspect oriented and more flexibile than the previous one,
- * becuase it allows the comparsion constructs, etc. See
- * AbstractValidatorAction documentation.
- *
- * This action returns null when validation fails, otherwise it provides
- * all validated parameters to the sitemap via {name} expression.
+ * file.
+ *
+ * @see org.apache.cocoon.acting.AbstractValidatorAction
*
* @author <a href="mailto:[EMAIL PROTECTED]">Martin Man</a>
+ * @author <a href="mailto:[EMAIL PROTECTED]">Christian Haul</a>
* @version CVS $Id$
*/
-public class SessionValidatorAction extends AbstractValidatorAction
implements ThreadSafe
-{
- /**
- * Main invocation routine.
+public class SessionValidatorAction extends AbstractValidatorAction
implements ThreadSafe {
+
+ /* (non-Javadoc)
+ * @see
org.apache.cocoon.acting.AbstractValidatorAction#createMapOfParameters(java.util.Map,
java.util.Collection)
+ */
+ protected HashMap createMapOfParameters(Map objectModel, Collection set)
{
+ String name;
+ HashMap params = new HashMap(set.size());
+ // put required params into hash
+ Session session =
ObjectModelHelper.getRequest(objectModel).getSession();
+ for (Iterator i = set.iterator(); i.hasNext();) {
+ name = ((Configuration) i.next()).getAttribute("name",
"").trim();
+ Object value = session.getAttribute(name);
+ params.put(name, value);
+ }
+ return params;
+ }
+
+
+ /* (non-Javadoc)
+ * @see
org.apache.cocoon.acting.AbstractValidatorAction#setResult(java.util.Map,
java.util.Map, java.util.Map, boolean)
*/
- public Map act (Redirector redirector, SourceResolver resolver, Map
objectModel, String src,
- Parameters parameters) throws Exception {
- Request req = ObjectModelHelper.getRequest(objectModel);
-
- /* check session validity */
- Session session = req.getSession (false);
- if (session == null) {
- if (this.getLogger().isDebugEnabled()) {
- getLogger ().debug ("No session object");
+ protected Map setResult(Map objectModel, Map actionMap, Map resultMap,
boolean allOK) {
+ if (allOK){
+ Session session =
ObjectModelHelper.getRequest(objectModel).getSession();
+ for (Iterator i = actionMap.keySet().iterator(); i.hasNext(); ){
+ String name = (String) i.next();
+ session.setAttribute(name, actionMap.get(name));
}
- return null;
}
+ return super.setResult(objectModel, actionMap, resultMap, allOK);
+ }
- // read global parameter settings
- boolean reloadable = Constants.DESCRIPTOR_RELOADABLE_DEFAULT;
- if (this.settings.containsKey("reloadable")) {
- reloadable = Boolean.valueOf((String)
this.settings.get("reloadable")).booleanValue();
- }
- try {
- Configuration conf = this.getConfiguration (
- parameters.getParameter ("descriptor", (String)
this.settings.get("descriptor")), resolver,
- parameters.getParameterAsBoolean("reloadable",reloadable));
-
- String valsetstr = parameters.getParameter ( "validate-set",
(String) settings.get("validate-set") );
- String valstr = parameters.getParameter ( "validate", (String)
settings.get("validate") );
-
- Configuration[] desc = conf.getChildren ("parameter");
- Configuration[] csets = conf.getChildren ("constraint-set");
- HashMap actionMap = new HashMap ();
- /*
- * old obsoleted method
- */
- if (valstr != null && !"".equals (valstr.trim ())) {
- if (this.getLogger().isDebugEnabled()) {
- getLogger ().debug ("Validating parameters "
- + "as specified via 'validate' parameter");
- }
- /* get list of params to be validated */
- String[] rparams = Tokenizer.tokenize (valstr, ",", false);
-
- /* perform actuall validation */
- ValidatorActionHelper result = null;
- String name = null;
- HashMap params = new HashMap (rparams.length);
- /* put required params into hash */
- for (int i = 0; i < rparams.length; i ++) {
- name = rparams[i];
- if (name == null || "".equals (name.trim ())) {
- if (this.getLogger().isDebugEnabled()) {
- getLogger ().debug ("Wrong syntax of the
'validate' parameter");
- }
- return null;
- }
- name = name.trim ();
- params.put (name, session.getAttribute (name));
- }
- for (int i = 0; i < rparams.length; i ++) {
- name = rparams[i].trim ();
- result = validateParameter (name, null, desc,
- params, false);
- if (!result.isOK()) {
- if (this.getLogger().isDebugEnabled()) {
- getLogger().debug ("Validation failed for
parameter " + name);
- }
- return null;
- }
- session.setAttribute (name, result.getObject());
- actionMap.put (name, result.getObject());
- }
- }
- /*
- * new set-based method
- */
- if (valsetstr != null && !"".equals (valsetstr.trim ())) {
- if (this.getLogger().isDebugEnabled()) {
- getLogger ().debug ("Validating parameters "
- + "from given constraint-set " + valsetstr);
- }
- Configuration cset = null;
- String setname = null;
- int j = 0;
- boolean found = false;
- for (j = 0; j < csets.length; j ++) {
- setname = csets[j].getAttribute ("name", "");
- if (valsetstr.trim().equals (setname.trim ())) {
- found = true;
- break;
- }
- }
- if (!found) {
- if (this.getLogger().isDebugEnabled()) {
- getLogger ().debug ("Given set "
- + valsetstr
- + " does not exist in a description file");
- }
- return null;
- }
- cset = csets[j];
- /* get the list of params to be validated */
- Configuration[] set = cset.getChildren ("validate");
-
- /* perform actuall validation */
- ValidatorActionHelper result = null;
- String name = null;
- HashMap params = new HashMap (set.length);
- if (this.getLogger().isDebugEnabled()) {
- getLogger ().debug ("Given set "
- + valsetstr
- + " contains " + set.length + " rules");
- }
- /* put required params into hash */
- for (int i = 0; i < set.length; i ++) {
- name = set[i].getAttribute ("name", "");
- if ("".equals (name.trim ())) {
- if (this.getLogger().isDebugEnabled()) {
- getLogger ().debug ("Wrong syntax "
- + " of 'validate' children nr. " + i);
- }
- return null;
- }
- name = name.trim ();
- params.put (name, session.getAttribute (name));
- }
- for (int i = 0; i < set.length; i ++) {
- name = set[i].getAttribute ("name", null);
- result = validateParameter(name, set[i],
- desc, params, false);
- if (!result.isOK()) {
- if (this.getLogger().isDebugEnabled()) {
- getLogger().debug("Validation failed for
parameter " + name);
- }
- return null;
- }
- session.setAttribute (name, result.getObject());
- actionMap.put (name, result.getObject());
- }
- }
- if (this.getLogger().isDebugEnabled()) {
- getLogger().debug("All session params validated");
- }
- return Collections.unmodifiableMap (actionMap);
- } catch (Exception e) {
- getLogger().warn ("exception: ", e);
- }
- return null;
+ /* (non-Javadoc)
+ * @see
org.apache.cocoon.acting.AbstractValidatorAction#isStringEncoded()
+ */
+ boolean isStringEncoded() {
+ return false;
}
-}
+}
1.5 +22 -213
cocoon-2.1/src/blocks/session-fw/java/org/apache/cocoon/webapps/session/acting/SessionFormAction.java
Index: SessionFormAction.java
===================================================================
RCS file:
/home/cvs/cocoon-2.1/src/blocks/session-fw/java/org/apache/cocoon/webapps/session/acting/SessionFormAction.java,v
retrieving revision 1.4
retrieving revision 1.5
diff -u -r1.4 -r1.5
--- SessionFormAction.java 4 May 2003 20:19:42 -0000 1.4
+++ SessionFormAction.java 15 Aug 2003 15:53:20 -0000 1.5
@@ -50,22 +50,16 @@
*/
package org.apache.cocoon.webapps.session.acting;
-import org.apache.cocoon.acting.AbstractValidatorAction;
-import org.apache.cocoon.acting.ValidatorActionHelper;
-import org.apache.cocoon.acting.ValidatorActionResult;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.thread.ThreadSafe;
-import org.apache.cocoon.Constants;
+
+import org.apache.cocoon.acting.FormValidatorAction;
import org.apache.cocoon.environment.ObjectModelHelper;
-import org.apache.cocoon.environment.Redirector;
-import org.apache.cocoon.environment.Request;
-import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.environment.Session;
+import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.webapps.session.SessionConstants;
-import org.apache.cocoon.util.Tokenizer;
-import java.util.HashMap;
import java.util.Map;
/**
@@ -129,212 +123,27 @@
*
* where "session-form" is configured as SessionFormAction
*
+ * @see org.apache.cocoon.acting.FormValidatorAction
+ * @see org.apache.cocoon.acting.AbstractValidatorAction
+ *
* @author <a href="mailto:[EMAIL PROTECTED]">Guido Casper</a>
+ * @author <a href="mailto:[EMAIL PROTECTED]">Christian Haul</a>
* @version CVS $Id$
*/
-public class SessionFormAction extends AbstractValidatorAction implements
ThreadSafe
-{
- /**
- * Main invocation routine.
- */
- public Map act (Redirector redirector, SourceResolver resolver, Map
objectModel, String src,
- Parameters parameters) throws Exception {
- Request req = ObjectModelHelper.getRequest(objectModel);
-
- // read local settings
- try {
-
- Session session = req.getSession(true);
-
- Configuration conf = (Configuration)session.getAttribute(
-
req.getParameter(SessionConstants.SESSION_FORM_PARAMETER));
-
- String valstr = parameters.getParameter ("validate", (String)
settings.get("validate",""));
- String valsetstr = parameters.getParameter ("validate-set",
(String) settings.get("validate-set",""));
+public class SessionFormAction extends FormValidatorAction implements
ThreadSafe {
- Configuration valConf = (Configuration)session.getAttribute(
-
req.getParameter(SessionConstants.SESSION_FORM_PARAMETER)+"validate-set");
- if (valConf != null) {
- valsetstr = valConf.getAttribute("name","");
- }
-
- Configuration[] desc = conf.getChildren ("parameter");
- Configuration[] csets = conf.getChildren ("constraint-set");
-
- HashMap actionMap = new HashMap ();
- HashMap resultMap = new HashMap ();
- boolean allOK = true;
-
- /*
- * old obsoleted method
- */
- if (!"".equals (valstr.trim ())) {
- if (getLogger().isDebugEnabled()) {
- getLogger().debug ("Validating parameters "
- + "as specified via 'validate'
parameter");
- }
-
- /* get list of params to be validated */
- String[] rparams = null;
- if (!"*".equals(valstr.trim())) {
- rparams = Tokenizer.tokenize (valstr, ",", false);
- } else {
- // validate _all_ parameters
- rparams = new String[desc.length];
- for (int i=0; i<desc.length; i++) {
- rparams[i] = desc[i].getAttribute("name","");
- if ("".equals(rparams[i])) {
- if (getLogger().isDebugEnabled()) {
- getLogger().debug ("Wrong syntax of the
'validate' parameter");
- }
- return null;
- }
- }
- }
- /* perform actual validation */
- ValidatorActionHelper result = null;
- String name = null;
- HashMap params = new HashMap (rparams.length);
- /* put required params into hash */
- for (int i = 0; i < rparams.length; i ++) {
- name = rparams[i];
- if (name == null || "".equals (name.trim ())) {
- if (getLogger().isDebugEnabled()) {
- getLogger().debug ("Wrong syntax of the
'validate' parameter");
- }
- return null;
- }
- name = name.trim ();
- params.put (name, req.getParameter (name));
- }
- for (int i = 0; i < rparams.length; i ++) {
- name = rparams[i].trim ();
- result = validateParameter (name, null, desc,
- params, true);
- if (!result.isOK()) {
- if (getLogger().isDebugEnabled()) {
- getLogger().debug ("Validation failed for
parameter " + name);
- }
- allOK = false;
- }
- actionMap.put (name, result.getObject());
- resultMap.put (name, result.getResult());
- }
- }
- /*
- * new set-based method
- */
- if (!"".equals (valsetstr.trim ())) {
- if (getLogger().isDebugEnabled()) {
- getLogger().debug ("Validating parameters "
- + "from given constraint-set " +
valsetstr);
- }
- // go over all constraint sets
- // untill the requested set is found
- // set number will be in j
- Configuration cset = null;
- String setname = null;
- int j = 0;
- boolean found = false;
- for (j = 0; j < csets.length; j ++) {
- setname = csets[j].getAttribute ("name", "");
- if (valsetstr.trim().equals (setname.trim ())) {
- found = true;
- break;
- }
- }
- if (!found) {
- if (getLogger().isDebugEnabled()) {
- getLogger().debug ("Given set "
- + valsetstr
- + " does not exist in a
description file");
- }
- return null;
- }
- cset = csets[j];
- /* get the list of params to be validated */
- Configuration[] set = cset.getChildren ("validate");
-
- /* perform actuall validation */
- ValidatorActionHelper result = null;
- String name = null;
- HashMap params = new HashMap (set.length);
- if (getLogger().isDebugEnabled()) {
- getLogger().debug ("Given set "
- + valsetstr
- + " contains " + set.length + "
rules");
- }
-
- /* put required params into hash */
- for (int i = 0; i < set.length; i ++) {
- name = set[i].getAttribute ("name", "").trim();
- if ("".equals(name)) {
- if (getLogger().isDebugEnabled()) {
- getLogger().debug ("Wrong syntax "
- + " of 'validate' children
nr. " + i);
- }
- return null;
- }
- Object[] values = req.getParameterValues(name);
- if (values != null) {
- switch (values.length) {
- case 0: params.put(name,null); break;
- case 1: params.put(name,values[0]); break;
- default: params.put(name,values);
- }
- } else {
- params.put(name,values);
- }
- }
- String rule = null;
- for (int i = 0; i < set.length; i ++) {
- name = set[i].getAttribute ("name", null);
- rule = set[i].getAttribute("rule",name);
- result = validateParameter (name, rule, set[i],
- desc, params, true);
- if (!result.isOK()) {
- if (getLogger().isDebugEnabled()) {
- getLogger().debug ("Validation failed for
parameter " + name);
- }
- allOK = false;
- }
- actionMap.put (name, result.getObject());
- resultMap.put (name, result.getResult());
- }
- }
-
- if (!allOK) {
-
- // if any validation failed return an empty map
- actionMap = null;
- resultMap.put("*", ValidatorActionResult.ERROR);
- if (getLogger().isDebugEnabled()) {
- getLogger().debug ("All form params validated. An error
occurred.");
- }
-
- } else {
-
- resultMap.put("*", ValidatorActionResult.OK);
- if (getLogger().isDebugEnabled()) {
- getLogger().debug ("All form params successfully
validated");
- }
- }
-
- // store validation results in request attribute
- req.setAttribute(Constants.XSP_FORMVALIDATOR_PATH, resultMap);
-
- // store validation results in session attribute
- // to be used by SessionTransformer
-
session.setAttribute(req.getParameter(SessionConstants.SESSION_FORM_PARAMETER)+
- "validation-result", resultMap);
-
- return actionMap;
-
- } catch (Exception ignore) {
- if (getLogger().isDebugEnabled()) {
- getLogger().debug ("exception: ", ignore);
- }
- }
- return null;
+ /* (non-Javadoc)
+ * @see
org.apache.cocoon.acting.AbstractValidatorAction#getDescriptor(org.apache.cocoon.environment.SourceResolver,
org.apache.avalon.framework.parameters.Parameters)
+ */
+ protected Configuration getDescriptor(
+ SourceResolver resolver,
+ Map objectModel,
+ Parameters parameters) {
+
+ Session session =
ObjectModelHelper.getRequest(objectModel).getSession(true);
+ return (Configuration) session.getAttribute(
+ ObjectModelHelper.getRequest(objectModel).getParameter(
+ SessionConstants.SESSION_FORM_PARAMETER));
}
+
}