1 package org.nuiton.validator.xwork2.field;
2
3 /*
4 * #%L
5 * Nuiton Validator
6 * %%
7 * Copyright (C) 2013 - 2014 Code Lutin, Tony Chemit
8 * %%
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Lesser General Public License as
11 * published by the Free Software Foundation, either version 3 of the
12 * License, or (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Lesser Public License for more details.
18 *
19 * You should have received a copy of the GNU General Lesser Public
20 * License along with this program. If not, see
21 * <http://www.gnu.org/licenses/lgpl-3.0.html>.
22 * #L%
23 */
24
25 import com.opensymphony.xwork2.validator.ValidationException;
26 import org.apache.commons.lang3.StringUtils;
27
28 import java.lang.reflect.Array;
29 import java.util.Collection;
30 import java.util.regex.Matcher;
31 import java.util.regex.Pattern;
32
33 /**
34 * @author Sylvain Bavencoff - bavencoff@codelutin.com
35 */
36 public class FrenchFinessFieldValidator extends NuitonFieldValidatorSupport {
37
38 protected static final String FINESS_REGEXP = "(0[1-9]|[1-9][0-9]|2A|2B)0([0-9]{6})";
39
40 protected static final Pattern p = Pattern.compile(FINESS_REGEXP);
41
42 @Override
43 protected void validateWhenNotSkip(Object object) throws ValidationException {
44 String fieldName = getFieldName();
45 Object value = getFieldValue(fieldName, object);
46
47 if (value == null) {
48 // no value defined
49 return;
50 }
51 String finess;
52
53 if (value.getClass().isArray()) {
54 // le finess est stocker dans un tableau, par exemple un byte[]
55 finess = "";
56 for (int i = 0; i < Array.getLength(value); i++) {
57 finess += String.valueOf(Array.get(value, i));
58 }
59 } else if (value instanceof Collection<?>) {
60 // le finess est stocker dans une collection,
61 // ca doit pas arriver souvent :D, mais autant le gerer
62 finess = "";
63 for (Object o : (Collection<?>) value) {
64 finess += String.valueOf(o);
65 }
66 } else {
67 // sinon dans tous les autres cas (String, int, long, BigInteger ...)
68 // on prend le toString
69 finess = String.valueOf(value);
70 }
71
72 if (StringUtils.isEmpty(finess)) {
73 // no value defined
74 return;
75 }
76
77 // Remove any space
78 finess = finess.replaceAll(" ", "");
79
80 Matcher m = p.matcher(finess);
81 if (!m.matches() || !FieldValidatorUtil.luhnChecksum(finess)) {
82 addFieldError(fieldName, object);
83 }
84 }
85
86 @Override
87 public String getValidatorType() {
88 return "frenchFiness";
89 }
90 }