cocoon-cvs mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From vgritse...@apache.org
Subject cvs commit: cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/formmodel AggregateField.java AggregateFieldDefinition.java AggregateFieldDefinitionBuilder.java
Date Sun, 29 Feb 2004 06:07:37 GMT
vgritsenko    2004/02/28 22:07:37

  Modified:    .        status.xml
               src/blocks/woody/java/org/apache/cocoon/woody/binding
                        AggregateJXPathBinding.java ValueJXPathBinding.java
               src/blocks/woody/java/org/apache/cocoon/woody/formmodel
                        AggregateField.java AggregateFieldDefinition.java
                        AggregateFieldDefinitionBuilder.java
  Log:
       CForms: Aggregate field supports both directions (split / combine), and arbitrary
       types (not strings only).
  
  Revision  Changes    Path
  1.253     +5 -1      cocoon-2.1/status.xml
  
  Index: status.xml
  ===================================================================
  RCS file: /home/cvs/cocoon-2.1/status.xml,v
  retrieving revision 1.252
  retrieving revision 1.253
  diff -u -r1.252 -r1.253
  --- status.xml	29 Feb 2004 00:59:14 -0000	1.252
  +++ status.xml	29 Feb 2004 06:07:37 -0000	1.253
  @@ -196,6 +196,10 @@
     <changes>
   
    <release version="@version@" date="@date@">
  +   <action dev="VG" type="update">
  +     CForms: Aggregate field supports both directions (split / combine), and arbitrary
  +     types (not strings only).
  +   </action>
      <action dev="VG" type="add">
        CForms: Added String() function. Converts argument to string value.
      </action>
  
  
  
  1.9       +4 -3      cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/binding/AggregateJXPathBinding.java
  
  Index: AggregateJXPathBinding.java
  ===================================================================
  RCS file: /home/cvs/cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/binding/AggregateJXPathBinding.java,v
  retrieving revision 1.8
  retrieving revision 1.9
  diff -u -r1.8 -r1.9
  --- AggregateJXPathBinding.java	3 Feb 2004 12:26:21 -0000	1.8
  +++ AggregateJXPathBinding.java	29 Feb 2004 06:07:37 -0000	1.9
  @@ -92,8 +92,9 @@
           AggregateField aggregate = (AggregateField) frmModel.getWidget(this.widgetId);
           JXPathContext subContext = jxpc.getRelativeContext(jxpc.getPointer(this.xpath));
           super.doLoad(aggregate, subContext);
  +        aggregate.combineFields();
           if (getLogger().isDebugEnabled()) {
  -            getLogger().debug("done loading " + toString());
  +            getLogger().debug("Done loading " + toString());
           }
       }
   
  @@ -107,7 +108,7 @@
           JXPathContext subContext = jxpc.getRelativeContext(jxpc.getPointer(this.xpath));
           super.doSave(aggregate, subContext);
           if (getLogger().isDebugEnabled()) {
  -            getLogger().debug("done saving " + toString());
  +            getLogger().debug("Done saving " + toString());
           }
       }
   
  
  
  
  1.13      +5 -5      cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/binding/ValueJXPathBinding.java
  
  Index: ValueJXPathBinding.java
  ===================================================================
  RCS file: /home/cvs/cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/binding/ValueJXPathBinding.java,v
  retrieving revision 1.12
  retrieving revision 1.13
  diff -u -r1.12 -r1.13
  --- ValueJXPathBinding.java	3 Feb 2004 12:26:21 -0000	1.12
  +++ ValueJXPathBinding.java	29 Feb 2004 06:07:37 -0000	1.13
  @@ -120,8 +120,8 @@
               throw new BindingException("The widget with the ID [" + this.fieldId
                       + "] referenced in the binding does not exist in the form definition.");
           }
  -        Object value = jxpc.getValue(this.xpath);
   
  +        Object value = jxpc.getValue(this.xpath);
           if (value != null && convertor != null) {
               if (value instanceof String) {
                   value = convertor.convertFromString((String)value, convertorLocale, null);
  @@ -131,9 +131,9 @@
           }
   
           widget.setValue(value);
  -
  -        if (getLogger().isDebugEnabled())
  -            getLogger().debug("done loading " + toString() + " -- value= " + value);
  +        if (getLogger().isDebugEnabled()) {
  +            getLogger().debug("Done loading " + toString() + " -- value= " + value);
  +        }
       }
   
       /**
  
  
  
  1.15      +143 -141  cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/formmodel/AggregateField.java
  
  Index: AggregateField.java
  ===================================================================
  RCS file: /home/cvs/cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/formmodel/AggregateField.java,v
  retrieving revision 1.14
  retrieving revision 1.15
  diff -u -r1.14 -r1.15
  --- AggregateField.java	4 Feb 2004 17:25:57 -0000	1.14
  +++ AggregateField.java	29 Feb 2004 06:07:37 -0000	1.15
  @@ -50,211 +50,214 @@
   */
   package org.apache.cocoon.woody.formmodel;
   
  -import java.util.ArrayList;
  -import java.util.HashMap;
  -import java.util.Iterator;
  -import java.util.List;
  -import java.util.Locale;
  -import java.util.Map;
  -
   import org.apache.cocoon.woody.Constants;
   import org.apache.cocoon.woody.FormContext;
  -import org.apache.cocoon.woody.validation.ValidationError;
  -import org.apache.cocoon.woody.validation.ValidationErrorAware;
  -import org.apache.cocoon.woody.datatype.ValidationRule;
   import org.apache.cocoon.woody.formmodel.AggregateFieldDefinition.SplitMapping;
   import org.apache.cocoon.woody.util.I18nMessage;
  +import org.apache.cocoon.woody.validation.ValidationError;
   import org.apache.cocoon.xml.AttributesImpl;
   import org.apache.excalibur.xml.sax.XMLizable;
   import org.apache.oro.text.regex.MatchResult;
   import org.apache.oro.text.regex.PatternMatcher;
   import org.apache.oro.text.regex.Perl5Matcher;
  +
   import org.outerj.expression.ExpressionException;
   import org.xml.sax.ContentHandler;
   import org.xml.sax.SAXException;
   
  +import java.util.ArrayList;
  +import java.util.HashMap;
  +import java.util.Iterator;
  +import java.util.List;
  +import java.util.Locale;
  +import java.util.Map;
  +
   /**
  - * 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.
  + * An aggregated field allows to represent one value as multiple input fields, or several
values
  + * as one field. Hence this widget is a field and a container widget simultaneously.
    *
  - * <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>Upon submit, it first attempts to read own value from the request, and splits
over nested
  + * field widgets using a regular expression. If split fails, this will simply give a validation
error.
  + * If own value was not submitted, it attempts to read values for nested field widgets,
and combines
  + * theirs values using combine expression.
    *
  - * <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
  + * <p>To validate this widget, both the validation rules of the nested widgets are
  + * checked, and those of the aggregated field themselves. 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>This field and nested fields can be of any supported type, as long as combine
expression
  + * gives result of the correct type, and split regular expression can split string representation
  + * into parts which can be converted to the values of nested fields.
    *
  - * <p>Currently the child widgets should always be field widgets whose datatype is
string.
  - * 
    * @version CVS $Id$
  - *
    */
  -public class AggregateField extends AbstractWidget implements ValidationErrorAware {
  -    private AggregateFieldDefinition aggregateDefinition;
  -    private String enteredValue;
  +public class AggregateField extends Field {
  +
  +    /**
  +     * List of nested fields
  +     */
       private List fields = new ArrayList();
  +
  +    /**
  +     * Map of nested fields
  +     */
       private Map fieldsById = new HashMap();
  -    private ValidationError validationError;
   
  -    protected AggregateField(AggregateFieldDefinition definition) {
  -        super.setDefinition(definition);
  -        this.aggregateDefinition = definition;
  -        setLocation(definition.getLocation());
  +
  +    public AggregateField(AggregateFieldDefinition definition) {
  +        super(definition);
  +    }
  +
  +    public final AggregateFieldDefinition getAggregateFieldDefinition() {
  +        return (AggregateFieldDefinition)super.definition;
       }
   
       protected void addField(Field field) {
  -        fields.add(field);
           field.setParent(this);
  +        fields.add(field);
           fieldsById.put(field.getId(), field);
       }
   
  -    public String getId() {
  -        return definition.getId();
  +    public Iterator getChildren() {
  +        return fields.iterator();
       }
   
       public void readFromRequest(FormContext formContext) {
           String newEnteredValue = formContext.getRequest().getParameter(getFullyQualifiedId());
  -        
  -        // whitespace & empty field handling
           if (newEnteredValue != null) {
  -            // TODO make whitespace behaviour configurable !!
  -            newEnteredValue.trim();
  -            if (newEnteredValue.length() == 0) {
  -                newEnteredValue = null;
  +            // There is one aggregated entered value. Read it and split it.
  +            super.readFromRequest(formContext);
  +            if (needsParse) {
  +                setFieldsValues(enteredValue);
  +            }
  +        } else {
  +            // Check if there are multiple splitted values. Read them and aggregate them.
  +            boolean needsParse = false;
  +            for (Iterator i = fields.iterator(); i.hasNext();) {
  +                Field field = (Field)i.next();
  +                field.readFromRequest(formContext);
  +                needsParse |= field.needsParse;
  +            }
  +            if (needsParse) {
  +                combineFields();
               }
           }
  +    }
   
  -        // Only convert if the text value actually changed. Otherwise, keep the old value
  -        // and/or the old validation error (allows to keep errors when clicking on actions)
  -        if (!(newEnteredValue == null ? "" : newEnteredValue).equals((enteredValue == null
? "" : enteredValue))) {
  -            
  -            enteredValue = newEnteredValue;
  -            validationError = null;
  -    
  -            if (enteredValue != null) {
  -                // try to split it
  -                PatternMatcher matcher = new Perl5Matcher();
  -                if (matcher.matches(enteredValue, aggregateDefinition.getSplitPattern()))
{
  -                    MatchResult matchResult = matcher.getMatch();
  -                    Iterator iterator = aggregateDefinition.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);
  -                    }
  -                } else {
  -                    // set values of the fields to null
  -                    Iterator fieldsIt = fields.iterator();
  -                    while (fieldsIt.hasNext()) {
  -                        Field field = (Field)fieldsIt.next();
  -                        field.setValue(null);
  -                    }
  -                }
  -            }
  +    public void setValue(Object newValue) {
  +        super.setValue(newValue);
  +        if (needsValidate) {
  +            setFieldsValues(enteredValue);
           }
       }
   
       /**
  -     * Always returns a String for this widget (or null).
  +     * Returns false if all fields have no value.
        */
  -    public Object getValue() {
  -        if (fieldsHaveValues()) {
  -            String value;
  -            try {
  -                value = (String)aggregateDefinition.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";
  +    private boolean fieldsHaveValues() {
  +        for (Iterator i = fields.iterator(); i.hasNext();) {
  +            Field field = (Field)i.next();
  +            if (field.getValue() != null) {
  +                return true;
               }
  -            return value;
  +        }
  +        return false;
  +    }
  +
  +    /**
  +     * Splits passed value and sets values of all nested fields.
  +     * If split fails, resets all fields.
  +     */
  +    private void setFieldsValues(String value) {
  +        if (value == null) {
  +            resetFieldsValues();
           } else {
  -            return enteredValue;
  +            PatternMatcher matcher = new Perl5Matcher();
  +            if (matcher.matches(value, getAggregateFieldDefinition().getSplitPattern()))
{
  +                MatchResult matchResult = matcher.getMatch();
  +                Iterator iterator = getAggregateFieldDefinition().getSplitMappingsIterator();
  +                while (iterator.hasNext()) {
  +                    SplitMapping splitMapping = (SplitMapping)iterator.next();
  +                    String result = matchResult.group(splitMapping.getGroup());
  +
  +                    // Fields can have a non-string datatype, going to the readFromRequest
  +                    Field field = (Field)fieldsById.get(splitMapping.getFieldId());
  +                    field.readFromRequest(result);
  +                }
  +            } else {
  +                resetFieldsValues();
  +            }
  +        }
  +    }
  +
  +    public void combineFields() {
  +        try {
  +            Object value = getAggregateFieldDefinition().getCombineExpression().evaluate(new
ExpressionContextImpl(this, true));
  +            super.setValue(value);
  +        } catch (CannotYetResolveWarning e) {
  +            super.setValue(null);
  +        } catch (ExpressionException e) {
  +            super.setValue(null);
  +        } catch (ClassCastException e) {
  +            super.setValue(null);
           }
       }
   
       /**
  -     * Returns false if their is at least one field which has no value.
  +     * Sets values of all nested fields to null
        */
  -    private boolean fieldsHaveValues() {
  -        Iterator fieldsIt = fields.iterator();
  -        while (fieldsIt.hasNext()) {
  -            Field field = (Field)fieldsIt.next();
  -            if (field.getValue() == null)
  -                return false;
  +    private void resetFieldsValues() {
  +        for (Iterator i = fields.iterator(); i.hasNext();) {
  +            Field field = (Field)i.next();
  +            field.setValue(null);
           }
  -        return true;
       }
   
       public boolean validate(FormContext formContext) {
  -        // valid unless proven otherwise
  -        validationError = null;
  -
  -        if (enteredValue == null) {
  -            if (isRequired()) {
  -                validationError = new ValidationError(new I18nMessage("general.field-required",
Constants.I18N_CATALOGUE));
  -                return false;
  -            }
  -            return true;
  -        } else if (!fieldsHaveValues()) {
  -            XMLizable splitFailMessage = aggregateDefinition.getSplitFailMessage();
  -            if (splitFailMessage != null) {
  -                validationError = new ValidationError(splitFailMessage);
  +        if ((enteredValue != null) != fieldsHaveValues()) {
  +            XMLizable failMessage = getAggregateFieldDefinition().getSplitFailMessage();
  +            if (failMessage != null) {
  +                validationError = new ValidationError(failMessage);
               } else {
  -                validationError = new ValidationError(new I18nMessage("aggregatedfield.split-failed",
new String[] { aggregateDefinition.getSplitRegexp()}, Constants.I18N_CATALOGUE));
  +                validationError = new ValidationError(new I18nMessage("aggregatedfield.split-failed",
  +                                                                      new String[] { getAggregateFieldDefinition().getSplitRegexp()
},
  +                                                                      Constants.I18N_CATALOGUE));
               }
               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 = aggregateDefinition.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;
  +        }
  +
  +        // validate my child fields
  +        for (Iterator i = fields.iterator(); i.hasNext();) {
  +            Field field = (Field)i.next();
  +            if (!field.validate(formContext)) {
  +                validationError = field.getValidationError();
  +                return false;
               }
           }
  -        return validationError == null ? super.validate(formContext) : false;
  -    }
   
  -    public boolean isRequired() {
  -        return aggregateDefinition.isRequired();
  +        return super.validate(formContext);
       }
   
  +
       private static final String AGGREGATEFIELD_EL = "aggregatefield";
       private static final String VALUE_EL = "value";
       private static final String VALIDATION_MSG_EL = "validation-message";
   
  -
       public void generateSaxFragment(ContentHandler contentHandler, Locale locale) throws
SAXException {
           AttributesImpl aggregatedFieldAttrs = new AttributesImpl();
           aggregatedFieldAttrs.addCDATAAttribute("id", getFullyQualifiedId());
  -        aggregatedFieldAttrs.addCDATAAttribute("required", String.valueOf(aggregateDefinition.isRequired()));
  -
  +        aggregatedFieldAttrs.addCDATAAttribute("required", String.valueOf(getAggregateFieldDefinition().isRequired()));
           contentHandler.startElement(Constants.WI_NS, AGGREGATEFIELD_EL, Constants.WI_PREFIX_COLON
+ AGGREGATEFIELD_EL, aggregatedFieldAttrs);
   
  -        String value = (String)getValue();
  -        if (value != null) {
  +        if (enteredValue != null || value != null) {
               contentHandler.startElement(Constants.WI_NS, VALUE_EL, Constants.WI_PREFIX_COLON
+ VALUE_EL, Constants.EMPTY_ATTRS);
  -            contentHandler.characters(value.toCharArray(), 0, value.length());
  +            String stringValue;
  +            if (value != null) {
  +                stringValue = getDatatype().convertToString(value, locale);
  +            } else {
  +                stringValue = enteredValue;
  +            }
  +            contentHandler.characters(stringValue.toCharArray(), 0, stringValue.length());
               contentHandler.endElement(Constants.WI_NS, VALUE_EL, Constants.WI_PREFIX_COLON
+ VALUE_EL);
           }
   
  @@ -267,6 +270,13 @@
   
           // generate label, help, hint, etc.
           definition.generateDisplayData(contentHandler);
  +
  +        // generate selection list, if any
  +        if (selectionList != null) {
  +            selectionList.generateSaxFragment(contentHandler, locale);
  +        } else if (getFieldDefinition().getSelectionList() != null) {
  +            getFieldDefinition().getSelectionList().generateSaxFragment(contentHandler,
locale);
  +        }
           contentHandler.endElement(Constants.WI_NS, AGGREGATEFIELD_EL, Constants.WI_PREFIX_COLON
+ AGGREGATEFIELD_EL);
       }
   
  @@ -276,13 +286,5 @@
   
       public Widget getWidget(String id) {
           return (Widget)fieldsById.get(id);
  -    }
  -
  -    public ValidationError getValidationError() {
  -        return this.validationError;
  -    }
  -
  -    public void setValidationError(ValidationError error) {
  -        this.validationError = error;
       }
   }
  
  
  
  1.7       +27 -36    cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/formmodel/AggregateFieldDefinition.java
  
  Index: AggregateFieldDefinition.java
  ===================================================================
  RCS file: /home/cvs/cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/formmodel/AggregateFieldDefinition.java,v
  retrieving revision 1.6
  retrieving revision 1.7
  diff -u -r1.6 -r1.7
  --- AggregateFieldDefinition.java	11 Feb 2004 10:43:30 -0000	1.6
  +++ AggregateFieldDefinition.java	29 Feb 2004 06:07:37 -0000	1.7
  @@ -50,47 +50,55 @@
   */
   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 org.apache.excalibur.xml.sax.XMLizable;
  +import org.apache.oro.text.regex.Pattern;
  +
  +import org.outerj.expression.Expression;
   
  -import java.util.List;
   import java.util.ArrayList;
   import java.util.Iterator;
  +import java.util.List;
   
   /**
    * The {@link WidgetDefinition} part of a AggregateField widget, see {@link AggregateField}
for more information.
  - * 
  + *
    * @version $Id$
    */
  -public class AggregateFieldDefinition extends AbstractWidgetDefinition {
  -    private Expression combineExpr;
  +public class AggregateFieldDefinition extends FieldDefinition {
  +
       /**
  -     * Compiled split pattern.
  +     * Defines expression which combines values of nested fields into this value
        */
  -    private Pattern splitPattern;
  +    private Expression combineExpr;
  +
       /**
  -     * The original regexp expression from which the {@link #splitPattern} was compiled,
  -     * used purely for informational purposes.
  +     * Regular expression which splits this value on the values of the nested fields.
  +     * It is compiled into the {@link #splitPattern}.
        */
       private String splitRegexp;
  +
  +    /**
  +     * Compiled pattern out of the {@link #splitRegexp} regular expression.
  +     */
  +    private Pattern splitPattern;
  +
       /**
        * Message to be displayed when the {@link #splitPattern} does not match what the
        * user entered. Optional.
        */
       protected XMLizable splitFailMessage;
  +
       /**
        * List containing instances of {@link #splitMappings}, 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;
  +    private ContainerDefinitionDelegate container = new ContainerDefinitionDelegate(this);
  +
   
       public void addWidgetDefinition(WidgetDefinition widgetDefinition) throws DuplicateIdException
{
           container.addWidgetDefinition(widgetDefinition);
  @@ -100,14 +108,6 @@
           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;
       }
  @@ -157,18 +157,9 @@
           return aggregateField;
       }
   
  -    public boolean isRequired() {
  -        return required;
  -    }
  -
  -    protected void setRequired(boolean required) {
  -        this.required = required;
  -    }
  -
  -    public static class SplitMapping
  -    {
  -        int group;
  -        String fieldId;
  +    public static class SplitMapping {
  +        private int group;
  +        private String fieldId;
   
           public SplitMapping(int group, String fieldId) {
               this.group = group;
  
  
  
  1.9       +33 -47    cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/formmodel/AggregateFieldDefinitionBuilder.java
  
  Index: AggregateFieldDefinitionBuilder.java
  ===================================================================
  RCS file: /home/cvs/cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/formmodel/AggregateFieldDefinitionBuilder.java,v
  retrieving revision 1.8
  retrieving revision 1.9
  diff -u -r1.8 -r1.9
  --- AggregateFieldDefinitionBuilder.java	11 Feb 2004 10:43:30 -0000	1.8
  +++ AggregateFieldDefinitionBuilder.java	29 Feb 2004 06:07:37 -0000	1.9
  @@ -50,40 +50,35 @@
   */
   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.apache.cocoon.woody.util.DomHelper;
   import org.apache.excalibur.xml.sax.XMLizable;
  +import org.apache.oro.text.regex.MalformedPatternException;
  +import org.apache.oro.text.regex.Pattern;
  +import org.apache.oro.text.regex.Perl5Compiler;
  +
   import org.outerj.expression.Expression;
  +import org.w3c.dom.Element;
   
   import java.util.HashSet;
   
   /**
    * Builds {@link AggregateFieldDefinition}s.
  - * 
  + *
    * @version $Id$
    */
  -public class AggregateFieldDefinitionBuilder extends AbstractWidgetDefinitionBuilder {
  +public class AggregateFieldDefinitionBuilder extends FieldDefinitionBuilder {
  +
       public WidgetDefinition buildWidgetDefinition(Element widgetElement) throws Exception
{
  -        AggregateFieldDefinition definition = new AggregateFieldDefinition();
  -        setLocation(widgetElement, definition);
  -        setId(widgetElement, definition);
  -        setDisplayData(widgetElement, definition);
  -//FIXME: these are currently type-related validators
  -//        setValidators(widgetElement, definition);
  +        AggregateFieldDefinition aggregateDefinition = new AggregateFieldDefinition();
  +        buildWidgetDefinition(aggregateDefinition, widgetElement);
   
  -        // make childfields
  +        // make children fields
           Element widgetsElement = DomHelper.getChildElement(widgetElement, Constants.WD_NS,
"widgets", true);
           Element[] fieldElements = DomHelper.getChildElements(widgetsElement, Constants.WD_NS,
"field");
           for (int i = 0; i < fieldElements.length; i++) {
               FieldDefinition fieldDefinition = (FieldDefinition)buildAnotherWidgetDefinition(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);
  +            aggregateDefinition.addWidgetDefinition(fieldDefinition);
           }
   
           // compile splitpattern
  @@ -96,7 +91,7 @@
           } catch (MalformedPatternException e) {
               throw new Exception("Invalid regular expression at " + DomHelper.getLocation(splitElement)
+ ": " + e.getMessage());
           }
  -        definition.setSplitPattern(pattern, patternString);
  +        aggregateDefinition.setSplitPattern(pattern, patternString);
   
           // read split mappings
           Element[] mapElements = DomHelper.getChildElements(splitElement, Constants.WD_NS,
"map");
  @@ -105,19 +100,23 @@
               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]));
  +            if (!aggregateDefinition.hasWidget(field)) {
  +                throw new Exception("Unkwon widget id \"" + field + "\", at " +
  +                                    DomHelper.getLocation(mapElements[i]));
  +            }
  +            if (encounteredFieldMappings.contains(field)) {
  +                throw new Exception("Two groups are mapped to the same widget id \"" +
field + "\", at " +
  +                                    DomHelper.getLocation(mapElements[i]));
  +            }
               encounteredFieldMappings.add(field);
  -            definition.addSplitMapping(group, field);
  +            aggregateDefinition.addSplitMapping(group, field);
           }
   
           // read split fail message (if any)
           Element failMessageElement = DomHelper.getChildElement(splitElement, Constants.WD_NS,
"failmessage");
           if (failMessageElement != null) {
               XMLizable failMessage = DomHelper.compileElementContent(failMessageElement);
  -            definition.setSplitFailMessage(failMessage);
  +            aggregateDefinition.setSplitFailMessage(failMessage);
           }
   
           // compile combine expression
  @@ -127,29 +126,16 @@
           try {
               combineExpr = expressionManager.parse(combineExprString);
           } catch (Exception e) {
  -            throw new Exception("Problem with combine expression defined at " + DomHelper.getLocation(combineElement)
+ ": " + e.getMessage());
  +            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);
  -            }
  +        Class clazz = aggregateDefinition.getDatatype().getTypeClass();
  +        if (combineExpr.getResultType() != null && !clazz.isAssignableFrom(combineExpr.getResultType()))
{
  +            throw new Exception("The result of the combine expression should be " + clazz.getName()
+ ", at " +
  +                                DomHelper.getLocation(combineElement));
           }
  +        aggregateDefinition.setCombineExpression(combineExpr);
   
  -        // requiredness
  -        boolean required = DomHelper.getAttributeAsBoolean(widgetElement, "required", false);
  -        definition.setRequired(required);
  -
  -        return definition;
  +        return aggregateDefinition;
       }
   }
  
  
  

Mime
View raw message