KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > forms > formmodel > BooleanField


1 /*
2  * Copyright 1999-2005 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.cocoon.forms.formmodel;
17
18 import java.util.Locale JavaDoc;
19
20 import org.apache.cocoon.forms.FormsConstants;
21 import org.apache.cocoon.forms.FormContext;
22 import org.apache.cocoon.forms.event.*;
23 import org.apache.cocoon.xml.AttributesImpl;
24 import org.apache.cocoon.xml.XMLUtils;
25 import org.xml.sax.ContentHandler JavaDoc;
26 import org.xml.sax.SAXException JavaDoc;
27 import org.apache.cocoon.forms.validation.ValidationErrorAware;
28 import org.apache.cocoon.forms.validation.ValidationError;
29 import org.apache.commons.lang.BooleanUtils;
30
31 /**
32  * A widget to select a boolean value. Usually rendered as a checkbox.
33  *
34  * <p>You may wonder why we don't use a {@link Field} widget with an associated
35  * Boolean Datatype instead. The reason is that many of the features of the Field
36  * widget are overkill for a Boolean: validation is unnecessary (if the field is
37  * not true it is false), the selectionlist associated with a Datatype also
38  * has no purpose here (there would always be only 2 choices: true or false),
39  * and the manner in which the request parameter of this widget is interpreted
40  * is different (missing or empty request parameter means 'false', rather than null value).
41  *
42  * @version $Id: BooleanField.java 328140 2005-10-24 19:22:55Z sylvain $
43  */

44 public class BooleanField extends AbstractWidget
45                           implements ValidationErrorAware, ValueChangedListenerEnabled {
46
47     private static final String JavaDoc BOOLEAN_FIELD_EL = "booleanfield";
48     private static final String JavaDoc VALUE_EL = "value";
49     private static final String JavaDoc VALIDATION_MSG_EL = "validation-message";
50
51     // FIXME(SW) : should the initial value be false or null ? This would allow
52
// event listeners to be triggered at bind time.
53
private Boolean JavaDoc value = Boolean.FALSE;
54     private final BooleanFieldDefinition definition;
55     /** Additional listeners to those defined as part of the widget definition (if any). */
56     private ValueChangedListener listener;
57     protected ValidationError validationError;
58
59
60     public BooleanField(BooleanFieldDefinition definition) {
61         super(definition);
62         this.definition = definition;
63         this.listener = definition.getValueChangedListener();
64     }
65
66     public WidgetDefinition getDefinition() {
67         return this.definition;
68     }
69
70     public void initialize() {
71         Boolean JavaDoc value = this.definition.getInitialValue();
72         if (value != null) {
73             setValue(value);
74         }
75         super.initialize();
76     }
77
78     public void readFromRequest(FormContext formContext) {
79         if (!getCombinedState().isAcceptingInputs()) {
80             return;
81         }
82
83         validationError = null;
84         Object JavaDoc oldValue = value;
85         String JavaDoc param = formContext.getRequest().getParameter(getRequestParameterName());
86
87         value = BooleanUtils.toBooleanObject(definition.getTrueParamValue().equals(param));
88
89         if (!value.equals(oldValue)) {
90             getForm().addWidgetEvent(new ValueChangedEvent(this, oldValue, value));
91         }
92     }
93
94     /**
95      * Returns the validation error, if any. There will always be a validation error in case the
96      * {@link #validate()} method returned false.
97      */

98     public ValidationError getValidationError() {
99         return validationError;
100     }
101
102     /**
103      * Set a validation error on this field. This allows fields to be externally marked as invalid by
104      * application logic.
105      *
106      * @param error the validation error
107      */

108     public void setValidationError(ValidationError error) {
109         this.validationError = error;
110         getForm().addWidgetUpdate(this);
111     }
112
113     /**
114      * @return "booleanfield"
115      */

116     public String JavaDoc getXMLElementName() {
117         return BOOLEAN_FIELD_EL;
118     }
119
120     protected AttributesImpl getXMLElementAttributes() {
121         AttributesImpl attrs = super.getXMLElementAttributes();
122         // Add the parameter value for true
123
attrs.addCDATAAttribute("true-value", definition.getTrueParamValue());
124         return attrs;
125     }
126
127     public void generateItemSaxFragment(ContentHandler JavaDoc contentHandler, Locale JavaDoc locale) throws SAXException JavaDoc {
128         // value element
129
contentHandler.startElement(FormsConstants.INSTANCE_NS, VALUE_EL, FormsConstants.INSTANCE_PREFIX_COLON + VALUE_EL, XMLUtils.EMPTY_ATTRIBUTES);
130
131         String JavaDoc stringValue = BooleanUtils.toBoolean(value) ? definition.getTrueParamValue() : "false";
132
133         contentHandler.characters(stringValue.toCharArray(), 0, stringValue.length());
134         contentHandler.endElement(FormsConstants.INSTANCE_NS, VALUE_EL, FormsConstants.INSTANCE_PREFIX_COLON + VALUE_EL);
135         // validation message element: only present if the value is not valid
136
if (validationError != null) {
137             contentHandler.startElement(FormsConstants.INSTANCE_NS, VALIDATION_MSG_EL, FormsConstants.INSTANCE_PREFIX_COLON + VALIDATION_MSG_EL, XMLUtils.EMPTY_ATTRIBUTES);
138             validationError.generateSaxFragment(contentHandler);
139             contentHandler.endElement(FormsConstants.INSTANCE_NS, VALIDATION_MSG_EL, FormsConstants.INSTANCE_PREFIX_COLON + VALIDATION_MSG_EL);
140         }
141     }
142
143     public Object JavaDoc getValue() {
144         return value;
145     }
146
147     /**
148      * Sets value of the field. If value is null, it is considered to be false
149      * (see class comment).
150      */

151     public void setValue(Object JavaDoc object) {
152         if (object == null) {
153             object = Boolean.FALSE;
154         }
155
156         if (!(object instanceof Boolean JavaDoc)) {
157             throw new RuntimeException JavaDoc("Cannot set value of boolean field \"" + getRequestParameterName() + "\" to a non-Boolean value.");
158         }
159
160         Object JavaDoc oldValue = value;
161         value = (Boolean JavaDoc)object;
162         if (!value.equals(oldValue)) {
163             Form form = getForm();
164             if (hasValueChangedListeners() || this.getForm().hasFormHandler()) {
165                 form.addWidgetEvent(new ValueChangedEvent(this, oldValue, value));
166             }
167             form.addWidgetUpdate(this);
168         }
169     }
170
171     /**
172      * Adds a ValueChangedListener to this widget instance. Listeners defined
173      * on the widget instance will be executed in addtion to any listeners
174      * that might have been defined in the widget definition.
175      */

176     public void addValueChangedListener(ValueChangedListener listener) {
177         this.listener = WidgetEventMulticaster.add(this.listener, listener);
178     }
179
180     public void removeValueChangedListener(ValueChangedListener listener) {
181         this.listener = WidgetEventMulticaster.remove(this.listener, listener);
182     }
183     
184     public boolean hasValueChangedListeners() {
185         return this.listener != null;
186     }
187
188     public void broadcastEvent(WidgetEvent event) {
189         if (event instanceof ValueChangedEvent) {
190             if (this.listener != null) {
191                 this.listener.valueChanged((ValueChangedEvent)event);
192             }
193         } else {
194             // Other kinds of events
195
super.broadcastEvent(event);
196         }
197     }
198 }
199
Popular Tags