KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > woody > validation > impl > ValidationRuleValidator


1 /*
2  * Copyright 1999-2004 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.woody.validation.impl;
17
18 import org.apache.cocoon.woody.FormContext;
19 import org.apache.cocoon.woody.datatype.ValidationRule;
20 import org.apache.cocoon.woody.formmodel.ExpressionContextImpl;
21 import org.apache.cocoon.woody.formmodel.Widget;
22 import org.apache.cocoon.woody.validation.ValidationError;
23 import org.apache.cocoon.woody.validation.ValidationErrorAware;
24 import org.apache.cocoon.woody.validation.WidgetValidator;
25
26 /**
27  * An adapter to transform a {@link org.apache.cocoon.woody.datatype.ValidationRule} into a
28  * {@link org.apache.cocoon.woody.validation.WidgetValidator}.
29  *
30  * @author <a HREF="http://www.apache.org/~sylvain/">Sylvain Wallez</a>
31  * @version CVS $Id: ValidationRuleValidator.java 30932 2004-07-29 17:35:38Z vgritsenko $
32  */

33 public class ValidationRuleValidator implements WidgetValidator {
34     
35     private ValidationRule rule;
36     
37     public ValidationRuleValidator(ValidationRule rule) {
38         this.rule = rule;
39     }
40
41     public boolean validate(Widget widget, FormContext context)
42     {
43         if (! (widget instanceof ValidationErrorAware)) {
44             // Invalid widget type
45
throw new IllegalArgumentException JavaDoc("Widget '" + widget.getFullyQualifiedId() + "' is not ValidationErrorAware");
46         }
47
48         Object JavaDoc value = widget.getValue();
49         if (value == null) {
50             // No value. Consider it as correct (required="true" will set an error if present)
51
return true;
52             
53         } else {
54             // Non-null value: perform validation
55
ValidationError error = this.rule.validate(value, new ExpressionContextImpl(widget));
56             if (error != null) {
57                 // Validation failed
58
((ValidationErrorAware)widget).setValidationError(error);
59                 return false;
60             } else {
61                 // Validation succeeded
62
return true;
63             }
64         }
65     }
66 }
67
Popular Tags