You are viewing a plain text version of this content. The canonical link for it is here.
Posted to cvs@cocoon.apache.org by br...@apache.org on 2003/06/26 11:09:59 UTC
cvs commit: cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/formmodel AggregateField.java AggregateFieldDefinition.java AggregateFieldDefinitionBuilder.java ContainerDefinitionDelegate.java
bruno 2003/06/26 02:09:59
Added: src/blocks/woody/java/org/apache/cocoon/woody/datatype/validationruleimpl
Mod10ValidationRule.java
Mod10ValidationRuleBuilder.java
src/blocks/woody/java/org/apache/cocoon/woody/formmodel
AggregateField.java AggregateFieldDefinition.java
AggregateFieldDefinitionBuilder.java
ContainerDefinitionDelegate.java
Log:
initial commit
Revision Changes Path
1.1 cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/datatype/validationruleimpl/Mod10ValidationRule.java
Index: Mod10ValidationRule.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, 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 acknowledgment: "This product includes software
developed by the Apache Software Foundation (http://www.apache.org/)."
Alternately, this acknowledgment may appear in the software itself, if
and wherever such third-party acknowledgments normally appear.
4. The names "Apache Cocoon" 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 name, without prior written permission of the
Apache Software Foundation.
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 (INCLU-
DING, 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 and was originally created by
Stefano Mazzocchi <st...@apache.org>. For more information on the Apache
Software Foundation, please see <http://www.apache.org/>.
*/
package org.apache.cocoon.woody.datatype.validationruleimpl;
import org.apache.cocoon.woody.datatype.ValidationError;
import org.outerj.expression.ExpressionContext;
/**
* Performs the so called "mod 10" algorithm to check the validity of credit card numbers
* such as VISA.
*
* <p>In addition to this, the credit card number can be further validated by its length
* and prefix, but those properties are depended on the credit card type and such validation
* is not performed by this validation rule.
*/
public class Mod10ValidationRule extends AbstractValidationRule {
public ValidationError validate(Object value, ExpressionContext expressionContext) {
String numberToCheck = (String)value;
int nulOffset = '0';
int sum = 0;
for (int i = 1; i <= numberToCheck.length(); i++) {
int currentDigit = numberToCheck.charAt(numberToCheck.length() - i) - nulOffset;
if ((i % 2) == 0) {
currentDigit *= 2;
currentDigit = currentDigit > 9 ? currentDigit - 9 : currentDigit;
sum += currentDigit;
} else {
sum += currentDigit;
}
}
if(!((sum % 10) == 0))
return hasFailMessage() ? getFailMessage() : new ValidationError("validation.mod10");
else
return null;
}
public boolean supportsType(Class clazz, boolean arrayType) {
return String.class.isAssignableFrom(clazz) && !arrayType;
}
}
1.1 cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/datatype/validationruleimpl/Mod10ValidationRuleBuilder.java
Index: Mod10ValidationRuleBuilder.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, 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 acknowledgment: "This product includes software
developed by the Apache Software Foundation (http://www.apache.org/)."
Alternately, this acknowledgment may appear in the software itself, if
and wherever such third-party acknowledgments normally appear.
4. The names "Apache Cocoon" 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 name, without prior written permission of the
Apache Software Foundation.
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 (INCLU-
DING, 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 and was originally created by
Stefano Mazzocchi <st...@apache.org>. For more information on the Apache
Software Foundation, please see <http://www.apache.org/>.
*/
package org.apache.cocoon.woody.datatype.validationruleimpl;
import org.apache.cocoon.woody.datatype.ValidationRule;
import org.w3c.dom.Element;
/**
* Builds {@link Mod10ValidationRule}s.
*/
public class Mod10ValidationRuleBuilder extends AbstractValidationRuleBuilder {
public ValidationRule build(Element validationRuleElement) throws Exception {
Mod10ValidationRule rule = new Mod10ValidationRule();
buildFailMessage(validationRuleElement, rule);
return rule;
}
}
1.1 cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/formmodel/AggregateField.java
Index: AggregateField.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, 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 acknowledgment: "This product includes software
developed by the Apache Software Foundation (http://www.apache.org/)."
Alternately, this acknowledgment may appear in the software itself, if
and wherever such third-party acknowledgments normally appear.
4. The names "Apache Cocoon" 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 name, without prior written permission of the
Apache Software Foundation.
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 (INCLU-
DING, 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 and was originally created by
Stefano Mazzocchi <st...@apache.org>. For more information on the Apache
Software Foundation, please see <http://www.apache.org/>.
*/
package org.apache.cocoon.woody.formmodel;
import org.apache.cocoon.woody.FormContext;
import org.apache.cocoon.woody.Constants;
import org.apache.cocoon.woody.datatype.ValidationError;
import org.apache.cocoon.woody.datatype.ValidationRule;
import org.apache.cocoon.woody.formmodel.AggregateFieldDefinition.SplitMapping;
import org.apache.cocoon.xml.AttributesImpl;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.Perl5Matcher;
import org.apache.oro.text.regex.MatchResult;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.outerj.expression.ExpressionException;
import java.util.*;
/**
* An aggregatedfield allows to edit the content of multiple fields through 1 textbox.
* Hence this widget is a container widget, though its individual widgets are never rendered.
*
* <p>Upon submit, the value from the textbox will be split over multiple field widgets
* using a regular expression. If this fails, this will simple give a validation error.
*
* <p>To validate this widget, both the validation rules of the containing widgets are
* checked, and those of the aggregated field themselve. The validation rules of the aggregated
* field can perform checks on the string as entered by the user (e.g. check its total length).
*
* <p>When getting the value from this widget (e.g. when generating its XML representation),
* the values of the individual child widgets are combined again into one string. This is done
* using an expression.
*
* <p>Currently the child widgets should always be field widgets whose datatype is string.
*
*/
public class AggregateField extends AbstractWidget implements ContainerWidget {
private AggregateFieldDefinition definition;
private String enteredValue;
private List fields = new ArrayList();
private Map fieldsById = new HashMap();
private boolean satisfiesSplitExpr = false;
private ValidationError validationError;
protected AggregateField(AggregateFieldDefinition definition) {
this.definition = definition;
}
protected void addField(Field field) {
fields.add(field);
fieldsById.put(field.getId(), field);
}
public String getId() {
return definition.getId();
}
public void readFromRequest(FormContext formContext) {
enteredValue = formContext.getRequest().getParameter(getFullyQualifiedId());
satisfiesSplitExpr = false;
validationError = null;
// whitespace & empty field handling
if (enteredValue != null) {
// TODO make whitespace behaviour configurable !!
enteredValue.trim();
if (enteredValue.equals(""))
enteredValue = null;
}
if (enteredValue != null) {
// try to split it
PatternMatcher matcher = new Perl5Matcher();
if (matcher.matches(enteredValue, definition.getSplitPattern())) {
MatchResult matchResult = matcher.getMatch();
Iterator iterator = definition.getSplitMappingsIterator();
while (iterator.hasNext()) {
SplitMapping splitMapping = (SplitMapping)iterator.next();
String result = matchResult.group(splitMapping.getGroup());
// Since we know the fields are guaranteed to have a string datatype, we
// can set the value immediately, instead of going to the readFromRequest
// (which would also require us to create wrapper FormContext and Request
// objects)
((Field)fieldsById.get(splitMapping.getFieldId())).setValue(result);
}
satisfiesSplitExpr = true;
}
}
}
/**
* Always returns a String for this widget (or null).
*/
public Object getValue() {
if (satisfiesSplitExpr) {
String value;
try {
value = (String)definition.getCombineExpression().evaluate(new ExpressionContextImpl(this, true));
} catch (ExpressionException e) {
return "#ERROR evaluating combine expression: " + e.getMessage();
} catch (ClassCastException e) {
return "#ERROR evaluating combine expression: result was not a string";
}
return value;
} else {
return enteredValue;
}
}
public boolean validate(FormContext formContext) {
// valid unless proven otherwise
validationError = null;
if (enteredValue == null && isRequired()) {
validationError = new ValidationError("general.field-required");
return false;
} else if (enteredValue == null)
return true;
else if (!satisfiesSplitExpr) {
Object splitFailMessage = definition.getSplitFailMessage();
if (splitFailMessage != null)
validationError = new ValidationError(splitFailMessage);
else
validationError = new ValidationError("aggregatedfield.split-failed", new String[] { definition.getSplitRegexp()});
return false;
} else {
// validate my child fields
Iterator fieldsIt = fields.iterator();
while (fieldsIt.hasNext()) {
Field field = (Field)fieldsIt.next();
if (!field.validate(formContext)) {
validationError = field.getValidationError();
return false;
}
}
// validate against my own validation rules
Iterator validationRuleIt = definition.getValidationRuleIterator();
ExpressionContextImpl exprCtx = new ExpressionContextImpl(this, true);
while (validationRuleIt.hasNext()) {
ValidationRule validationRule = (ValidationRule)validationRuleIt.next();
validationError = validationRule.validate(enteredValue, exprCtx);
if (validationError != null)
return false;
}
}
return validationError == null;
}
public boolean isRequired() {
return definition.isRequired();
}
private static final String AGGREGATEFIELD_EL = "aggregatefield";
private static final String VALUE_EL = "value";
private static final String VALIDATION_MSG_EL = "validation-message";
private static final String LABEL_EL = "label";
public void generateSaxFragment(ContentHandler contentHandler, Locale locale) throws SAXException {
AttributesImpl aggregatedFieldAttrs = new AttributesImpl();
aggregatedFieldAttrs.addCDATAAttribute("id", getFullyQualifiedId());
contentHandler.startElement(Constants.WI_NS, AGGREGATEFIELD_EL, Constants.WI_PREFIX_COLON + AGGREGATEFIELD_EL, aggregatedFieldAttrs);
String value = (String)getValue();
if (value != null) {
contentHandler.startElement(Constants.WI_NS, VALUE_EL, Constants.WI_PREFIX_COLON + VALUE_EL, Constants.EMPTY_ATTRS);
String stringValue; stringValue = value;
contentHandler.characters(stringValue.toCharArray(), 0, stringValue.length());
contentHandler.endElement(Constants.WI_NS, VALUE_EL, Constants.WI_PREFIX_COLON + VALUE_EL);
}
// validation message element: only present if the value is not valid
if (validationError != null) {
contentHandler.startElement(Constants.WI_NS, VALIDATION_MSG_EL, Constants.WI_PREFIX_COLON + VALIDATION_MSG_EL, Constants.EMPTY_ATTRS);
validationError.generateSaxFragment(contentHandler);
contentHandler.endElement(Constants.WI_NS, VALIDATION_MSG_EL, Constants.WI_PREFIX_COLON + VALIDATION_MSG_EL);
}
// the label
contentHandler.startElement(Constants.WI_NS, LABEL_EL, Constants.WI_PREFIX_COLON + LABEL_EL, Constants.EMPTY_ATTRS);
definition.generateLabel(contentHandler);
contentHandler.endElement(Constants.WI_NS, LABEL_EL, Constants.WI_PREFIX_COLON + LABEL_EL);
contentHandler.endElement(Constants.WI_NS, AGGREGATEFIELD_EL, Constants.WI_PREFIX_COLON + AGGREGATEFIELD_EL);
}
public void generateLabel(ContentHandler contentHandler) throws SAXException {
definition.generateLabel(contentHandler);
}
public Widget getWidget(String id) {
return (Widget)fieldsById.get(id);
}
}
1.1 cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/formmodel/AggregateFieldDefinition.java
Index: AggregateFieldDefinition.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, 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 acknowledgment: "This product includes software
developed by the Apache Software Foundation (http://www.apache.org/)."
Alternately, this acknowledgment may appear in the software itself, if
and wherever such third-party acknowledgments normally appear.
4. The names "Apache Cocoon" 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 name, without prior written permission of the
Apache Software Foundation.
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 (INCLU-
DING, 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 and was originally created by
Stefano Mazzocchi <st...@apache.org>. For more information on the Apache
Software Foundation, please see <http://www.apache.org/>.
*/
package org.apache.cocoon.woody.formmodel;
import org.outerj.expression.Expression;
import org.apache.oro.text.regex.Pattern;
import org.apache.cocoon.woody.datatype.ValidationRule;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
/**
* The {@link WidgetDefinition} part of a AggregateField widget, see {@link AggregateField} for more information.
*/
public class AggregateFieldDefinition extends AbstractWidgetDefinition {
private Expression combineExpr;
private Pattern splitPattern;
/**
* The original regexp expression from which the {@link #splitPattern} was compiled,
* used purely for informational purposes.
*/
private String splitRegexp;
/**
* Message to be displayed when the {@link #splitPattern} does not match what the
* user entered. Optional.
*/
protected Object splitFailMessage;
/**
* List containing instances of {@link SplitMapping}, i.e. the mapping between
* a group (paren) from the regular expression and corresponding field id.
*/
private List splitMappings = new ArrayList();
private ContainerDefinitionDelegate container = new ContainerDefinitionDelegate(this);
/**
* Validation rules to be applied to the not-splitted value.
*/
private List validationRules = new ArrayList();
protected boolean required = false;
public void addWidgetDefinition(WidgetDefinition widgetDefinition) throws DuplicateIdException {
container.addWidgetDefinition(widgetDefinition);
}
public boolean hasWidget(String id) {
return container.hasWidget(id);
}
protected void addValidationRule(ValidationRule validationRule) {
validationRules.add(validationRule);
}
public Iterator getValidationRuleIterator() {
return validationRules.iterator();
}
protected void setCombineExpression(Expression expression) {
combineExpr = expression;
}
public Expression getCombineExpression() {
return combineExpr;
}
protected void setSplitPattern(Pattern pattern, String regexp) {
this.splitPattern = pattern;
this.splitRegexp = regexp;
}
public Pattern getSplitPattern() {
return splitPattern;
}
public String getSplitRegexp() {
return splitRegexp;
}
public Object getSplitFailMessage() {
return splitFailMessage;
}
protected void setSplitFailMessage(Object splitFailMessage) {
this.splitFailMessage = splitFailMessage;
}
protected void addSplitMapping(int group, String fieldId) {
splitMappings.add(new SplitMapping(group, fieldId));
}
public Iterator getSplitMappingsIterator() {
return splitMappings.iterator();
}
public Widget createInstance() {
AggregateField aggregateField = new AggregateField(this);
Iterator fieldDefinitionIt = container.getWidgetDefinitions().iterator();
while (fieldDefinitionIt.hasNext()) {
FieldDefinition fieldDefinition = (FieldDefinition)fieldDefinitionIt.next();
aggregateField.addField((Field)fieldDefinition.createInstance());
}
return aggregateField;
}
public boolean isRequired() {
return required;
}
protected void setRequired(boolean required) {
this.required = required;
}
public static class SplitMapping
{
int group;
String fieldId;
public SplitMapping(int group, String fieldId) {
this.group = group;
this.fieldId = fieldId;
}
public int getGroup() {
return group;
}
public String getFieldId() {
return fieldId;
}
}
}
1.1 cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/formmodel/AggregateFieldDefinitionBuilder.java
Index: AggregateFieldDefinitionBuilder.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, 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 acknowledgment: "This product includes software
developed by the Apache Software Foundation (http://www.apache.org/)."
Alternately, this acknowledgment may appear in the software itself, if
and wherever such third-party acknowledgments normally appear.
4. The names "Apache Cocoon" 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 name, without prior written permission of the
Apache Software Foundation.
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 (INCLU-
DING, 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 and was originally created by
Stefano Mazzocchi <st...@apache.org>. For more information on the Apache
Software Foundation, please see <http://www.apache.org/>.
*/
package org.apache.cocoon.woody.formmodel;
import org.w3c.dom.Element;
import org.apache.cocoon.woody.util.DomHelper;
import org.apache.cocoon.woody.Constants;
import org.apache.cocoon.woody.datatype.ValidationRule;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.MalformedPatternException;
import org.outerj.expression.Expression;
import java.util.HashSet;
/**
* Builds {@link AggregateFieldDefinition}s.
*/
public class AggregateFieldDefinitionBuilder extends AbstractWidgetDefinitionBuilder {
public WidgetDefinition buildWidgetDefinition(Element widgetElement) throws Exception {
AggregateFieldDefinition definition = new AggregateFieldDefinition();
setId(widgetElement, definition);
setLabel(widgetElement, definition);
// make childfields
Element childrenElement = DomHelper.getChildElement(widgetElement, Constants.WD_NS, "children", true);
Element[] fieldElements = DomHelper.getChildElements(childrenElement, Constants.WD_NS, "field");
for (int i = 0; i < fieldElements.length; i++) {
FieldDefinition fieldDefinition = (FieldDefinition)formManager.buildWidgetDefinition(fieldElements[i]);
if (!String.class.isAssignableFrom(fieldDefinition.getDatatype().getTypeClass()))
throw new Exception("An aggregatefield can only contain fields with datatype string, at " + DomHelper.getLocation(fieldElements[i]));
definition.addWidgetDefinition(fieldDefinition);
}
// compile splitpattern
Element splitElement = DomHelper.getChildElement(widgetElement, Constants.WD_NS, "split", true);
String patternString = DomHelper.getAttribute(splitElement, "pattern");
Perl5Compiler compiler = new Perl5Compiler();
Pattern pattern = null;
try {
pattern = compiler.compile(patternString, Perl5Compiler.READ_ONLY_MASK);
} catch (MalformedPatternException e) {
throw new Exception("Invalid regular expression at " + DomHelper.getLocation(splitElement) + ": " + e.getMessage());
}
definition.setSplitPattern(pattern, patternString);
// read split mappings
Element[] mapElements = DomHelper.getChildElements(splitElement, Constants.WD_NS, "map");
HashSet encounteredFieldMappings = new HashSet();
for (int i = 0; i < mapElements.length; i++) {
int group = DomHelper.getAttributeAsInteger(mapElements[i], "group");
String field = DomHelper.getAttribute(mapElements[i], "field");
// check that this field exists
if (!definition.hasWidget(field))
throw new Exception("Unkwon widget id \"" + field + "\"mentioned on mapping at " + DomHelper.getLocation(mapElements[i]));
if (encounteredFieldMappings.contains(field))
throw new Exception("It makes no sense to map two groups to the widget with id \"" + field + "\", at " + DomHelper.getLocation(mapElements[i]));
encounteredFieldMappings.add(field);
definition.addSplitMapping(group, field);
}
// read split fail message (if any)
Element failMessageElement = DomHelper.getChildElement(splitElement, Constants.WD_NS, "failmessage");
if (failMessageElement != null) {
Object failMessage = DomHelper.compileElementContent(failMessageElement);
definition.setSplitFailMessage(failMessage);
}
// compile combine expression
Element combineElement = DomHelper.getChildElement(widgetElement, Constants.WD_NS, "combine", true);
String combineExprString = DomHelper.getAttribute(combineElement, "expression");
Expression combineExpr = null;
try {
combineExpr = expressionManager.parse(combineExprString);
} catch (Exception e) {
throw new Exception("Problem with combine expression defined at " + DomHelper.getLocation(combineElement) + ": " + e.getMessage());
}
if (combineExpr.getResultType() != null && !String.class.isAssignableFrom(combineExpr.getResultType()))
throw new Exception("The result of the combine expression should be a string, at " + DomHelper.getLocation(combineElement));
definition.setCombineExpression(combineExpr);
// add validation rules
Element validationElement = DomHelper.getChildElement(widgetElement, Constants.WD_NS, "validation", false);
if (validationElement != null) {
Element[] validationRuleElements = DomHelper.getChildElements(validationElement, Constants.WD_NS);
for (int i = 0; i < validationRuleElements.length; i++) {
Element validationRuleElement = validationRuleElements[i];
ValidationRule validationRule = datatypeManager.createValidationRule(validationRuleElement);
if (!validationRule.supportsType(String.class, false))
throw new Exception("The validation rule for the aggregatefield " + definition.getId() + " specified at " + DomHelper.getLocation(validationRuleElement) + " does not work with strings.");
definition.addValidationRule(validationRule);
}
}
// requiredness
boolean required = DomHelper.getAttributeAsBoolean(widgetElement, "required", false);
definition.setRequired(required);
return definition;
}
}
1.1 cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/formmodel/ContainerDefinitionDelegate.java
Index: ContainerDefinitionDelegate.java
===================================================================
package org.apache.cocoon.woody.formmodel;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
/**
* Helper class for the Definition implementation of widgets containing
* other widgets.
*/
public class ContainerDefinitionDelegate {
private List widgetDefinitions = new ArrayList();
private Map widgetDefinitionsById = new HashMap();
private WidgetDefinition definition;
/**
* @param definition the widget definition to which this container delegate belongs
*/
public ContainerDefinitionDelegate(WidgetDefinition definition) {
this.definition = definition;
}
public void addWidgetDefinition(WidgetDefinition widgetDefinition) throws DuplicateIdException {
if (widgetDefinitionsById.containsKey(widgetDefinition.getId()))
throw new DuplicateIdException("Duplicate widget id detected: widget " + definition.getId() + " already contains a widget with id \"" + widgetDefinition.getId() + "\"");
widgetDefinitions.add(widgetDefinition);
widgetDefinitionsById.put(widgetDefinition.getId(), widgetDefinition);
}
public List getWidgetDefinitions() {
return widgetDefinitions;
}
public boolean hasWidget(String id) {
return widgetDefinitionsById.containsKey(id);
}
}