View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.validator;
18  
19  import static org.junit.jupiter.api.Assertions.assertEquals;
20  import static org.junit.jupiter.api.Assertions.assertFalse;
21  import static org.junit.jupiter.api.Assertions.assertNotNull;
22  import static org.junit.jupiter.api.Assertions.assertTrue;
23  import static org.junit.jupiter.api.Assertions.fail;
24  
25  import java.text.DateFormat;
26  import java.text.ParseException;
27  import java.util.ArrayList;
28  import java.util.Date;
29  import java.util.List;
30  import java.util.Locale;
31  
32  import org.apache.commons.validator.util.ValidatorUtils;
33  import org.junit.jupiter.api.Test;
34  
35  /**
36   * Performs Validation Test.
37   */
38  public class ValidatorTest {
39  
40      public static class TestBean {
41          private String letter;
42          private String date;
43  
44          public String getDate() {
45              return date;
46          }
47  
48          public String getLetter() {
49              return letter;
50          }
51  
52          public void setDate(final String date) {
53              this.date = date;
54          }
55  
56          public void setLetter(final String letter) {
57              this.letter = letter;
58          }
59      }
60  
61      /**
62       * Formats a <code>String</code> to a <code>Date</code>. The <code>Validator</code> will interpret a <code>null</code> as validation having failed.
63       */
64      public static Date formatDate(final Object bean, final Field field) {
65          final String value = ValidatorUtils.getValueAsString(bean, field.getProperty());
66          Date date = null;
67  
68          try {
69              final DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
70  
71              formatter.setLenient(false);
72  
73              date = formatter.parse(value);
74          } catch (final ParseException e) {
75              System.out.println("ValidatorTest.formatDate() - " + e.getMessage());
76          }
77  
78          return date;
79      }
80  
81      /**
82       * Checks if the field is one upper case letter between 'A' and 'Z'.
83       */
84      public static boolean isCapLetter(final Object bean, final Field field, final List<String> l) {
85          final String value = ValidatorUtils.getValueAsString(bean, field.getProperty());
86  
87          if (value == null || value.length() != 1) {
88              l.add("Error");
89              return false;
90          }
91          if (value.charAt(0) >= 'A' && value.charAt(0) <= 'Z') {
92              return true;
93          }
94          l.add("Error");
95          return false;
96      }
97  
98      private ValidatorResources setupDateResources(final String property, final String action) {
99  
100         final ValidatorResources resources = new ValidatorResources();
101 
102         final ValidatorAction va = new ValidatorAction();
103         va.setName(action);
104         va.setClassname("org.apache.commons.validator.ValidatorTest");
105         va.setMethod("formatDate");
106         va.setMethodParams("java.lang.Object,org.apache.commons.validator.Field");
107 
108         final FormSet fs = new FormSet();
109         final Form form = new Form();
110         form.setName("testForm");
111         final Field field = new Field();
112         field.setProperty(property);
113         field.setDepends(action);
114         form.addField(field);
115         fs.addForm(form);
116 
117         resources.addValidatorAction(va);
118         resources.addFormSet(fs);
119         resources.process();
120 
121         return resources;
122     }
123 
124     /**
125      * Verify that one value generates an error and the other passes. The validation method being tested returns a <code>boolean</code> value.
126      */
127     @Test
128     public void testManualBoolean() {
129         final ValidatorResources resources = new ValidatorResources();
130 
131         final ValidatorAction va = new ValidatorAction();
132         va.setName("capLetter");
133         va.setClassName("org.apache.commons.validator.ValidatorTest");
134         va.setMethod("isCapLetter");
135         va.setMethodParams("java.lang.Object,org.apache.commons.validator.Field,java.util.List");
136 
137         final FormSet fs = new FormSet();
138         final Form form = new Form();
139         form.setName("testForm");
140         final Field field = new Field();
141         field.setProperty("letter");
142         field.setDepends("capLetter");
143         form.addField(field);
144         fs.addForm(form);
145 
146         resources.addValidatorAction(va);
147         resources.addFormSet(fs);
148         resources.process();
149 
150         final List<?> l = new ArrayList<>();
151 
152         final TestBean bean = new TestBean();
153         bean.setLetter("A");
154 
155         final Validator validator = new Validator(resources, "testForm");
156         validator.setParameter(Validator.BEAN_PARAM, bean);
157         validator.setParameter("java.util.List", l);
158 
159         try {
160             validator.validate();
161         } catch (final Exception e) {
162             fail("An exception was thrown while calling Validator.validate()");
163         }
164 
165         assertEquals(0, l.size(), "Validation of the letter 'A'.");
166 
167         l.clear();
168         bean.setLetter("AA");
169 
170         try {
171             validator.validate();
172         } catch (final Exception e) {
173             fail("An exception was thrown while calling Validator.validate()");
174         }
175 
176         assertEquals(1, l.size(), "Validation of the letter 'AA'.");
177     }
178 
179     /**
180      * Verify that one value generates an error and the other passes. The validation method being tested returns a <code>boolean</code> value.
181      */
182     @Test
183     public void testManualBooleanDeprecated() {
184         final ValidatorResources resources = new ValidatorResources();
185 
186         final ValidatorAction va = new ValidatorAction();
187         va.setName("capLetter");
188         va.setClassname("org.apache.commons.validator.ValidatorTest");
189         va.setMethod("isCapLetter");
190         va.setMethodParams("java.lang.Object,org.apache.commons.validator.Field,java.util.List");
191 
192         final FormSet fs = new FormSet();
193         final Form form = new Form();
194         form.setName("testForm");
195         final Field field = new Field();
196         field.setProperty("letter");
197         field.setDepends("capLetter");
198         form.addField(field);
199         fs.addForm(form);
200 
201         resources.addValidatorAction(va);
202         resources.addFormSet(fs);
203         resources.process();
204 
205         final List<?> l = new ArrayList<>();
206 
207         final TestBean bean = new TestBean();
208         bean.setLetter("A");
209 
210         final Validator validator = new Validator(resources, "testForm");
211         validator.setParameter(Validator.BEAN_PARAM, bean);
212         validator.setParameter("java.util.List", l);
213 
214         try {
215             validator.validate();
216         } catch (final Exception e) {
217             fail("An exception was thrown while calling Validator.validate()");
218         }
219 
220         assertEquals(0, l.size(), "Validation of the letter 'A'.");
221 
222         l.clear();
223         bean.setLetter("AA");
224 
225         try {
226             validator.validate();
227         } catch (final Exception e) {
228             fail("An exception was thrown while calling Validator.validate()");
229         }
230 
231         assertEquals(1, l.size(), "Validation of the letter 'AA'.");
232     }
233 
234     /**
235      * Verify that one value generates an error and the other passes. The validation method being tested returns an object (<code>null</code> will be considered
236      * an error).
237      */
238     @Test
239     public void testManualObject() {
240         // property name of the method we are validating
241         final String property = "date";
242         // name of ValidatorAction
243         final String action = "date";
244         final ValidatorResources resources = setupDateResources(property, action);
245 
246         final TestBean bean = new TestBean();
247         bean.setDate("2/3/1999");
248 
249         final Validator validator = new Validator(resources, "testForm");
250         validator.setParameter(Validator.BEAN_PARAM, bean);
251 
252         try {
253             final ValidatorResults results = validator.validate();
254 
255             assertNotNull(results, "Results are null.");
256 
257             final ValidatorResult result = results.getValidatorResult(property);
258 
259             assertNotNull(results, "Results are null.");
260 
261             assertTrue(result.containsAction(action), "ValidatorResult does not contain '" + action + "' validator result.");
262 
263             assertTrue(result.isValid(action), "Validation of the date formatting has failed.");
264         } catch (final Exception e) {
265             fail("An exception was thrown while calling Validator.validate()");
266         }
267 
268         bean.setDate("2/30/1999");
269 
270         try {
271             final ValidatorResults results = validator.validate();
272 
273             assertNotNull(results, "Results are null.");
274 
275             final ValidatorResult result = results.getValidatorResult(property);
276 
277             assertNotNull(results, "Results are null.");
278 
279             assertTrue(result.containsAction(action), "ValidatorResult does not contain '" + action + "' validator result.");
280 
281             assertTrue(!result.isValid(action), "Validation of the date formatting has passed when it should have failed.");
282         } catch (final Exception e) {
283             fail("An exception was thrown while calling Validator.validate()");
284         }
285 
286     }
287 
288     @Test
289     public void testOnlyReturnErrors() throws ValidatorException {
290         // property name of the method we are validating
291         final String property = "date";
292         // name of ValidatorAction
293         final String action = "date";
294         final ValidatorResources resources = setupDateResources(property, action);
295 
296         final TestBean bean = new TestBean();
297         bean.setDate("2/3/1999");
298 
299         final Validator validator = new Validator(resources, "testForm");
300         validator.setParameter(Validator.BEAN_PARAM, bean);
301 
302         ValidatorResults results = validator.validate();
303 
304         assertNotNull(results);
305 
306         // Field passed and should be in results
307         assertTrue(results.getPropertyNames().contains(property));
308 
309         // Field passed but should not be in results
310         validator.setOnlyReturnErrors(true);
311         results = validator.validate();
312         assertFalse(results.getPropertyNames().contains(property));
313     }
314 
315     @Test
316     public void testOnlyValidateField() throws ValidatorException {
317         // property name of the method we are validating
318         final String property = "date";
319         // name of ValidatorAction
320         final String action = "date";
321         final ValidatorResources resources = setupDateResources(property, action);
322 
323         final TestBean bean = new TestBean();
324         bean.setDate("2/3/1999");
325 
326         final Validator validator = new Validator(resources, "testForm", property);
327         validator.setParameter(Validator.BEAN_PARAM, bean);
328 
329         final ValidatorResults results = validator.validate();
330 
331         assertNotNull(results);
332 
333         // Field passed and should be in results
334         assertTrue(results.getPropertyNames().contains(property));
335     }
336 
337 }