View Javadoc

1   /*
2    * $Id: ValidWhen.java 421119 2006-07-12 04:49:11Z wsmoak $
3    *
4    * Copyright 2003-2005 The Apache Software Foundation.
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *      http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.struts.validator.validwhen;
19  
20  import org.apache.commons.logging.Log;
21  import org.apache.commons.logging.LogFactory;
22  import org.apache.commons.validator.Field;
23  import org.apache.commons.validator.Validator;
24  import org.apache.commons.validator.ValidatorAction;
25  import org.apache.commons.validator.util.ValidatorUtils;
26  import org.apache.struts.action.ActionMessage;
27  import org.apache.struts.action.ActionMessages;
28  import org.apache.struts.util.MessageResources;
29  import org.apache.struts.validator.Resources;
30  
31  import javax.servlet.http.HttpServletRequest;
32  
33  import java.io.StringReader;
34  
35  /***
36   * This class contains the validwhen validation that is used in the
37   * validator-rules.xml file.
38   *
39   * @since Struts 1.2
40   */
41  public class ValidWhen {
42      /***
43       * Commons Logging instance.
44       */
45      private static final Log log = LogFactory.getLog(ValidWhen.class);
46  
47      /***
48       * The message resources for this package.
49       */
50      private static MessageResources sysmsgs =
51          MessageResources.getMessageResources(
52              "org.apache.struts.validator.LocalStrings");
53  
54      /***
55       * Returns true if <code>obj</code> is null or a String.
56       */
57      private static boolean isString(Object obj) {
58          return (obj == null) ? true : String.class.isInstance(obj);
59      }
60  
61      /***
62       * Checks if the field matches the boolean expression specified in
63       * <code>test</code> parameter.
64       *
65       * @param bean    The bean validation is being performed on.
66       * @param va      The <code>ValidatorAction</code> that is currently being
67       *                performed.
68       * @param field   The <code>Field</code> object associated with the
69       *                current field being validated.
70       * @param errors  The <code>ActionMessages</code> object to add errors to
71       *                if any validation errors occur.
72       * @param request Current request object.
73       * @return <code>true</code> if meets stated requirements,
74       *         <code>false</code> otherwise.
75       */
76      public static boolean validateValidWhen(Object bean, ValidatorAction va,
77          Field field, ActionMessages errors, Validator validator,
78          HttpServletRequest request) {
79          Object form = validator.getParameterValue(Validator.BEAN_PARAM);
80          String value = null;
81          boolean valid = false;
82          int index = -1;
83  
84          if (field.isIndexed()) {
85              String key = field.getKey();
86  
87              final int leftBracket = key.indexOf("[");
88              final int rightBracket = key.indexOf("]");
89  
90              if ((leftBracket > -1) && (rightBracket > -1)) {
91                  index =
92                      Integer.parseInt(key.substring(leftBracket + 1,
93                          rightBracket));
94              }
95          }
96  
97          if (isString(bean)) {
98              value = (String) bean;
99          } else {
100             value = ValidatorUtils.getValueAsString(bean, field.getProperty());
101         }
102 
103         String test = null;
104 
105         try {
106             test =
107                 Resources.getVarValue("test", field, validator, request, true);
108         } catch (IllegalArgumentException ex) {
109             String logErrorMsg =
110                 sysmsgs.getMessage("validation.failed", "validwhen",
111                     field.getProperty(), ex.toString());
112 
113             log.error(logErrorMsg);
114 
115             String userErrorMsg = sysmsgs.getMessage("system.error");
116 
117             errors.add(field.getKey(), new ActionMessage(userErrorMsg, false));
118 
119             return false;
120         }
121 
122         // Create the Lexer
123         ValidWhenLexer lexer = null;
124 
125         try {
126             lexer = new ValidWhenLexer(new StringReader(test));
127         } catch (Exception ex) {
128             String logErrorMsg =
129                 "ValidWhenLexer Error for field ' " + field.getKey() + "' - "
130                 + ex;
131 
132             log.error(logErrorMsg);
133 
134             String userErrorMsg = sysmsgs.getMessage("system.error");
135 
136             errors.add(field.getKey(), new ActionMessage(userErrorMsg, false));
137 
138             return false;
139         }
140 
141         // Create the Parser
142         ValidWhenParser parser = null;
143 
144         try {
145             parser = new ValidWhenParser(lexer);
146         } catch (Exception ex) {
147             String logErrorMsg =
148                 "ValidWhenParser Error for field ' " + field.getKey() + "' - "
149                 + ex;
150 
151             log.error(logErrorMsg);
152 
153             String userErrorMsg = sysmsgs.getMessage("system.error");
154 
155             errors.add(field.getKey(), new ActionMessage(userErrorMsg, false));
156 
157             return false;
158         }
159 
160         parser.setForm(form);
161         parser.setIndex(index);
162         parser.setValue(value);
163 
164         try {
165             parser.expression();
166             valid = parser.getResult();
167         } catch (Exception ex) {
168             String logErrorMsg =
169                 "ValidWhen Error for field ' " + field.getKey() + "' - " + ex;
170 
171             log.error(logErrorMsg);
172 
173             String userErrorMsg = sysmsgs.getMessage("system.error");
174 
175             errors.add(field.getKey(), new ActionMessage(userErrorMsg, false));
176 
177             return false;
178         }
179 
180         if (!valid) {
181             errors.add(field.getKey(),
182                 Resources.getActionMessage(validator, request, va, field));
183 
184             return false;
185         }
186 
187         return true;
188     }
189 }