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/08/12 14:54:45 UTC

cvs commit: cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/formmodel Output.java OutputDefinition.java OutputDefinitionBuilder.java

bruno       2003/08/12 05:54:45

  Added:       src/blocks/woody/java/org/apache/cocoon/woody/binding
                        ValueJXPathBinding.java
                        ValueJXPathBindingBuilder.java
               src/blocks/woody/java/org/apache/cocoon/woody/datatype/convertor
                        PlainBooleanConvertor.java
                        PlainBooleanConvertorBuilder.java
               src/blocks/woody/java/org/apache/cocoon/woody/datatype/typeimpl
                        BooleanType.java BooleanTypeBuilder.java
               src/blocks/woody/java/org/apache/cocoon/woody/formmodel
                        Output.java OutputDefinition.java
                        OutputDefinitionBuilder.java
  Log:
  initial commit
  
  Revision  Changes    Path
  1.1                  cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/binding/ValueJXPathBinding.java
  
  Index: ValueJXPathBinding.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.binding;
  
  import org.apache.avalon.framework.logger.Logger;
  import org.apache.cocoon.woody.formmodel.Widget;
  import org.apache.cocoon.woody.datatype.convertor.Convertor;
  import org.apache.commons.jxpath.JXPathContext;
  import org.apache.commons.jxpath.JXPathException;
  
  import java.util.Locale;
  
  /**
   * ValueJXPathBinding provides an implementation of a {@link Binding}
   * that loads and saves the information behind a specific xpath expresion
   * (pointing to an attribute or text-node) to and from a specific Woody
   * widget as identified by its id.
   */
  public class ValueJXPathBinding extends JXPathBindingBase {
  
      /**
       * The xpath expression to the objectModel property
       */
      private final String xpath;
  
      /**
       * The id of the Woody form-widget
       */
      private final String fieldId;
  
      /**
       * Flag indicating if the objectModel-property can be altered or not
       */
      private final boolean readonly;
  
      /**
       * Flag indicating if the objectModel-property can be altered or not
       */
      private final JXPathBindingBase updateBinding;
  
      /**
       * Optional convertor to convert values to and from strings when setting or reading
       * the from the model. Especially used in combination with XML models where everything
       * are strings.
       */
      private final Convertor convertor;
  
      /**
       * The locale to pass to the {@link #convertor}.
       */
      private final Locale convertorLocale;
  
      /**
       * Constructs FieldJXPathBinding.
       *
       * @param convertor may be null
       */
      public ValueJXPathBinding(String widgetId, String xpath, boolean readonly, JXPathBindingBase[] updateBindings,
                                Convertor convertor, Locale convertorLocale) {
          this.fieldId = widgetId;
          this.xpath = xpath;
          this.readonly = readonly;
          this.updateBinding = new ComposedJXPathBindingBase(updateBindings);
          this.convertor = convertor;
          this.convertorLocale = convertorLocale;
      }
  
      /**
       * Actively performs the binding from the ObjectModel wrapped in a jxpath
       * context to the Woody-form-widget specified in this object.
       */
      public void loadFormFromModel(Widget frmModel, JXPathContext jxpc) {
          try {
              Widget widget = frmModel.getWidget(this.fieldId);
              Object value = jxpc.getValue(this.xpath);
  
              if (convertor != null)
                  value = convertor.convertFromString((String)value, convertorLocale, null);
  
              widget.setValue(value);
  
              if (getLogger().isDebugEnabled())
                  getLogger().debug("done loading " + toString() + " -- value= " + value);
          } catch (Exception e) {
              getLogger().warn("JXPath failed to find value for " + this.xpath, e);
          }
      }
  
      /**
       * Actively performs the binding from the Woody-form to the ObjectModel
       * wrapped in a jxpath context
       */
      public void saveFormToModel(Widget frmModel, JXPathContext jxpc) throws BindingException {
          if (!this.readonly) {
              try {
                  Widget widget = frmModel.getWidget(this.fieldId);
                  Object value = widget.getValue();
                  if (value != null && convertor != null)
                      value = convertor.convertToString(value, convertorLocale, null);
                  Object oldValue = jxpc.getValue(this.xpath);
                  if (getLogger().isDebugEnabled())
                      getLogger().debug("value= " + value + "-- oldvalue=" + oldValue);
                  boolean update = false;
  
                  if ((value == null && oldValue != null) || value != null && !value.equals(oldValue)) {
                      // first update the value itself
                      jxpc.setValue(this.xpath, value);
  
                      // now perform any other bindings that need to be performed when the value is updated
                      JXPathContext subContext = null;
                      try {
                          subContext = jxpc.getRelativeContext(jxpc.getPointer(this.xpath));
                      } catch (JXPathException e) {
                          // if the value has been set to null and the underlying model is a bean, then
                          // JXPath will not be able to create a relative context
                          if (getLogger().isDebugEnabled())
                              getLogger().debug("(Ignorable) problem binding field " + widget.getFullyQualifiedId(), e);
                      }
                      if (subContext != null)
                          this.updateBinding.saveFormToModel(frmModel, subContext);
                      update = true;
                  }
                  if (getLogger().isDebugEnabled())
                      getLogger().debug("done saving " + toString() + " -- value= " + value + " -- on-update == " + update);
              } catch (Exception e) {
                  throw new BindingException("Problem binding field " + this.fieldId + " (parent = \"" + frmModel.getFullyQualifiedId() + "\") to xpath " + this.xpath + " (context xpath = \"" + jxpc.getContextPointer().asPath() + "\")", e);
              }
          }
      }
  
      public String toString() {
          return "FieldJXPathBinding [widget=" + this.fieldId + ", xpath=" + this.xpath + "]";
      }
  
      public void enableLogging(Logger logger) {
          super.enableLogging(logger);
          this.updateBinding.enableLogging(logger);
      }
  
  }
  
  
  
  1.1                  cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/binding/ValueJXPathBindingBuilder.java
  
  Index: ValueJXPathBindingBuilder.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.binding;
  
  import org.apache.cocoon.woody.util.DomHelper;
  import org.apache.cocoon.woody.Constants;
  import org.apache.cocoon.woody.datatype.convertor.Convertor;
  import org.apache.cocoon.i18n.I18nUtils;
  import org.w3c.dom.Element;
  
  import java.util.Locale;
  
  /**
   * ValueJXPathBindingBuilder provides a helper class for the Factory
   * implemented in {@link JXPathBindingManager} that helps construct the 
   * actual {@link ValueJXPathBinding} out of the configuration in the
   * provided configElement which looks like:
   * <pre><code>
   * &lt;wb:value id="<i>widget-id</i>" path="<i>xpath-expression</i>"&gt;
   *   &lt;!-- optional child binding to be executed upon 'save' of changed value --&gt;
   *   &lt;wb:on-update&gt;
   *     &lt;!-- any childbinding --&gt;
   *   &lt;/wb:on-update&gt;
   * &lt;/wb:value&gt;
   * </code></pre>
   */
  public class ValueJXPathBindingBuilder extends JXpathBindingBuilderBase {
  
  
      /**
       * Creates an instance of {@link ValueJXPathBinding} based on the attributes
       * and nested configuration of the provided bindingElm.
       */
      public JXPathBindingBase buildBinding(Element bindingElm, JXPathBindingManager.Assistant assistant) throws BindingException {
  
          try {
              boolean readonly = DomHelper.getAttributeAsBoolean(bindingElm, "readonly", false);
              String xpath = DomHelper.getAttribute(bindingElm, "path");
              String widgetId = DomHelper.getAttribute(bindingElm, "id");
  
              Element updateWrapElement =
                  DomHelper.getChildElement(bindingElm, BindingManager.NAMESPACE, "on-update");
              JXPathBindingBase[] updateBindings = assistant.makeChildBindings(updateWrapElement);
  
              Convertor convertor = null;
              Locale convertorLocale = Locale.US;
              Element convertorEl = DomHelper.getChildElement(bindingElm, Constants.WD_NS, "convertor");
              if (convertorEl != null) {
                  String datatype = DomHelper.getAttribute(convertorEl, "datatype");
                  String localeStr = convertorEl.getAttribute("datatype");
                  if (!localeStr.equals(""))
                      convertorLocale = I18nUtils.parseLocale(localeStr);
                  convertor = assistant.getDatatypeManager().createConvertor(datatype, convertorEl);
              }
  
              ValueJXPathBinding fieldBinding =
                      new ValueJXPathBinding(widgetId, xpath, readonly, updateBindings, convertor, convertorLocale);
  
              return fieldBinding;
          } catch (BindingException e) {
              throw e;
          } catch (Exception e) {
              throw new BindingException("Error building binding defined at " + DomHelper.getLocation(bindingElm), e);
          }
      }
  }
  
  
  
  1.1                  cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/datatype/convertor/PlainBooleanConvertor.java
  
  Index: PlainBooleanConvertor.java
  ===================================================================
  package org.apache.cocoon.woody.datatype.convertor;
  
  import java.util.Locale;
  
  /**
   * Convertor for java.lang.Boolean's.
   */
  public class PlainBooleanConvertor implements Convertor {
      public Object convertFromString(String value, Locale locale, Convertor.FormatCache formatCache) {
          return Boolean.valueOf(value);
      }
  
      public String convertToString(Object value, Locale locale, Convertor.FormatCache formatCache) {
          return value.toString();
      }
  
      public Class getTypeClass() {
          return Boolean.class;
      }
  }
  
  
  
  1.1                  cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/datatype/convertor/PlainBooleanConvertorBuilder.java
  
  Index: PlainBooleanConvertorBuilder.java
  ===================================================================
  package org.apache.cocoon.woody.datatype.convertor;
  
  import org.w3c.dom.Element;
  
  /**
   * Builds {PlainBooleanConvertor}s.
   */
  public class PlainBooleanConvertorBuilder implements ConvertorBuilder {
      public Convertor build(Element configElement) throws Exception {
          return new PlainBooleanConvertor();
      }
  }
  
  
  
  1.1                  cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/datatype/typeimpl/BooleanType.java
  
  Index: BooleanType.java
  ===================================================================
  package org.apache.cocoon.woody.datatype.typeimpl;
  
  /**
   * A {@link org.apache.cocoon.woody.datatype.Datatype Datatype} implementation for
   * java.lang.Boolean's.
   */
  public class BooleanType extends AbstractDatatype {
      public Class getTypeClass() {
          return Boolean.class;
      }
  
      public String getDescriptiveName() {
          return "boolean";
      }
  }
  
  
  
  1.1                  cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/datatype/typeimpl/BooleanTypeBuilder.java
  
  Index: BooleanTypeBuilder.java
  ===================================================================
  package org.apache.cocoon.woody.datatype.typeimpl;
  
  import org.apache.cocoon.woody.datatype.Datatype;
  import org.apache.cocoon.woody.datatype.DatatypeManager;
  import org.w3c.dom.Element;
  
  /**
   * Builds {@link BooleanType}s.
   */
  public class BooleanTypeBuilder extends AbstractDatatypeBuilder {
      public Datatype build(Element datatypeElement, boolean arrayType, DatatypeManager datatypeManager) throws Exception {
          BooleanType type = new BooleanType();
          type.setArrayType(arrayType);
          type.setBuilder(this);
  
          buildValidationRules(datatypeElement, type, datatypeManager);
          buildConvertor(datatypeElement, type);
  
          return type;
      }
  }
  
  
  
  1.1                  cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/formmodel/Output.java
  
  Index: Output.java
  ===================================================================
  package org.apache.cocoon.woody.formmodel;
  
  import org.apache.cocoon.woody.FormContext;
  import org.apache.cocoon.woody.Constants;
  import org.apache.cocoon.xml.AttributesImpl;
  import org.xml.sax.ContentHandler;
  import org.xml.sax.SAXException;
  
  import java.util.Locale;
  
  /**
   * An Output widget can be used to show a non-editable value to the user.
   * An Output widget is associated with a certain
   * {@link org.apache.cocoon.woody.datatype.Datatype Datatype}.
   *
   * <p>An Output widget is always valid and never required.
   */
  public class Output extends AbstractWidget {
      private OutputDefinition definition;
      private Object value;
  
      protected Output(OutputDefinition definition) {
          this.definition = definition;
      }
  
      public String getId() {
          return definition.getId();
      }
  
      public void readFromRequest(FormContext formContext) {
          // do nothing
      }
  
      public boolean validate(FormContext formContext) {
          return true;
      }
  
      private static final String OUTPUT_EL = "output";
      private static final String LABEL_EL = "label";
      private static final String VALUE_EL = "value";
  
      public void generateSaxFragment(ContentHandler contentHandler, Locale locale) throws SAXException {
          AttributesImpl outputAttrs = new AttributesImpl();
          outputAttrs.addCDATAAttribute("id", getFullyQualifiedId());
          contentHandler.startElement(Constants.WI_NS, OUTPUT_EL, Constants.WI_PREFIX_COLON + OUTPUT_EL, outputAttrs);
  
          // the value
          if (value != null) {
              contentHandler.startElement(Constants.WI_NS, VALUE_EL, Constants.WI_PREFIX_COLON + VALUE_EL, Constants.EMPTY_ATTRS);
              String stringValue;
              stringValue = definition.getDatatype().convertToString(value, locale);
              contentHandler.characters(stringValue.toCharArray(), 0, stringValue.length());
              contentHandler.endElement(Constants.WI_NS, VALUE_EL, Constants.WI_PREFIX_COLON + VALUE_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, OUTPUT_EL, Constants.WI_PREFIX_COLON + OUTPUT_EL);
      }
  
      public void generateLabel(ContentHandler contentHandler) throws SAXException {
          definition.generateLabel(contentHandler);
      }
  
      public Object getValue() {
          return value;
      }
  
      public void setValue(Object object) {
          if (object != null && !definition.getDatatype().getTypeClass().isAssignableFrom(object.getClass()))
              throw new RuntimeException("Tried to set value of output widget \"" + getFullyQualifiedId() + "\" with an object of an incorrect type.");
  
          value = object;
      }
  }
  
  
  
  1.1                  cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/formmodel/OutputDefinition.java
  
  Index: OutputDefinition.java
  ===================================================================
  package org.apache.cocoon.woody.formmodel;
  
  /**
   * The {@link WidgetDefinition} part of a {@link Output} widget.
   */
  public class OutputDefinition extends AbstractDatatypeWidgetDefinition {
      public Widget createInstance() {
          return new Output(this);
      }
  }
  
  
  
  1.1                  cocoon-2.1/src/blocks/woody/java/org/apache/cocoon/woody/formmodel/OutputDefinitionBuilder.java
  
  Index: OutputDefinitionBuilder.java
  ===================================================================
  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.Datatype;
  
  /**
   * Builds {@link OutputDefinition}s.
   */
  public class OutputDefinitionBuilder extends AbstractDatatypeWidgetDefinitionBuilder {
      public WidgetDefinition buildWidgetDefinition(Element widgetElement) throws Exception {
          OutputDefinition definition = new OutputDefinition();
          setId(widgetElement, definition);
  
          Element datatypeElement = DomHelper.getChildElement(widgetElement, Constants.WD_NS, "datatype");
          if (datatypeElement == null)
              throw new Exception("A nested datatype element is required for the widget specified at " + DomHelper.getLocation(widgetElement));
  
          Datatype datatype = datatypeManager.createDatatype(datatypeElement, false);
          definition.setDatatype(datatype);
  
          setLabel(widgetElement, definition);
  
          return definition;
      }
  }