index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/commons-validator/src/test/java/org/apache/commons | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/ByteTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
/**
* Performs Validation Test for <code>byte</code> validations.
*/
public class ByteTest extends AbstractNumberTest {
public ByteTest(final String name) {
super(name);
ACTION = "byte";
FORM_KEY = "byteForm";
}
/**
* Tests the byte validation.
*/
public void testByte() throws ValidatorException {
// Create bean to run test on.
final ValueBean info = new ValueBean();
info.setValue("0");
valueTest(info, true);
}
/**
* Tests the byte validation.
*/
public void testByteMin() throws ValidatorException {
// Create bean to run test on.
final ValueBean info = new ValueBean();
info.setValue(Byte.toString(Byte.MIN_VALUE));
valueTest(info, true);
}
/**
* Tests the byte validation.
*/
public void testByteMax() throws ValidatorException {
// Create bean to run test on.
final ValueBean info = new ValueBean();
info.setValue(Byte.toString(Byte.MAX_VALUE));
valueTest(info, true);
}
/**
* Tests the byte validation failure.
*/
public void testByteFailure() throws ValidatorException {
// Create bean to run test on.
final ValueBean info = new ValueBean();
valueTest(info, false);
}
/**
* Tests the byte validation failure.
*/
public void testByteBeyondMin() throws ValidatorException {
// Create bean to run test on.
final ValueBean info = new ValueBean();
info.setValue(Byte.MIN_VALUE + "1");
valueTest(info, false);
}
/**
* Tests the byte validation failure.
*/
public void testByteBeyondMax() throws ValidatorException {
// Create bean to run test on.
final ValueBean info = new ValueBean();
info.setValue(Byte.MAX_VALUE + "1");
valueTest(info, false);
}
} | 7,900 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/UrlTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import junit.framework.TestCase;
/**
* Performs Validation Test for url validations.
*
* @deprecated to be removed when org.apache.commons.validator.UrlValidator is removed
*/
@Deprecated
public class UrlTest extends TestCase {
private final boolean printStatus = false;
private final boolean printIndex = false;//print index that indicates current scheme,host,port,path, query test were using.
public UrlTest(final String testName) {
super(testName);
}
@Override
protected void setUp() {
for (int index = 0; index < testPartsIndex.length - 1; index++) {
testPartsIndex[index] = 0;
}
}
public void testIsValid() {
testIsValid(testUrlParts, UrlValidator.ALLOW_ALL_SCHEMES);
setUp();
final int options =
UrlValidator.ALLOW_2_SLASHES
+ UrlValidator.ALLOW_ALL_SCHEMES
+ UrlValidator.NO_FRAGMENTS;
testIsValid(testUrlPartsOptions, options);
}
public void testIsValidScheme() {
if (printStatus) {
System.out.print("\n testIsValidScheme() ");
}
final String[] schemes = {"http", "gopher"};
//UrlValidator urlVal = new UrlValidator(schemes,false,false,false);
final UrlValidator urlVal = new UrlValidator(schemes, 0);
for (final ResultPair testPair : testScheme) {
final boolean result = urlVal.isValidScheme(testPair.item);
assertEquals(testPair.item, testPair.valid, result);
if (printStatus) {
if (result == testPair.valid) {
System.out.print('.');
} else {
System.out.print('X');
}
}
}
if (printStatus) {
System.out.println();
}
}
/**
* Create set of tests by taking the testUrlXXX arrays and
* running through all possible permutations of their combinations.
*
* @param testObjects Used to create a url.
*/
public void testIsValid(final Object[] testObjects, final int options) {
final UrlValidator urlVal = new UrlValidator(null, options);
assertTrue(urlVal.isValid("http://www.google.com"));
assertTrue(urlVal.isValid("http://www.google.com/"));
int statusPerLine = 60;
int printed = 0;
if (printIndex) {
statusPerLine = 6;
}
do {
final StringBuilder testBuffer = new StringBuilder();
boolean expected = true;
for (int testPartsIndexIndex = 0; testPartsIndexIndex < testPartsIndex.length; ++testPartsIndexIndex) {
final int index = testPartsIndex[testPartsIndexIndex];
final ResultPair[] part = (ResultPair[]) testObjects[testPartsIndexIndex];
testBuffer.append(part[index].item);
expected &= part[index].valid;
}
final String url = testBuffer.toString();
final boolean result = urlVal.isValid(url);
assertEquals(url, expected, result);
if (printStatus) {
if (printIndex) {
System.out.print(testPartsIndextoString());
} else if (result == expected) {
System.out.print('.');
} else {
System.out.print('X');
}
printed++;
if (printed == statusPerLine) {
System.out.println();
printed = 0;
}
}
} while (incrementTestPartsIndex(testPartsIndex, testObjects));
if (printStatus) {
System.out.println();
}
}
public void testValidator202() {
final String[] schemes = {"http","https"};
final UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.NO_FRAGMENTS);
urlValidator.isValid("http://www.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.log");
}
public void testValidator204() {
final String[] schemes = {"http","https"};
final UrlValidator urlValidator = new UrlValidator(schemes);
assertTrue(urlValidator.isValid("http://tech.yahoo.com/rc/desktops/102;_ylt=Ao8yevQHlZ4On0O3ZJGXLEQFLZA5"));
}
static boolean incrementTestPartsIndex(final int[] testPartsIndex, final Object[] testParts) {
boolean carry = true; //add 1 to lowest order part.
boolean maxIndex = true;
for (int testPartsIndexIndex = testPartsIndex.length - 1; testPartsIndexIndex >= 0; --testPartsIndexIndex) {
int index = testPartsIndex[testPartsIndexIndex];
final ResultPair[] part = (ResultPair[]) testParts[testPartsIndexIndex];
if (carry) {
if (index < part.length - 1) {
index++;
testPartsIndex[testPartsIndexIndex] = index;
carry = false;
} else {
testPartsIndex[testPartsIndexIndex] = 0;
carry = true;
}
}
maxIndex &= index == part.length - 1;
}
return !maxIndex;
}
private String testPartsIndextoString() {
final StringBuilder carryMsg = new StringBuilder("{");
for (int testPartsIndexIndex = 0; testPartsIndexIndex < testPartsIndex.length; ++testPartsIndexIndex) {
carryMsg.append(testPartsIndex[testPartsIndexIndex]);
if (testPartsIndexIndex < testPartsIndex.length - 1) {
carryMsg.append(',');
} else {
carryMsg.append('}');
}
}
return carryMsg.toString();
}
public void testValidateUrl() {
assertTrue(true);
}
/**
* Only used to debug the unit tests.
* @param argv
*/
public static void main(final String[] argv) {
final UrlTest fct = new UrlTest("url test");
fct.setUp();
fct.testIsValid();
fct.testIsValidScheme();
}
//-------------------- Test data for creating a composite URL
/**
* The data given below approximates the 4 parts of a URL
* <scheme>://<authority><path>?<query> except that the port number
* is broken out of authority to increase the number of permutations.
* A complete URL is composed of a scheme+authority+port+path+query,
* all of which must be individually valid for the entire URL to be considered
* valid.
*/
ResultPair[] testUrlScheme = {new ResultPair("http://", true),
new ResultPair("ftp://", true),
new ResultPair("h3t://", true),
new ResultPair("3ht://", false),
new ResultPair("http:/", false),
new ResultPair("http:", false),
new ResultPair("http/", false),
new ResultPair("://", false),
new ResultPair("", true)};
ResultPair[] testUrlAuthority = {new ResultPair("www.google.com", true),
new ResultPair("go.com", true),
new ResultPair("go.au", true),
new ResultPair("0.0.0.0", true),
new ResultPair("255.255.255.255", true),
new ResultPair("256.256.256.256", false),
new ResultPair("255.com", true),
new ResultPair("1.2.3.4.5", false),
new ResultPair("1.2.3.4.", false),
new ResultPair("1.2.3", false),
new ResultPair(".1.2.3.4", false),
new ResultPair("go.a", false),
new ResultPair("go.a1a", true),
new ResultPair("go.1aa", false),
new ResultPair("aaa.", false),
new ResultPair(".aaa", false),
new ResultPair("aaa", false),
new ResultPair("", false)
};
ResultPair[] testUrlPort = {new ResultPair(":80", true),
new ResultPair(":65535", true),
new ResultPair(":0", true),
new ResultPair("", true),
new ResultPair(":-1", false),
new ResultPair(":65636", true),
new ResultPair(":65a", false)
};
ResultPair[] testPath = {new ResultPair("/test1", true),
new ResultPair("/t123", true),
new ResultPair("/$23", true),
new ResultPair("/..", false),
new ResultPair("/../", false),
new ResultPair("/test1/", true),
new ResultPair("", true),
new ResultPair("/test1/file", true),
new ResultPair("/..//file", false),
new ResultPair("/test1//file", false)
};
//Test allow2slash, noFragment
ResultPair[] testUrlPathOptions = {new ResultPair("/test1", true),
new ResultPair("/t123", true),
new ResultPair("/$23", true),
new ResultPair("/..", false),
new ResultPair("/../", false),
new ResultPair("/test1/", true),
new ResultPair("/#", false),
new ResultPair("", true),
new ResultPair("/test1/file", true),
new ResultPair("/t123/file", true),
new ResultPair("/$23/file", true),
new ResultPair("/../file", false),
new ResultPair("/..//file", false),
new ResultPair("/test1//file", true),
new ResultPair("/#/file", false)
};
ResultPair[] testUrlQuery = {new ResultPair("?action=view", true),
new ResultPair("?action=edit&mode=up", true),
new ResultPair("", true)
};
Object[] testUrlParts = {testUrlScheme, testUrlAuthority, testUrlPort, testPath, testUrlQuery};
Object[] testUrlPartsOptions = {testUrlScheme, testUrlAuthority, testUrlPort, testUrlPathOptions, testUrlQuery};
int[] testPartsIndex = {0, 0, 0, 0, 0};
//---------------- Test data for individual url parts ----------------
ResultPair[] testScheme = {new ResultPair("http", true),
new ResultPair("ftp", false),
new ResultPair("httpd", false),
new ResultPair("telnet", false)};
}
| 7,901 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/FieldTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import junit.framework.TestCase;
/**
* Test <code>Field</code> objects.
*/
public class FieldTest extends TestCase {
protected Field field;
/**
* FieldTest constructor.
*/
public FieldTest() {
}
/**
* FieldTest constructor.
* @param name
*/
public FieldTest(final String name) {
super(name);
}
/**
* Test setup
*/
@Override
public void setUp() {
field = new Field();
}
/**
* Test clean up
*/
@Override
public void tearDown() {
field = null;
}
/**
* test Field with no arguments
*/
public void testEmptyArgs() {
assertEquals("Empty Args(1) ", 0, field.getArgs("required").length);
}
/**
* test Field with only 'default' arguments, no positions specified.
*/
public void testDefaultPositionImplied() {
field.addArg(createArg("default-position-0"));
field.addArg(createArg("default-position-1"));
field.addArg(createArg("default-position-2"));
assertEquals("testDefaultPositionImplied(1) ", 3, field.getArgs("required").length);
assertEquals("testDefaultPositionImplied(2) ", "default-position-0", field.getArg("required", 0).getKey());
assertEquals("testDefaultPositionImplied(3) ", "default-position-1", field.getArg("required", 1).getKey());
assertEquals("testDefaultPositionImplied(4) ", "default-position-2", field.getArg("required", 2).getKey());
}
/**
* test Field with only 'default' arguments, positions specified.
*/
public void testDefaultUsingPositions() {
field.addArg(createArg("default-position-1", 1));
field.addArg(createArg("default-position-0", 0));
field.addArg(createArg("default-position-2", 2));
assertEquals("testDefaultUsingPositions(1) ", 3, field.getArgs("required").length);
assertEquals("testDefaultUsingPositions(2) ", "default-position-0", field.getArg("required", 0).getKey());
assertEquals("testDefaultUsingPositions(3) ", "default-position-1", field.getArg("required", 1).getKey());
assertEquals("testDefaultUsingPositions(4) ", "default-position-2", field.getArg("required", 2).getKey());
}
/**
* test Field with only 'default' arguments, position specified for one argument
*/
public void testDefaultOnePosition() {
field.addArg(createArg("default-position-0"));
field.addArg(createArg("default-position-2", 2));
field.addArg(createArg("default-position-3"));
assertEquals("testDefaultOnePosition(1) ", 4, field.getArgs("required").length);
assertEquals("testDefaultOnePosition(2) ", "default-position-0", field.getArg("required", 0).getKey());
assertNull("testDefaultOnePosition(3) ", field.getArg("required", 1));
assertEquals("testDefaultOnePosition(4) ", "default-position-2", field.getArg("required", 2).getKey());
assertEquals("testDefaultOnePosition(5) ", "default-position-3", field.getArg("required", 3).getKey());
}
/**
* test Field with only 'default' arguments, some position specified.
*/
public void testDefaultSomePositions() {
field.addArg(createArg("default-position-0"));
field.addArg(createArg("default-position-2", 2));
field.addArg(createArg("default-position-3"));
field.addArg(createArg("default-position-1", 1));
assertEquals("testDefaultSomePositions(1) ", 4, field.getArgs("required").length);
assertEquals("testDefaultSomePositions(2) ", "default-position-0", field.getArg("required", 0).getKey());
assertEquals("testDefaultSomePositions(3) ", "default-position-1", field.getArg("required", 1).getKey());
assertEquals("testDefaultSomePositions(4) ", "default-position-2", field.getArg("required", 2).getKey());
assertEquals("testDefaultSomePositions(5) ", "default-position-3", field.getArg("required", 3).getKey());
}
/**
* test Field with a 'default' argument overriden using 'position' property
*/
public void testOverrideUsingPositionA() {
field.addArg(createArg("default-position-0"));
field.addArg(createArg("default-position-1"));
field.addArg(createArg("default-position-2"));
field.addArg(createArg("required-position-1", "required", 1));
// use 'required' as name
assertEquals("testOverrideUsingPositionA(1) ", 3, field.getArgs("required").length);
assertEquals("testOverrideUsingPositionA(2) ", "required-position-1", field.getArg("required", 1).getKey());
// use 'mask' as name
assertEquals("testOverrideUsingPositionA(3) ", 3, field.getArgs("mask").length);
assertEquals("testOverrideUsingPositionA(4) ", "default-position-1", field.getArg("mask", 1).getKey());
// Get Default
assertEquals("testOverrideUsingPositionA(5) ", "default-position-1", field.getArg(1).getKey());
}
/**
* test Field with a 'default' argument overriden using 'position' property
*/
public void testOverrideUsingPositionB() {
field.addArg(createArg("required-position-3", "required", 3));
field.addArg(createArg("required-position-1", "required", 1));
field.addArg(createArg("default-position-0"));
field.addArg(createArg("default-position-1"));
field.addArg(createArg("default-position-2"));
// use 'required' as name
assertEquals("testOverrideUsingPositionB(1) ", 4, field.getArgs("required").length);
assertEquals("testOverrideUsingPositionB(2) ", "default-position-0", field.getArg("required", 0).getKey());
assertEquals("testOverrideUsingPositionB(3) ", "required-position-1", field.getArg("required", 1).getKey());
assertEquals("testOverrideUsingPositionB(4) ", "default-position-2", field.getArg("required", 2).getKey());
assertEquals("testOverrideUsingPositionB(5) ", "required-position-3", field.getArg("required", 3).getKey());
// use 'mask' as name
assertEquals("testOverrideUsingPositionB(6) ", 4, field.getArgs("mask").length);
assertEquals("testOverrideUsingPositionB(6) ", "default-position-0", field.getArg("mask", 0).getKey());
assertEquals("testOverrideUsingPositionB(7) ", "default-position-1", field.getArg("mask", 1).getKey());
assertEquals("testOverrideUsingPositionB(8) ", "default-position-2", field.getArg("mask", 2).getKey());
assertNull("testOverrideUsingPositionB(9) ", field.getArg("mask", 3));
}
/**
* test Field with a 'default' argument overriden without positions specified.
*/
public void testOverridePositionImplied() {
field.addArg(createArg("default-position-0"));
field.addArg(createArg("required-position-1", "required"));
field.addArg(createArg("required-position-2", "required"));
field.addArg(createArg("mask-position-1", "mask"));
// use 'required' as name
assertEquals("testOverridePositionImplied(1) ", 3, field.getArgs("required").length);
assertEquals("testOverridePositionImplied(2) ", "default-position-0", field.getArg("required", 0).getKey());
assertEquals("testOverridePositionImplied(3) ", "required-position-1", field.getArg("required", 1).getKey());
assertEquals("testOverridePositionImplied(4) ", "required-position-2", field.getArg("required", 2).getKey());
// use 'mask' as name
assertEquals("testOverridePositionImplied(5) ", 3, field.getArgs("mask").length);
assertEquals("testOverridePositionImplied(6) ", "default-position-0", field.getArg("mask", 0).getKey());
assertEquals("testOverridePositionImplied(7) ", "mask-position-1", field.getArg("mask", 1).getKey());
assertNull("testOverridePositionImplied(8) ", field.getArg("mask", 2));
// Get Defaults
assertEquals("testOverridePositionImplied(9) ", "default-position-0", field.getArg(0).getKey());
assertNull("testOverridePositionImplied(10) ", field.getArg(1));
assertNull("testOverridePositionImplied(11) ", field.getArg(2));
}
/**
* test Field with a 'default' argument overriden with some positions specified
*/
public void testOverrideSomePosition() {
field.addArg(createArg("default-position-0"));
field.addArg(createArg("default-position-1"));
field.addArg(createArg("default-position-2"));
field.addArg(createArg("required-position-1", "required", 1));
field.addArg(createArg("required-position-2", "required"));
field.addArg(createArg("mask-position-3", "mask"));
// use 'required' as name
assertEquals("testOverrideSomePosition(1) ", 4, field.getArgs("required").length);
assertEquals("testOverrideSomePosition(2) ", "default-position-0", field.getArg("required", 0).getKey());
assertEquals("testOverrideSomePosition(3) ", "required-position-1", field.getArg("required", 1).getKey());
assertEquals("testOverrideSomePosition(4) ", "required-position-2", field.getArg("required", 2).getKey());
assertNull("testOverrideSomePosition(5) ", field.getArg("required", 3));
// use 'mask' as name
assertEquals("testOverrideSomePosition(6) ", 4, field.getArgs("mask").length);
assertEquals("testOverrideSomePosition(7) ", "default-position-0", field.getArg("mask", 0).getKey());
assertEquals("testOverrideSomePosition(8) ", "default-position-1", field.getArg("mask", 1).getKey());
assertEquals("testOverrideSomePosition(9) ", "default-position-2", field.getArg("mask", 2).getKey());
assertEquals("testOverrideSomePosition(10) ", "mask-position-3", field.getArg("mask", 3).getKey());
// Get Defaults
assertEquals("testOverrideSomePosition(11) ", "default-position-0", field.getArg(0).getKey());
assertEquals("testOverrideSomePosition(12) ", "default-position-1", field.getArg(1).getKey());
assertEquals("testOverrideSomePosition(13) ", "default-position-2", field.getArg(2).getKey());
assertNull("testOverrideSomePosition(14) ", field.getArg(3));
}
/**
* Convenience Method - create argument (no name or position specified)
*/
private Arg createArg(final String key) {
final Arg arg = new Arg();
arg.setKey(key);
return arg;
}
/**
* Convenience Method - create argument (no name, position specified)
*/
private Arg createArg(final String key, final int position) {
final Arg arg = createArg(key);
arg.setPosition(position);
return arg;
}
/**
* Convenience Method - create argument (name specified, no position)
*/
private Arg createArg(final String key, final String name) {
final Arg arg = createArg(key);
arg.setName(name);
return arg;
}
/**
* Convenience Method - create argument (name & position specified)
*/
private Arg createArg(final String key, final String name, final int position) {
final Arg arg = createArg(key, name);
arg.setPosition(position);
return arg;
}
}
| 7,902 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/ExtensionTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import java.io.InputStream;
import junit.framework.TestCase;
/**
* <p>Performs tests for extension in form definitions. Performs the same tests
* RequiredNameTest does but with an equivalent validation definition with extension
* definitions (validator-extension.xml), plus an extra check on overriding rules and
* another one checking it mantains correct order when extending.</p>
*/
public class ExtensionTest extends TestCase {
/**
* The key used to retrieve the set of validation
* rules from the xml file.
*/
protected static String FORM_KEY = "nameForm";
/**
* The key used to retrieve the set of validation
* rules from the xml file.
*/
protected static String FORM_KEY2 = "nameForm2";
/**
* The key used to retrieve the set of validation
* rules from the xml file.
*/
protected static String CHECK_MSG_KEY = "nameForm.lastname.displayname";
/**
* The key used to retrieve the validator action.
*/
protected static String ACTION = "required";
/**
* Resources used for validation tests.
*/
private ValidatorResources resources;
/**
* Constructor de ExtensionTest.
* @param arg0
*/
public ExtensionTest(final String arg0) {
super(arg0);
}
/**
* Load <code>ValidatorResources</code> from
* validator-extension.xml.
*/
@Override
protected void setUp() throws Exception {
// Load resources
try (InputStream in = this.getClass().getResourceAsStream("ExtensionTest-config.xml")) {
resources = new ValidatorResources(in);
}
}
@Override
protected void tearDown() {
}
/**
* Tests the required validation failure.
*/
public void testRequired() throws ValidatorException {
// Create bean to run test on.
final NameBean name = new NameBean();
// Construct validator based on the loaded resources
// and the form key
final Validator validator = new Validator(resources, FORM_KEY);
// add the name bean to the validator as a resource
// for the validations to be performed on.
validator.setParameter(Validator.BEAN_PARAM, name);
// Get results of the validation.
// throws ValidatorException,
// but we aren't catching for testing
// since no validation methods we use
// throw this
final ValidatorResults results = validator.validate();
assertNotNull("Results are null.", results);
final ValidatorResult firstNameResult = results.getValidatorResult("firstName");
final ValidatorResult lastNameResult = results.getValidatorResult("lastName");
assertNotNull("First Name ValidatorResult should not be null.", firstNameResult);
assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION));
assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION));
assertNotNull("First Name ValidatorResult should not be null.", lastNameResult);
assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION));
assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have failed.", !lastNameResult.isValid(ACTION));
}
/**
* Tests the required validation for first name if it is blank.
*/
public void testRequiredFirstNameBlank() throws ValidatorException {
// Create bean to run test on.
final NameBean name = new NameBean();
name.setFirstName("");
// Construct validator based on the loaded resources
// and the form key
final Validator validator = new Validator(resources, FORM_KEY);
// add the name bean to the validator as a resource
// for the validations to be performed on.
validator.setParameter(Validator.BEAN_PARAM, name);
// Get results of the validation.
final ValidatorResults results = validator.validate();
assertNotNull("Results are null.", results);
final ValidatorResult firstNameResult = results.getValidatorResult("firstName");
final ValidatorResult lastNameResult = results.getValidatorResult("lastName");
assertNotNull("First Name ValidatorResult should not be null.", firstNameResult);
assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION));
assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION));
assertNotNull("First Name ValidatorResult should not be null.", lastNameResult);
assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION));
assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have failed.", !lastNameResult.isValid(ACTION));
}
/**
* Tests the required validation for first name.
*/
public void testRequiredFirstName() throws ValidatorException {
// Create bean to run test on.
final NameBean name = new NameBean();
name.setFirstName("Joe");
// Construct validator based on the loaded resources
// and the form key
final Validator validator = new Validator(resources, FORM_KEY);
// add the name bean to the validator as a resource
// for the validations to be performed on.
validator.setParameter(Validator.BEAN_PARAM, name);
// Get results of the validation.
final ValidatorResults results = validator.validate();
assertNotNull("Results are null.", results);
final ValidatorResult firstNameResult = results.getValidatorResult("firstName");
final ValidatorResult lastNameResult = results.getValidatorResult("lastName");
assertNotNull("First Name ValidatorResult should not be null.", firstNameResult);
assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION));
assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have passed.", firstNameResult.isValid(ACTION));
assertNotNull("First Name ValidatorResult should not be null.", lastNameResult);
assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION));
assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have failed.", !lastNameResult.isValid(ACTION));
}
/**
* Tests the required validation for last name if it is blank.
*/
public void testRequiredLastNameBlank() throws ValidatorException {
// Create bean to run test on.
final NameBean name = new NameBean();
name.setLastName("");
// Construct validator based on the loaded resources
// and the form key
final Validator validator = new Validator(resources, FORM_KEY);
// add the name bean to the validator as a resource
// for the validations to be performed on.
validator.setParameter(Validator.BEAN_PARAM, name);
// Get results of the validation.
final ValidatorResults results = validator.validate();
assertNotNull("Results are null.", results);
final ValidatorResult firstNameResult = results.getValidatorResult("firstName");
final ValidatorResult lastNameResult = results.getValidatorResult("lastName");
assertNotNull("First Name ValidatorResult should not be null.", firstNameResult);
assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION));
assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION));
assertNotNull("First Name ValidatorResult should not be null.", lastNameResult);
assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION));
assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have failed.", !lastNameResult.isValid(ACTION));
}
/**
* Tests the required validation for last name.
*/
public void testRequiredLastName() throws ValidatorException {
// Create bean to run test on.
final NameBean name = new NameBean();
name.setLastName("Smith");
// Construct validator based on the loaded resources
// and the form key
final Validator validator = new Validator(resources, FORM_KEY);
// add the name bean to the validator as a resource
// for the validations to be performed on.
validator.setParameter(Validator.BEAN_PARAM, name);
// Get results of the validation.
final ValidatorResults results = validator.validate();
assertNotNull("Results are null.", results);
final ValidatorResult firstNameResult = results.getValidatorResult("firstName");
final ValidatorResult lastNameResult = results.getValidatorResult("lastName");
assertNotNull("First Name ValidatorResult should not be null.", firstNameResult);
assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION));
assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION));
assertNotNull("First Name ValidatorResult should not be null.", lastNameResult);
assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION));
assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have passed.", lastNameResult.isValid(ACTION));
}
/**
* Tests the required validation for first and last name.
*/
public void testRequiredName() throws ValidatorException {
// Create bean to run test on.
final NameBean name = new NameBean();
name.setFirstName("Joe");
name.setLastName("Smith");
// Construct validator based on the loaded resources
// and the form key
final Validator validator = new Validator(resources, FORM_KEY);
// add the name bean to the validator as a resource
// for the validations to be performed on.
validator.setParameter(Validator.BEAN_PARAM, name);
// Get results of the validation.
final ValidatorResults results = validator.validate();
assertNotNull("Results are null.", results);
final ValidatorResult firstNameResult = results.getValidatorResult("firstName");
final ValidatorResult lastNameResult = results.getValidatorResult("lastName");
assertNotNull("First Name ValidatorResult should not be null.", firstNameResult);
assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION));
assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have passed.", firstNameResult.isValid(ACTION));
assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult);
assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION));
assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have passed.", lastNameResult.isValid(ACTION));
}
/**
* Tests if we can override a rule. We "can" override a rule if the message shown
* when the firstName required test fails and the lastName test is null.
*/
public void testOverrideRule() throws ValidatorException {
// Create bean to run test on.
final NameBean name = new NameBean();
name.setLastName("Smith");
// Construct validator based on the loaded resources
// and the form key
final Validator validator = new Validator(resources, FORM_KEY2);
// add the name bean to the validator as a resource
// for the validations to be performed on.
validator.setParameter(Validator.BEAN_PARAM, name);
// Get results of the validation.
final ValidatorResults results = validator.validate();
assertNotNull("Results are null.", results);
final ValidatorResult firstNameResult = results.getValidatorResult("firstName");
final ValidatorResult lastNameResult = results.getValidatorResult("lastName");
assertNotNull("First Name ValidatorResult should not be null.", firstNameResult);
assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have '" + CHECK_MSG_KEY + " as a key.", firstNameResult.field.getArg(0).getKey().equals(CHECK_MSG_KEY));
assertNull("Last Name ValidatorResult should be null.", lastNameResult);
}
/**
* Tests if the order is mantained when extending a form. Parent form fields should
* preceed self form fields, except if we override the rules.
*/
public void testOrder() {
final Form form = resources.getForm(ValidatorResources.defaultLocale, FORM_KEY);
final Form form2 = resources.getForm(ValidatorResources.defaultLocale, FORM_KEY2);
assertNotNull(FORM_KEY + " is null.", form);
assertEquals("There should only be 2 fields in " + FORM_KEY, 2, form.getFields().size());
assertNotNull(FORM_KEY2 + " is null.", form2);
assertEquals("There should only be 2 fields in " + FORM_KEY2, 2, form2.getFields().size());
//get the first field
Field fieldFirstName = form.getFields().get(0);
//get the second field
Field fieldLastName = form.getFields().get(1);
assertTrue("firstName in " + FORM_KEY + " should be the first in the list", fieldFirstName.getKey().equals("firstName"));
assertTrue("lastName in " + FORM_KEY + " should be the first in the list", fieldLastName.getKey().equals("lastName"));
// get the second field
fieldLastName = form2.getFields().get(0);
//get the first field
fieldFirstName = form2.getFields().get(1);
assertTrue("firstName in " + FORM_KEY2 + " should be the first in the list", fieldFirstName.getKey().equals("firstName"));
assertTrue("lastName in " + FORM_KEY2 + " should be the first in the list", fieldLastName.getKey().equals("lastName"));
}
} | 7,903 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/ParameterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import java.io.IOException;
import java.util.Locale;
import org.xml.sax.SAXException;
/**
* This TestCase is a confirmation of the parameter of the validator's method.
*/
public class ParameterTest extends AbstractCommonTest {
private static final String FORM_KEY = "nameForm";
private String firstName;
private String middleName;
private String lastName;
/**
* Constructor.
*/
public ParameterTest(final String name) {
super(name);
}
/**
* Load <code>ValidatorResources</code> from
* ValidatorResultsTest-config.xml.
*/
@Override
protected void setUp() throws IOException, SAXException {
// Load resources
loadResources("ParameterTest-config.xml");
// initialize values
firstName = "foo";
middleName = "123";
lastName = "456";
}
@Override
protected void tearDown() {
}
/**
* Test all validations ran and passed.
*/
public void testAllValid() {
// Create bean to run test on.
final NameBean bean = createNameBean();
final Validator validator = new Validator(resources, FORM_KEY);
// add the name bean to the validator as a resource
// for the validations to be performed on.
validator.setParameter(Validator.BEAN_PARAM, bean);
validator.setParameter(Validator.LOCALE_PARAM, Locale.getDefault());
// Get results of the validation.
try {
validator.validate();
} catch (final Exception e) {
fail("Validator.validate() threw " + e);
}
assertParameterValue(validator, Validator.BEAN_PARAM, Object.class);
assertParameterValue(validator, Validator.FIELD_PARAM, Field.class);
assertParameterValue(validator, Validator.FORM_PARAM, Form.class);
assertParameterValue(validator, Validator.LOCALE_PARAM, Locale.class);
assertParameterValue(validator, Validator.VALIDATOR_ACTION_PARAM,
ValidatorAction.class);
assertParameterValue(validator, Validator.VALIDATOR_PARAM,
Validator.class);
assertParameterValue(validator, Validator.VALIDATOR_RESULTS_PARAM,
ValidatorResults.class);
}
private void assertParameterValue(final Validator validator, final String name,
final Class<?> type) {
final Object value = validator.getParameterValue(name);
assertNotNull("Expected '" + type.getName() + "' but was null", value);
assertTrue("Expected '" + type.getName() + "' but was '" + value.getClass().getName() + "'",
type.isInstance(value));
}
/**
* Create a NameBean.
*/
private NameBean createNameBean() {
final NameBean name = new NameBean();
name.setFirstName(firstName);
name.setMiddleName(middleName);
name.setLastName(lastName);
return name;
}
}
| 7,904 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/DoubleTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
/**
* Performs Validation Test for <code>double</code> validations.
*/
public class DoubleTest extends AbstractNumberTest {
public DoubleTest(final String name) {
super(name);
ACTION = "double";
FORM_KEY = "doubleForm";
}
/**
* Tests the double validation.
*/
public void testDouble() throws ValidatorException {
// Create bean to run test on.
final ValueBean info = new ValueBean();
info.setValue("0");
valueTest(info, true);
}
/**
* Tests the double validation.
*/
public void testDoubleMin() throws ValidatorException {
// Create bean to run test on.
final ValueBean info = new ValueBean();
info.setValue(Double.toString(Double.MIN_VALUE));
valueTest(info, true);
}
/**
* Tests the double validation.
*/
public void testDoubleMax() throws ValidatorException {
// Create bean to run test on.
final ValueBean info = new ValueBean();
info.setValue(Double.toString(Double.MAX_VALUE));
valueTest(info, true);
}
/**
* Tests the double validation failure.
*/
public void testDoubleFailure() throws ValidatorException {
// Create bean to run test on.
final ValueBean info = new ValueBean();
valueTest(info, false);
}
} | 7,905 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/MultipleConfigFilesTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import java.io.IOException;
import java.io.InputStream;
import org.xml.sax.SAXException;
import junit.framework.TestCase;
/**
* Tests that validator rules split between 2 different XML files get
* merged properly.
*/
public class MultipleConfigFilesTest extends TestCase {
/**
* Resources used for validation tests.
*/
private ValidatorResources resources;
/**
* The key used to retrieve the set of validation
* rules from the xml file.
*/
private static final String FORM_KEY = "nameForm";
/**
* The key used to retrieve the validator action.
*/
private static final String ACTION = "required";
/**
* Constructor for MultipleConfigFilesTest.
* @param name
*/
public MultipleConfigFilesTest(final String name) {
super(name);
}
/**
* Load <code>ValidatorResources</code> from multiple xml files.
*/
@Override
protected void setUp() throws IOException, SAXException {
final InputStream[] streams =
{
this.getClass().getResourceAsStream(
"MultipleConfigFilesTest-1-config.xml"),
this.getClass().getResourceAsStream(
"MultipleConfigFilesTest-2-config.xml")};
this.resources = new ValidatorResources(streams);
for (final InputStream stream : streams) {
stream.close();
}
}
/**
* Check the forms and constants from different config files have
* been merged into the same FormSet.
*/
public void testMergedConfig() {
// *********** Default Locale *******************
// Check the form from the first config file exists
final Form form1 = resources.getForm("", "", "", "testForm1");
assertNotNull("Form 'testForm1' not found", form1);
// Check the form from the second config file exists
final Form form2 = resources.getForm("", "", "", "testForm2");
assertNotNull("Form 'testForm2' not found", form2);
// Check the Constants for the form from the first config file
final Field field1 = form1.getField("testProperty1");
assertEquals("testProperty1 - const 1", "testConstValue1", field1.getVarValue("var11"));
assertEquals("testProperty1 - const 2", "testConstValue2", field1.getVarValue("var12"));
// Check the Constants for the form from the second config file
final Field field2 = form2.getField("testProperty2");
assertEquals("testProperty2 - const 1", "testConstValue1", field2.getVarValue("var21"));
assertEquals("testProperty2 - const 2", "testConstValue2", field2.getVarValue("var22"));
// *********** 'fr' locale *******************
// Check the form from the first config file exists
final Form form1_fr = resources.getForm("fr", "", "", "testForm1_fr");
assertNotNull("Form 'testForm1_fr' not found", form1_fr);
// Check the form from the second config file exists
final Form form2_fr = resources.getForm("fr", "", "", "testForm2_fr");
assertNotNull("Form 'testForm2_fr' not found", form2_fr);
// Check the Constants for the form from the first config file
final Field field1_fr = form1_fr.getField("testProperty1_fr");
assertEquals("testProperty1_fr - const 1", "testConstValue1_fr", field1_fr.getVarValue("var11_fr"));
assertEquals("testProperty1_fr - const 2", "testConstValue2_fr", field1_fr.getVarValue("var12_fr"));
// Check the Constants for the form from the second config file
final Field field2_fr = form2_fr.getField("testProperty2_fr");
assertEquals("testProperty2_fr - const 1", "testConstValue1_fr", field2_fr.getVarValue("var21_fr"));
assertEquals("testProperty2_fr - const 2", "testConstValue2_fr", field2_fr.getVarValue("var22_fr"));
}
/**
* With nothing provided, we should fail both because both are required.
*/
public void testBothBlank() throws ValidatorException {
// Create bean to run test on.
final NameBean name = new NameBean();
// Construct validator based on the loaded resources
// and the form key
final Validator validator = new Validator(resources, FORM_KEY);
// add the name bean to the validator as a resource
// for the validations to be performed on.
validator.setParameter(Validator.BEAN_PARAM, name);
// Get results of the validation.
// throws ValidatorException,
// but we aren't catching for testing
// since no validation methods we use
// throw this
final ValidatorResults results = validator.validate();
assertNotNull("Results are null.", results);
final ValidatorResult firstNameResult = results.getValidatorResult("firstName");
final ValidatorResult lastNameResult = results.getValidatorResult("lastName");
assertNotNull(firstNameResult);
assertTrue(firstNameResult.containsAction(ACTION));
assertTrue(!firstNameResult.isValid(ACTION));
assertNotNull(lastNameResult);
assertTrue(lastNameResult.containsAction(ACTION));
assertTrue(!lastNameResult.isValid(ACTION));
assertTrue(!lastNameResult.containsAction("int"));
}
/**
* If the first name fails required, and the second test fails int, we should get two errors.
*/
public void testRequiredFirstNameBlankLastNameShort()
throws ValidatorException {
// Create bean to run test on.
final NameBean name = new NameBean();
name.setFirstName("");
name.setLastName("Test");
// Construct validator based on the loaded resources
// and the form key
final Validator validator = new Validator(resources, FORM_KEY);
// add the name bean to the validator as a resource
// for the validations to be performed on.
validator.setParameter(Validator.BEAN_PARAM, name);
// Get results of the validation.
final ValidatorResults results = validator.validate();
assertNotNull("Results are null.", results);
final ValidatorResult firstNameResult = results.getValidatorResult("firstName");
final ValidatorResult lastNameResult = results.getValidatorResult("lastName");
assertNotNull(firstNameResult);
assertTrue(firstNameResult.containsAction(ACTION));
assertTrue(!firstNameResult.isValid(ACTION));
assertNotNull(lastNameResult);
assertTrue(lastNameResult.containsAction("int"));
assertTrue(!lastNameResult.isValid("int"));
}
/**
* If the first name is there, and the last name fails int, we should get one error.
*/
public void testRequiredLastNameShort() throws ValidatorException {
// Create bean to run test on.
final NameBean name = new NameBean();
name.setFirstName("Test");
name.setLastName("Test");
// Construct validator based on the loaded resources
// and the form key
final Validator validator = new Validator(resources, FORM_KEY);
// add the name bean to the validator as a resource
// for the validations to be performed on.
validator.setParameter(Validator.BEAN_PARAM, name);
// Get results of the validation.
final ValidatorResults results = validator.validate();
assertNotNull("Results are null.", results);
final ValidatorResult firstNameResult = results.getValidatorResult("firstName");
final ValidatorResult lastNameResult = results.getValidatorResult("lastName");
assertNotNull(firstNameResult);
assertTrue(firstNameResult.containsAction(ACTION));
assertTrue(firstNameResult.isValid(ACTION));
assertNotNull(lastNameResult);
assertTrue(lastNameResult.containsAction("int"));
assertTrue(!lastNameResult.isValid("int"));
}
/**
* If first name is ok and last name is ok and is an int, no errors.
*/
public void testRequiredLastNameLong() throws ValidatorException {
// Create bean to run test on.
final NameBean name = new NameBean();
name.setFirstName("Joe");
name.setLastName("12345678");
// Construct validator based on the loaded resources
// and the form key
final Validator validator = new Validator(resources, FORM_KEY);
// add the name bean to the validator as a resource
// for the validations to be performed on.
validator.setParameter(Validator.BEAN_PARAM, name);
// Get results of the validation.
final ValidatorResults results = validator.validate();
assertNotNull("Results are null.", results);
final ValidatorResult firstNameResult = results.getValidatorResult("firstName");
final ValidatorResult lastNameResult = results.getValidatorResult("lastName");
assertNotNull(firstNameResult);
assertTrue(firstNameResult.containsAction(ACTION));
assertTrue(firstNameResult.isValid(ACTION));
assertNotNull(lastNameResult);
assertTrue(lastNameResult.containsAction("int"));
assertTrue(lastNameResult.isValid("int"));
}
}
| 7,906 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/util/FlagsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.util;
import junit.framework.TestCase;
/**
* Test the Flags class.
*/
public class FlagsTest extends TestCase {
/**
* Declare some flags for testing.
*/
private static final long LONG_FLAG = 1;
private static final long LONG_FLAG_2 = 2;
private static final int INT_FLAG = 4;
/**
* Constructor for FlagsTest.
*/
public FlagsTest(final String name) {
super(name);
}
public void testHashCode() {
final Flags f = new Flags(45);
assertEquals(f.hashCode(), 45);
}
public void testGetFlags() {
final Flags f = new Flags(45);
assertEquals(f.getFlags(), 45);
}
public void testIsOnOff() {
final Flags f = new Flags();
f.turnOn(LONG_FLAG);
f.turnOn(INT_FLAG);
assertTrue(f.isOn(LONG_FLAG));
assertTrue(!f.isOff(LONG_FLAG));
assertTrue(f.isOn(INT_FLAG));
assertTrue(!f.isOff(INT_FLAG));
assertTrue(f.isOff(LONG_FLAG_2));
}
public void testTurnOnOff() {
}
public void testTurnOff() {
}
public void testTurnOffAll() {
final Flags f = new Flags(98432);
f.turnOffAll();
assertEquals(0, f.getFlags());
}
public void testClear() {
final Flags f = new Flags(98432);
f.clear();
assertEquals(0, f.getFlags());
}
public void testTurnOnAll() {
final Flags f = new Flags();
f.turnOnAll();
assertEquals(~0, f.getFlags());
}
public void testIsOn_isFalseWhenNotAllFlagsInArgumentAreOn() {
final Flags first = new Flags(1);
final long firstAndSecond = 3;
assertFalse(first.isOn(firstAndSecond));
}
public void testIsOn_isTrueWhenHighOrderBitIsSetAndQueried() {
final Flags allOn = new Flags(~0);
final long highOrderBit = 0x8000000000000000L;
assertTrue(allOn.isOn(highOrderBit));
}
/**
* Test for Object clone()
*/
public void testClone() {
}
/**
* Test for boolean equals(Object)
*/
public void testEqualsObject() {
}
/**
* Test for String toString()
*/
public void testToString() {
final Flags f = new Flags();
String s = f.toString();
assertEquals(64, s.length());
f.turnOn(INT_FLAG);
s = f.toString();
assertEquals(64, s.length());
assertEquals(
"0000000000000000000000000000000000000000000000000000000000000100",
s);
}
}
| 7,907 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/UrlValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.validator.ResultPair;
import org.junit.Before;
import org.junit.Test;
/**
* Performs Validation Test for url validations.
*/
public class UrlValidatorTest {
private final boolean printStatus = false;
private final boolean printIndex = false;//print index that indicates current scheme,host,port,path, query test were using.
@Before
public void setUp() {
for (int index = 0; index < testPartsIndex.length - 1; index++) {
testPartsIndex[index] = 0;
}
}
@Test
public void testIsValid() {
testIsValid(testUrlParts, UrlValidator.ALLOW_ALL_SCHEMES);
setUp();
final long options =
UrlValidator.ALLOW_2_SLASHES
+ UrlValidator.ALLOW_ALL_SCHEMES
+ UrlValidator.NO_FRAGMENTS;
testIsValid(testUrlPartsOptions, options);
}
@Test
public void testIsValidScheme() {
if (printStatus) {
System.out.print("\n testIsValidScheme() ");
}
//UrlValidator urlVal = new UrlValidator(schemes,false,false,false);
final UrlValidator urlVal = new UrlValidator(schemes, 0);
for (final ResultPair testPair : testScheme) {
final boolean result = urlVal.isValidScheme(testPair.item);
assertEquals(testPair.item, testPair.valid, result);
if (printStatus) {
if (result == testPair.valid) {
System.out.print('.');
} else {
System.out.print('X');
}
}
}
if (printStatus) {
System.out.println();
}
}
/**
* Create set of tests by taking the testUrlXXX arrays and
* running through all possible permutations of their combinations.
*
* @param testObjects Used to create a url.
*/
public void testIsValid(final Object[] testObjects, final long options) {
final UrlValidator urlVal = new UrlValidator(null, null, options);
assertTrue(urlVal.isValid("http://www.google.com"));
assertTrue(urlVal.isValid("http://www.google.com/"));
int statusPerLine = 60;
int printed = 0;
if (printIndex) {
statusPerLine = 6;
}
do {
final StringBuilder testBuffer = new StringBuilder();
boolean expected = true;
for (int testPartsIndexIndex = 0; testPartsIndexIndex < testPartsIndex.length; ++testPartsIndexIndex) {
final int index = testPartsIndex[testPartsIndexIndex];
final ResultPair[] part = (ResultPair[]) testObjects[testPartsIndexIndex];
testBuffer.append(part[index].item);
expected &= part[index].valid;
}
final String url = testBuffer.toString();
final boolean result = urlVal.isValid(url);
assertEquals(url, expected, result);
if (printStatus) {
if (printIndex) {
System.out.print(testPartsIndextoString());
} else if (result == expected) {
System.out.print('.');
} else {
System.out.print('X');
}
printed++;
if (printed == statusPerLine) {
System.out.println();
printed = 0;
}
}
} while (incrementTestPartsIndex(testPartsIndex, testObjects));
if (printStatus) {
System.out.println();
}
}
@Test
public void testValidator202() {
final String[] schemes = {"http","https"};
final UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.NO_FRAGMENTS);
assertTrue(urlValidator.isValid("http://l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.org"));
}
@Test
public void testValidator204() {
final String[] schemes = {"http","https"};
final UrlValidator urlValidator = new UrlValidator(schemes);
assertTrue(urlValidator.isValid("http://tech.yahoo.com/rc/desktops/102;_ylt=Ao8yevQHlZ4On0O3ZJGXLEQFLZA5"));
}
@Test
public void testValidator218() {
final UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_2_SLASHES);
assertTrue("parentheses should be valid in URLs",
validator.isValid("http://somewhere.com/pathxyz/file(1).html"));
}
@Test
public void testValidator235() {
final String version = System.getProperty("java.version");
if (version.compareTo("1.6") < 0) {
System.out.println("Cannot run Unicode IDN tests");
return; // Cannot run the test
}
final UrlValidator validator = new UrlValidator();
assertTrue("xn--d1abbgf6aiiy.xn--p1ai should validate", validator.isValid("http://xn--d1abbgf6aiiy.xn--p1ai"));
assertTrue("президент.рф should validate", validator.isValid("http://президент.рф"));
assertTrue("www.b\u00fccher.ch should validate", validator.isValid("http://www.b\u00fccher.ch"));
assertFalse("www.\uFFFD.ch FFFD should fail", validator.isValid("http://www.\uFFFD.ch"));
assertTrue("www.b\u00fccher.ch should validate", validator.isValid("ftp://www.b\u00fccher.ch"));
assertFalse("www.\uFFFD.ch FFFD should fail", validator.isValid("ftp://www.\uFFFD.ch"));
}
@Test
public void testValidator248() {
final RegexValidator regex = new RegexValidator("localhost", ".*\\.my-testing");
UrlValidator validator = new UrlValidator(regex, 0);
assertTrue("localhost URL should validate",
validator.isValid("http://localhost/test/index.html"));
assertTrue("first.my-testing should validate",
validator.isValid("http://first.my-testing/test/index.html"));
assertTrue("sup3r.my-testing should validate",
validator.isValid("http://sup3r.my-testing/test/index.html"));
assertFalse("broke.my-test should not validate",
validator.isValid("http://broke.my-test/test/index.html"));
assertTrue("www.apache.org should still validate",
validator.isValid("http://www.apache.org/test/index.html"));
// Now check using options
validator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS);
assertTrue("localhost URL should validate",
validator.isValid("http://localhost/test/index.html"));
assertTrue("machinename URL should validate",
validator.isValid("http://machinename/test/index.html"));
assertTrue("www.apache.org should still validate",
validator.isValid("http://www.apache.org/test/index.html"));
}
@Test
public void testValidator288() {
UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS);
assertTrue("hostname should validate",
validator.isValid("http://hostname"));
assertTrue("hostname with path should validate",
validator.isValid("http://hostname/test/index.html"));
assertTrue("localhost URL should validate",
validator.isValid("http://localhost/test/index.html"));
assertFalse("first.my-testing should not validate",
validator.isValid("http://first.my-testing/test/index.html"));
assertFalse("broke.hostname should not validate",
validator.isValid("http://broke.hostname/test/index.html"));
assertTrue("www.apache.org should still validate",
validator.isValid("http://www.apache.org/test/index.html"));
// Turn it off, and check
validator = new UrlValidator(0);
assertFalse("hostname should no longer validate",
validator.isValid("http://hostname"));
assertFalse("localhost URL should no longer validate",
validator.isValid("http://localhost/test/index.html"));
assertTrue("www.apache.org should still validate",
validator.isValid("http://www.apache.org/test/index.html"));
}
@Test
public void testValidator276() {
// file:// isn't allowed by default
UrlValidator validator = new UrlValidator();
assertTrue("http://apache.org/ should be allowed by default",
validator.isValid("http://www.apache.org/test/index.html"));
assertFalse("file:///c:/ shouldn't be allowed by default",
validator.isValid("file:///C:/some.file"));
assertFalse("file:///c:\\ shouldn't be allowed by default",
validator.isValid("file:///C:\\some.file"));
assertFalse("file:///etc/ shouldn't be allowed by default",
validator.isValid("file:///etc/hosts"));
assertFalse("file://localhost/etc/ shouldn't be allowed by default",
validator.isValid("file://localhost/etc/hosts"));
assertFalse("file://localhost/c:/ shouldn't be allowed by default",
validator.isValid("file://localhost/c:/some.file"));
// Turn it on, and check
// Note - we need to enable local urls when working with file:
validator = new UrlValidator(new String[] {"http","file"}, UrlValidator.ALLOW_LOCAL_URLS);
assertTrue("http://apache.org/ should be allowed by default",
validator.isValid("http://www.apache.org/test/index.html"));
assertTrue("file:///c:/ should now be allowed",
validator.isValid("file:///C:/some.file"));
assertFalse("file:///c:\\ should not be allowed", // Only allow forward slashes
validator.isValid("file:///C:\\some.file"));
assertTrue("file:///etc/ should now be allowed",
validator.isValid("file:///etc/hosts"));
assertTrue("file://localhost/etc/ should now be allowed",
validator.isValid("file://localhost/etc/hosts"));
assertTrue("file://localhost/c:/ should now be allowed",
validator.isValid("file://localhost/c:/some.file"));
// These are never valid
assertFalse("file://c:/ shouldn't ever be allowed, needs file:///c:/",
validator.isValid("file://C:/some.file"));
assertFalse("file://c:\\ shouldn't ever be allowed, needs file:///c:/",
validator.isValid("file://C:\\some.file"));
}
@Test
public void testValidator391OK() {
final String[] schemes = {"file"};
final UrlValidator urlValidator = new UrlValidator(schemes);
assertTrue(urlValidator.isValid("file:///C:/path/to/dir/"));
}
@Test
public void testValidator391FAILS() {
final String[] schemes = {"file"};
final UrlValidator urlValidator = new UrlValidator(schemes);
assertTrue(urlValidator.isValid("file:/C:/path/to/dir/"));
}
@Test
public void testValidator309() {
UrlValidator urlValidator = new UrlValidator();
assertTrue(urlValidator.isValid("http://sample.ondemand.com/"));
assertTrue(urlValidator.isValid("hTtP://sample.ondemand.CoM/"));
assertTrue(urlValidator.isValid("httpS://SAMPLE.ONEMAND.COM/"));
urlValidator = new UrlValidator(new String[] {"HTTP","HTTPS"});
assertTrue(urlValidator.isValid("http://sample.ondemand.com/"));
assertTrue(urlValidator.isValid("hTtP://sample.ondemand.CoM/"));
assertTrue(urlValidator.isValid("httpS://SAMPLE.ONEMAND.COM/"));
}
@Test
public void testValidator339(){
final UrlValidator urlValidator = new UrlValidator();
assertTrue(urlValidator.isValid("http://www.cnn.com/WORLD/?hpt=sitenav")); // without
assertTrue(urlValidator.isValid("http://www.cnn.com./WORLD/?hpt=sitenav")); // with
assertFalse(urlValidator.isValid("http://www.cnn.com../")); // doubly dotty
assertFalse(urlValidator.isValid("http://www.cnn.invalid/"));
assertFalse(urlValidator.isValid("http://www.cnn.invalid./")); // check . does not affect invalid domains
}
@Test
public void testValidator339IDN(){
final UrlValidator urlValidator = new UrlValidator();
assertTrue(urlValidator.isValid("http://президент.рф/WORLD/?hpt=sitenav")); // without
assertTrue(urlValidator.isValid("http://президент.рф./WORLD/?hpt=sitenav")); // with
assertFalse(urlValidator.isValid("http://президент.рф..../")); // very dotty
assertFalse(urlValidator.isValid("http://президент.рф.../")); // triply dotty
assertFalse(urlValidator.isValid("http://президент.рф../")); // doubly dotty
}
@Test
public void testValidator342(){
final UrlValidator urlValidator = new UrlValidator();
assertTrue(urlValidator.isValid("http://example.rocks/"));
assertTrue(urlValidator.isValid("http://example.rocks"));
}
@Test
public void testValidator411(){
final UrlValidator urlValidator = new UrlValidator();
assertTrue(urlValidator.isValid("http://example.rocks:/"));
assertTrue(urlValidator.isValid("http://example.rocks:0/"));
assertTrue(urlValidator.isValid("http://example.rocks:65535/"));
assertFalse(urlValidator.isValid("http://example.rocks:65536/"));
assertFalse(urlValidator.isValid("http://example.rocks:100000/"));
}
@Test
public void testValidator464() {
final String[] schemes = {"file"};
final UrlValidator urlValidator = new UrlValidator(schemes);
final String fileNAK = "file://bad ^ domain.com/label/test";
assertFalse(fileNAK, urlValidator.isValid(fileNAK));
}
@Test
public void testValidator452(){
final UrlValidator urlValidator = new UrlValidator();
assertTrue(urlValidator.isValid("http://[::FFFF:129.144.52.38]:80/index.html"));
}
@Test
public void testValidator473_1() { // reject null DomainValidator
final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () ->
new UrlValidator(new String[]{}, null, 0L, null));
assertThat(thrown.getMessage(), is(equalTo("DomainValidator must not be null")));
}
@Test
public void testValidator473_2() { // reject null DomainValidator with mismatched allowLocal
final List<DomainValidator.Item> items = new ArrayList<>();
final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () ->
new UrlValidator(new String[]{}, null, 0L, DomainValidator.getInstance(true, items)));
assertThat(thrown.getMessage(), is(equalTo("DomainValidator disagrees with ALLOW_LOCAL_URLS setting")));
}
@Test
public void testValidator473_3() { // reject null DomainValidator with mismatched allowLocal
final List<DomainValidator.Item> items = new ArrayList<>();
final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () ->
new UrlValidator(new String[]{}, null, UrlValidator.ALLOW_LOCAL_URLS, DomainValidator.getInstance(false, items)));
assertThat(thrown.getMessage(), is(equalTo("DomainValidator disagrees with ALLOW_LOCAL_URLS setting")));
}
static boolean incrementTestPartsIndex(final int[] testPartsIndex, final Object[] testParts) {
boolean carry = true; //add 1 to lowest order part.
boolean maxIndex = true;
for (int testPartsIndexIndex = testPartsIndex.length - 1; testPartsIndexIndex >= 0; --testPartsIndexIndex) {
int index = testPartsIndex[testPartsIndexIndex];
final ResultPair[] part = (ResultPair[]) testParts[testPartsIndexIndex];
maxIndex &= index == part.length - 1;
if (carry) {
if (index < part.length - 1) {
index++;
testPartsIndex[testPartsIndexIndex] = index;
carry = false;
} else {
testPartsIndex[testPartsIndexIndex] = 0;
carry = true;
}
}
}
return !maxIndex;
}
private String testPartsIndextoString() {
final StringBuilder carryMsg = new StringBuilder("{");
for (int testPartsIndexIndex = 0; testPartsIndexIndex < testPartsIndex.length; ++testPartsIndexIndex) {
carryMsg.append(testPartsIndex[testPartsIndexIndex]);
if (testPartsIndexIndex < testPartsIndex.length - 1) {
carryMsg.append(',');
} else {
carryMsg.append('}');
}
}
return carryMsg.toString();
}
@Test
public void testValidateUrl() {
assertTrue(true);
}
@Test
public void testValidator290() {
final UrlValidator validator = new UrlValidator();
assertTrue(validator.isValid("http://xn--h1acbxfam.idn.icann.org/"));
// assertTrue(validator.isValid("http://xn--e1afmkfd.xn--80akhbyknj4f"));
// Internationalized country code top-level domains
assertTrue(validator.isValid("http://test.xn--lgbbat1ad8j")); //Algeria
assertTrue(validator.isValid("http://test.xn--fiqs8s")); // China
assertTrue(validator.isValid("http://test.xn--fiqz9s")); // China
assertTrue(validator.isValid("http://test.xn--wgbh1c")); // Egypt
assertTrue(validator.isValid("http://test.xn--j6w193g")); // Hong Kong
assertTrue(validator.isValid("http://test.xn--h2brj9c")); // India
assertTrue(validator.isValid("http://test.xn--mgbbh1a71e")); // India
assertTrue(validator.isValid("http://test.xn--fpcrj9c3d")); // India
assertTrue(validator.isValid("http://test.xn--gecrj9c")); // India
assertTrue(validator.isValid("http://test.xn--s9brj9c")); // India
assertTrue(validator.isValid("http://test.xn--xkc2dl3a5ee0h")); // India
assertTrue(validator.isValid("http://test.xn--45brj9c")); // India
assertTrue(validator.isValid("http://test.xn--mgba3a4f16a")); // Iran
assertTrue(validator.isValid("http://test.xn--mgbayh7gpa")); // Jordan
assertTrue(validator.isValid("http://test.xn--mgbc0a9azcg")); // Morocco
assertTrue(validator.isValid("http://test.xn--ygbi2ammx")); // Palestinian Territory
assertTrue(validator.isValid("http://test.xn--wgbl6a")); // Qatar
assertTrue(validator.isValid("http://test.xn--p1ai")); // Russia
assertTrue(validator.isValid("http://test.xn--mgberp4a5d4ar")); // Saudi Arabia
assertTrue(validator.isValid("http://test.xn--90a3ac")); // Serbia
assertTrue(validator.isValid("http://test.xn--yfro4i67o")); // Singapore
assertTrue(validator.isValid("http://test.xn--clchc0ea0b2g2a9gcd")); // Singapore
assertTrue(validator.isValid("http://test.xn--3e0b707e")); // South Korea
assertTrue(validator.isValid("http://test.xn--fzc2c9e2c")); // Sri Lanka
assertTrue(validator.isValid("http://test.xn--xkc2al3hye2a")); // Sri Lanka
assertTrue(validator.isValid("http://test.xn--ogbpf8fl")); // Syria
assertTrue(validator.isValid("http://test.xn--kprw13d")); // Taiwan
assertTrue(validator.isValid("http://test.xn--kpry57d")); // Taiwan
assertTrue(validator.isValid("http://test.xn--o3cw4h")); // Thailand
assertTrue(validator.isValid("http://test.xn--pgbs0dh")); // Tunisia
assertTrue(validator.isValid("http://test.xn--mgbaam7a8h")); // United Arab Emirates
// Proposed internationalized ccTLDs
// assertTrue(validator.isValid("http://test.xn--54b7fta0cc")); // Bangladesh
// assertTrue(validator.isValid("http://test.xn--90ae")); // Bulgaria
// assertTrue(validator.isValid("http://test.xn--node")); // Georgia
// assertTrue(validator.isValid("http://test.xn--4dbrk0ce")); // Israel
// assertTrue(validator.isValid("http://test.xn--mgb9awbf")); // Oman
// assertTrue(validator.isValid("http://test.xn--j1amh")); // Ukraine
// assertTrue(validator.isValid("http://test.xn--mgb2ddes")); // Yemen
// Test TLDs
// assertTrue(validator.isValid("http://test.xn--kgbechtv")); // Arabic
// assertTrue(validator.isValid("http://test.xn--hgbk6aj7f53bba")); // Persian
// assertTrue(validator.isValid("http://test.xn--0zwm56d")); // Chinese
// assertTrue(validator.isValid("http://test.xn--g6w251d")); // Chinese
// assertTrue(validator.isValid("http://test.xn--80akhbyknj4f")); // Russian
// assertTrue(validator.isValid("http://test.xn--11b5bs3a9aj6g")); // Hindi
// assertTrue(validator.isValid("http://test.xn--jxalpdlp")); // Greek
// assertTrue(validator.isValid("http://test.xn--9t4b11yi5a")); // Korean
// assertTrue(validator.isValid("http://test.xn--deba0ad")); // Yiddish
// assertTrue(validator.isValid("http://test.xn--zckzah")); // Japanese
// assertTrue(validator.isValid("http://test.xn--hlcj6aya9esc7a")); // Tamil
}
@Test
public void testValidator361() {
final UrlValidator validator = new UrlValidator();
assertTrue(validator.isValid("http://hello.tokyo/"));
}
@Test
public void testValidator363(){
final UrlValidator urlValidator = new UrlValidator();
assertTrue(urlValidator.isValid("http://www.example.org/a/b/hello..world"));
assertTrue(urlValidator.isValid("http://www.example.org/a/hello..world"));
assertTrue(urlValidator.isValid("http://www.example.org/hello.world/"));
assertTrue(urlValidator.isValid("http://www.example.org/hello..world/"));
assertTrue(urlValidator.isValid("http://www.example.org/hello.world"));
assertTrue(urlValidator.isValid("http://www.example.org/hello..world"));
assertTrue(urlValidator.isValid("http://www.example.org/..world"));
assertTrue(urlValidator.isValid("http://www.example.org/.../world"));
assertFalse(urlValidator.isValid("http://www.example.org/../world"));
assertFalse(urlValidator.isValid("http://www.example.org/.."));
assertFalse(urlValidator.isValid("http://www.example.org/../"));
assertFalse(urlValidator.isValid("http://www.example.org/./.."));
assertFalse(urlValidator.isValid("http://www.example.org/././.."));
assertTrue(urlValidator.isValid("http://www.example.org/..."));
assertTrue(urlValidator.isValid("http://www.example.org/.../"));
assertTrue(urlValidator.isValid("http://www.example.org/.../.."));
}
@Test
public void testValidator375() {
final UrlValidator validator = new UrlValidator();
String url = "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html";
assertTrue("IPv6 address URL should validate: " + url, validator.isValid(url));
url = "http://[::1]:80/index.html";
assertTrue("IPv6 address URL should validate: " + url, validator.isValid(url));
url = "http://FEDC:BA98:7654:3210:FEDC:BA98:7654:3210:80/index.html";
assertFalse("IPv6 address without [] should not validate: " + url, validator.isValid(url));
}
@Test
public void testValidator353() { // userinfo
final UrlValidator validator = new UrlValidator();
assertTrue(validator.isValid("http://www.apache.org:80/path"));
assertTrue(validator.isValid("http://user:pass@www.apache.org:80/path"));
assertTrue(validator.isValid("http://user:@www.apache.org:80/path"));
assertTrue(validator.isValid("http://user@www.apache.org:80/path"));
assertTrue(validator.isValid("http://us%00er:-._~!$&'()*+,;=@www.apache.org:80/path"));
assertFalse(validator.isValid("http://:pass@www.apache.org:80/path"));
assertFalse(validator.isValid("http://:@www.apache.org:80/path"));
assertFalse(validator.isValid("http://user:pa:ss@www.apache.org/path"));
assertFalse(validator.isValid("http://user:pa@ss@www.apache.org/path"));
}
@Test
public void testValidator382() {
final UrlValidator validator = new UrlValidator();
assertTrue(validator.isValid("ftp://username:password@example.com:8042/over/there/index.dtb?type=animal&name=narwhal#nose"));
}
@Test
public void testValidator380() {
final UrlValidator validator = new UrlValidator();
assertTrue(validator.isValid("http://www.apache.org:80/path"));
assertTrue(validator.isValid("http://www.apache.org:8/path"));
assertTrue(validator.isValid("http://www.apache.org:/path"));
}
@Test
public void testValidator420() {
final UrlValidator validator = new UrlValidator();
assertFalse(validator.isValid("http://example.com/serach?address=Main Avenue"));
assertTrue(validator.isValid("http://example.com/serach?address=Main%20Avenue"));
assertTrue(validator.isValid("http://example.com/serach?address=Main+Avenue"));
}
@Test
public void testValidator467() {
final UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_2_SLASHES);
assertTrue(validator.isValid("https://example.com/some_path/path/"));
assertTrue(validator.isValid("https://example.com//somepath/path/"));
assertTrue(validator.isValid("https://example.com//some_path/path/"));
assertTrue(validator.isValid("http://example.com//_test")); // VALIDATOR-429
}
@Test
public void testValidator283() {
final UrlValidator validator = new UrlValidator();
assertFalse(validator.isValid("http://finance.yahoo.com/news/Owners-54B-NY-housing-apf-2493139299.html?x=0&ap=%fr"));
assertTrue(validator.isValid("http://finance.yahoo.com/news/Owners-54B-NY-housing-apf-2493139299.html?x=0&ap=%22"));
}
@Test
public void testFragments() {
final String[] schemes = {"http","https"};
UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.NO_FRAGMENTS);
assertFalse(urlValidator.isValid("http://apache.org/a/b/c#frag"));
urlValidator = new UrlValidator(schemes);
assertTrue(urlValidator.isValid("http://apache.org/a/b/c#frag"));
}
//-------------------- Test data for creating a composite URL
/**
* The data given below approximates the 4 parts of a URL
* <scheme>://<authority><path>?<query> except that the port number
* is broken out of authority to increase the number of permutations.
* A complete URL is composed of a scheme+authority+port+path+query,
* all of which must be individually valid for the entire URL to be considered
* valid.
*/
ResultPair[] testUrlScheme = {new ResultPair("http://", true),
new ResultPair("ftp://", true),
new ResultPair("h3t://", true),
new ResultPair("3ht://", false),
new ResultPair("http:/", false),
new ResultPair("http:", false),
new ResultPair("http/", false),
new ResultPair("://", false)};
ResultPair[] testUrlAuthority = {new ResultPair("www.google.com", true),
new ResultPair("www.google.com.", true),
new ResultPair("go.com", true),
new ResultPair("go.au", true),
new ResultPair("0.0.0.0", true),
new ResultPair("255.255.255.255", true),
new ResultPair("256.256.256.256", false),
new ResultPair("255.com", true),
new ResultPair("1.2.3.4.5", false),
new ResultPair("1.2.3.4.", false),
new ResultPair("1.2.3", false),
new ResultPair(".1.2.3.4", false),
new ResultPair("go.a", false),
new ResultPair("go.a1a", false),
new ResultPair("go.cc", true),
new ResultPair("go.1aa", false),
new ResultPair("aaa.", false),
new ResultPair(".aaa", false),
new ResultPair("aaa", false),
new ResultPair("", false)
};
ResultPair[] testUrlPort = {new ResultPair(":80", true),
new ResultPair(":65535", true), // max possible
new ResultPair(":65536", false), // max possible +1
new ResultPair(":0", true),
new ResultPair("", true),
new ResultPair(":-1", false),
new ResultPair(":65636", false),
new ResultPair(":999999999999999999", false),
new ResultPair(":65a", false)
};
ResultPair[] testPath = {new ResultPair("/test1", true),
new ResultPair("/t123", true),
new ResultPair("/$23", true),
new ResultPair("/..", false),
new ResultPair("/../", false),
new ResultPair("/test1/", true),
new ResultPair("", true),
new ResultPair("/test1/file", true),
new ResultPair("/..//file", false),
new ResultPair("/test1//file", false)
};
//Test allow2slash, noFragment
ResultPair[] testUrlPathOptions = {new ResultPair("/test1", true),
new ResultPair("/t123", true),
new ResultPair("/$23", true),
new ResultPair("/..", false),
new ResultPair("/../", false),
new ResultPair("/test1/", true),
new ResultPair("/#", false),
new ResultPair("", true),
new ResultPair("/test1/file", true),
new ResultPair("/t123/file", true),
new ResultPair("/$23/file", true),
new ResultPair("/../file", false),
new ResultPair("/..//file", false),
new ResultPair("/test1//file", true),
new ResultPair("/#/file", false)
};
ResultPair[] testUrlQuery = {new ResultPair("?action=view", true),
new ResultPair("?action=edit&mode=up", true),
new ResultPair("", true)
};
Object[] testUrlParts = {testUrlScheme, testUrlAuthority, testUrlPort, testPath, testUrlQuery};
Object[] testUrlPartsOptions = {testUrlScheme, testUrlAuthority, testUrlPort, testUrlPathOptions, testUrlQuery};
int[] testPartsIndex = {0, 0, 0, 0, 0};
//---------------- Test data for individual url parts ----------------
private final String[] schemes = {"http", "gopher", "g0-To+.",
"not_valid" // TODO this will need to be dropped if the ctor validates schemes
};
ResultPair[] testScheme = {new ResultPair("http", true),
new ResultPair("ftp", false),
new ResultPair("httpd", false),
new ResultPair("gopher", true),
new ResultPair("g0-to+.", true),
new ResultPair("not_valid", false), // underscore not allowed
new ResultPair("HtTp", true),
new ResultPair("telnet", false)};
/**
* Validator for checking URL parsing
* @param args - URLs to validate
*/
public static void main(final String[] args) {
final UrlValidator uv = new UrlValidator();
for(final String arg: args) {
try {
URI uri = new URI(arg);
uri = uri.normalize();
System.out.println(uri.toString());
System.out.printf("URI scheme: %s%n", uri.getScheme());
System.out.printf("URI scheme specific part: %s%n", uri.getSchemeSpecificPart());
System.out.printf("URI raw scheme specific part: %s%n", uri.getRawSchemeSpecificPart());
System.out.printf("URI auth: %s%n", uri.getAuthority());
System.out.printf("URI raw auth: %s%n", uri.getRawAuthority());
System.out.printf("URI userInfo: %s%n", uri.getUserInfo());
System.out.printf("URI raw userInfo: %s%n", uri.getRawUserInfo());
System.out.printf("URI host: %s%n", uri.getHost());
System.out.printf("URI port: %s%n", uri.getPort());
System.out.printf("URI path: %s%n", uri.getPath());
System.out.printf("URI raw path: %s%n", uri.getRawPath());
System.out.printf("URI query: %s%n", uri.getQuery());
System.out.printf("URI raw query: %s%n", uri.getRawQuery());
System.out.printf("URI fragment: %s%n", uri.getFragment());
System.out.printf("URI raw fragment: %s%n", uri.getRawFragment());
} catch (final URISyntaxException e) {
System.out.println(e.getMessage());
}
System.out.printf("isValid: %s%n",uv.isValid(arg));
}
}
}
| 7,908 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/LongValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.util.Locale;
/**
* Test Case for LongValidator.
*/
public class LongValidatorTest extends AbstractNumberValidatorTest {
private static final Long LONG_MIN_VAL = Long.valueOf(Long.MIN_VALUE);
private static final Long LONG_MAX_VAL = Long.valueOf(Long.MAX_VALUE);
private static final String LONG_MAX = "9223372036854775807";
private static final String LONG_MAX_0 = "9223372036854775807.99999999999999999999999"; // force double rounding
private static final String LONG_MAX_1 = "9223372036854775808";
private static final String LONG_MIN = "-9223372036854775808";
private static final String LONG_MIN_0 = "-9223372036854775808.99999999999999999999999"; // force double rounding
private static final String LONG_MIN_1 = "-9223372036854775809";
private static final String NINES = "9999999999999999999999999999999999999";
/**
* Constructor
* @param name test name
*/
public LongValidatorTest(final String name) {
super(name);
}
@Override
protected void setUp() {
super.setUp();
validator = new LongValidator(false, 0);
strictValidator = new LongValidator();
testPattern = "#,###";
// testValidateMinMax()
max = null;
maxPlusOne = null;
min = null;
minMinusOne = null;
// testInvalidStrict()
invalidStrict = new String[] {null, "", "X", "X12", "12X", "1X2", "1.2", LONG_MAX_1, LONG_MIN_1, NINES};
// testInvalidNotStrict()
invalid = new String[] {null, "", "X", "X12", "", LONG_MAX_1, LONG_MIN_1, NINES};
// testValid()
testNumber = Long.valueOf(1234);
testZero = Long.valueOf(0);
validStrict = new String[] {"0", "1234", "1,234", LONG_MAX, LONG_MIN};
validStrictCompare = new Number[] {testZero, testNumber, testNumber, LONG_MAX_VAL, LONG_MIN_VAL};
valid = new String[] {"0", "1234", "1,234", "1,234.5", "1234X", LONG_MAX, LONG_MIN, LONG_MAX_0, LONG_MIN_0};
validCompare = new Number[] {testZero, testNumber, testNumber, testNumber, testNumber, LONG_MAX_VAL, LONG_MIN_VAL, LONG_MAX_VAL, LONG_MIN_VAL};
testStringUS = "1,234";
testStringDE = "1.234";
// Localized Pattern test
localeValue = testStringDE;
localePattern = "#.###";
testLocale = Locale.GERMANY;
localeExpected = testNumber;
}
/**
* Test LongValidator validate Methods
*/
public void testLongValidatorMethods() {
final Locale locale = Locale.GERMAN;
final String pattern = "0,00,00";
final String patternVal = "1,23,45";
final String germanPatternVal = "1.23.45";
final String localeVal = "12.345";
final String defaultVal = "12,345";
final String XXXX = "XXXX";
final Long expected = Long.valueOf(12345);
assertEquals("validate(A) default", expected, LongValidator.getInstance().validate(defaultVal));
assertEquals("validate(A) locale ", expected, LongValidator.getInstance().validate(localeVal, locale));
assertEquals("validate(A) pattern", expected, LongValidator.getInstance().validate(patternVal, pattern));
assertEquals("validate(A) both", expected, LongValidator.getInstance().validate(germanPatternVal, pattern, Locale.GERMAN));
assertTrue("isValid(A) default", LongValidator.getInstance().isValid(defaultVal));
assertTrue("isValid(A) locale ", LongValidator.getInstance().isValid(localeVal, locale));
assertTrue("isValid(A) pattern", LongValidator.getInstance().isValid(patternVal, pattern));
assertTrue("isValid(A) both", LongValidator.getInstance().isValid(germanPatternVal, pattern, Locale.GERMAN));
assertNull("validate(B) default", LongValidator.getInstance().validate(XXXX));
assertNull("validate(B) locale ", LongValidator.getInstance().validate(XXXX, locale));
assertNull("validate(B) pattern", LongValidator.getInstance().validate(XXXX, pattern));
assertNull("validate(B) both", LongValidator.getInstance().validate(patternVal, pattern, Locale.GERMAN));
assertFalse("isValid(B) default", LongValidator.getInstance().isValid(XXXX));
assertFalse("isValid(B) locale ", LongValidator.getInstance().isValid(XXXX, locale));
assertFalse("isValid(B) pattern", LongValidator.getInstance().isValid(XXXX, pattern));
assertFalse("isValid(B) both", LongValidator.getInstance().isValid(patternVal, pattern, Locale.GERMAN));
}
/**
* Test Long Range/Min/Max
*/
public void testLongRangeMinMax() {
final LongValidator validator = (LongValidator)strictValidator;
final Long number9 = validator.validate("9", "#");
final Long number10 = validator.validate("10", "#");
final Long number11 = validator.validate("11", "#");
final Long number19 = validator.validate("19", "#");
final Long number20 = validator.validate("20", "#");
final Long number21 = validator.validate("21", "#");
// Test isInRange()
assertFalse("isInRange() < min", validator.isInRange(number9, 10, 20));
assertTrue("isInRange() = min", validator.isInRange(number10, 10, 20));
assertTrue("isInRange() in range", validator.isInRange(number11, 10, 20));
assertTrue("isInRange() = max", validator.isInRange(number20, 10, 20));
assertFalse("isInRange() > max", validator.isInRange(number21, 10, 20));
// Test minValue()
assertFalse("minValue() < min", validator.minValue(number9, 10));
assertTrue("minValue() = min", validator.minValue(number10, 10));
assertTrue("minValue() > min", validator.minValue(number11, 10));
// Test minValue()
assertTrue("maxValue() < max", validator.maxValue(number19, 20));
assertTrue("maxValue() = max", validator.maxValue(number20, 20));
assertFalse("maxValue() > max", validator.maxValue(number21, 20));
}
}
| 7,909 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/RegexValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import junit.framework.TestCase;
/**
* Test Case for RegexValidatorTest.
*
* @since 1.4
*/
public class RegexValidatorTest extends TestCase {
private static final String REGEX = "^([abc]*)(?:\\-)([DEF]*)(?:\\-)([123]*)$";
private static final String COMPONENT_1 = "([abc]{3})";
private static final String COMPONENT_2 = "([DEF]{3})";
private static final String COMPONENT_3 = "([123]{3})";
private static final String SEPARATOR_1 = "(?:\\-)";
private static final String SEPARATOR_2 = "(?:\\s)";
private static final String REGEX_1 = "^" + COMPONENT_1 + SEPARATOR_1 + COMPONENT_2 + SEPARATOR_1 + COMPONENT_3 + "$";
private static final String REGEX_2 = "^" + COMPONENT_1 + SEPARATOR_2 + COMPONENT_2 + SEPARATOR_2 + COMPONENT_3 + "$";
private static final String REGEX_3 = "^" + COMPONENT_1 + COMPONENT_2 + COMPONENT_3 + "$";
private static final String[] MULTIPLE_REGEX = {REGEX_1, REGEX_2, REGEX_3};
/**
* Constrct a new test case.
* @param name The name of the test
*/
public RegexValidatorTest(final String name) {
super(name);
}
/**
* Compare two arrays
* @param label Label for the test
* @param expect Expected array
* @param result Actual array
*/
private void checkArray(final String label, final String[] expect, final String[] result) {
// Handle nulls
if (expect == null || result == null) {
if (expect == null && result == null) {
return; // valid, both null
}
fail(label + " Null expect=" + expect + " result=" + result);
return; // not strictly necessary, but prevents possible NPE below
}
// Check Length
if (expect.length != result.length) {
fail(label + " Length expect=" + expect.length + " result=" + result.length);
}
// Check Values
for (int i = 0; i < expect.length; i++) {
assertEquals(label +" value[" + i + "]", expect[i], result[i]);
}
}
/**
* Test exceptions
*/
public void testExceptions() {
final String invalidRegex = "^([abCD12]*$";
try {
new RegexValidator(invalidRegex);
} catch (final PatternSyntaxException e) {
// expected
}
}
public void testGetPatterns() {
final RegexValidator regexValidator = new RegexValidator(MULTIPLE_REGEX);
assertNotSame(regexValidator.getPatterns(), regexValidator.getPatterns());
final Pattern[] patterns = regexValidator.getPatterns();
assertEquals(REGEX_1, patterns[0].pattern());
assertEquals(REGEX_2, patterns[1].pattern());
assertEquals(REGEX_3, patterns[2].pattern());
}
/**
* Test exceptions
*/
public void testMissingRegex() {
// Single Regular Expression - null
try {
new RegexValidator((String) null);
fail("Single Null - expected IllegalArgumentException");
} catch (final IllegalArgumentException e) {
assertEquals("Single Null", "Regular expression[0] is missing", e.getMessage());
}
// Single Regular Expression - Zero Length
try {
new RegexValidator("");
fail("Single Zero Length - expected IllegalArgumentException");
} catch (final IllegalArgumentException e) {
assertEquals("Single Zero Length", "Regular expression[0] is missing", e.getMessage());
}
// Multiple Regular Expression - Null array
try {
new RegexValidator((String[]) null);
fail("Null Array - expected IllegalArgumentException");
} catch (final IllegalArgumentException e) {
assertEquals("Null Array", "Regular expressions are missing", e.getMessage());
}
// Multiple Regular Expression - Zero Length array
try {
new RegexValidator();
fail("Zero Length Array - expected IllegalArgumentException");
} catch (final IllegalArgumentException e) {
assertEquals("Zero Length Array", "Regular expressions are missing", e.getMessage());
}
// Multiple Regular Expression - Array has Null
String[] expressions = { "ABC", null };
try {
new RegexValidator(expressions);
fail("Array has Null - expected IllegalArgumentException");
} catch (final IllegalArgumentException e) {
assertEquals("Array has Null", "Regular expression[1] is missing", e.getMessage());
}
// Multiple Regular Expression - Array has Zero Length
expressions = new String[] { "", "ABC" };
try {
new RegexValidator(expressions);
fail("Array has Zero Length - expected IllegalArgumentException");
} catch (final IllegalArgumentException e) {
assertEquals("Array has Zero Length", "Regular expression[0] is missing", e.getMessage());
}
}
/**
* Test with multiple regular expressions (case in-sensitive).
*/
public void testMultipleInsensitive() {
// ------------ Set up In-sensitive Validators
final RegexValidator multiple = new RegexValidator(MULTIPLE_REGEX, false);
final RegexValidator single1 = new RegexValidator(REGEX_1, false);
final RegexValidator single2 = new RegexValidator(REGEX_2, false);
final RegexValidator single3 = new RegexValidator(REGEX_3, false);
// ------------ Set up test values
String value = "AAC FDE 321";
final String expect = "AACFDE321";
final String[] array = {"AAC", "FDE", "321"};
// isValid()
assertEquals("isValid() Multiple", true, multiple.isValid(value));
assertEquals("isValid() 1st", false, single1.isValid(value));
assertEquals("isValid() 2nd", true, single2.isValid(value));
assertEquals("isValid() 3rd", false, single3.isValid(value));
// validate()
assertEquals("validate() Multiple", expect, multiple.validate(value));
assertEquals("validate() 1st", null, single1.validate(value));
assertEquals("validate() 2nd", expect, single2.validate(value));
assertEquals("validate() 3rd", null, single3.validate(value));
// match()
checkArray("match() Multiple", array, multiple.match(value));
checkArray("match() 1st", null, single1.match(value));
checkArray("match() 2nd", array, single2.match(value));
checkArray("match() 3rd", null, single3.match(value));
// All invalid
value = "AAC*FDE*321";
assertEquals("isValid() Invalid", false, multiple.isValid(value));
assertEquals("validate() Invalid", null, multiple.validate(value));
assertEquals("match() Multiple", null, multiple.match(value));
}
/**
* Test with multiple regular expressions (case sensitive).
*/
public void testMultipleSensitive() {
// ------------ Set up Sensitive Validators
final RegexValidator multiple = new RegexValidator(MULTIPLE_REGEX);
final RegexValidator single1 = new RegexValidator(REGEX_1);
final RegexValidator single2 = new RegexValidator(REGEX_2);
final RegexValidator single3 = new RegexValidator(REGEX_3);
// ------------ Set up test values
String value = "aac FDE 321";
final String expect = "aacFDE321";
final String[] array = {"aac", "FDE", "321"};
// isValid()
assertEquals("Sensitive isValid() Multiple", true, multiple.isValid(value));
assertEquals("Sensitive isValid() 1st", false, single1.isValid(value));
assertEquals("Sensitive isValid() 2nd", true, single2.isValid(value));
assertEquals("Sensitive isValid() 3rd", false, single3.isValid(value));
// validate()
assertEquals("Sensitive validate() Multiple", expect, multiple.validate(value));
assertEquals("Sensitive validate() 1st", null, single1.validate(value));
assertEquals("Sensitive validate() 2nd", expect, single2.validate(value));
assertEquals("Sensitive validate() 3rd", null, single3.validate(value));
// match()
checkArray("Sensitive match() Multiple", array, multiple.match(value));
checkArray("Sensitive match() 1st", null, single1.match(value));
checkArray("Sensitive match() 2nd", array, single2.match(value));
checkArray("Sensitive match() 3rd", null, single3.match(value));
// All invalid
value = "AAC*FDE*321";
assertEquals("isValid() Invalid", false, multiple.isValid(value));
assertEquals("validate() Invalid", null, multiple.validate(value));
assertEquals("match() Multiple", null, multiple.match(value));
}
/**
* Test Null value
*/
public void testNullValue() {
final RegexValidator validator = new RegexValidator(REGEX);
assertEquals("Instance isValid()", false, validator.isValid(null));
assertEquals("Instance validate()", null, validator.validate(null));
assertEquals("Instance match()", null, validator.match(null));
}
/**
* Test instance methods with single regular expression.
*/
public void testSingle() {
final RegexValidator sensitive = new RegexValidator(REGEX);
final RegexValidator insensitive = new RegexValidator(REGEX, false);
// isValid()
assertEquals("Sensitive isValid() valid", true, sensitive.isValid("ac-DE-1"));
assertEquals("Sensitive isValid() invalid", false, sensitive.isValid("AB-de-1"));
assertEquals("Insensitive isValid() valid", true, insensitive.isValid("AB-de-1"));
assertEquals("Insensitive isValid() invalid", false, insensitive.isValid("ABd-de-1"));
// validate()
assertEquals("Sensitive validate() valid", "acDE1", sensitive.validate("ac-DE-1"));
assertEquals("Sensitive validate() invalid", null, sensitive.validate("AB-de-1"));
assertEquals("Insensitive validate() valid", "ABde1", insensitive.validate("AB-de-1"));
assertEquals("Insensitive validate() invalid", null, insensitive.validate("ABd-de-1"));
// match()
checkArray("Sensitive match() valid", new String[] {"ac", "DE", "1"}, sensitive.match("ac-DE-1"));
checkArray("Sensitive match() invalid", null, sensitive.match("AB-de-1"));
checkArray("Insensitive match() valid", new String[] {"AB", "de", "1"}, insensitive.match("AB-de-1"));
checkArray("Insensitive match() invalid", null, insensitive.match("ABd-de-1"));
assertEquals("validate one", "ABC", new RegexValidator("^([A-Z]*)$").validate("ABC"));
checkArray("match one", new String[] {"ABC"}, new RegexValidator("^([A-Z]*)$").match("ABC"));
}
/**
* Test toString() method
*/
public void testToString() {
final RegexValidator single = new RegexValidator(REGEX);
assertEquals("Single", "RegexValidator{" + REGEX + "}", single.toString());
final RegexValidator multiple = new RegexValidator(REGEX, REGEX);
assertEquals("Multiple", "RegexValidator{" + REGEX + "," + REGEX + "}", multiple.toString());
}
}
| 7,910 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/ISSNValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.util.Random;
import org.apache.commons.validator.routines.checkdigit.CheckDigit;
import org.apache.commons.validator.routines.checkdigit.EAN13CheckDigit;
import junit.framework.TestCase;
/**
* ISSNValidator Test Case.
*
* @since 1.5.0
*/
public class ISSNValidatorTest extends TestCase {
private static final ISSNValidator VALIDATOR = ISSNValidator.getInstance();
private final String[] validFormat = {
"ISSN 0317-8471",
"1050-124X",
"ISSN 1562-6865",
"1063-7710",
"1748-7188",
"ISSN 0264-2875",
"1750-0095",
"1188-1534",
"1911-1479",
"ISSN 1911-1460",
"0001-6772",
"1365-201X",
"0264-3596",
"1144-875X",
};
private final String[] invalidFormat = {
"", // empty
" ", // empty
"ISBN 0317-8471", // wrong prefix
"'1050-124X", // leading garbage
"ISSN1562-6865", // missing separator
"10637710", // missing separator
"1748-7188'", // trailing garbage
"ISSN 0264-2875", // extra space
"1750 0095", // invalid separator
"1188_1534", // invalid separator
"1911-1478", // invalid checkdigit
};
/**
* Create a test case with the specified name.
* @param name The name of the test
*/
public ISSNValidatorTest(final String name) {
super(name);
}
/**
* Test isValid() ISSN codes
*/
public void testIsValidISSN() {
for(final String f : validFormat) {
assertTrue(f, VALIDATOR.isValid(f));
}
}
/**
* Test null values
*/
public void testNull() {
assertFalse("isValid", VALIDATOR.isValid(null));
}
/**
* Test Invalid ISSN codes
*/
public void testInvalid() {
for(final String f : invalidFormat) {
assertFalse(f, VALIDATOR.isValid(f));
}
}
public void testIsValidISSNConvertNull() {
assertNull(VALIDATOR.convertToEAN13(null, "00"));
}
public void testIsValidISSNConvertSuffix() {
try {
assertNull(VALIDATOR.convertToEAN13(null, null));
fail("Expected IllegalArgumentException");
} catch (final IllegalArgumentException expected) {
}
try {
assertNull(VALIDATOR.convertToEAN13(null, ""));
fail("Expected IllegalArgumentException");
} catch (final IllegalArgumentException expected) {
}
try {
assertNull(VALIDATOR.convertToEAN13(null, "0"));
fail("Expected IllegalArgumentException");
} catch (final IllegalArgumentException expected) {
}
try {
assertNull(VALIDATOR.convertToEAN13(null, "A"));
fail("Expected IllegalArgumentException");
} catch (final IllegalArgumentException expected) {
}
try {
assertNull(VALIDATOR.convertToEAN13(null, "AA"));
fail("Expected IllegalArgumentException");
} catch (final IllegalArgumentException expected) {
}
try {
assertNull(VALIDATOR.convertToEAN13(null, "999"));
fail("Expected IllegalArgumentException");
} catch (final IllegalArgumentException expected) {
}
}
/**
* Test isValid() ISSN codes and convert them
*/
public void testIsValidISSNConvert() {
final CheckDigit ean13cd = EAN13CheckDigit.EAN13_CHECK_DIGIT;
final Random r = new Random();
for(final String f : validFormat) {
final String suffix = String.format("%02d", r.nextInt(100));
final String ean13 = VALIDATOR.convertToEAN13(f, suffix);
assertTrue(ean13, ean13cd.isValid(ean13));
}
// internet samples
assertEquals("9771144875007", VALIDATOR.convertToEAN13("1144-875X", "00"));
assertEquals("9770264359008", VALIDATOR.convertToEAN13("0264-3596", "00"));
assertEquals("9771234567003", VALIDATOR.convertToEAN13("1234-5679", "00"));
}
/**
* Test Invalid EAN-13 ISSN prefix codes
* Test Input length
*/
public void testConversionErrors() {
String input = null;
try {
input = "9780072129519";
VALIDATOR.extractFromEAN13(input);
fail("Expected IllegalArgumentException for '" + input + "'");
} catch (final IllegalArgumentException e) {
// expected result
}
try {
input = "9791090636071";
VALIDATOR.extractFromEAN13(input);
fail("Expected IllegalArgumentException for '" + input + "'");
} catch (final IllegalArgumentException e) {
// expected result
}
try {
input = "03178471";
VALIDATOR.extractFromEAN13(input);
fail("Expected IllegalArgumentException for '" + input + "'");
} catch (final IllegalArgumentException e) {
// expected result
}
}
/**
* Test Invalid EAN-13 ISSN codes
*/
public void testValidCheckDigitEan13() {
assertNull(VALIDATOR.extractFromEAN13("9771234567001"));
assertNull(VALIDATOR.extractFromEAN13("9771234567002"));
assertNotNull(VALIDATOR.extractFromEAN13("9771234567003")); // valid check digit
assertNull(VALIDATOR.extractFromEAN13("9771234567004"));
assertNull(VALIDATOR.extractFromEAN13("9771234567005"));
assertNull(VALIDATOR.extractFromEAN13("9771234567006"));
assertNull(VALIDATOR.extractFromEAN13("9771234567007"));
assertNull(VALIDATOR.extractFromEAN13("9771234567008"));
assertNull(VALIDATOR.extractFromEAN13("9771234567009"));
assertNull(VALIDATOR.extractFromEAN13("9771234567000"));
}
/**
* Test valid EAN-13 ISSN codes and extract the ISSN
*/
public void testIsValidExtract() {
assertEquals("12345679", VALIDATOR.extractFromEAN13("9771234567003"));
assertEquals("00014664", VALIDATOR.extractFromEAN13("9770001466006"));
assertEquals("03178471", VALIDATOR.extractFromEAN13("9770317847001"));
assertEquals("1144875X", VALIDATOR.extractFromEAN13("9771144875007"));
}
}
| 7,911 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/ISINValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import junit.framework.TestCase;
/**
* ISINValidator Test Case.
*
* @since 1.7
*/
public class ISINValidatorTest extends TestCase {
private static final ISINValidator VALIDATOR_TRUE = ISINValidator.getInstance(true);
private static final ISINValidator VALIDATOR_FALSE = ISINValidator.getInstance(false);
private final String[] validFormat = {
"US0378331005",
"BMG8571G1096",
"AU0000XVGZA3",
"GB0002634946",
"FR0004026250",
"DK0009763344",
"GB00B03MLX29",
"US7562071065",
"US56845T3059",
"LU0327357389",
"US032511BN64",
"INE112A01023",
"EZ0000000003", // Invented; for use in ISINValidator
"XS0000000009",
};
private final String[] invalidFormat = {
null,
"", // empty
" ", // empty
"US037833100O", // proper check digit is '5', see above
"BMG8571G109D", // proper check digit is '6', see above
"AU0000XVGZAD", // proper check digit is '3', see above
"GB000263494I", // proper check digit is '6', see above
"FR000402625C", // proper check digit is '0', see above
"DK000976334H", // proper check digit is '4', see above
"3133EHHF3", // see VALIDATOR-422 Valid check-digit, but not valid ISIN
"AU0000xvgzA3", // disallow lower case NSIN
"gb0002634946", // disallow lower case ISO code
};
// Invalid codes if country checking is enabled
private final String[] invalidFormatTrue = {
"AA0000000006", // Invalid country code
};
public ISINValidatorTest(final String name) {
super(name);
}
public void testIsValidTrue() {
for(final String f : validFormat) {
assertTrue(f, VALIDATOR_TRUE.isValid(f));
}
}
public void testInvalidTrue() {
for(final String f : invalidFormat) {
assertFalse(f, VALIDATOR_TRUE.isValid(f));
}
for(final String f : invalidFormatTrue) {
assertFalse(f, VALIDATOR_TRUE.isValid(f));
}
}
public void testIsValidFalse() {
for(final String f : validFormat) {
assertTrue(f, VALIDATOR_FALSE.isValid(f));
}
}
public void testInvalidFalse() {
for(final String f : invalidFormat) {
assertFalse(f, VALIDATOR_FALSE.isValid(f));
}
}
}
| 7,912 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/BigIntegerValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.math.BigInteger;
import java.util.Locale;
/**
* Test Case for BigIntegerValidator.
*/
public class BigIntegerValidatorTest extends AbstractNumberValidatorTest {
/**
* Constructor
* @param name test name
*/
public BigIntegerValidatorTest(final String name) {
super(name);
}
@Override
protected void setUp() {
super.setUp();
validator = new BigIntegerValidator(false, 0);
strictValidator = new BigIntegerValidator();
testPattern = "#,###";
// testValidateMinMax()
max = null;
maxPlusOne = null;
min = null;
minMinusOne = null;
// testInvalidStrict()
invalidStrict = new String[] {null, "", "X", "X12", "12X", "1X2", "1.2"};
// testInvalidNotStrict()
invalid = new String[] {null, "", "X", "X12"};
// testValid()
testNumber = new BigInteger("1234");
testZero = new BigInteger("0");
validStrict = new String[] {"0", "1234", "1,234"};
validStrictCompare = new Number[] {testZero, testNumber, testNumber};
valid = new String[] {"0", "1234", "1,234", "1,234.5", "1234X"};
validCompare = new Number[] {testZero, testNumber, testNumber, testNumber, testNumber};
testStringUS = "1,234";
testStringDE = "1.234";
// Localized Pattern test
localeValue = testStringDE;
localePattern = "#.###";
testLocale = Locale.GERMANY;
localeExpected = testNumber;
}
/**
* Test BigIntegerValidator validate Methods
*/
public void testBigIntegerValidatorMethods() {
final Locale locale = Locale.GERMAN;
final String pattern = "0,00,00";
final String patternVal = "1,23,45";
final String germanPatternVal = "1.23.45";
final String localeVal = "12.345";
final String defaultVal = "12,345";
final String XXXX = "XXXX";
final BigInteger expected = new BigInteger("12345");
assertEquals("validate(A) default", expected, BigIntegerValidator.getInstance().validate(defaultVal));
assertEquals("validate(A) locale ", expected, BigIntegerValidator.getInstance().validate(localeVal, locale));
assertEquals("validate(A) pattern", expected, BigIntegerValidator.getInstance().validate(patternVal, pattern));
assertEquals("validate(A) both", expected, BigIntegerValidator.getInstance().validate(germanPatternVal, pattern, Locale.GERMAN));
assertTrue("isValid(A) default", BigIntegerValidator.getInstance().isValid(defaultVal));
assertTrue("isValid(A) locale ", BigIntegerValidator.getInstance().isValid(localeVal, locale));
assertTrue("isValid(A) pattern", BigIntegerValidator.getInstance().isValid(patternVal, pattern));
assertTrue("isValid(A) both", BigIntegerValidator.getInstance().isValid(germanPatternVal, pattern, Locale.GERMAN));
assertNull("validate(B) default", BigIntegerValidator.getInstance().validate(XXXX));
assertNull("validate(B) locale ", BigIntegerValidator.getInstance().validate(XXXX, locale));
assertNull("validate(B) pattern", BigIntegerValidator.getInstance().validate(XXXX, pattern));
assertNull("validate(B) both", BigIntegerValidator.getInstance().validate(patternVal, pattern, Locale.GERMAN));
assertFalse("isValid(B) default", BigIntegerValidator.getInstance().isValid(XXXX));
assertFalse("isValid(B) locale ", BigIntegerValidator.getInstance().isValid(XXXX, locale));
assertFalse("isValid(B) pattern", BigIntegerValidator.getInstance().isValid(XXXX, pattern));
assertFalse("isValid(B) both", BigIntegerValidator.getInstance().isValid(patternVal, pattern, Locale.GERMAN));
}
/**
* Test BigInteger Range/Min/Max
*/
public void testBigIntegerRangeMinMax() {
final BigIntegerValidator validator = (BigIntegerValidator)strictValidator;
final BigInteger number9 = validator.validate("9", "#");
final BigInteger number10 = validator.validate("10", "#");
final BigInteger number11 = validator.validate("11", "#");
final BigInteger number19 = validator.validate("19", "#");
final BigInteger number20 = validator.validate("20", "#");
final BigInteger number21 = validator.validate("21", "#");
// Test isInRange()
assertFalse("isInRange() < min", validator.isInRange(number9, 10, 20));
assertTrue("isInRange() = min", validator.isInRange(number10, 10, 20));
assertTrue("isInRange() in range", validator.isInRange(number11, 10, 20));
assertTrue("isInRange() = max", validator.isInRange(number20, 10, 20));
assertFalse("isInRange() > max", validator.isInRange(number21, 10, 20));
// Test minValue()
assertFalse("minValue() < min", validator.minValue(number9, 10));
assertTrue("minValue() = min", validator.minValue(number10, 10));
assertTrue("minValue() > min", validator.minValue(number11, 10));
// Test minValue()
assertTrue("maxValue() < max", validator.maxValue(number19, 20));
assertTrue("maxValue() = max", validator.maxValue(number20, 20));
assertFalse("maxValue() > max", validator.maxValue(number21, 20));
}
}
| 7,913 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/DomainValidatorStartupTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.validator.routines.DomainValidator.ArrayType;
import org.bitstrings.test.junit.runner.ClassLoaderPerTestRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Startup Tests for the DomainValidator.
*/
@RunWith(ClassLoaderPerTestRunner.class)
public class DomainValidatorStartupTest {
@Test
public void testUpdateBaseArrayCC() {
final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class,
() -> DomainValidator.updateTLDOverride(ArrayType.COUNTRY_CODE_RO, "com"));
assertThat(thrown.getMessage(), is(equalTo("Cannot update the table: COUNTRY_CODE_RO")));
}
@Test
public void testUpdateBaseArrayGeneric() {
final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class,
() -> DomainValidator.updateTLDOverride(ArrayType.GENERIC_RO, "com"));
assertThat(thrown.getMessage(), is(equalTo("Cannot update the table: GENERIC_RO")));
}
@Test
public void testUpdateBaseArrayInfra() {
final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class,
() -> DomainValidator.updateTLDOverride(ArrayType.INFRASTRUCTURE_RO, "com"));
assertThat(thrown.getMessage(), is(equalTo("Cannot update the table: INFRASTRUCTURE_RO")));
}
@Test
public void testUpdateBaseArrayLocal() {
final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class,
() -> DomainValidator.updateTLDOverride(ArrayType.LOCAL_RO, "com"));
assertThat(thrown.getMessage(), is(equalTo("Cannot update the table: LOCAL_RO")));
}
@Test
public void testUpdateCountryCode1a() {
final DomainValidator validator = DomainValidator.getInstance();
assertFalse(validator.isValidCountryCodeTld("com")); // cannot be valid
}
@Test
public void testUpdateCountryCode1b() {
DomainValidator.updateTLDOverride(ArrayType.COUNTRY_CODE_PLUS, "com");
final DomainValidator validator = DomainValidator.getInstance();
assertTrue(validator.isValidCountryCodeTld("com")); // it is now!
}
@Test
public void testUpdateCountryCode2() {
DomainValidator.updateTLDOverride(ArrayType.COUNTRY_CODE_PLUS, "com");
DomainValidator.updateTLDOverride(ArrayType.COUNTRY_CODE_MINUS, "com");
final DomainValidator validator = DomainValidator.getInstance();
assertFalse(validator.isValidCountryCodeTld("com")); // show that minus overrides the rest
}
@Test
public void testUpdateCountryCode3a() { // show ch is valid
final DomainValidator validator = DomainValidator.getInstance();
assertTrue(validator.isValidCountryCodeTld("ch"));
}
@Test
public void testUpdateCountryCode3b() { // show ch can be made invalid
DomainValidator.updateTLDOverride(ArrayType.COUNTRY_CODE_MINUS, "ch");
final DomainValidator validator = DomainValidator.getInstance();
assertFalse(validator.isValidCountryCodeTld("ch"));
}
@Test
public void testUpdateCountryCode3c() { // show ch can be made valid again by replacing the CC array
DomainValidator.updateTLDOverride(ArrayType.COUNTRY_CODE_MINUS, "ch");
DomainValidator.updateTLDOverride(ArrayType.COUNTRY_CODE_MINUS, "xx");
final DomainValidator validator = DomainValidator.getInstance();
assertTrue(validator.isValidCountryCodeTld("ch"));
}
@Test
public void testUpdateGeneric1() {
final DomainValidator validator = DomainValidator.getInstance();
assertFalse(validator.isValidGenericTld("ch")); // cannot be valid
}
@Test
public void testUpdateGeneric2() {
DomainValidator.updateTLDOverride(ArrayType.GENERIC_PLUS, "ch");
final DomainValidator validator = DomainValidator.getInstance();
assertTrue(validator.isValidGenericTld("ch")); // it is now!
}
@Test
public void testUpdateGeneric3() {
DomainValidator.updateTLDOverride(ArrayType.GENERIC_PLUS, "ch");
DomainValidator.updateTLDOverride(ArrayType.GENERIC_MINUS, "ch");
final DomainValidator validator = DomainValidator.getInstance();
assertFalse(validator.isValidGenericTld("ch")); // show that minus overrides the rest
assertTrue(validator.isValidGenericTld("com"));
}
@Test
public void testUpdateGeneric4() {
DomainValidator.updateTLDOverride(ArrayType.GENERIC_PLUS, "ch");
DomainValidator.updateTLDOverride(ArrayType.GENERIC_MINUS, "ch");
DomainValidator.updateTLDOverride(ArrayType.GENERIC_MINUS, "com");
final DomainValidator validator = DomainValidator.getInstance();
assertFalse(validator.isValidGenericTld("com"));
}
@Test
public void testUpdateGeneric5() {
DomainValidator.updateTLDOverride(ArrayType.GENERIC_PLUS, "ch");
DomainValidator.updateTLDOverride(ArrayType.GENERIC_MINUS, "ch");
DomainValidator.updateTLDOverride(ArrayType.GENERIC_MINUS, "com");
DomainValidator.updateTLDOverride(ArrayType.GENERIC_MINUS, "xx"); // change the minus list
final DomainValidator validator = DomainValidator.getInstance();
assertTrue(validator.isValidGenericTld("com"));
}
@Test
public void testVALIDATOR_412a() {
final DomainValidator validator = DomainValidator.getInstance();
assertFalse(validator.isValidGenericTld("local"));
assertFalse(validator.isValid("abc.local"));
assertFalse(validator.isValidGenericTld("pvt"));
assertFalse(validator.isValid("abc.pvt"));
}
@Test
public void testVALIDATOR_412b() {
DomainValidator.updateTLDOverride(ArrayType.GENERIC_PLUS, "local", "pvt");
final DomainValidator validator = DomainValidator.getInstance();
assertTrue(validator.isValidGenericTld("local"));
assertTrue(validator.isValid("abc.local"));
assertTrue(validator.isValidGenericTld("pvt"));
assertTrue(validator.isValid("abc.pvt"));
}
@Test
public void testVALIDATOR_412c() {
final DomainValidator validator = DomainValidator.getInstance(true);
assertFalse(validator.isValidLocalTld("local"));
assertFalse(validator.isValid("abc.local"));
assertFalse(validator.isValidLocalTld("pvt"));
assertFalse(validator.isValid("abc.pvt"));
}
@Test
public void testVALIDATOR_412d() {
DomainValidator.updateTLDOverride(ArrayType.LOCAL_PLUS, "local", "pvt");
final DomainValidator validator = DomainValidator.getInstance(true);
assertTrue(validator.isValidLocalTld("local"));
assertTrue(validator.isValidLocalTld("pvt"));
assertTrue(validator.isValid("abc.local"));
assertTrue(validator.isValid("abc.pvt"));
}
@Test
public void testCannotUpdate() {
DomainValidator.updateTLDOverride(ArrayType.GENERIC_PLUS, "ch"); // OK
final DomainValidator dv = DomainValidator.getInstance();
assertNotNull(dv);
try {
DomainValidator.updateTLDOverride(ArrayType.GENERIC_PLUS, "ch");
fail("Expected IllegalStateException");
} catch (final IllegalStateException ise) {
// expected
}
}
@Test
public void testInstanceOverride() { // Show that the instance picks up static values
DomainValidator.updateTLDOverride(ArrayType.GENERIC_PLUS, "gp");
DomainValidator.updateTLDOverride(ArrayType.GENERIC_MINUS, "com");
DomainValidator.updateTLDOverride(ArrayType.COUNTRY_CODE_PLUS, "cp");
DomainValidator.updateTLDOverride(ArrayType.COUNTRY_CODE_MINUS, "ch");
DomainValidator validator = DomainValidator.getInstance(false);
assertTrue(validator.isValidGenericTld("gp"));
assertFalse(validator.isValidGenericTld("com"));
assertTrue(validator.isValidCountryCodeTld("cp"));
assertFalse(validator.isValidCountryCodeTld("ch"));
// show we can override them for a new instance
final List<DomainValidator.Item> items = new ArrayList<>();
items.add(new DomainValidator.Item(ArrayType.GENERIC_MINUS, "" ));
items.add(new DomainValidator.Item(ArrayType.COUNTRY_CODE_MINUS, ""));
validator = DomainValidator.getInstance(false, items);
assertTrue(validator.isValidGenericTld("gp"));
assertTrue(validator.isValidGenericTld("com")); // Should be true again
assertTrue(validator.isValidCountryCodeTld("cp"));
assertTrue(validator.isValidCountryCodeTld("ch")); // Should be true again
// Show the class overrides are unaffected
validator = DomainValidator.getInstance(false);
assertTrue(validator.isValidGenericTld("gp"));
assertFalse(validator.isValidGenericTld("com"));
assertTrue(validator.isValidCountryCodeTld("cp"));
assertFalse(validator.isValidCountryCodeTld("ch"));
}
}
| 7,914 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/AbstractCalendarValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import junit.framework.TestCase;
/**
* Base Calendar Test Case.
*/
public abstract class AbstractCalendarValidatorTest extends TestCase {
protected AbstractCalendarValidator validator;
protected static final TimeZone GMT = TimeZone.getTimeZone("GMT"); // 0 offset
protected static final TimeZone EST = TimeZone.getTimeZone("EST"); // - 5 hours
protected static final TimeZone EET = TimeZone.getTimeZone("EET"); // + 2 hours
protected static final TimeZone UTC = TimeZone.getTimeZone("UTC"); // + 2 hours
protected String[] patternValid = {
"2005-01-01"
,"2005-12-31"
,"2004-02-29" // valid leap
,"2005-04-30"
,"05-12-31"
,"2005-1-1"
,"05-1-1"};
protected String[] localeValid = {
"01/01/2005"
,"12/31/2005"
,"02/29/2004" // valid leap
,"04/30/2005"
,"12/31/05"
,"1/1/2005"
,"1/1/05"};
protected Date[] patternExpect = {
createDate(null, 20050101, 0)
,createDate(null, 20051231, 0)
,createDate(null, 20040229, 0)
,createDate(null, 20050430, 0)
,createDate(null, 20051231, 0)
,createDate(null, 20050101, 0)
,createDate(null, 20050101, 0)};
protected String[] patternInvalid = {
"2005-00-01" // zero month
,"2005-01-00" // zero day
,"2005-13-03" // month invalid
,"2005-04-31" // invalid day
,"2005-03-32" // invalid day
,"2005-02-29" // invalid leap
,"200X-01-01" // invalid char
,"2005-0X-01" // invalid char
,"2005-01-0X" // invalid char
,"01/01/2005" // invalid pattern
,"2005-01" // invalid pattern
,"2005--01" // invalid pattern
,"2005-01-"}; // invalid pattern
protected String[] localeInvalid = {
"01/00/2005" // zero month
,"00/01/2005" // zero day
,"13/01/2005" // month invalid
,"04/31/2005" // invalid day
,"03/32/2005" // invalid day
,"02/29/2005" // invalid leap
,"01/01/200X" // invalid char
,"01/0X/2005" // invalid char
,"0X/01/2005" // invalid char
,"01-01-2005" // invalid pattern
,"01/2005" // invalid pattern
// -------- ,"/01/2005" ---- passes on some JDK
,"01//2005"}; // invalid pattern
/**
* Constructor
* @param name test name
*/
public AbstractCalendarValidatorTest(final String name) {
super(name);
}
/**
* Tear down
*/
@Override
protected void tearDown() {
validator = null;
}
/**
* Test Valid Dates with "pattern" validation
*/
public void testPatternValid() {
for (int i = 0; i < patternValid.length; i++) {
final String text = i + " value=[" +patternValid[i]+"] failed ";
Object date = validator.parse(patternValid[i], "yy-MM-dd", null, null);
assertNotNull("validateObj() " + text + date, date);
assertTrue("isValid() " + text, validator.isValid(patternValid[i], "yy-MM-dd"));
if (date instanceof Calendar) {
date = ((Calendar)date).getTime();
}
assertEquals("compare " + text, patternExpect[i], date);
}
}
/**
* Test Invalid Dates with "pattern" validation
*/
public void testPatternInvalid() {
for (int i = 0; i < patternInvalid.length; i++) {
final String text = i + " value=[" +patternInvalid[i]+"] passed ";
final Object date = validator.parse(patternInvalid[i], "yy-MM-dd", null, null);
assertNull("validateObj() " + text + date, date);
assertFalse("isValid() " + text, validator.isValid(patternInvalid[i], "yy-MM-dd"));
}
}
/**
* Test Valid Dates with "locale" validation
*/
public void testLocaleValid() {
for (int i = 0; i < localeValid.length; i++) {
final String text = i + " value=[" +localeValid[i]+"] failed ";
Object date = validator.parse(localeValid[i], null, Locale.US, null);
assertNotNull("validateObj() " + text + date, date);
assertTrue("isValid() " + text, validator.isValid(localeValid[i], Locale.US));
if (date instanceof Calendar) {
date = ((Calendar)date).getTime();
}
assertEquals("compare " + text, patternExpect[i], date);
}
}
/**
* Test Invalid Dates with "locale" validation
*/
public void testLocaleInvalid() {
for (int i = 0; i < localeInvalid.length; i++) {
final String text = i + " value=[" +localeInvalid[i]+"] passed ";
final Object date = validator.parse(localeInvalid[i], null, Locale.US, null);
assertNull("validateObj() " + text + date, date);
assertFalse("isValid() " + text, validator.isValid(localeInvalid[i], Locale.US));
}
}
/**
* Test Invalid Dates with "locale" validation
*/
public void testFormat() {
// Create a Date or Calendar
final Object test = validator.parse("2005-11-28", "yyyy-MM-dd", null, null);
assertNotNull("Test Date ", test);
assertEquals("Format pattern", "28.11.05", validator.format(test, "dd.MM.yy"));
assertEquals("Format locale", "11/28/05", validator.format(test, Locale.US));
}
/**
* Test validator serialization.
*/
public void testSerialization() {
// Serialize the check digit routine
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
final ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(validator);
oos.flush();
oos.close();
} catch (final Exception e) {
fail(validator.getClass().getName() + " error during serialization: " + e);
}
// Deserialize the test object
Object result = null;
try {
final ByteArrayInputStream bais =
new ByteArrayInputStream(baos.toByteArray());
final ObjectInputStream ois = new ObjectInputStream(bais);
result = ois.readObject();
bais.close();
} catch (final Exception e) {
fail(validator.getClass().getName() + " error during deserialization: " + e);
}
assertNotNull(result);
}
/**
* Create a calendar instance for a specified time zone, date and time.
*
* @param zone The time zone
* @param date The date in yyyyMMdd format
* @param time the time in HH:mm:ss format
* @return the new Calendar instance.
*/
protected static Calendar createCalendar(final TimeZone zone, final int date, final int time) {
final Calendar calendar = zone == null ? Calendar.getInstance()
: Calendar.getInstance(zone);
final int year = date / 10000 * 10000;
final int mth = date / 100 * 100 - year;
final int day = date - (year + mth);
final int hour = time / 10000 * 10000;
final int min = time / 100 * 100 - hour;
final int sec = time - (hour + min);
calendar.set(Calendar.YEAR, year / 10000);
calendar.set(Calendar.MONTH, mth / 100 - 1);
calendar.set(Calendar.DATE, day);
calendar.set(Calendar.HOUR_OF_DAY, hour / 10000);
calendar.set(Calendar.MINUTE, min / 100);
calendar.set(Calendar.SECOND, sec);
calendar.set(Calendar.MILLISECOND, 0);
return calendar;
}
/**
* Create a date instance for a specified time zone, date and time.
*
* @param zone The time zone
* @param date The date in yyyyMMdd format
* @param time the time in HH:mm:ss format
* @return the new Date instance.
*/
protected static Date createDate(final TimeZone zone, final int date, final int time) {
final Calendar calendar = createCalendar(zone, date, time);
return calendar.getTime();
}
}
| 7,915 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/FloatValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.text.DecimalFormat;
import java.util.Locale;
/**
* Test Case for FloatValidator.
*/
public class FloatValidatorTest extends AbstractNumberValidatorTest {
/**
* Constructor
* @param name test name
*/
public FloatValidatorTest(final String name) {
super(name);
}
@Override
protected void setUp() {
super.setUp();
validator = new FloatValidator(false, 0);
strictValidator = new FloatValidator();
testPattern = "#,###.#";
// testValidateMinMax()
max = Float.valueOf(Float.MAX_VALUE);
maxPlusOne = Double.valueOf(max.doubleValue() * 10);
min = Float.valueOf(Float.MAX_VALUE * -1);
minMinusOne = Double.valueOf(min.doubleValue() * 10);
// testInvalidStrict()
invalidStrict = new String[] {null, "", "X", "X12", "12X", "1X2"};
// testInvalidNotStrict()
invalid = new String[] {null, "", "X", "X12"};
// testValid()
testNumber = Float.valueOf(1234.5f);
testZero = Float.valueOf(0);
validStrict = new String[] {"0", "1234.5", "1,234.5"};
validStrictCompare = new Number[] {testZero, testNumber, testNumber};
valid = new String[] {"0", "1234.5", "1,234.5", "1,234.5", "1234.5X"};
validCompare = new Number[] {testZero, testNumber, testNumber, testNumber, testNumber};
testStringUS = "1,234.5";
testStringDE = "1.234,5";
// Localized Pattern test
localeValue = testStringDE;
localePattern = "#.###,#";
testLocale = Locale.GERMANY;
localeExpected = testNumber;
}
/**
* Test FloatValidator validate Methods
*/
public void testFloatValidatorMethods() {
final Locale locale = Locale.GERMAN;
final String pattern = "0,00,00";
final String patternVal = "1,23,45";
final String localeVal = "12.345";
final String germanPatternVal = "1.23.45";
final String defaultVal = "12,345";
final String XXXX = "XXXX";
final Float expected = Float.valueOf(12345);
assertEquals("validate(A) default", expected, FloatValidator.getInstance().validate(defaultVal));
assertEquals("validate(A) locale ", expected, FloatValidator.getInstance().validate(localeVal, locale));
assertEquals("validate(A) pattern", expected, FloatValidator.getInstance().validate(patternVal, pattern));
assertEquals("validate(A) both", expected, FloatValidator.getInstance().validate(germanPatternVal, pattern, Locale.GERMAN));
assertTrue("isValid(A) default", FloatValidator.getInstance().isValid(defaultVal));
assertTrue("isValid(A) locale ", FloatValidator.getInstance().isValid(localeVal, locale));
assertTrue("isValid(A) pattern", FloatValidator.getInstance().isValid(patternVal, pattern));
assertTrue("isValid(A) both", FloatValidator.getInstance().isValid(germanPatternVal, pattern, Locale.GERMAN));
assertNull("validate(B) default", FloatValidator.getInstance().validate(XXXX));
assertNull("validate(B) locale ", FloatValidator.getInstance().validate(XXXX, locale));
assertNull("validate(B) pattern", FloatValidator.getInstance().validate(XXXX, pattern));
assertNull("validate(B) both", FloatValidator.getInstance().validate(patternVal, pattern, Locale.GERMAN));
assertFalse("isValid(B) default", FloatValidator.getInstance().isValid(XXXX));
assertFalse("isValid(B) locale ", FloatValidator.getInstance().isValid(XXXX, locale));
assertFalse("isValid(B) pattern", FloatValidator.getInstance().isValid(XXXX, pattern));
assertFalse("isValid(B) both", FloatValidator.getInstance().isValid(patternVal, pattern, Locale.GERMAN));
}
/**
* Test Float validation for values too small to handle.
* (slightly different from max/min which are the largest +ve/-ve
*/
public void testFloatSmallestValues() {
final String pattern = "#.#################################################################";
final DecimalFormat fmt = new DecimalFormat(pattern);
// Validate Smallest +ve value
final Float smallestPositive = Float.valueOf(Float.MIN_VALUE);
final String strSmallestPositive = fmt.format(smallestPositive);
assertEquals("Smallest +ve", smallestPositive, FloatValidator.getInstance().validate(strSmallestPositive, pattern));
// Validate Smallest -ve value
final Float smallestNegative = Float.valueOf(Float.MIN_VALUE * -1);
final String strSmallestNegative = fmt.format(smallestNegative);
assertEquals("Smallest -ve", smallestNegative, FloatValidator.getInstance().validate(strSmallestNegative, pattern));
// Validate Too Small +ve
final Double tooSmallPositive = Double.valueOf((double)Float.MIN_VALUE / (double)10);
final String strTooSmallPositive = fmt.format(tooSmallPositive);
assertFalse("Too small +ve", FloatValidator.getInstance().isValid(strTooSmallPositive, pattern));
// Validate Too Small -ve
final Double tooSmallNegative = Double.valueOf(tooSmallPositive.doubleValue() * -1);
final String strTooSmallNegative = fmt.format(tooSmallNegative);
assertFalse("Too small -ve", FloatValidator.getInstance().isValid(strTooSmallNegative, pattern));
}
/**
* Test Float Range/Min/Max
*/
public void testFloatRangeMinMax() {
final FloatValidator validator = (FloatValidator)strictValidator;
final Float number9 = validator.validate("9", "#");
final Float number10 = validator.validate("10", "#");
final Float number11 = validator.validate("11", "#");
final Float number19 = validator.validate("19", "#");
final Float number20 = validator.validate("20", "#");
final Float number21 = validator.validate("21", "#");
// Test isInRange()
assertFalse("isInRange() < min", validator.isInRange(number9, 10, 20));
assertTrue("isInRange() = min", validator.isInRange(number10, 10, 20));
assertTrue("isInRange() in range", validator.isInRange(number11, 10, 20));
assertTrue("isInRange() = max", validator.isInRange(number20, 10, 20));
assertFalse("isInRange() > max", validator.isInRange(number21, 10, 20));
// Test minValue()
assertFalse("minValue() < min", validator.minValue(number9, 10));
assertTrue("minValue() = min", validator.minValue(number10, 10));
assertTrue("minValue() > min", validator.minValue(number11, 10));
// Test minValue()
assertTrue("maxValue() < max", validator.maxValue(number19, 20));
assertTrue("maxValue() = max", validator.maxValue(number20, 20));
assertFalse("maxValue() > max", validator.maxValue(number21, 20));
}
}
| 7,916 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/ByteValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.util.Locale;
/**
* Test Case for ByteValidator.
*/
public class ByteValidatorTest extends AbstractNumberValidatorTest {
private static final Byte BYTE_MIN_VAL = Byte.valueOf(Byte.MIN_VALUE);
private static final Byte BYTE_MAX_VAL = Byte.valueOf(Byte.MAX_VALUE);
private static final String BYTE_MAX = "127";
private static final String BYTE_MAX_0 = "127.99999999999999999999999"; // force double rounding
private static final String BYTE_MAX_1 = "128";
private static final String BYTE_MIN = "-128";
private static final String BYTE_MIN_0 = "-128.99999999999999999999999"; // force double rounding";
private static final String BYTE_MIN_1 = "-129";
/**
* Constructor
* @param name test name
*/
public ByteValidatorTest(final String name) {
super(name);
}
@Override
protected void setUp() {
super.setUp();
validator = new ByteValidator(false, 0);
strictValidator = new ByteValidator();
testPattern = "#,###";
// testValidateMinMax()
max = Byte.valueOf(Byte.MAX_VALUE);
maxPlusOne = Long.valueOf(max.longValue() + 1);
min = Byte.valueOf(Byte.MIN_VALUE);
minMinusOne = Long.valueOf(min.longValue() - 1);
// testInvalidStrict()
invalidStrict = new String[] {null, "", "X", "X12", "12X", "1X2", "1.2", BYTE_MAX_1, BYTE_MIN_1, BYTE_MAX_0, BYTE_MIN_0};
// testInvalidNotStrict()
invalid = new String[] {null, "", "X", "X12", BYTE_MAX_1, BYTE_MIN_1};
// testValid()
testNumber = Byte.valueOf((byte)123);
testZero = Byte.valueOf((byte)0);
validStrict = new String[] {"0", "123", ",123", BYTE_MAX, BYTE_MIN};
validStrictCompare = new Number[] {testZero, testNumber, testNumber, BYTE_MAX_VAL, BYTE_MIN_VAL};
valid = new String[] {"0", "123", ",123", ",123.5", "123X", BYTE_MAX, BYTE_MIN, BYTE_MAX_0, BYTE_MIN_0};
validCompare = new Number[] {testZero, testNumber, testNumber, testNumber, testNumber, BYTE_MAX_VAL, BYTE_MIN_VAL, BYTE_MAX_VAL, BYTE_MIN_VAL};
testStringUS = ",123";
testStringDE = ".123";
// Localized Pattern test
localeValue = testStringDE;
localePattern = "#.###";
testLocale = Locale.GERMANY;
localeExpected = testNumber;
}
/**
* Test ByteValidator validate Methods
*/
public void testByteValidatorMethods() {
final Locale locale = Locale.GERMAN;
final String pattern = "0,00";
final String patternVal = "1,23";
final String germanPatternVal = "1.23";
final String localeVal = ".123";
final String defaultVal = ",123";
final String XXXX = "XXXX";
final Byte expected = Byte.valueOf((byte)123);
assertEquals("validate(A) default", expected, ByteValidator.getInstance().validate(defaultVal));
assertEquals("validate(A) locale ", expected, ByteValidator.getInstance().validate(localeVal, locale));
assertEquals("validate(A) pattern", expected, ByteValidator.getInstance().validate(patternVal, pattern));
assertEquals("validate(A) both", expected, ByteValidator.getInstance().validate(germanPatternVal, pattern, Locale.GERMAN));
assertTrue("isValid(A) default", ByteValidator.getInstance().isValid(defaultVal));
assertTrue("isValid(A) locale ", ByteValidator.getInstance().isValid(localeVal, locale));
assertTrue("isValid(A) pattern", ByteValidator.getInstance().isValid(patternVal, pattern));
assertTrue("isValid(A) both", ByteValidator.getInstance().isValid(germanPatternVal, pattern, Locale.GERMAN));
assertNull("validate(B) default", ByteValidator.getInstance().validate(XXXX));
assertNull("validate(B) locale ", ByteValidator.getInstance().validate(XXXX, locale));
assertNull("validate(B) pattern", ByteValidator.getInstance().validate(XXXX, pattern));
assertNull("validate(B) both", ByteValidator.getInstance().validate(patternVal, pattern, Locale.GERMAN));
assertFalse("isValid(B) default", ByteValidator.getInstance().isValid(XXXX));
assertFalse("isValid(B) locale ", ByteValidator.getInstance().isValid(XXXX, locale));
assertFalse("isValid(B) pattern", ByteValidator.getInstance().isValid(XXXX, pattern));
assertFalse("isValid(B) both", ByteValidator.getInstance().isValid(patternVal, pattern, Locale.GERMAN));
}
/**
* Test Byte Range/Min/Max
*/
public void testByteRangeMinMax() {
final ByteValidator validator = (ByteValidator)strictValidator;
final Byte number9 = validator.validate("9", "#");
final Byte number10 = validator.validate("10", "#");
final Byte number11 = validator.validate("11", "#");
final Byte number19 = validator.validate("19", "#");
final Byte number20 = validator.validate("20", "#");
final Byte number21 = validator.validate("21", "#");
final byte min = (byte)10;
final byte max = (byte)20;
// Test isInRange()
assertFalse("isInRange() < min", validator.isInRange(number9, min, max));
assertTrue("isInRange() = min", validator.isInRange(number10, min, max));
assertTrue("isInRange() in range", validator.isInRange(number11, min, max));
assertTrue("isInRange() = max", validator.isInRange(number20, min, max));
assertFalse("isInRange() > max", validator.isInRange(number21, min, max));
// Test minValue()
assertFalse("minValue() < min", validator.minValue(number9, min));
assertTrue("minValue() = min", validator.minValue(number10, min));
assertTrue("minValue() > min", validator.minValue(number11, min));
// Test minValue()
assertTrue("maxValue() < max", validator.maxValue(number19, max));
assertTrue("maxValue() = max", validator.maxValue(number20, max));
assertFalse("maxValue() > max", validator.maxValue(number21, max));
}
}
| 7,917 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/CreditCardValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import org.apache.commons.validator.routines.CreditCardValidator.CreditCardRange;
import org.apache.commons.validator.routines.checkdigit.LuhnCheckDigit;
import junit.framework.TestCase;
/**
* Test the CreditCardValidator class.
*/
public class CreditCardValidatorTest extends TestCase {
private static final String VALID_VISA = "4417123456789113"; // 16
private static final String ERROR_VISA = "4417123456789112";
private static final String VALID_SHORT_VISA = "4222222222222"; // 13
private static final String ERROR_SHORT_VISA = "4222222222229";
private static final String VALID_AMEX = "378282246310005"; // 15
private static final String ERROR_AMEX = "378282246310001";
private static final String VALID_MASTERCARD = "5105105105105100";
private static final String ERROR_MASTERCARD = "5105105105105105";
private static final String VALID_DISCOVER = "6011000990139424";
private static final String ERROR_DISCOVER = "6011000990139421";
private static final String VALID_DISCOVER65 = "6534567890123458"; // FIXME need verified test data for Discover with "65" prefix
private static final String ERROR_DISCOVER65 = "6534567890123450"; // FIXME need verified test data for Discover with "65" prefix
private static final String VALID_DINERS = "30569309025904"; // 14
private static final String ERROR_DINERS = "30569309025901";
private static final String VALID_VPAY = "4370000000000061"; // 16
private static final String VALID_VPAY2 = "4370000000000012";
private static final String ERROR_VPAY = "4370000000000069";
private static final String [] VALID_CARDS = {
VALID_VISA,
VALID_SHORT_VISA,
VALID_AMEX,
VALID_MASTERCARD,
VALID_DISCOVER,
VALID_DISCOVER65,
VALID_DINERS,
VALID_VPAY,
VALID_VPAY2,
"60115564485789458", // VALIDATOR-403
};
private static final String [] ERROR_CARDS = {
ERROR_VISA,
ERROR_SHORT_VISA,
ERROR_AMEX,
ERROR_MASTERCARD,
ERROR_DISCOVER,
ERROR_DISCOVER65,
ERROR_DINERS,
ERROR_VPAY,
// ERROR_VPAY2,
"",
"12345678901", // too short (11)
"12345678901234567890", // too long (20)
"4417123456789112", // invalid check digit
};
/**
* Constructor for CreditCardValidatorTest.
*/
public CreditCardValidatorTest(final String name) {
super(name);
}
public void testIsValid() {
CreditCardValidator ccv = new CreditCardValidator();
assertNull(ccv.validate(null));
assertFalse(ccv.isValid(null));
assertFalse(ccv.isValid(""));
assertFalse(ccv.isValid("123456789012")); // too short
assertFalse(ccv.isValid("12345678901234567890")); // too long
assertFalse(ccv.isValid("4417123456789112"));
assertFalse(ccv.isValid("4417q23456w89113"));
assertTrue(ccv.isValid(VALID_VISA));
assertTrue(ccv.isValid(VALID_SHORT_VISA));
assertTrue(ccv.isValid(VALID_AMEX));
assertTrue(ccv.isValid(VALID_MASTERCARD));
assertTrue(ccv.isValid(VALID_DISCOVER));
assertTrue(ccv.isValid(VALID_DISCOVER65));
assertFalse(ccv.isValid(ERROR_VISA));
assertFalse(ccv.isValid(ERROR_SHORT_VISA));
assertFalse(ccv.isValid(ERROR_AMEX));
assertFalse(ccv.isValid(ERROR_MASTERCARD));
assertFalse(ccv.isValid(ERROR_DISCOVER));
assertFalse(ccv.isValid(ERROR_DISCOVER65));
// disallow Visa so it should fail even with good number
ccv = new CreditCardValidator(CreditCardValidator.AMEX);
assertFalse(ccv.isValid("4417123456789113"));
}
public void testAddAllowedCardType() {
final CreditCardValidator ccv = new CreditCardValidator(CreditCardValidator.NONE);
// Turned off all cards so even valid numbers should fail
assertFalse(ccv.isValid(VALID_VISA));
assertFalse(ccv.isValid(VALID_AMEX));
assertFalse(ccv.isValid(VALID_MASTERCARD));
assertFalse(ccv.isValid(VALID_DISCOVER));
assertFalse(ccv.isValid(VALID_DINERS));
}
/**
* Test the CodeValidator array constructor
*/
public void testArrayConstructor() {
final CreditCardValidator ccv = new CreditCardValidator(new CodeValidator[]
{CreditCardValidator.VISA_VALIDATOR, CreditCardValidator.AMEX_VALIDATOR});
assertTrue(ccv.isValid(VALID_VISA));
assertTrue(ccv.isValid(VALID_SHORT_VISA));
assertTrue(ccv.isValid(VALID_AMEX));
assertFalse(ccv.isValid(VALID_MASTERCARD));
assertFalse(ccv.isValid(VALID_DISCOVER));
assertFalse(ccv.isValid(ERROR_VISA));
assertFalse(ccv.isValid(ERROR_SHORT_VISA));
assertFalse(ccv.isValid(ERROR_AMEX));
assertFalse(ccv.isValid(ERROR_MASTERCARD));
assertFalse(ccv.isValid(ERROR_DISCOVER));
try {
new CreditCardValidator((CodeValidator[]) null);
fail("Expected IllegalArgumentException");
} catch (final IllegalArgumentException iae) {
// expected result
}
}
/**
* Test the Amex Card validator
*/
public void testAmexValidator() {
final CodeValidator validator = CreditCardValidator.AMEX_VALIDATOR;
final RegexValidator regex = validator.getRegexValidator();
// ****** Test Regular Expression ******
// length 15 and start with a "34" or "37"
assertFalse("Length 12", regex.isValid("343456789012"));
assertFalse("Length 13", regex.isValid("3434567890123"));
assertFalse("Length 14", regex.isValid("34345678901234"));
assertTrue("Length 15", regex.isValid("343456789012345"));
assertFalse("Length 16", regex.isValid("3434567890123456"));
assertFalse("Length 17", regex.isValid("34345678901234567"));
assertFalse("Length 18", regex.isValid("343456789012345678"));
assertFalse("Prefix 33", regex.isValid("333456789012345"));
assertTrue("Prefix 34", regex.isValid("343456789012345"));
assertFalse("Prefix 35", regex.isValid("353456789012345"));
assertFalse("Prefix 36", regex.isValid("363456789012345"));
assertTrue("Prefix 37", regex.isValid("373456789012345"));
assertFalse("Prefix 38", regex.isValid("383456789012345"));
assertFalse("Prefix 41", regex.isValid("413456789012345"));
assertFalse("Invalid Char", regex.isValid("3434567x9012345"));
// *********** Test Validator **********
assertTrue("Valid regex", regex.isValid(ERROR_AMEX));
assertFalse("Invalid", validator.isValid(ERROR_AMEX));
assertNull("validate()", validator.validate(ERROR_AMEX));
assertEquals(VALID_AMEX, validator.validate(VALID_AMEX));
assertTrue("Amex", validator.isValid(VALID_AMEX));
assertFalse("Diners", validator.isValid(VALID_DINERS));
assertFalse("Discover", validator.isValid(VALID_DISCOVER));
assertFalse("Mastercard", validator.isValid(VALID_MASTERCARD));
assertFalse("Visa", validator.isValid(VALID_VISA));
assertFalse("Visa Short", validator.isValid(VALID_SHORT_VISA));
assertTrue("Valid-A", validator.isValid("371449635398431"));
assertTrue("Valid-B", validator.isValid("340000000000009"));
assertTrue("Valid-C", validator.isValid("370000000000002"));
assertTrue("Valid-D", validator.isValid("378734493671000"));
}
/**
* Test the Amex Card option
*/
public void testAmexOption() {
final CreditCardValidator validator = new CreditCardValidator(CreditCardValidator.AMEX);
assertFalse("Invalid", validator.isValid(ERROR_AMEX));
assertNull("validate()", validator.validate(ERROR_AMEX));
assertEquals(VALID_AMEX, validator.validate(VALID_AMEX));
assertTrue("Amex", validator.isValid(VALID_AMEX));
assertFalse("Diners", validator.isValid(VALID_DINERS));
assertFalse("Discover", validator.isValid(VALID_DISCOVER));
assertFalse("Mastercard", validator.isValid(VALID_MASTERCARD));
assertFalse("Visa", validator.isValid(VALID_VISA));
assertFalse("Visa Short", validator.isValid(VALID_SHORT_VISA));
}
/**
* Test the Diners Card validator
*/
public void testDinersValidator() {
final CodeValidator validator = CreditCardValidator.DINERS_VALIDATOR;
final RegexValidator regex = validator.getRegexValidator();
// ****** Test Regular Expression ******
// length 14 and start with a "300-305" or "3095" or "36" or "38" or "39"
assertFalse("Length 12-300", regex.isValid("300456789012"));
assertFalse("Length 12-36", regex.isValid("363456789012"));
assertFalse("Length 13-300", regex.isValid("3004567890123"));
assertFalse("Length 13-36", regex.isValid("3634567890123"));
assertTrue("Length 14-300", regex.isValid("30045678901234"));
assertTrue("Length 14-36", regex.isValid("36345678901234"));
assertFalse("Length 15-300", regex.isValid("300456789012345"));
assertFalse("Length 15-36", regex.isValid("363456789012345"));
assertFalse("Length 16-300", regex.isValid("3004567890123456"));
assertFalse("Length 16-36", regex.isValid("3634567890123456"));
assertFalse("Length 17-300", regex.isValid("30045678901234567"));
assertFalse("Length 17-36", regex.isValid("36345678901234567"));
assertFalse("Length 18-300", regex.isValid("300456789012345678"));
assertFalse("Length 18-36", regex.isValid("363456789012345678"));
assertTrue("Prefix 300", regex.isValid("30045678901234"));
assertTrue("Prefix 301", regex.isValid("30145678901234"));
assertTrue("Prefix 302", regex.isValid("30245678901234"));
assertTrue("Prefix 303", regex.isValid("30345678901234"));
assertTrue("Prefix 304", regex.isValid("30445678901234"));
assertTrue("Prefix 305", regex.isValid("30545678901234"));
assertFalse("Prefix 306", regex.isValid("30645678901234"));
assertFalse("Prefix 3094", regex.isValid("30945678901234"));
assertTrue( "Prefix 3095", regex.isValid("30955678901234"));
assertFalse("Prefix 3096", regex.isValid("30965678901234"));
assertFalse("Prefix 35", regex.isValid("35345678901234"));
assertTrue("Prefix 36", regex.isValid("36345678901234"));
assertFalse("Prefix 37", regex.isValid("37345678901234"));
assertTrue("Prefix 38", regex.isValid("38345678901234"));
assertTrue("Prefix 39", regex.isValid("39345678901234"));
assertFalse("Invalid Char-A", regex.isValid("3004567x901234"));
assertFalse("Invalid Char-B", regex.isValid("3634567x901234"));
// *********** Test Validator **********
assertTrue("Valid regex", regex.isValid(ERROR_DINERS));
assertFalse("Invalid", validator.isValid(ERROR_DINERS));
assertNull("validate()", validator.validate(ERROR_DINERS));
assertEquals(VALID_DINERS, validator.validate(VALID_DINERS));
assertFalse("Amex", validator.isValid(VALID_AMEX));
assertTrue("Diners", validator.isValid(VALID_DINERS));
assertFalse("Discover", validator.isValid(VALID_DISCOVER));
assertFalse("Mastercard", validator.isValid(VALID_MASTERCARD));
assertFalse("Visa", validator.isValid(VALID_VISA));
assertFalse("Visa Short", validator.isValid(VALID_SHORT_VISA));
assertTrue("Valid-A", validator.isValid("30000000000004"));
assertTrue("Valid-B", validator.isValid("30123456789019"));
assertTrue("Valid-C", validator.isValid("36432685260294"));
}
/**
* Test the Diners Card option
*/
public void testDinersOption() {
final CreditCardValidator validator = new CreditCardValidator(CreditCardValidator.DINERS);
assertFalse("Invalid", validator.isValid(ERROR_DINERS));
assertNull("validate()", validator.validate(ERROR_DINERS));
assertEquals(VALID_DINERS, validator.validate(VALID_DINERS));
assertFalse("Amex", validator.isValid(VALID_AMEX));
assertTrue("Diners", validator.isValid(VALID_DINERS));
assertFalse("Discover", validator.isValid(VALID_DISCOVER));
assertFalse("Mastercard", validator.isValid(VALID_MASTERCARD));
assertFalse("Visa", validator.isValid(VALID_VISA));
assertFalse("Visa Short", validator.isValid(VALID_SHORT_VISA));
}
/**
* Test the Discover Card validator
*/
public void testDiscoverValidator() {
final CodeValidator validator = CreditCardValidator.DISCOVER_VALIDATOR;
final RegexValidator regex = validator.getRegexValidator();
// ****** Test Regular Expression ******
// length 16 and start with either "6011" or or "64[4-9]" or "65"
assertFalse("Length 12-6011", regex.isValid("601156789012"));
assertFalse("Length 12-65", regex.isValid("653456789012"));
assertFalse("Length 13-6011", regex.isValid("6011567890123"));
assertFalse("Length 13-65", regex.isValid("6534567890123"));
assertFalse("Length 14-6011", regex.isValid("60115678901234"));
assertFalse("Length 14-65", regex.isValid("65345678901234"));
assertFalse("Length 15-6011", regex.isValid("601156789012345"));
assertFalse("Length 15-65", regex.isValid("653456789012345"));
assertTrue("Length 16-6011", regex.isValid("6011567890123456"));
assertTrue("Length 16-644", regex.isValid("6444567890123456"));
assertTrue("Length 16-648", regex.isValid("6484567890123456"));
assertTrue("Length 16-65", regex.isValid("6534567890123456"));
assertFalse("Length 17-65", regex.isValid("65345678901234567"));
assertFalse("Length 18-6011", regex.isValid("601156789012345678"));
assertFalse("Length 18-65", regex.isValid("653456789012345678"));
assertFalse("Prefix 640", regex.isValid("6404567890123456"));
assertFalse("Prefix 641", regex.isValid("6414567890123456"));
assertFalse("Prefix 642", regex.isValid("6424567890123456"));
assertFalse("Prefix 643", regex.isValid("6434567890123456"));
assertFalse("Prefix 6010", regex.isValid("6010567890123456"));
assertFalse("Prefix 6012", regex.isValid("6012567890123456"));
assertFalse("Invalid Char", regex.isValid("6011567x90123456"));
// *********** Test Validator **********
assertTrue("Valid regex", regex.isValid(ERROR_DISCOVER));
assertTrue("Valid regex65", regex.isValid(ERROR_DISCOVER65));
assertFalse("Invalid", validator.isValid(ERROR_DISCOVER));
assertFalse("Invalid65", validator.isValid(ERROR_DISCOVER65));
assertNull("validate()", validator.validate(ERROR_DISCOVER));
assertEquals(VALID_DISCOVER, validator.validate(VALID_DISCOVER));
assertEquals(VALID_DISCOVER65, validator.validate(VALID_DISCOVER65));
assertFalse("Amex", validator.isValid(VALID_AMEX));
assertFalse("Diners", validator.isValid(VALID_DINERS));
assertTrue("Discover", validator.isValid(VALID_DISCOVER));
assertTrue("Discover", validator.isValid(VALID_DISCOVER65));
assertFalse("Mastercard", validator.isValid(VALID_MASTERCARD));
assertFalse("Visa", validator.isValid(VALID_VISA));
assertFalse("Visa Short", validator.isValid(VALID_SHORT_VISA));
assertTrue("Valid-A", validator.isValid("6011111111111117"));
assertTrue("Valid-B", validator.isValid("6011000000000004"));
assertTrue("Valid-C", validator.isValid("6011000000000012"));
}
/**
* Test the Discover Card option
*/
public void testDiscoverOption() {
final CreditCardValidator validator = new CreditCardValidator(CreditCardValidator.DISCOVER);
assertFalse("Invalid", validator.isValid(ERROR_DISCOVER));
assertFalse("Invalid65", validator.isValid(ERROR_DISCOVER65));
assertNull("validate()", validator.validate(ERROR_DISCOVER));
assertEquals(VALID_DISCOVER, validator.validate(VALID_DISCOVER));
assertEquals(VALID_DISCOVER65, validator.validate(VALID_DISCOVER65));
assertFalse("Amex", validator.isValid(VALID_AMEX));
assertFalse("Diners", validator.isValid(VALID_DINERS));
assertTrue("Discover", validator.isValid(VALID_DISCOVER));
assertTrue("Discover", validator.isValid(VALID_DISCOVER65));
assertFalse("Mastercard", validator.isValid(VALID_MASTERCARD));
assertFalse("Visa", validator.isValid(VALID_VISA));
assertFalse("Visa Short", validator.isValid(VALID_SHORT_VISA));
}
/**
* Test the Mastercard Card validator
*/
public void testMastercardValidator() {
final CodeValidator validator = CreditCardValidator.MASTERCARD_VALIDATOR;
final RegexValidator regex = validator.getRegexValidator();
// ****** Test Regular Expression ******
// length 16 and start with a "51-55"
assertFalse("Length 12", regex.isValid("513456789012"));
assertFalse("Length 13", regex.isValid("5134567890123"));
assertFalse("Length 14", regex.isValid("51345678901234"));
assertFalse("Length 15", regex.isValid("513456789012345"));
assertTrue("Length 16", regex.isValid("5134567890123456"));
assertFalse("Length 17", regex.isValid("51345678901234567"));
assertFalse("Length 18", regex.isValid("513456789012345678"));
assertFalse("Prefix 41", regex.isValid("4134567890123456"));
assertFalse("Prefix 50", regex.isValid("5034567890123456"));
assertTrue("Prefix 51", regex.isValid("5134567890123456"));
assertTrue("Prefix 52", regex.isValid("5234567890123456"));
assertTrue("Prefix 53", regex.isValid("5334567890123456"));
assertTrue("Prefix 54", regex.isValid("5434567890123456"));
assertTrue("Prefix 55", regex.isValid("5534567890123456"));
assertFalse("Prefix 56", regex.isValid("5634567890123456"));
assertFalse("Prefix 61", regex.isValid("6134567890123456"));
assertFalse("Invalid Char", regex.isValid("5134567x90123456"));
// *********** Test Validator **********
assertTrue("Valid regex", regex.isValid(ERROR_MASTERCARD));
assertFalse("Invalid", validator.isValid(ERROR_MASTERCARD));
assertNull("validate()", validator.validate(ERROR_MASTERCARD));
assertEquals(VALID_MASTERCARD, validator.validate(VALID_MASTERCARD));
assertFalse("Amex", validator.isValid(VALID_AMEX));
assertFalse("Diners", validator.isValid(VALID_DINERS));
assertFalse("Discover", validator.isValid(VALID_DISCOVER));
assertTrue("Mastercard", validator.isValid(VALID_MASTERCARD));
assertFalse("Visa", validator.isValid(VALID_VISA));
assertFalse("Visa Short", validator.isValid(VALID_SHORT_VISA));
assertTrue("Valid-A", validator.isValid("5500000000000004"));
assertTrue("Valid-B", validator.isValid("5424000000000015"));
assertTrue("Valid-C", validator.isValid("5301250070000191"));
assertTrue("Valid-D", validator.isValid("5123456789012346"));
assertTrue("Valid-E", validator.isValid("5555555555554444"));
final RegexValidator rev = validator.getRegexValidator();
final String PAD = "0000000000";
assertFalse("222099",rev.isValid("222099"+PAD));
for(int i=222100; i <= 272099; i++) {
final String j = Integer.toString(i)+PAD;
assertTrue(j, rev.isValid(j));
}
assertFalse("272100",rev.isValid("272100"+PAD));
}
/**
* Test the Mastercard Card option
*/
public void testMastercardOption() {
final CreditCardValidator validator = new CreditCardValidator(CreditCardValidator.MASTERCARD);
assertFalse("Invalid", validator.isValid(ERROR_MASTERCARD));
assertNull("validate()", validator.validate(ERROR_MASTERCARD));
assertEquals(VALID_MASTERCARD, validator.validate(VALID_MASTERCARD));
assertFalse("Amex", validator.isValid(VALID_AMEX));
assertFalse("Diners", validator.isValid(VALID_DINERS));
assertFalse("Discover", validator.isValid(VALID_DISCOVER));
assertTrue("Mastercard", validator.isValid(VALID_MASTERCARD));
assertFalse("Visa", validator.isValid(VALID_VISA));
assertFalse("Visa Short", validator.isValid(VALID_SHORT_VISA));
}
/**
* Test the Visa Card validator
*/
public void testVisaValidator() {
final CodeValidator validator = CreditCardValidator.VISA_VALIDATOR;
final RegexValidator regex = validator.getRegexValidator();
// ****** Test Regular Expression ******
// length 13 or 16, must start with a "4"
assertFalse("Length 12", regex.isValid("423456789012"));
assertTrue("Length 13", regex.isValid("4234567890123"));
assertFalse("Length 14", regex.isValid("42345678901234"));
assertFalse("Length 15", regex.isValid("423456789012345"));
assertTrue("Length 16", regex.isValid("4234567890123456"));
assertFalse("Length 17", regex.isValid("42345678901234567"));
assertFalse("Length 18", regex.isValid("423456789012345678"));
assertFalse("Invalid Pref-A", regex.isValid("3234567890123"));
assertFalse("Invalid Pref-B", regex.isValid("3234567890123456"));
assertFalse("Invalid Char-A", regex.isValid("4234567x90123"));
assertFalse("Invalid Char-B", regex.isValid("4234567x90123456"));
// *********** Test Validator **********
assertTrue("Valid regex", regex.isValid(ERROR_VISA));
assertTrue("Valid regex-S", regex.isValid(ERROR_SHORT_VISA));
assertFalse("Invalid", validator.isValid(ERROR_VISA));
assertFalse("Invalid-S", validator.isValid(ERROR_SHORT_VISA));
assertNull("validate()", validator.validate(ERROR_VISA));
assertEquals(VALID_VISA, validator.validate(VALID_VISA));
assertEquals(VALID_SHORT_VISA, validator.validate(VALID_SHORT_VISA));
assertFalse("Amex", validator.isValid(VALID_AMEX));
assertFalse("Diners", validator.isValid(VALID_DINERS));
assertFalse("Discover", validator.isValid(VALID_DISCOVER));
assertFalse("Mastercard", validator.isValid(VALID_MASTERCARD));
assertTrue("Visa", validator.isValid(VALID_VISA));
assertTrue("Visa Short", validator.isValid(VALID_SHORT_VISA));
assertTrue("Valid-A", validator.isValid("4111111111111111"));
assertTrue("Valid-C", validator.isValid("4543059999999982"));
assertTrue("Valid-B", validator.isValid("4462000000000003"));
assertTrue("Valid-D", validator.isValid("4508750000000009")); // Electron
assertTrue("Valid-E", validator.isValid("4012888888881881"));
}
/**
* Test the Visa Card option
*/
public void testVisaOption() {
final CreditCardValidator validator = new CreditCardValidator(CreditCardValidator.VISA);
assertFalse("Invalid", validator.isValid(ERROR_VISA));
assertFalse("Invalid-S", validator.isValid(ERROR_SHORT_VISA));
assertNull("validate()", validator.validate(ERROR_VISA));
assertEquals(VALID_VISA, validator.validate(VALID_VISA));
assertEquals(VALID_SHORT_VISA, validator.validate(VALID_SHORT_VISA));
assertFalse("Amex", validator.isValid(VALID_AMEX));
assertFalse("Diners", validator.isValid(VALID_DINERS));
assertFalse("Discover", validator.isValid(VALID_DISCOVER));
assertFalse("Mastercard", validator.isValid(VALID_MASTERCARD));
assertTrue("Visa", validator.isValid(VALID_VISA));
assertTrue("Visa Short", validator.isValid(VALID_SHORT_VISA));
}
public void testVPayOption() {
final CreditCardValidator validator = new CreditCardValidator(CreditCardValidator.VPAY);
assertTrue("Valid", validator.isValid(VALID_VPAY));
assertTrue("Valid", validator.isValid(VALID_VPAY2));
assertFalse("Invalid", validator.isValid(ERROR_VPAY));
assertEquals(VALID_VPAY, validator.validate(VALID_VPAY));
assertEquals(VALID_VPAY2, validator.validate(VALID_VPAY2));
assertFalse("Amex", validator.isValid(VALID_AMEX));
assertFalse("Diners", validator.isValid(VALID_DINERS));
assertFalse("Discover", validator.isValid(VALID_DISCOVER));
assertFalse("Mastercard", validator.isValid(VALID_MASTERCARD));
assertTrue("Visa", validator.isValid(VALID_VISA));
assertTrue("Visa Short", validator.isValid(VALID_SHORT_VISA));
}
/**
* Test using separators
*/
public void testMastercardUsingSeparators() {
final String MASTERCARD_REGEX_SEP = "^(5[1-5]\\d{2})(?:[- ])?(\\d{4})(?:[- ])?(\\d{4})(?:[- ])?(\\d{4})$";
final CodeValidator validator = new CodeValidator(MASTERCARD_REGEX_SEP, LuhnCheckDigit.LUHN_CHECK_DIGIT);
final RegexValidator regex = validator.getRegexValidator();
// ****** Test Regular Expression ******
// length 16 and start with a "51-55"
assertEquals("Number", "5134567890123456", regex.validate("5134567890123456"));
assertEquals("Hyphen", "5134567890123456", regex.validate("5134-5678-9012-3456"));
assertEquals("Space", "5134567890123456", regex.validate("5134 5678 9012 3456"));
assertEquals("MixedA", "5134567890123456", regex.validate("5134-5678 9012-3456"));
assertEquals("MixedB", "5134567890123456", regex.validate("5134 5678-9012 3456"));
assertFalse("Invalid Separator A", regex.isValid("5134.5678.9012.3456"));
assertFalse("Invalid Separator B", regex.isValid("5134_5678_9012_3456"));
assertFalse("Invalid Grouping A", regex.isValid("513-45678-9012-3456"));
assertFalse("Invalid Grouping B", regex.isValid("5134-567-89012-3456"));
assertFalse("Invalid Grouping C", regex.isValid("5134-5678-901-23456"));
// *********** Test Validator **********
assertEquals("Valid-A", "5500000000000004", validator.validate("5500-0000-0000-0004"));
assertEquals("Valid-B", "5424000000000015", validator.validate("5424 0000 0000 0015"));
assertEquals("Valid-C", "5301250070000191", validator.validate("5301-250070000191"));
assertEquals("Valid-D", "5123456789012346", validator.validate("5123456789012346"));
}
public void testGeneric() {
final CreditCardValidator ccv = CreditCardValidator.genericCreditCardValidator();
for(final String s : VALID_CARDS) {
assertTrue(s, ccv.isValid(s));
}
for(final String s : ERROR_CARDS) {
assertFalse(s, ccv.isValid(s));
}
}
public void testRangeGeneratorNoLuhn() {
final CodeValidator cv = CreditCardValidator.createRangeValidator(
new CreditCardRange[]{
new CreditCardRange("1",null,6,7),
new CreditCardRange("644","65", 8, 8)
},
null);
assertTrue(cv.isValid("1990000"));
assertTrue(cv.isValid("199000"));
assertFalse(cv.isValid("000000"));
assertFalse(cv.isValid("099999"));
assertFalse(cv.isValid("200000"));
assertFalse(cv.isValid("64399999"));
assertTrue(cv.isValid("64400000"));
assertTrue(cv.isValid("64900000"));
assertTrue(cv.isValid("65000000"));
assertTrue(cv.isValid("65999999"));
assertFalse(cv.isValid("66000000"));
}
public void testRangeGenerator() {
final CreditCardValidator ccv = new CreditCardValidator(
new CodeValidator[] {
CreditCardValidator.AMEX_VALIDATOR,
CreditCardValidator.VISA_VALIDATOR,
CreditCardValidator.MASTERCARD_VALIDATOR,
CreditCardValidator.DISCOVER_VALIDATOR,
},
// Add missing validator
new CreditCardRange[]{
new CreditCardRange("300", "305", 14, 14), // Diners
new CreditCardRange("3095", null, 14, 14), // Diners
new CreditCardRange("36", null, 14, 14), // Diners
new CreditCardRange("38", "39", 14, 14), // Diners
}
// we don't have any VPAY examples yet that aren't handled by VISA
);
for(final String s : VALID_CARDS) {
assertTrue(s, ccv.isValid(s));
}
for(final String s : ERROR_CARDS) {
assertFalse(s, ccv.isValid(s));
}
}
public void testValidLength() {
assertTrue(CreditCardValidator.validLength(14, new CreditCardRange("", "", 14, 14)));
assertFalse(CreditCardValidator.validLength(15, new CreditCardRange("", "", 14, 14)));
assertFalse(CreditCardValidator.validLength(13, new CreditCardRange("", "", 14, 14)));
assertFalse(CreditCardValidator.validLength(14, new CreditCardRange("", "", 15, 17)));
assertTrue(CreditCardValidator.validLength(15, new CreditCardRange("", "", 15, 17)));
assertTrue(CreditCardValidator.validLength(16, new CreditCardRange("", "", 15, 17)));
assertTrue(CreditCardValidator.validLength(17, new CreditCardRange("", "", 15, 17)));
assertFalse(CreditCardValidator.validLength(18, new CreditCardRange("", "", 15, 17)));
assertFalse(CreditCardValidator.validLength(14, new CreditCardRange("", "", new int[]{15, 17})));
assertTrue(CreditCardValidator.validLength(15, new CreditCardRange("", "", new int[]{15, 17})));
assertFalse(CreditCardValidator.validLength(16, new CreditCardRange("", "", new int[]{15, 17})));
assertTrue(CreditCardValidator.validLength(17, new CreditCardRange("", "", new int[]{15, 17})));
assertFalse(CreditCardValidator.validLength(18, new CreditCardRange("", "", new int[]{15, 17})));
}
public void testDisjointRange() {
CreditCardValidator ccv = new CreditCardValidator(
new CreditCardRange[]{
new CreditCardRange("305", "4", new int[]{13, 16}),
}
);
assertEquals(13, VALID_SHORT_VISA.length());
assertEquals(16, VALID_VISA.length());
assertEquals(14, VALID_DINERS.length());
assertTrue(ccv.isValid(VALID_SHORT_VISA));
assertTrue(ccv.isValid(VALID_VISA));
assertFalse(ccv.isValid(ERROR_SHORT_VISA));
assertFalse(ccv.isValid(ERROR_VISA));
assertFalse(ccv.isValid(VALID_DINERS));
ccv = new CreditCardValidator(
new CreditCardRange[]{
// add 14 as a valid length
new CreditCardRange("305", "4", new int[]{13, 14, 16}),
}
);
assertTrue(ccv.isValid(VALID_DINERS));
}
}
| 7,918 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/DomainValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.HttpURLConnection;
import java.net.IDN;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.validator.routines.DomainValidator.ArrayType;
import junit.framework.TestCase;
/**
* Tests for the DomainValidator.
*/
public class DomainValidatorTest extends TestCase {
private DomainValidator validator;
@Override
public void setUp() {
validator = DomainValidator.getInstance();
}
public void testValidDomains() {
assertTrue("apache.org should validate", validator.isValid("apache.org"));
assertTrue("www.google.com should validate", validator.isValid("www.google.com"));
assertTrue("test-domain.com should validate", validator.isValid("test-domain.com"));
assertTrue("test---domain.com should validate", validator.isValid("test---domain.com"));
assertTrue("test-d-o-m-ain.com should validate", validator.isValid("test-d-o-m-ain.com"));
assertTrue("two-letter domain label should validate", validator.isValid("as.uk"));
assertTrue("case-insensitive ApAchE.Org should validate", validator.isValid("ApAchE.Org"));
assertTrue("single-character domain label should validate", validator.isValid("z.com"));
assertTrue("i.have.an-example.domain.name should validate", validator.isValid("i.have.an-example.domain.name"));
}
public void testInvalidDomains() {
assertFalse("bare TLD .org shouldn't validate", validator.isValid(".org"));
assertFalse("domain name with spaces shouldn't validate", validator.isValid(" apache.org "));
assertFalse("domain name containing spaces shouldn't validate", validator.isValid("apa che.org"));
assertFalse("domain name starting with dash shouldn't validate", validator.isValid("-testdomain.name"));
assertFalse("domain name ending with dash shouldn't validate", validator.isValid("testdomain-.name"));
assertFalse("domain name starting with multiple dashes shouldn't validate", validator.isValid("---c.com"));
assertFalse("domain name ending with multiple dashes shouldn't validate", validator.isValid("c--.com"));
assertFalse("domain name with invalid TLD shouldn't validate", validator.isValid("apache.rog"));
assertFalse("URL shouldn't validate", validator.isValid("http://www.apache.org"));
assertFalse("Empty string shouldn't validate as domain name", validator.isValid(" "));
assertFalse("Null shouldn't validate as domain name", validator.isValid(null));
}
public void testTopLevelDomains() {
// infrastructure TLDs
assertTrue(".arpa should validate as iTLD", validator.isValidInfrastructureTld(".arpa"));
assertFalse(".com shouldn't validate as iTLD", validator.isValidInfrastructureTld(".com"));
// generic TLDs
assertTrue(".name should validate as gTLD", validator.isValidGenericTld(".name"));
assertFalse(".us shouldn't validate as gTLD", validator.isValidGenericTld(".us"));
// country code TLDs
assertTrue(".uk should validate as ccTLD", validator.isValidCountryCodeTld(".uk"));
assertFalse(".org shouldn't validate as ccTLD", validator.isValidCountryCodeTld(".org"));
// case-insensitive
assertTrue(".COM should validate as TLD", validator.isValidTld(".COM"));
assertTrue(".BiZ should validate as TLD", validator.isValidTld(".BiZ"));
// corner cases
assertFalse("invalid TLD shouldn't validate", validator.isValid(".nope")); // TODO this is not guaranteed invalid forever
assertFalse("empty string shouldn't validate as TLD", validator.isValid(""));
assertFalse("null shouldn't validate as TLD", validator.isValid(null));
}
public void testAllowLocal() {
final DomainValidator noLocal = DomainValidator.getInstance(false);
final DomainValidator allowLocal = DomainValidator.getInstance(true);
// Default is false, and should use singletons
assertEquals(noLocal, validator);
// Default won't allow local
assertFalse("localhost.localdomain should validate", noLocal.isValid("localhost.localdomain"));
assertFalse("localhost should validate", noLocal.isValid("localhost"));
// But it may be requested
assertTrue("localhost.localdomain should validate", allowLocal.isValid("localhost.localdomain"));
assertTrue("localhost should validate", allowLocal.isValid("localhost"));
assertTrue("hostname should validate", allowLocal.isValid("hostname"));
assertTrue("machinename should validate", allowLocal.isValid("machinename"));
// Check the localhost one with a few others
assertTrue("apache.org should validate", allowLocal.isValid("apache.org"));
assertFalse("domain name with spaces shouldn't validate", allowLocal.isValid(" apache.org "));
}
public void testIDN() {
assertTrue("b\u00fccher.ch in IDN should validate", validator.isValid("www.xn--bcher-kva.ch"));
}
public void testIDNJava6OrLater() {
final String version = System.getProperty("java.version");
if (version.compareTo("1.6") < 0) {
System.out.println("Cannot run Unicode IDN tests");
return; // Cannot run the test
} // xn--d1abbgf6aiiy.xn--p1ai http://президент.рф
assertTrue("b\u00fccher.ch should validate", validator.isValid("www.b\u00fccher.ch"));
assertTrue("xn--d1abbgf6aiiy.xn--p1ai should validate", validator.isValid("xn--d1abbgf6aiiy.xn--p1ai"));
assertTrue("президент.рф should validate", validator.isValid("президент.рф"));
assertFalse("www.\uFFFD.ch FFFD should fail", validator.isValid("www.\uFFFD.ch"));
}
// RFC2396: domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum
public void testRFC2396domainlabel() { // use fixed valid TLD
assertTrue("a.ch should validate", validator.isValid("a.ch"));
assertTrue("9.ch should validate", validator.isValid("9.ch"));
assertTrue("az.ch should validate", validator.isValid("az.ch"));
assertTrue("09.ch should validate", validator.isValid("09.ch"));
assertTrue("9-1.ch should validate", validator.isValid("9-1.ch"));
assertFalse("91-.ch should not validate", validator.isValid("91-.ch"));
assertFalse("-.ch should not validate", validator.isValid("-.ch"));
}
// RFC2396 toplabel = alpha | alpha *( alphanum | "-" ) alphanum
public void testRFC2396toplabel() {
// These tests use non-existent TLDs so currently need to use a package protected method
assertTrue("a.c (alpha) should validate", validator.isValidDomainSyntax("a.c"));
assertTrue("a.cc (alpha alpha) should validate", validator.isValidDomainSyntax("a.cc"));
assertTrue("a.c9 (alpha alphanum) should validate", validator.isValidDomainSyntax("a.c9"));
assertTrue("a.c-9 (alpha - alphanum) should validate", validator.isValidDomainSyntax("a.c-9"));
assertTrue("a.c-z (alpha - alpha) should validate", validator.isValidDomainSyntax("a.c-z"));
assertFalse("a.9c (alphanum alpha) should fail", validator.isValidDomainSyntax("a.9c"));
assertFalse("a.c- (alpha -) should fail", validator.isValidDomainSyntax("a.c-"));
assertFalse("a.- (-) should fail", validator.isValidDomainSyntax("a.-"));
assertFalse("a.-9 (- alphanum) should fail", validator.isValidDomainSyntax("a.-9"));
}
public void testDomainNoDots() {// rfc1123
assertTrue("a (alpha) should validate", validator.isValidDomainSyntax("a"));
assertTrue("9 (alphanum) should validate", validator.isValidDomainSyntax("9"));
assertTrue("c-z (alpha - alpha) should validate", validator.isValidDomainSyntax("c-z"));
assertFalse("c- (alpha -) should fail", validator.isValidDomainSyntax("c-"));
assertFalse("-c (- alpha) should fail", validator.isValidDomainSyntax("-c"));
assertFalse("- (-) should fail", validator.isValidDomainSyntax("-"));
}
public void testValidator297() {
assertTrue("xn--d1abbgf6aiiy.xn--p1ai should validate", validator.isValid("xn--d1abbgf6aiiy.xn--p1ai")); // This uses a valid TLD
}
// labels are a max of 63 chars and domains 253
public void testValidator306() {
final String longString = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789A";
assertEquals(63, longString.length()); // 26 * 2 + 11
assertTrue("63 chars label should validate", validator.isValidDomainSyntax(longString+".com"));
assertFalse("64 chars label should fail", validator.isValidDomainSyntax(longString+"x.com"));
assertTrue("63 chars TLD should validate", validator.isValidDomainSyntax("test."+longString));
assertFalse("64 chars TLD should fail", validator.isValidDomainSyntax("test.x"+longString));
final String longDomain =
longString
+ "." + longString
+ "." + longString
+ "." + longString.substring(0,61)
;
assertEquals(253, longDomain.length());
assertTrue("253 chars domain should validate", validator.isValidDomainSyntax(longDomain));
assertFalse("254 chars domain should fail", validator.isValidDomainSyntax(longDomain+"x"));
}
// Check that IDN.toASCII behaves as it should (when wrapped by DomainValidator.unicodeToASCII)
// Tests show that method incorrectly trims a trailing "." character
public void testUnicodeToASCII() {
final String[] asciidots = {
"",
",",
".", // fails IDN.toASCII, but should pass wrapped version
"a.", // ditto
"a.b",
"a..b",
"a...b",
".a",
"..a",
};
for(final String s : asciidots) {
assertEquals(s,DomainValidator.unicodeToASCII(s));
}
// RFC3490 3.1. 1)
// Whenever dots are used as label separators, the following
// characters MUST be recognized as dots: U+002E (full stop), U+3002
// (ideographic full stop), U+FF0E (fullwidth full stop), U+FF61
// (halfwidth ideographic full stop).
final String otherDots[][] = {
{"b\u3002", "b.",},
{"b\uFF0E", "b.",},
{"b\uFF61", "b.",},
{"\u3002", ".",},
{"\uFF0E", ".",},
{"\uFF61", ".",},
};
for(final String s[] : otherDots) {
assertEquals(s[1],DomainValidator.unicodeToASCII(s[0]));
}
}
// Check if IDN.toASCII is broken or not
public void testIsIDNtoASCIIBroken() {
System.out.println(">>DomainValidatorTest.testIsIDNtoASCIIBroken()");
final String input = ".";
final boolean ok = input.equals(IDN.toASCII(input));
System.out.println("IDN.toASCII is " + (ok? "OK" : "BROKEN"));
final String[] props = {
"java.version", // Java Runtime Environment version
"java.vendor", // Java Runtime Environment vendor
"java.vm.specification.version", // Java Virtual Machine specification version
"java.vm.specification.vendor", // Java Virtual Machine specification vendor
"java.vm.specification.name", // Java Virtual Machine specification name
"java.vm.version", // Java Virtual Machine implementation version
"java.vm.vendor", // Java Virtual Machine implementation vendor
"java.vm.name", // Java Virtual Machine implementation name
"java.specification.version", // Java Runtime Environment specification version
"java.specification.vendor", // Java Runtime Environment specification vendor
"java.specification.name", // Java Runtime Environment specification name
"java.class.version", // Java class format version number
};
for(final String t : props) {
System.out.println(t + "=" + System.getProperty(t));
}
System.out.println("<<DomainValidatorTest.testIsIDNtoASCIIBroken()");
assertTrue(true); // dummy assertion to satisfy lint
}
// Check array is sorted and is lower-case
public void test_INFRASTRUCTURE_TLDS_sortedAndLowerCase() throws Exception {
final boolean sorted = isSortedLowerCase("INFRASTRUCTURE_TLDS");
assertTrue(sorted);
}
// Check array is sorted and is lower-case
public void test_COUNTRY_CODE_TLDS_sortedAndLowerCase() throws Exception {
final boolean sorted = isSortedLowerCase("COUNTRY_CODE_TLDS");
assertTrue(sorted);
}
// Check array is sorted and is lower-case
public void test_GENERIC_TLDS_sortedAndLowerCase() throws Exception {
final boolean sorted = isSortedLowerCase("GENERIC_TLDS");
assertTrue(sorted);
}
// Check array is sorted and is lower-case
public void test_LOCAL_TLDS_sortedAndLowerCase() throws Exception {
final boolean sorted = isSortedLowerCase("LOCAL_TLDS");
assertTrue(sorted);
}
public void testEnumIsPublic() {
assertTrue(Modifier.isPublic(DomainValidator.ArrayType.class.getModifiers()));
}
public void testGetArray() {
assertNotNull(DomainValidator.getTLDEntries(ArrayType.COUNTRY_CODE_MINUS));
assertNotNull(DomainValidator.getTLDEntries(ArrayType.COUNTRY_CODE_PLUS));
assertNotNull(DomainValidator.getTLDEntries(ArrayType.GENERIC_MINUS));
assertNotNull(DomainValidator.getTLDEntries(ArrayType.GENERIC_PLUS));
assertNotNull(DomainValidator.getTLDEntries(ArrayType.LOCAL_MINUS));
assertNotNull(DomainValidator.getTLDEntries(ArrayType.LOCAL_PLUS));
assertNotNull(DomainValidator.getTLDEntries(ArrayType.COUNTRY_CODE_RO));
assertNotNull(DomainValidator.getTLDEntries(ArrayType.GENERIC_RO));
assertNotNull(DomainValidator.getTLDEntries(ArrayType.INFRASTRUCTURE_RO));
assertNotNull(DomainValidator.getTLDEntries(ArrayType.LOCAL_RO));
}
// Download and process local copy of http://data.iana.org/TLD/tlds-alpha-by-domain.txt
// Check if the internal TLD table is up to date
// Check if the internal TLD tables have any spurious entries
public static void main(final String a[]) throws Exception {
// Check the arrays first as this affects later checks
// Doing this here makes it easier when updating the lists
boolean OK = true;
for(final String list : new String[]{"INFRASTRUCTURE_TLDS","COUNTRY_CODE_TLDS","GENERIC_TLDS","LOCAL_TLDS"}) {
OK &= isSortedLowerCase(list);
}
if (!OK) {
System.out.println("Fix arrays before retrying; cannot continue");
return;
}
final Set<String> ianaTlds = new HashSet<>(); // keep for comparison with array contents
final DomainValidator dv = DomainValidator.getInstance();
final File txtFile = new File("target/tlds-alpha-by-domain.txt");
final long timestamp = download(txtFile, "https://data.iana.org/TLD/tlds-alpha-by-domain.txt", 0L);
final File htmlFile = new File("target/tlds-alpha-by-domain.html");
// N.B. sometimes the html file may be updated a day or so after the txt file
// if the txt file contains entries not found in the html file, try again in a day or two
download(htmlFile,"https://www.iana.org/domains/root/db", timestamp);
final BufferedReader br = new BufferedReader(new FileReader(txtFile));
String line;
final String header;
line = br.readLine(); // header
if (!line.startsWith("# Version ")) {
br.close();
throw new IOException("File does not have expected Version header");
}
header = line.substring(2);
final boolean generateUnicodeTlds = false; // Change this to generate Unicode TLDs as well
// Parse html page to get entries
final Map<String, String[]> htmlInfo = getHtmlInfo(htmlFile);
final Map<String, String> missingTLD = new TreeMap<>(); // stores entry and comments as String[]
final Map<String, String> missingCC = new TreeMap<>();
while((line = br.readLine()) != null) {
if (!line.startsWith("#")) {
final String unicodeTld; // only different from asciiTld if that was punycode
final String asciiTld = line.toLowerCase(Locale.ENGLISH);
if (line.startsWith("XN--")) {
unicodeTld = IDN.toUnicode(line);
} else {
unicodeTld = asciiTld;
}
if (!dv.isValidTld(asciiTld)) {
final String [] info = htmlInfo.get(asciiTld);
if (info != null) {
final String type = info[0];
final String comment = info[1];
if ("country-code".equals(type)) { // Which list to use?
missingCC.put(asciiTld, unicodeTld + " " + comment);
if (generateUnicodeTlds) {
missingCC.put(unicodeTld, asciiTld + " " + comment);
}
} else {
missingTLD.put(asciiTld, unicodeTld + " " + comment);
if (generateUnicodeTlds) {
missingTLD.put(unicodeTld, asciiTld + " " + comment);
}
}
} else {
System.err.println("Expected to find HTML info for "+ asciiTld);
}
}
ianaTlds.add(asciiTld);
// Don't merge these conditions; generateUnicodeTlds is final so needs to be separate to avoid a warning
if (generateUnicodeTlds && !unicodeTld.equals(asciiTld)) {
ianaTlds.add(unicodeTld);
}
}
}
br.close();
// List html entries not in TLD text list
for(final String key : new TreeMap<>(htmlInfo).keySet()) {
if (!ianaTlds.contains(key)) {
if (isNotInRootZone(key)) {
System.out.println("INFO: HTML entry not yet in root zone: "+key);
} else {
System.err.println("WARN: Expected to find text entry for html: "+key);
}
}
}
if (!missingTLD.isEmpty()) {
printMap(header, missingTLD, "GENERIC_TLDS");
}
if (!missingCC.isEmpty()) {
printMap(header, missingCC, "COUNTRY_CODE_TLDS");
}
// Check if internal tables contain any additional entries
isInIanaList("INFRASTRUCTURE_TLDS", ianaTlds);
isInIanaList("COUNTRY_CODE_TLDS", ianaTlds);
isInIanaList("GENERIC_TLDS", ianaTlds);
// Don't check local TLDS isInIanaList("LOCAL_TLDS", ianaTlds);
System.out.println("Finished checks");
}
private static void printMap(final String header, final Map<String, String> map, final String string) {
System.out.println("Entries missing from "+ string +" List\n");
if (header != null) {
System.out.println(" // Taken from " + header);
}
for (Entry<String, String> me : map.entrySet()) {
System.out.println(" \"" + me.getKey() + "\", // " + me.getValue());
}
System.out.println("\nDone");
}
private static Map<String, String[]> getHtmlInfo(final File f) throws IOException {
final Map<String, String[]> info = new HashMap<>();
// <td><span class="domain tld"><a href="/domains/root/db/ax.html">.ax</a></span></td>
final Pattern domain = Pattern.compile(".*<a href=\"/domains/root/db/([^.]+)\\.html");
// <td>country-code</td>
final Pattern type = Pattern.compile("\\s+<td>([^<]+)</td>");
// <!-- <td>Åland Islands<br/><span class="tld-table-so">Ålands landskapsregering</span></td> </td> -->
// <td>Ålands landskapsregering</td>
final Pattern comment = Pattern.compile("\\s+<td>([^<]+)</td>");
final BufferedReader br = new BufferedReader(new FileReader(f));
String line;
while((line=br.readLine())!=null){
final Matcher m = domain.matcher(line);
if (m.lookingAt()) {
final String dom = m.group(1);
String typ = "??";
String com = "??";
line = br.readLine();
while (line.matches("^\\s*$")) { // extra blank lines introduced
line = br.readLine();
}
final Matcher t = type.matcher(line);
if (t.lookingAt()) {
typ = t.group(1);
line = br.readLine();
if (line.matches("\\s+<!--.*")) {
while(!line.matches(".*-->.*")){
line = br.readLine();
}
line = br.readLine();
}
// Should have comment; is it wrapped?
while(!line.matches(".*</td>.*")){
line += " " +br.readLine();
}
final Matcher n = comment.matcher(line);
if (n.lookingAt()) {
com = n.group(1);
}
// Don't save unused entries
if (com.contains("Not assigned") || com.contains("Retired") || typ.equals("test")) {
// System.out.println("Ignored: " + typ + " " + dom + " " +com);
} else {
info.put(dom.toLowerCase(Locale.ENGLISH), new String[]{typ, com});
// System.out.println("Storing: " + typ + " " + dom + " " +com);
}
} else {
System.err.println("Unexpected type: " + line);
}
}
}
br.close();
return info;
}
/*
* Download a file if it is more recent than our cached copy.
* Unfortunately the server does not seem to honor If-Modified-Since for the
* Html page, so we check if it is newer than the txt file and skip download if so
*/
private static long download(final File f, final String tldurl, final long timestamp) throws IOException {
final int HOUR = 60*60*1000; // an hour in ms
final long modTime;
// For testing purposes, don't download files more than once an hour
if (f.canRead()) {
modTime = f.lastModified();
if (modTime > System.currentTimeMillis()-HOUR) {
System.out.println("Skipping download - found recent " + f);
return modTime;
}
} else {
modTime = 0;
}
final HttpURLConnection hc = (HttpURLConnection) new URL(tldurl).openConnection();
if (modTime > 0) {
final SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");//Sun, 06 Nov 1994 08:49:37 GMT
final String since = sdf.format(new Date(modTime));
hc.addRequestProperty("If-Modified-Since", since);
System.out.println("Found " + f + " with date " + since);
}
if (hc.getResponseCode() == 304) {
System.out.println("Already have most recent " + tldurl);
} else {
System.out.println("Downloading " + tldurl);
final byte[] buff = new byte[1024];
final InputStream is = hc.getInputStream();
final FileOutputStream fos = new FileOutputStream(f);
int len;
while((len=is.read(buff)) != -1) {
fos.write(buff, 0, len);
}
fos.close();
is.close();
System.out.println("Done");
}
return f.lastModified();
}
/**
* Check whether the domain is in the root zone currently.
* Reads the URL http://www.iana.org/domains/root/db/*domain*.html
* (using a local disk cache)
* and checks for the string "This domain is not present in the root zone at this time."
* @param domain the domain to check
* @return true if the string is found
*/
private static boolean isNotInRootZone(final String domain) {
final String tldurl = "http://www.iana.org/domains/root/db/" + domain + ".html";
final File rootCheck = new File("target","tld_" + domain + ".html");
BufferedReader in = null;
try {
download(rootCheck, tldurl, 0L);
in = new BufferedReader(new FileReader(rootCheck));
String inputLine;
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("This domain is not present in the root zone at this time.")) {
return true;
}
}
in.close();
} catch (final IOException e) {
} finally {
closeQuietly(in);
}
return false;
}
private static void closeQuietly(final Closeable in) {
if (in != null) {
try {
in.close();
} catch (final IOException e) {
}
}
}
// isInIanaList and isSorted are split into two methods.
// If/when access to the arrays is possible without reflection, the intermediate
// methods can be dropped
private static boolean isInIanaList(final String arrayName, final Set<String> ianaTlds) throws Exception {
final Field f = DomainValidator.class.getDeclaredField(arrayName);
final boolean isPrivate = Modifier.isPrivate(f.getModifiers());
if (isPrivate) {
f.setAccessible(true);
}
final String[] array = (String[]) f.get(null);
try {
return isInIanaList(arrayName, array, ianaTlds);
} finally {
if (isPrivate) {
f.setAccessible(false);
}
}
}
private static boolean isInIanaList(final String name, final String [] array, final Set<String> ianaTlds) {
for (final String element : array) {
if (!ianaTlds.contains(element)) {
System.out.println(name + " contains unexpected value: " + element);
}
}
return true;
}
private static boolean isSortedLowerCase(final String arrayName) throws Exception {
final Field f = DomainValidator.class.getDeclaredField(arrayName);
final boolean isPrivate = Modifier.isPrivate(f.getModifiers());
if (isPrivate) {
f.setAccessible(true);
}
final String[] array = (String[]) f.get(null);
try {
return isSortedLowerCase(arrayName, array);
} finally {
if (isPrivate) {
f.setAccessible(false);
}
}
}
private static boolean isLowerCase(final String string) {
return string.equals(string.toLowerCase(Locale.ENGLISH));
}
// Check if an array is strictly sorted - and lowerCase
private static boolean isSortedLowerCase(final String name, final String [] array) {
boolean sorted = true;
boolean strictlySorted = true;
final int length = array.length;
boolean lowerCase = isLowerCase(array[length-1]); // Check the last entry
for(int i = 0; i < length-1; i++) { // compare all but last entry with next
final String entry = array[i];
final String nextEntry = array[i+1];
final int cmp = entry.compareTo(nextEntry);
if (cmp > 0) { // out of order
System.out.println("Out of order entry: " + entry + " < " + nextEntry + " in " + name);
sorted = false;
} else if (cmp == 0) {
strictlySorted = false;
System.out.println("Duplicated entry: " + entry + " in " + name);
}
if (!isLowerCase(entry)) {
System.out.println("Non lowerCase entry: " + entry + " in " + name);
lowerCase = false;
}
}
return sorted && strictlySorted && lowerCase;
}
}
| 7,919 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/IBANValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.validator.routines.IBANValidator.Validator;
import org.apache.commons.validator.routines.checkdigit.IBANCheckDigit;
import org.junit.Test;
/**
* IBANValidator Test Case.
* @since 1.5.0
*/
public class IBANValidatorTest {
private static final IBANValidator VALIDATOR = IBANValidator.getInstance();
// Unfortunately Java only returns the last match of repeated patterns
// Use a manual repeat instead
private static final String IBAN_PART = "(?:(\\d+)!([acn]))"; // Assume all parts are fixed length
private static final Pattern IBAN_PAT = Pattern
.compile("([A-Z]{2})" + IBAN_PART + IBAN_PART + IBAN_PART + IBAN_PART + "?" + IBAN_PART + "?" + IBAN_PART + "?" + IBAN_PART + "?");
private static int checkIBAN(final File file, final IBANValidator val) throws Exception {
// The IBAN Registry (TXT) file is a TAB-separated file
// Rows are the entry types, columns are the countries
final CSVFormat format = CSVFormat.DEFAULT.builder().setDelimiter('\t').build();
final Reader rdr = new InputStreamReader(new FileInputStream(file), "ISO_8859_1");
try (final CSVParser p = new CSVParser(rdr, format)) {
CSVRecord country = null;
CSVRecord cc = null;
CSVRecord structure = null;
CSVRecord length = null;
for (final CSVRecord o : p) {
final String item = o.get(0);
if ("Name of country".equals(item)) {
country = o;
} else if ("IBAN prefix country code (ISO 3166)".equals(item)) {
cc = o;
} else if ("IBAN structure".equals(item)) {
structure = o;
} else if ("IBAN length".equals(item)) {
length = o;
}
}
assertNotNull(country);
assertNotNull(length);
assertNotNull(structure);
assertNotNull(cc);
for (int i = 1; i < country.size(); i++) {
try {
final String newLength = length.get(i).split("!")[0]; // El Salvador currently has "28!n"
final String newRE = fmtRE(structure.get(i), Integer.parseInt(newLength));
final Validator valre = val.getValidator(cc.get(i));
if (valre == null) {
System.out.println("// Missing entry:");
printEntry(cc.get(i), newLength, newRE, country.get(i));
} else {
final String currentLength = Integer.toString(valre.ibanLength);
final String currentRE = valre.getRegexValidator().toString().replaceAll("^.+?\\{(.+)}", "$1") // Extract RE from RegexValidator{re}
// string
.replace("\\d", "\\\\d"); // convert \d to \\d
// The above assumes that the RegexValidator contains a single Regex
if (currentRE.equals(newRE) && currentLength.equals(newLength)) {
} else {
System.out.println("// Expected: " + newRE + ", " + newLength + " Actual: " + currentRE + ", " + currentLength);
printEntry(cc.get(i), newLength, newRE, country.get(i));
}
}
} catch (final IllegalArgumentException e) {
e.printStackTrace();
}
}
p.close();
return country.size();
}
}
private static String fmtRE(final String iban_pat, final int iban_len) {
final Matcher m = IBAN_PAT.matcher(iban_pat);
if (!m.matches()) {
throw new IllegalArgumentException("Unexpected IBAN pattern " + iban_pat);
}
final StringBuilder sb = new StringBuilder();
final String cc = m.group(1); // country code
int totalLen = cc.length();
sb.append(cc);
int len = Integer.parseInt(m.group(2)); // length of part
String curType = m.group(3); // part type
for (int i = 4; i <= m.groupCount(); i += 2) {
if (m.group(i) == null) { // reached an optional group
break;
}
final int count = Integer.parseInt(m.group(i));
final String type = m.group(i + 1);
if (type.equals(curType)) { // more of the same type
len += count;
} else {
sb.append(formatToRE(curType, len));
totalLen += len;
curType = type;
len = count;
}
}
sb.append(formatToRE(curType, len));
totalLen += len;
if (iban_len != totalLen) {
throw new IllegalArgumentException("IBAN pattern " + iban_pat + " does not match length " + iban_len);
}
return sb.toString();
}
// convert IBAN type string and length to regex
private static String formatToRE(final String type, final int len) {
final char ctype = type.charAt(0); // assume type.length() == 1
switch (ctype) {
case 'n':
return String.format("\\\\d{%d}", len);
case 'a':
return String.format("[A-Z]{%d}", len);
case 'c':
return String.format("[A-Z0-9]{%d}", len);
default:
throw new IllegalArgumentException("Unexpected type " + type);
}
}
public static void main(final String[] a) throws Exception {
final IBANValidator validator = new IBANValidator();
final File iban_tsv = new File("target", "iban-registry.tsv");
int countries = 0;
if (iban_tsv.canRead()) {
countries = checkIBAN(iban_tsv, validator);
} else {
System.out.println("Please load the file " + iban_tsv.getCanonicalPath() + " from https://www.swift.com/standards/data-standards/iban");
}
System.out.println("Processed " + countries + " countries.");
}
private static void printEntry(final String ccode, final String length, final String ib, final String country) {
final String fmt = String.format("\"%s\"", ib);
System.out.printf(" new Validator(\"%s\", %s, %-40s), // %s\n",
ccode,
length,
fmt,
country);
}
// It's not clear whether IBANs can contain lower case characters
// so we test for both where possible
// Note that the BIC near the start of the code is always upper case or digits
// @formatter:off
private static final String[] VALID_IBAN_FIXTURES = {
"AD1200012030200359100100",
"AE070331234567890123456",
"AL47212110090000000235698741",
"AT611904300234573201",
"AZ21NABZ00000000137010001944",
"BA391290079401028494",
"BE68539007547034",
"BG80BNBG96611020345678",
"BH67BMAG00001299123456",
"BI4210000100010000332045181",
"BR1800000000141455123924100C2",
"BR1800360305000010009795493C1",
"BR9700360305000010009795493P1",
"BY13NBRB3600900000002Z00AB00",
"CH9300762011623852957",
"CR05015202001026284066",
"CY17002001280000001200527600",
"CZ6508000000192000145399",
"CZ9455000000001011038930",
"DE89370400440532013000",
"DJ2110002010010409943020008",
"DK5000400440116243",
"DO28BAGR00000001212453611324",
"EE382200221020145685",
"EG380019000500000000263180002",
"ES9121000418450200051332",
"FI2112345600000785",
"FI5542345670000081",
// FI other
"AX2112345600000785", // FI other
"AX5542345670000081", // FI other
"FO6264600001631634",
"FR1420041010050500013M02606",
// FR 'other'
"BL6820041010050500013M02606", // FR other
"GF4120041010050500013M02606", // FR other
"GP1120041010050500013M02606", // FR other
"MF8420041010050500013M02606", // FR other
"MQ5120041010050500013M02606", // FR other
"NC8420041010050500013M02606", // FR other
"PF5720041010050500013M02606", // FR other
"PM3620041010050500013M02606", // FR other
"RE4220041010050500013M02606", // FR other
"TF2120041010050500013M02606", // FR other
"WF9120041010050500013M02606", // FR other
"YT3120041010050500013M02606", // FR other
"GB29NWBK60161331926819",
// GB 'other'
// "IM...", // GB other
// "JE...", // GB other
// "GG...", // GB other
"GE29NB0000000101904917",
"GI75NWBK000000007099453",
"GL8964710001000206",
"GR1601101250000000012300695",
"GT82TRAJ01020000001210029690",
"HR1210010051863000160",
"HU42117730161111101800000000",
"IE29AIBK93115212345678",
"IL620108000000099999999",
"IQ98NBIQ850123456789012",
"IS140159260076545510730339",
"IT60X0542811101000000123456",
"JO94CBJO0010000000000131000302",
"KW81CBKU0000000000001234560101",
"KZ86125KZT5004100100",
"LB62099900000001001901229114",
"LC55HEMM000100010012001200023015",
"LI21088100002324013AA",
"LT121000011101001000",
"LU280019400644750000",
"LY83002048000020100120361",
"LV80BANK0000435195001",
"LY83002048000020100120361",
"MC5811222000010123456789030",
"MD24AG000225100013104168",
"ME25505000012345678951",
"MK07250120000058984",
"MR1300020001010000123456753",
"MT84MALT011000012345MTLCAST001S",
"MU17BOMM0101101030300200000MUR",
"NL91ABNA0417164300",
"NO9386011117947",
"PK36SCBL0000001123456702",
"PL61109010140000071219812874",
"PS92PALS000000000400123456702",
"PT50000201231234567890154",
"QA58DOHB00001234567890ABCDEFG",
"RO49AAAA1B31007593840000",
"RS35260005601001611379",
"RU0204452560040702810412345678901",
"SA0380000000608010167519",
"SC18SSCB11010000000000001497USD",
"SD8811123456789012",
"SE4550000000058398257466",
"SI56191000000123438",
"SI56263300012039086",
"SK3112000000198742637541",
"SM86U0322509800000000270100",
"ST68000100010051845310112",
"SV62CENR00000000000000700025",
"SV43ACAT00000000000000123123",
"TL380080012345678910157",
"TN5910006035183598478831",
"TR330006100519786457841326",
"UA213223130000026007233566001",
"UA213996220000026007233566001",
"VA59001123000012345678",
"VG96VPVG0000012345678901",
"XK051212012345678906",
};
// @formatter:on
// @formatter:off
private static final String[] INVALID_IBAN_FIXTURES = {
"", // empty
" ", // empty
"A", // too short
"AB", // too short
"FR1420041010050500013m02606", // lowercase version
"MT84MALT011000012345mtlcast001s", // lowercase version
"LI21088100002324013aa", // lowercase version
"QA58DOHB00001234567890abcdefg", // lowercase version
"RO49AAAA1b31007593840000", // lowercase version
"LC62HEMM000100010012001200023015", // wrong in SWIFT
"BY00NBRB3600000000000Z00AB00", // Wrong in SWIFT v73
"ST68000200010192194210112", // ditto
"SV62CENR0000000000000700025", // ditto
};
// @formatter:on
@Test
public void testGetRegexValidatortPatterns() {
assertNotNull("GB", VALIDATOR.getValidator("GB").getRegexValidator().getPatterns());
}
@Test
public void testGetValidator() {
assertNotNull("GB", VALIDATOR.getValidator("GB"));
assertNull("gb", VALIDATOR.getValidator("gb"));
}
@Test
public void testHasValidator() {
assertTrue("GB", VALIDATOR.hasValidator("GB"));
assertFalse("gb", VALIDATOR.hasValidator("gb"));
}
@Test
public void testInValid() {
for (final String f : INVALID_IBAN_FIXTURES) {
assertFalse(f, VALIDATOR.isValid(f));
}
}
@Test
public void testNull() {
assertFalse("isValid(null)", VALIDATOR.isValid(null));
}
@Test
public void testSetDefaultValidator1() {
final IllegalStateException thrown = assertThrows(IllegalStateException.class, () -> VALIDATOR.setValidator("GB", 15, "GB"));
assertThat(thrown.getMessage(), is(equalTo("The singleton validator cannot be modified")));
}
@Test
public void testSetDefaultValidator2() {
final IllegalStateException thrown = assertThrows(IllegalStateException.class, () -> VALIDATOR.setValidator("GB", -1, "GB"));
assertThat(thrown.getMessage(), is(equalTo("The singleton validator cannot be modified")));
}
@Test
public void testSetValidatorLC() {
final IBANValidator validator = new IBANValidator();
final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> validator.setValidator("gb", 15, "GB"));
assertThat(thrown.getMessage(), is(equalTo("Invalid country Code; must be exactly 2 upper-case characters")));
}
@Test
public void testSetValidatorLen_1() {
final IBANValidator validator = new IBANValidator();
assertNotNull("should be present", validator.setValidator("GB", -1, ""));
assertNull("no longer present", validator.setValidator("GB", -1, ""));
}
@Test
public void testSetValidatorLen35() {
final IBANValidator validator = new IBANValidator();
final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> validator.setValidator("GB", 35, "GB"));
assertThat(thrown.getMessage(), is(equalTo("Invalid length parameter, must be in range 8 to 34 inclusive: 35")));
}
@Test
public void testSetValidatorLen7() {
final IBANValidator validator = new IBANValidator();
final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> validator.setValidator("GB", 7, "GB"));
assertThat(thrown.getMessage(), is(equalTo("Invalid length parameter, must be in range 8 to 34 inclusive: 7")));
}
@Test
public void testSorted() {
final IBANValidator validator = new IBANValidator();
final Validator[] vals = validator.getDefaultValidators();
assertNotNull(vals);
for (int i = 1; i < vals.length; i++) {
if (vals[i].countryCode.compareTo(vals[i - 1].countryCode) <= 0) {
fail("Not sorted: " + vals[i].countryCode + " <= " + vals[i - 1].countryCode);
}
}
}
@Test
public void testValid() {
for (final String f : VALID_IBAN_FIXTURES) {
assertTrue("Checksum fail: " + f, IBANCheckDigit.IBAN_CHECK_DIGIT.isValid(f));
assertTrue("Missing validator: " + f, VALIDATOR.hasValidator(f));
assertTrue(f, VALIDATOR.isValid(f));
}
}
}
| 7,920 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/DoubleValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.util.Locale;
/**
* Test Case for DoubleValidator.
*/
public class DoubleValidatorTest extends AbstractNumberValidatorTest {
/**
* Constructor
* @param name test name
*/
public DoubleValidatorTest(final String name) {
super(name);
}
@Override
protected void setUp() {
super.setUp();
validator = new DoubleValidator(false, 0);
strictValidator = new DoubleValidator();
testPattern = "#,###.#";
// testValidateMinMax()
max = null;
maxPlusOne = null;
min = null;
minMinusOne = null;
// testInvalidStrict()
invalidStrict = new String[] {null, "", "X", "X12", "12X", "1X2"};
// testInvalidNotStrict()
invalid = new String[] {null, "", "X", "X12"};
// testValid()
testNumber = Double.valueOf(1234.5);
testZero = Double.valueOf(0);
validStrict = new String[] {"0", "1234.5", "1,234.5"};
validStrictCompare = new Number[] {testZero, testNumber, testNumber};
valid = new String[] {"0", "1234.5", "1,234.5", "1,234.5", "1234.5X"};
validCompare = new Number[] {testZero, testNumber, testNumber, testNumber, testNumber};
testStringUS = "1,234.5";
testStringDE = "1.234,5";
// Localized Pattern test
localeValue = testStringDE;
localePattern = "#.###,#";
testLocale = Locale.GERMANY;
localeExpected = testNumber;
}
/**
* Test DoubleValidator validate Methods
*/
public void testDoubleValidatorMethods() {
final Locale locale = Locale.GERMAN;
final String pattern = "0,00,00";
final String patternVal = "1,23,45";
final String germanPatternVal = "1.23.45";
final String localeVal = "12.345";
final String defaultVal = "12,345";
final String XXXX = "XXXX";
final Double expected = Double.valueOf(12345);
assertEquals("validate(A) default", expected, DoubleValidator.getInstance().validate(defaultVal));
assertEquals("validate(A) locale ", expected, DoubleValidator.getInstance().validate(localeVal, locale));
assertEquals("validate(A) pattern", expected, DoubleValidator.getInstance().validate(patternVal, pattern));
assertEquals("validate(A) both", expected, DoubleValidator.getInstance().validate(germanPatternVal, pattern, Locale.GERMAN));
assertTrue("isValid(A) default", DoubleValidator.getInstance().isValid(defaultVal));
assertTrue("isValid(A) locale ", DoubleValidator.getInstance().isValid(localeVal, locale));
assertTrue("isValid(A) pattern", DoubleValidator.getInstance().isValid(patternVal, pattern));
assertTrue("isValid(A) both", DoubleValidator.getInstance().isValid(germanPatternVal, pattern, Locale.GERMAN));
assertNull("validate(B) default", DoubleValidator.getInstance().validate(XXXX));
assertNull("validate(B) locale ", DoubleValidator.getInstance().validate(XXXX, locale));
assertNull("validate(B) pattern", DoubleValidator.getInstance().validate(XXXX, pattern));
assertNull("validate(B) both", DoubleValidator.getInstance().validate(patternVal, pattern, Locale.GERMAN));
assertFalse("isValid(B) default", DoubleValidator.getInstance().isValid(XXXX));
assertFalse("isValid(B) locale ", DoubleValidator.getInstance().isValid(XXXX, locale));
assertFalse("isValid(B) pattern", DoubleValidator.getInstance().isValid(XXXX, pattern));
assertFalse("isValid(B) both", DoubleValidator.getInstance().isValid(patternVal, pattern, Locale.GERMAN));
}
/**
* Test Double Range/Min/Max
*/
public void testDoubleRangeMinMax() {
final DoubleValidator validator = (DoubleValidator)strictValidator;
final Double number9 = validator.validate("9", "#");
final Double number10 = validator.validate("10", "#");
final Double number11 = validator.validate("11", "#");
final Double number19 = validator.validate("19", "#");
final Double number20 = validator.validate("20", "#");
final Double number21 = validator.validate("21", "#");
// Test isInRange()
assertFalse("isInRange() < min", validator.isInRange(number9, 10, 20));
assertTrue("isInRange() = min", validator.isInRange(number10, 10, 20));
assertTrue("isInRange() in range", validator.isInRange(number11, 10, 20));
assertTrue("isInRange() = max", validator.isInRange(number20, 10, 20));
assertFalse("isInRange() > max", validator.isInRange(number21, 10, 20));
// Test minValue()
assertFalse("minValue() < min", validator.minValue(number9, 10));
assertTrue("minValue() = min", validator.minValue(number10, 10));
assertTrue("minValue() > min", validator.minValue(number11, 10));
// Test minValue()
assertTrue("maxValue() < max", validator.maxValue(number19, 20));
assertTrue("maxValue() = max", validator.maxValue(number20, 20));
assertFalse("maxValue() > max", validator.maxValue(number21, 20));
}
}
| 7,921 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/IntegerValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.util.Locale;
/**
* Test Case for IntegerValidator.
*/
public class IntegerValidatorTest extends AbstractNumberValidatorTest {
private static final Integer INT_MIN_VAL = Integer.valueOf(Integer.MIN_VALUE);
private static final Integer INT_MAX_VAL = Integer.valueOf(Integer.MAX_VALUE);
private static final String INT_MAX = "2147483647";
private static final String INT_MAX_0 = "2147483647.99999999999999999999999"; // force double rounding
private static final String INT_MAX_1 = "2147483648";
private static final String INT_MIN = "-2147483648";
private static final String INT_MIN_0 = "-2147483648.99999999999999999999999"; // force double rounding";
private static final String INT_MIN_1 = "-2147483649";
/**
* Constructor
* @param name test name
*/
public IntegerValidatorTest(final String name) {
super(name);
}
@Override
protected void setUp() {
super.setUp();
validator = new IntegerValidator(false, 0);
strictValidator = new IntegerValidator();
testPattern = "#,###";
// testValidateMinMax()
max = Integer.valueOf(Integer.MAX_VALUE);
maxPlusOne = Long.valueOf(max.longValue() + 1);
min = Integer.valueOf(Integer.MIN_VALUE);
minMinusOne = Long.valueOf(min.longValue() - 1);
// testInvalidStrict()
invalidStrict = new String[] {null, "", "X", "X12", "12X", "1X2", "1.2", INT_MAX_1, INT_MIN_1};
// testInvalidNotStrict()
invalid = new String[] {null, "", "X", "X12", INT_MAX_1, INT_MIN_1};
// testValid()
testNumber = Integer.valueOf(1234);
testZero = Integer.valueOf(0);
validStrict = new String[] {"0", "1234", "1,234", INT_MAX, INT_MIN};
validStrictCompare = new Number[] {testZero, testNumber, testNumber, INT_MAX_VAL, INT_MIN_VAL};
valid = new String[] {"0", "1234", "1,234", "1,234.5", "1234X", INT_MAX, INT_MIN, INT_MAX_0, INT_MIN_0};
validCompare = new Number[] {testZero, testNumber, testNumber, testNumber, testNumber, INT_MAX_VAL, INT_MIN_VAL, INT_MAX_VAL, INT_MIN_VAL};
testStringUS = "1,234";
testStringDE = "1.234";
// Localized Pattern test
localeValue = testStringDE;
localePattern = "#.###";
testLocale = Locale.GERMANY;
localeExpected = testNumber;
}
/**
* Test IntegerValidator validate Methods
*/
public void testIntegerValidatorMethods() {
final Locale locale = Locale.GERMAN;
final String pattern = "0,00,00";
final String patternVal = "1,23,45";
final String germanPatternVal = "1.23.45";
final String localeVal = "12.345";
final String defaultVal = "12,345";
final String XXXX = "XXXX";
final Integer expected = Integer.valueOf(12345);
assertEquals("validate(A) default", expected, IntegerValidator.getInstance().validate(defaultVal));
assertEquals("validate(A) locale ", expected, IntegerValidator.getInstance().validate(localeVal, locale));
assertEquals("validate(A) pattern", expected, IntegerValidator.getInstance().validate(patternVal, pattern));
assertEquals("validate(A) both", expected, IntegerValidator.getInstance().validate(germanPatternVal, pattern, Locale.GERMAN));
assertTrue("isValid(A) default", IntegerValidator.getInstance().isValid(defaultVal));
assertTrue("isValid(A) locale ", IntegerValidator.getInstance().isValid(localeVal, locale));
assertTrue("isValid(A) pattern", IntegerValidator.getInstance().isValid(patternVal, pattern));
assertTrue("isValid(A) both", IntegerValidator.getInstance().isValid(germanPatternVal, pattern, Locale.GERMAN));
assertNull("validate(B) default", IntegerValidator.getInstance().validate(XXXX));
assertNull("validate(B) locale ", IntegerValidator.getInstance().validate(XXXX, locale));
assertNull("validate(B) pattern", IntegerValidator.getInstance().validate(XXXX, pattern));
assertNull("validate(B) both", IntegerValidator.getInstance().validate(patternVal, pattern, Locale.GERMAN));
assertFalse("isValid(B) default", IntegerValidator.getInstance().isValid(XXXX));
assertFalse("isValid(B) locale ", IntegerValidator.getInstance().isValid(XXXX, locale));
assertFalse("isValid(B) pattern", IntegerValidator.getInstance().isValid(XXXX, pattern));
assertFalse("isValid(B) both", IntegerValidator.getInstance().isValid(patternVal, pattern, Locale.GERMAN));
}
/**
* Test Integer Range/Min/Max
*/
public void testIntegerRangeMinMax() {
final IntegerValidator validator = (IntegerValidator)strictValidator;
final Integer number9 = validator.validate("9", "#");
final Integer number10 = validator.validate("10", "#");
final Integer number11 = validator.validate("11", "#");
final Integer number19 = validator.validate("19", "#");
final Integer number20 = validator.validate("20", "#");
final Integer number21 = validator.validate("21", "#");
// Test isInRange()
assertFalse("isInRange() < min", validator.isInRange(number9, 10, 20));
assertTrue("isInRange() = min", validator.isInRange(number10, 10, 20));
assertTrue("isInRange() in range", validator.isInRange(number11, 10, 20));
assertTrue("isInRange() = max", validator.isInRange(number20, 10, 20));
assertFalse("isInRange() > max", validator.isInRange(number21, 10, 20));
// Test minValue()
assertFalse("minValue() < min", validator.minValue(number9, 10));
assertTrue("minValue() = min", validator.minValue(number10, 10));
assertTrue("minValue() > min", validator.minValue(number11, 10));
// Test minValue()
assertTrue("maxValue() < max", validator.maxValue(number19, 20));
assertTrue("maxValue() = max", validator.maxValue(number20, 20));
assertFalse("maxValue() > max", validator.maxValue(number21, 20));
}
public void testMinMaxValues() {
assertTrue("2147483647 is max integer", validator.isValid("2147483647"));
assertFalse("2147483648 > max integer", validator.isValid("2147483648"));
assertTrue("-2147483648 is min integer", validator.isValid("-2147483648"));
assertFalse("-2147483649 < min integer", validator.isValid("-2147483649"));
}
}
| 7,922 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/ISBNValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.util.regex.Pattern;
import junit.framework.TestCase;
/**
* ISBNValidator Test Case.
*/
public class ISBNValidatorTest extends TestCase {
private final String[] validISBN10Format = {
"1234567890",
"123456789X",
"12345-1234567-123456-X",
"12345 1234567 123456 X",
"1-2-3-4",
"1 2 3 4",
};
private final String[] invalidISBN10Format = {
"", // empty
" ", // empty
"1", // too short
"123456789", // too short
"12345678901", // too long
"12345678X0", // X not at end
"123456-1234567-123456-X", // Group too long
"12345-12345678-123456-X", // Publisher too long
"12345-1234567-1234567-X", // Title too long
"12345-1234567-123456-X2", // Check Digit too long
"--1 930110 99 5", // format
"1 930110 99 5--", // format
"1 930110-99 5-", // format
"1.2.3.4", // Invalid Separator
"1=2=3=4", // Invalid Separator
"1_2_3_4", // Invalid Separator
"123456789Y", // Other character at the end
"dsasdsadsa", // invalid characters
"I love sparrows!", // invalid characters
"068-556-98-45" // format
};
private final String[] validISBN13Format = {
"9781234567890",
"9791234567890",
"978-12345-1234567-123456-1",
"979-12345-1234567-123456-1",
"978 12345 1234567 123456 1",
"979 12345 1234567 123456 1",
"978-1-2-3-4",
"979-1-2-3-4",
"978 1 2 3 4",
"979 1 2 3 4",
};
private final String[] invalidISBN13Format = {
"", // empty
" ", // empty
"1", // too short
"978123456789", // too short
"97812345678901", // too long
"978-123456-1234567-123456-1", // Group too long
"978-12345-12345678-123456-1", // Publisher too long
"978-12345-1234567-1234567-1", // Title too long
"978-12345-1234567-123456-12", // Check Digit too long
"--978 1 930110 99 1", // format
"978 1 930110 99 1--", // format
"978 1 930110-99 1-", // format
"123-4-567890-12-8", // format
"978.1.2.3.4", // Invalid Separator
"978=1=2=3=4", // Invalid Separator
"978_1_2_3_4", // Invalid Separator
"978123456789X", // invalid character
"978-0-201-63385-X", // invalid character
"dsasdsadsadsa", // invalid characters
"I love sparrows!", // invalid characters
"979-1-234-567-89-6" // format
};
/**
* Create a test case with the specified name.
* @param name The name of the test
*/
public ISBNValidatorTest(final String name) {
super(name);
}
/**
* Test Valid ISBN-10 formats.
*/
public void testValidISBN10Format() {
final Pattern pattern = Pattern.compile(ISBNValidator.ISBN10_REGEX);
for (int i = 0; i < validISBN10Format.length; i++) {
assertTrue("Pattern[" + i + "]=" + validISBN10Format[i], pattern.matcher(validISBN10Format[i]).matches());
}
}
/**
* Test Invalid ISBN-10 formats.
*/
public void testInvalidISBN10Format() {
final ISBNValidator validator = ISBNValidator.getInstance();
final Pattern pattern = Pattern.compile(ISBNValidator.ISBN10_REGEX);
for (int i = 0; i < invalidISBN10Format.length; i++) {
assertFalse("Pattern[" + i + "]=" + invalidISBN10Format[i], pattern.matcher(invalidISBN10Format[i]).matches());
assertFalse("isValidISBN10[" + i + "]=" + invalidISBN10Format[i], validator.isValidISBN10(invalidISBN10Format[i]));
assertNull("validateISBN10[" + i + "]=" + invalidISBN10Format[i], validator.validateISBN10(invalidISBN10Format[i]));
}
}
/**
* Test Valid ISBN-13 formats.
*/
public void testValidISBN13Format() {
final Pattern pattern = Pattern.compile(ISBNValidator.ISBN13_REGEX);
for (int i = 0; i < validISBN13Format.length; i++) {
assertTrue("Pattern[" + i + "]=" + validISBN13Format[i], pattern.matcher(validISBN13Format[i]).matches());
}
}
/**
* Test Invalid ISBN-13 formats.
*/
public void testInvalidISBN13Format() {
final Pattern pattern = Pattern.compile(ISBNValidator.ISBN13_REGEX);
final ISBNValidator validator = ISBNValidator.getInstance();
for (int i = 0; i < invalidISBN13Format.length; i++) {
assertFalse("Pattern[" + i + "]=" + invalidISBN13Format[i], pattern.matcher(invalidISBN13Format[i]).matches());
assertFalse("isValidISBN13[" + i + "]=" + invalidISBN13Format[i], validator.isValidISBN13(invalidISBN13Format[i]));
assertNull("validateISBN13[" + i + "]=" + invalidISBN13Format[i], validator.validateISBN13(invalidISBN13Format[i]));
}
}
/**
* Test isValid() ISBN-10 codes
*/
public void testIsValidISBN10() {
final ISBNValidator validator = ISBNValidator.getInstance();
assertTrue("isValidISBN10-1", validator.isValidISBN10("1930110995"));
assertTrue("isValidISBN10-2", validator.isValidISBN10("1-930110-99-5"));
assertTrue("isValidISBN10-3", validator.isValidISBN10("1 930110 99 5"));
assertTrue("isValidISBN10-4", validator.isValidISBN10("020163385X"));
assertTrue("isValidISBN10-5", validator.isValidISBN10("0-201-63385-X"));
assertTrue("isValidISBN10-6", validator.isValidISBN10("0 201 63385 X"));
assertTrue("isValid-1", validator.isValid("1930110995"));
assertTrue("isValid-2", validator.isValid("1-930110-99-5"));
assertTrue("isValid-3", validator.isValid("1 930110 99 5"));
assertTrue("isValid-4", validator.isValid("020163385X"));
assertTrue("isValid-5", validator.isValid("0-201-63385-X"));
assertTrue("isValid-6", validator.isValid("0 201 63385 X"));
}
/**
* Test isValid() ISBN-13 codes
*/
public void testIsValidISBN13() {
final ISBNValidator validator = ISBNValidator.getInstance();
assertTrue("isValidISBN13-1", validator.isValidISBN13("9781930110991"));
assertTrue("isValidISBN13-2", validator.isValidISBN13("978-1-930110-99-1"));
assertTrue("isValidISBN13-3", validator.isValidISBN13("978 1 930110 99 1"));
assertTrue("isValidISBN13-4", validator.isValidISBN13("9780201633856"));
assertTrue("isValidISBN13-5", validator.isValidISBN13("978-0-201-63385-6"));
assertTrue("isValidISBN13-6", validator.isValidISBN13("978 0 201 63385 6"));
assertTrue("isValid-1", validator.isValid("9781930110991"));
assertTrue("isValid-2", validator.isValid("978-1-930110-99-1"));
assertTrue("isValid-3", validator.isValid("978 1 930110 99 1"));
assertTrue("isValid-4", validator.isValid("9780201633856"));
assertTrue("isValid-5", validator.isValid("978-0-201-63385-6"));
assertTrue("isValid-6", validator.isValid("978 0 201 63385 6"));
}
/**
* Test validate() ISBN-10 codes (don't convert)
*/
public void testValidateISBN10() {
final ISBNValidator validator = ISBNValidator.getInstance(false);
assertEquals("validateISBN10-1", "1930110995", validator.validateISBN10("1930110995"));
assertEquals("validateISBN10-2", "1930110995", validator.validateISBN10("1-930110-99-5"));
assertEquals("validateISBN10-3", "1930110995", validator.validateISBN10("1 930110 99 5"));
assertEquals("validateISBN10-4", "020163385X", validator.validateISBN10("020163385X"));
assertEquals("validateISBN10-5", "020163385X", validator.validateISBN10("0-201-63385-X"));
assertEquals("validateISBN10-6", "020163385X", validator.validateISBN10("0 201 63385 X"));
assertEquals("validate-1", "1930110995", validator.validate("1930110995"));
assertEquals("validate-2", "1930110995", validator.validate("1-930110-99-5"));
assertEquals("validate-3", "1930110995", validator.validate("1 930110 99 5"));
assertEquals("validate-4", "020163385X", validator.validate("020163385X"));
assertEquals("validate-5", "020163385X", validator.validate("0-201-63385-X"));
assertEquals("validate-6", "020163385X", validator.validate("0 201 63385 X"));
}
/**
* Test validate() ISBN-10 codes (convert)
*/
public void testValidateISBN10Convert() {
final ISBNValidator validator = ISBNValidator.getInstance();
assertEquals("validate-1", "9781930110991", validator.validate("1930110995"));
assertEquals("validate-2", "9781930110991", validator.validate("1-930110-99-5"));
assertEquals("validate-3", "9781930110991", validator.validate("1 930110 99 5"));
assertEquals("validate-4", "9780201633856", validator.validate("020163385X"));
assertEquals("validate-5", "9780201633856", validator.validate("0-201-63385-X"));
assertEquals("validate-6", "9780201633856", validator.validate("0 201 63385 X"));
}
/**
* Test validate() ISBN-13 codes
*/
public void testValidateISBN13() {
final ISBNValidator validator = ISBNValidator.getInstance();
assertEquals("validateISBN13-1", "9781930110991", validator.validateISBN13("9781930110991"));
assertEquals("validateISBN13-2", "9781930110991", validator.validateISBN13("978-1-930110-99-1"));
assertEquals("validateISBN13-3", "9781930110991", validator.validateISBN13("978 1 930110 99 1"));
assertEquals("validateISBN13-4", "9780201633856", validator.validateISBN13("9780201633856"));
assertEquals("validateISBN13-5", "9780201633856", validator.validateISBN13("978-0-201-63385-6"));
assertEquals("validateISBN13-6", "9780201633856", validator.validateISBN13("978 0 201 63385 6"));
assertEquals("validate-1", "9781930110991", validator.validate("9781930110991"));
assertEquals("validate-2", "9781930110991", validator.validate("978-1-930110-99-1"));
assertEquals("validate-3", "9781930110991", validator.validate("978 1 930110 99 1"));
assertEquals("validate-4", "9780201633856", validator.validate("9780201633856"));
assertEquals("validate-5", "9780201633856", validator.validate("978-0-201-63385-6"));
assertEquals("validate-6", "9780201633856", validator.validate("978 0 201 63385 6"));
}
/**
* Test null values
*/
public void testNull() {
final ISBNValidator validator = ISBNValidator.getInstance();
assertFalse("isValid", validator.isValid(null));
assertFalse("isValidISBN10", validator.isValidISBN10(null));
assertFalse("isValidISBN13", validator.isValidISBN13(null));
assertNull("validate", validator.validate(null));
assertNull("validateISBN10", validator.validateISBN10(null));
assertNull("validateISBN13", validator.validateISBN13(null));
assertNull("convertToISBN13", validator.convertToISBN13(null));
}
/**
* Test Invalid ISBN-10 codes
*/
public void testInvalid() {
final ISBNValidator validator = ISBNValidator.getInstance();
String baseCode = "193011099";
assertFalse("ISBN10-0", validator.isValid(baseCode + "0"));
assertFalse("ISBN10-1", validator.isValid(baseCode + "1"));
assertFalse("ISBN10-2", validator.isValid(baseCode + "2"));
assertFalse("ISBN10-3", validator.isValid(baseCode + "3"));
assertFalse("ISBN10-4", validator.isValid(baseCode + "4"));
assertTrue("ISBN10-5", validator.isValid(baseCode + "5")); // valid check digit
assertFalse("ISBN10-6", validator.isValid(baseCode + "6"));
assertFalse("ISBN10-7", validator.isValid(baseCode + "7"));
assertFalse("ISBN10-8", validator.isValid(baseCode + "8"));
assertFalse("ISBN10-9", validator.isValid(baseCode + "9"));
assertFalse("ISBN10-X", validator.isValid(baseCode + "X"));
baseCode = "978193011099";
assertFalse("ISBN13-0", validator.isValid(baseCode + "0"));
assertTrue("ISBN13-1", validator.isValid(baseCode + "1")); // valid check digit
assertFalse("ISBN13-2", validator.isValid(baseCode + "2"));
assertFalse("ISBN13-3", validator.isValid(baseCode + "3"));
assertFalse("ISBN13-4", validator.isValid(baseCode + "4"));
assertFalse("ISBN13-5", validator.isValid(baseCode + "5"));
assertFalse("ISBN13-6", validator.isValid(baseCode + "6"));
assertFalse("ISBN13-7", validator.isValid(baseCode + "7"));
assertFalse("ISBN13-8", validator.isValid(baseCode + "8"));
assertFalse("ISBN13-9", validator.isValid(baseCode + "9"));
}
/**
* Test method for {@link org.apache.commons.validator.routines.ISBNValidator#convertToISBN13(java.lang.String)}.
*/
public void testConversionErrors() {
final ISBNValidator validator = ISBNValidator.getInstance();
String input = null;
try {
input = "123456789 ";
validator.convertToISBN13(input);
fail("Expected IllegalArgumentException for '" + input + "'");
} catch (final IllegalArgumentException e) {
// expected result
}
try {
input = "12345678901";
validator.convertToISBN13(input);
fail("Expected IllegalArgumentException for '" + input + "'");
} catch (final IllegalArgumentException e) {
// expected result
}
try {
input = "";
validator.convertToISBN13(input);
fail("Expected IllegalArgumentException for '" + input + "'");
} catch (final IllegalArgumentException e) {
// expected result
}
try {
input = "X234567890";
validator.convertToISBN13(input);
fail("Expected IllegalArgumentException for '" + input + "'");
} catch (final IllegalArgumentException e) {
// expected result
}
}
}
| 7,923 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/TimeValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import junit.framework.TestCase;
/**
* Test Case for TimeValidator.
*/
public class TimeValidatorTest extends TestCase {
protected static final TimeZone GMT = TimeZone.getTimeZone("GMT"); // 0 offset
protected static final TimeZone EST = TimeZone.getTimeZone("EST"); // - 5 hours
protected TimeValidator validator;
protected String[] patternValid = {
"23-59-59"
,"00-00-00"
,"00-00-01"
,"0-0-0"
,"1-12-1"
,"10-49-18"
,"16-23-46"};
protected Date[] patternExpect = {
createDate(null, 235959, 0)
,createDate(null, 0, 0)
,createDate(null, 1, 0)
,createDate(null, 0, 0)
,createDate(null, 11201, 0)
,createDate(null, 104918, 0)
,createDate(null, 162346, 0)};
protected String[] localeValid = {
"23:59"
,"00:00"
,"00:01"
,"0:0"
,"1:12"
,"10:49"
,"16:23"};
protected Date[] localeExpect = {
createDate(null, 235900, 0)
,createDate(null, 0, 0)
,createDate(null, 100, 0)
,createDate(null, 0, 0)
,createDate(null, 11200, 0)
,createDate(null, 104900, 0)
,createDate(null, 162300, 0)};
protected String[] patternInvalid = {
"24-00-00" // midnight
,"24-00-01" // past midnight
,"25-02-03" // invalid hour
,"10-61-31" // invalid minute
,"10-01-61" // invalid second
,"05:02-29" // invalid sep
,"0X-01:01" // invalid sep
,"05-0X-01" // invalid char
,"10-01-0X" // invalid char
,"01:01:05" // invalid pattern
,"10-10" // invalid pattern
,"10--10" // invalid pattern
,"10-10-"}; // invalid pattern
protected String[] localeInvalid = {
"24:00" // midnight
,"24:00" // past midnight
,"25:02" // invalid hour
,"10:61" // invalid minute
,"05-02" // invalid sep
,"0X:01" // invalid sep
,"05:0X" // invalid char
,"01-01" // invalid pattern
,"10:" // invalid pattern
,"10::1" // invalid pattern
,"10:1:"}; // invalid pattern
private Locale origDefault;
private TimeZone defaultZone;
/**
* Constructor
* @param name test name
*/
public TimeValidatorTest(final String name) {
super(name);
}
@Override
protected void setUp() {
validator = new TimeValidator();
defaultZone = TimeZone.getDefault();
origDefault = Locale.getDefault();
}
/**
* Tear down
*/
@Override
protected void tearDown() {
validator = null;
Locale.setDefault(origDefault);
TimeZone.setDefault(defaultZone);
}
/**
* Test Valid Dates with "pattern" validation
*/
public void testPatternValid() {
for (int i = 0; i < patternValid.length; i++) {
final String text = i + " value=[" +patternValid[i]+"] failed ";
final Calendar calendar = validator.validate(patternValid[i], "HH-mm-ss");
assertNotNull("validateObj() " + text, calendar);
final Date date = calendar.getTime();
assertTrue("isValid() " + text, validator.isValid(patternValid[i], "HH-mm-ss"));
assertEquals("compare " + text, patternExpect[i], date);
}
}
/**
* Test Invalid Dates with "pattern" validation
*/
public void testPatternInvalid() {
for (int i = 0; i < patternInvalid.length; i++) {
final String text = i + " value=[" +patternInvalid[i]+"] passed ";
final Object date = validator.validate(patternInvalid[i], "HH-mm-ss");
assertNull("validate() " + text + date, date);
assertFalse("isValid() " + text, validator.isValid(patternInvalid[i], "HH-mm-ss"));
}
}
/**
* Test Valid Dates with "locale" validation
*/
public void testLocaleValid() {
for (int i = 0; i < localeValid.length; i++) {
final String text = i + " value=[" +localeValid[i]+"] failed ";
final Calendar calendar = validator.validate(localeValid[i], Locale.UK);
assertNotNull("validate() " + text, calendar);
final Date date = calendar.getTime();
assertTrue("isValid() " + text, validator.isValid(localeValid[i], Locale.UK));
assertEquals("compare " + text, localeExpect[i], date);
}
}
/**
* Test Invalid Dates with "locale" validation
*/
public void testLocaleInvalid() {
for (int i = 0; i < localeInvalid.length; i++) {
final String text = i + " value=[" +localeInvalid[i]+"] passed ";
final Object date = validator.validate(localeInvalid[i], Locale.US);
assertNull("validate() " + text + date, date);
assertFalse("isValid() " + text, validator.isValid(localeInvalid[i], Locale.UK));
}
}
/**
* Test time zone methods.
*/
public void testTimeZone() {
// Set the default Locale & TimeZone
Locale.setDefault(Locale.UK);
TimeZone.setDefault(GMT);
Calendar result;
// Default Locale, Default TimeZone
result = validator.validate("18:01");
assertNotNull("default result", result);
assertEquals("default zone", GMT, result.getTimeZone());
assertEquals("default hour", 18, result.get(Calendar.HOUR_OF_DAY));
assertEquals("default minute", 01, result.get(Calendar.MINUTE));
result = null;
// Default Locale, diff TimeZone
result = validator.validate("16:49", EST);
assertNotNull("zone result", result);
assertEquals("zone zone", EST, result.getTimeZone());
assertEquals("zone hour", 16, result.get(Calendar.HOUR_OF_DAY));
assertEquals("zone minute", 49, result.get(Calendar.MINUTE));
result = null;
// Pattern, diff TimeZone
result = validator.validate("14-34", "HH-mm", EST);
assertNotNull("pattern result", result);
assertEquals("pattern zone", EST, result.getTimeZone());
assertEquals("pattern hour", 14, result.get(Calendar.HOUR_OF_DAY));
assertEquals("pattern minute", 34, result.get(Calendar.MINUTE));
result = null;
// Locale, diff TimeZone
result = validator.validate("7:18 PM", Locale.US, EST);
assertNotNull("locale result", result);
assertEquals("locale zone", EST, result.getTimeZone());
assertEquals("locale hour", 19, result.get(Calendar.HOUR_OF_DAY));
assertEquals("locale minute", 18, result.get(Calendar.MINUTE));
result = null;
// Locale & Pattern, diff TimeZone
result = validator.validate("31/Dez/05 21-05", "dd/MMM/yy HH-mm", Locale.GERMAN, EST);
assertNotNull("pattern result", result);
assertEquals("pattern zone", EST, result.getTimeZone());
assertEquals("pattern day", 2005, result.get(Calendar.YEAR));
assertEquals("pattern day", 11, result.get(Calendar.MONTH)); // months are 0-11
assertEquals("pattern day", 31, result.get(Calendar.DATE));
assertEquals("pattern hour", 21, result.get(Calendar.HOUR_OF_DAY));
assertEquals("pattern minute", 05, result.get(Calendar.MINUTE));
result = null;
// Locale & Pattern, default TimeZone
result = validator.validate("31/Dez/05 21-05", "dd/MMM/yy HH-mm", Locale.GERMAN);
assertNotNull("pattern result", result);
assertEquals("pattern zone", GMT, result.getTimeZone());
assertEquals("pattern day", 2005, result.get(Calendar.YEAR));
assertEquals("pattern day", 11, result.get(Calendar.MONTH)); // months are 0-11
assertEquals("pattern day", 31, result.get(Calendar.DATE));
assertEquals("pattern hour", 21, result.get(Calendar.HOUR_OF_DAY));
assertEquals("pattern minute", 05, result.get(Calendar.MINUTE));
result = null;
}
/**
* Test Invalid Dates with "locale" validation
*/
public void testFormat() {
// Set the default Locale
Locale.setDefault(Locale.UK);
final Object test = TimeValidator.getInstance().validate("16:49:23", "HH:mm:ss");
assertNotNull("Test Date ", test);
assertEquals("Format pattern", "16-49-23", validator.format(test, "HH-mm-ss"));
assertEquals("Format locale", "4:49 PM", validator.format(test, Locale.US));
assertEquals("Format default", "16:49", validator.format(test));
}
/**
* Test compare date methods
*/
public void testCompare() {
final int testTime = 154523;
final int min = 100;
final int hour = 10000;
final Calendar milliGreater = createTime(GMT, testTime, 500); // > milli sec
final Calendar value = createTime(GMT, testTime, 400); // test value
final Calendar milliLess = createTime(GMT, testTime, 300); // < milli sec
final Calendar secGreater = createTime(GMT, testTime + 1, 100); // +1 sec
final Calendar secLess = createTime(GMT, testTime - 1, 100); // -1 sec
final Calendar minGreater = createTime(GMT, testTime + min, 100); // +1 min
final Calendar minLess = createTime(GMT, testTime - min, 100); // -1 min
final Calendar hourGreater = createTime(GMT, testTime + hour, 100); // +1 hour
final Calendar hourLess = createTime(GMT, testTime - hour, 100); // -1 hour
assertEquals("mili LT", -1, validator.compareTime(value, milliGreater)); // > milli
assertEquals("mili EQ", 0, validator.compareTime(value, value)); // same time
assertEquals("mili GT", 1, validator.compareTime(value, milliLess)); // < milli
assertEquals("secs LT", -1, validator.compareSeconds(value, secGreater)); // +1 sec
assertEquals("secs =1", 0, validator.compareSeconds(value, milliGreater)); // > milli
assertEquals("secs =2", 0, validator.compareSeconds(value, value)); // same time
assertEquals("secs =3", 0, validator.compareSeconds(value, milliLess)); // < milli
assertEquals("secs GT", 1, validator.compareSeconds(value, secLess)); // -1 sec
assertEquals("mins LT", -1, validator.compareMinutes(value, minGreater)); // +1 min
assertEquals("mins =1", 0, validator.compareMinutes(value, secGreater)); // +1 sec
assertEquals("mins =2", 0, validator.compareMinutes(value, value)); // same time
assertEquals("mins =3", 0, validator.compareMinutes(value, secLess)); // -1 sec
assertEquals("mins GT", 1, validator.compareMinutes(value, minLess)); // -1 min
assertEquals("hour LT", -1, validator.compareHours(value, hourGreater)); // +1 hour
assertEquals("hour =1", 0, validator.compareHours(value, minGreater)); // +1 min
assertEquals("hour =2", 0, validator.compareHours(value, value)); // same time
assertEquals("hour =3", 0, validator.compareHours(value, minLess)); // -1 min
assertEquals("hour GT", 1, validator.compareHours(value, hourLess)); // -1 hour
}
/**
* Create a calendar instance for a specified time zone, date and time.
*
* @param zone The time zone
* @param time the time in HH:mm:ss format
* @param millisecond the milliseconds
* @return the new Calendar instance.
*/
protected static Calendar createTime(final TimeZone zone, final int time, final int millisecond) {
final Calendar calendar = zone == null ? Calendar.getInstance()
: Calendar.getInstance(zone);
final int hour = time / 10000 * 10000;
final int min = time / 100 * 100 - hour;
final int sec = time - (hour + min);
calendar.set(Calendar.YEAR, 1970);
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.DATE, 1);
calendar.set(Calendar.HOUR_OF_DAY, hour / 10000);
calendar.set(Calendar.MINUTE, min / 100);
calendar.set(Calendar.SECOND, sec);
calendar.set(Calendar.MILLISECOND, millisecond);
return calendar;
}
/**
* Create a date instance for a specified time zone, date and time.
*
* @param zone The time zone
* @param time the time in HH:mm:ss format
* @param millisecond the milliseconds
* @return the new Date instance.
*/
protected static Date createDate(final TimeZone zone, final int time, final int millisecond) {
final Calendar calendar = createTime(zone, time, millisecond);
return calendar.getTime();
}
}
| 7,924 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/InetAddressValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import junit.framework.TestCase;
/**
* Test cases for InetAddressValidator.
*/
public class InetAddressValidatorTest extends TestCase {
private InetAddressValidator validator;
/**
* Constructor.
* @param name
*/
public InetAddressValidatorTest(final String name) {
super(name);
}
@Override
protected void setUp() {
validator = new InetAddressValidator();
}
/**
* Test IPs that point to real, well-known hosts (without actually looking them up).
*/
public void testInetAddressesFromTheWild() {
assertTrue("www.apache.org IP should be valid", validator.isValid("140.211.11.130"));
assertTrue("www.l.google.com IP should be valid", validator.isValid("72.14.253.103"));
assertTrue("fsf.org IP should be valid", validator.isValid("199.232.41.5"));
assertTrue("appscs.ign.com IP should be valid", validator.isValid("216.35.123.87"));
}
public void testVALIDATOR_335() {
assertTrue("2001:0438:FFFE:0000:0000:0000:0000:0A35 should be valid", validator.isValid("2001:0438:FFFE:0000:0000:0000:0000:0A35"));
}
public void testVALIDATOR_419() {
String addr;
addr = "0:0:0:0:0:0:13.1.68.3";
assertTrue(addr, validator.isValid(addr));
addr = "0:0:0:0:0:FFFF:129.144.52.38";
assertTrue(addr, validator.isValid(addr));
addr = "::13.1.68.3";
assertTrue(addr, validator.isValid(addr));
addr = "::FFFF:129.144.52.38";
assertTrue(addr, validator.isValid(addr));
addr = "::ffff:192.168.1.1:192.168.1.1";
assertFalse(addr, validator.isValid(addr));
addr = "::192.168.1.1:192.168.1.1";
assertFalse(addr, validator.isValid(addr));
}
/**
* Inet6Address may also contain a scope id
*/
public void testVALIDATOR_445() {
final String [] valid = {
"2001:0000:1234:0000:0000:C1C0:ABCD:0876",
"2001:0000:1234:0000:0000:C1C0:ABCD:0876/123",
"2001:0000:1234:0000:0000:C1C0:ABCD:0876/0",
"2001:0000:1234:0000:0000:C1C0:ABCD:0876%0",
"2001:0000:1234:0000:0000:C1C0:ABCD:0876%abcdefgh",
};
final String [] invalid = {
"2001:0000:1234:0000:0000:C1C0:ABCD:0876/129", // too big
"2001:0000:1234:0000:0000:C1C0:ABCD:0876/-0", // sign not allowed
"2001:0000:1234:0000:0000:C1C0:ABCD:0876/+0", // sign not allowed
"2001:0000:1234:0000:0000:C1C0:ABCD:0876/10O", // non-digit
"2001:0000:1234:0000:0000:C1C0:ABCD:0876/0%0", // /bits before %node-id
"2001:0000:1234:0000:0000:C1C0:ABCD:0876%abc defgh", // space in node id
"2001:0000:1234:0000:0000:C1C0:ABCD:0876%abc%defgh", // '%' in node id
};
for(final String item : valid) {
assertTrue(String.format("%s should be valid", item), validator.isValid(item));
}
for(final String item : invalid) {
assertFalse(String.format("%s should be invalid", item), validator.isValid(item));
}
}
/**
* Test valid and invalid IPs from each address class.
*/
public void testInetAddressesByClass() {
assertTrue("class A IP should be valid", validator.isValid("24.25.231.12"));
assertFalse("illegal class A IP should be invalid", validator.isValid("2.41.32.324"));
assertTrue("class B IP should be valid", validator.isValid("135.14.44.12"));
assertFalse("illegal class B IP should be invalid", validator.isValid("154.123.441.123"));
assertTrue("class C IP should be valid", validator.isValid("213.25.224.32"));
assertFalse("illegal class C IP should be invalid", validator.isValid("201.543.23.11"));
assertTrue("class D IP should be valid", validator.isValid("229.35.159.6"));
assertFalse("illegal class D IP should be invalid", validator.isValid("231.54.11.987"));
assertTrue("class E IP should be valid", validator.isValid("248.85.24.92"));
assertFalse("illegal class E IP should be invalid", validator.isValid("250.21.323.48"));
}
/**
* Test reserved IPs.
*/
public void testReservedInetAddresses() {
assertTrue("localhost IP should be valid", validator.isValid("127.0.0.1"));
assertTrue("broadcast IP should be valid", validator.isValid("255.255.255.255"));
}
/**
* Test obviously broken IPs.
*/
public void testBrokenInetAddresses() {
assertFalse("IP with characters should be invalid", validator.isValid("124.14.32.abc"));
// TODO: there is some debate as to whether leading zeros should be allowed
// They are ambiguous: does the leading 0 mean octal?
assertFalse("IP with leading zeroes should be invalid", validator.isValid("124.14.32.01"));
assertFalse("IP with three groups should be invalid", validator.isValid("23.64.12"));
assertFalse("IP with five groups should be invalid", validator.isValid("26.34.23.77.234"));
assertFalse("IP empty string should be invalid", validator.isValidInet6Address(""));// empty string
}
/**
* Test IPv6 addresses.
* <p>These tests were ported from a
* <a href="http://download.dartware.com/thirdparty/test-ipv6-regex.pl">Perl script</a>.</p>
*
*/
public void testIPv6() {
// The original Perl script contained a lot of duplicate tests.
// I removed the duplicates I noticed, but there may be more.
assertFalse("IPV6 empty string should be invalid", validator.isValidInet6Address(""));// empty string
assertTrue("IPV6 ::1 should be valid", validator.isValidInet6Address("::1"));// loopback, compressed, non-routable
assertTrue("IPV6 :: should be valid", validator.isValidInet6Address("::"));// unspecified, compressed, non-routable
assertTrue("IPV6 0:0:0:0:0:0:0:1 should be valid", validator.isValidInet6Address("0:0:0:0:0:0:0:1"));// loopback, full
assertTrue("IPV6 0:0:0:0:0:0:0:0 should be valid", validator.isValidInet6Address("0:0:0:0:0:0:0:0"));// unspecified, full
assertTrue("IPV6 2001:DB8:0:0:8:800:200C:417A should be valid", validator.isValidInet6Address("2001:DB8:0:0:8:800:200C:417A"));// unicast, full
assertTrue("IPV6 FF01:0:0:0:0:0:0:101 should be valid", validator.isValidInet6Address("FF01:0:0:0:0:0:0:101"));// multicast, full
assertTrue("IPV6 2001:DB8::8:800:200C:417A should be valid", validator.isValidInet6Address("2001:DB8::8:800:200C:417A"));// unicast, compressed
assertTrue("IPV6 FF01::101 should be valid", validator.isValidInet6Address("FF01::101"));// multicast, compressed
assertFalse("IPV6 2001:DB8:0:0:8:800:200C:417A:221 should be invalid", validator.isValidInet6Address("2001:DB8:0:0:8:800:200C:417A:221"));// unicast, full
assertFalse("IPV6 FF01::101::2 should be invalid", validator.isValidInet6Address("FF01::101::2"));// multicast, compressed
assertTrue("IPV6 fe80::217:f2ff:fe07:ed62 should be valid", validator.isValidInet6Address("fe80::217:f2ff:fe07:ed62"));
assertTrue("IPV6 2001:0000:1234:0000:0000:C1C0:ABCD:0876 should be valid", validator.isValidInet6Address("2001:0000:1234:0000:0000:C1C0:ABCD:0876"));
assertTrue("IPV6 3ffe:0b00:0000:0000:0001:0000:0000:000a should be valid", validator.isValidInet6Address("3ffe:0b00:0000:0000:0001:0000:0000:000a"));
assertTrue("IPV6 FF02:0000:0000:0000:0000:0000:0000:0001 should be valid", validator.isValidInet6Address("FF02:0000:0000:0000:0000:0000:0000:0001"));
assertTrue("IPV6 0000:0000:0000:0000:0000:0000:0000:0001 should be valid", validator.isValidInet6Address("0000:0000:0000:0000:0000:0000:0000:0001"));
assertTrue("IPV6 0000:0000:0000:0000:0000:0000:0000:0000 should be valid", validator.isValidInet6Address("0000:0000:0000:0000:0000:0000:0000:0000"));
assertFalse("IPV6 02001:0000:1234:0000:0000:C1C0:ABCD:0876 should be invalid", validator.isValidInet6Address("02001:0000:1234:0000:0000:C1C0:ABCD:0876")); // extra 0 not allowed!
assertFalse("IPV6 2001:0000:1234:0000:00001:C1C0:ABCD:0876 should be invalid", validator.isValidInet6Address("2001:0000:1234:0000:00001:C1C0:ABCD:0876")); // extra 0 not allowed!
assertFalse("IPV6 2001:0000:1234:0000:0000:C1C0:ABCD:0876 0 should be invalid", validator.isValidInet6Address("2001:0000:1234:0000:0000:C1C0:ABCD:0876 0")); // junk after valid address
assertFalse("IPV6 2001:0000:1234: 0000:0000:C1C0:ABCD:0876 should be invalid", validator.isValidInet6Address("2001:0000:1234: 0000:0000:C1C0:ABCD:0876")); // internal space
assertFalse("IPV6 3ffe:0b00:0000:0001:0000:0000:000a should be invalid", validator.isValidInet6Address("3ffe:0b00:0000:0001:0000:0000:000a")); // seven segments
assertFalse("IPV6 FF02:0000:0000:0000:0000:0000:0000:0000:0001 should be invalid", validator.isValidInet6Address("FF02:0000:0000:0000:0000:0000:0000:0000:0001")); // nine segments
assertFalse("IPV6 3ffe:b00::1::a should be invalid", validator.isValidInet6Address("3ffe:b00::1::a")); // double "::"
assertFalse("IPV6 ::1111:2222:3333:4444:5555:6666:: should be invalid", validator.isValidInet6Address("::1111:2222:3333:4444:5555:6666::")); // double "::"
assertTrue("IPV6 2::10 should be valid", validator.isValidInet6Address("2::10"));
assertTrue("IPV6 ff02::1 should be valid", validator.isValidInet6Address("ff02::1"));
assertTrue("IPV6 fe80:: should be valid", validator.isValidInet6Address("fe80::"));
assertTrue("IPV6 2002:: should be valid", validator.isValidInet6Address("2002::"));
assertTrue("IPV6 2001:db8:: should be valid", validator.isValidInet6Address("2001:db8::"));
assertTrue("IPV6 2001:0db8:1234:: should be valid", validator.isValidInet6Address("2001:0db8:1234::"));
assertTrue("IPV6 ::ffff:0:0 should be valid", validator.isValidInet6Address("::ffff:0:0"));
assertTrue("IPV6 1:2:3:4:5:6:7:8 should be valid", validator.isValidInet6Address("1:2:3:4:5:6:7:8"));
assertTrue("IPV6 1:2:3:4:5:6::8 should be valid", validator.isValidInet6Address("1:2:3:4:5:6::8"));
assertTrue("IPV6 1:2:3:4:5::8 should be valid", validator.isValidInet6Address("1:2:3:4:5::8"));
assertTrue("IPV6 1:2:3:4::8 should be valid", validator.isValidInet6Address("1:2:3:4::8"));
assertTrue("IPV6 1:2:3::8 should be valid", validator.isValidInet6Address("1:2:3::8"));
assertTrue("IPV6 1:2::8 should be valid", validator.isValidInet6Address("1:2::8"));
assertTrue("IPV6 1::8 should be valid", validator.isValidInet6Address("1::8"));
assertTrue("IPV6 1::2:3:4:5:6:7 should be valid", validator.isValidInet6Address("1::2:3:4:5:6:7"));
assertTrue("IPV6 1::2:3:4:5:6 should be valid", validator.isValidInet6Address("1::2:3:4:5:6"));
assertTrue("IPV6 1::2:3:4:5 should be valid", validator.isValidInet6Address("1::2:3:4:5"));
assertTrue("IPV6 1::2:3:4 should be valid", validator.isValidInet6Address("1::2:3:4"));
assertTrue("IPV6 1::2:3 should be valid", validator.isValidInet6Address("1::2:3"));
assertTrue("IPV6 ::2:3:4:5:6:7:8 should be valid", validator.isValidInet6Address("::2:3:4:5:6:7:8"));
assertTrue("IPV6 ::2:3:4:5:6:7 should be valid", validator.isValidInet6Address("::2:3:4:5:6:7"));
assertTrue("IPV6 ::2:3:4:5:6 should be valid", validator.isValidInet6Address("::2:3:4:5:6"));
assertTrue("IPV6 ::2:3:4:5 should be valid", validator.isValidInet6Address("::2:3:4:5"));
assertTrue("IPV6 ::2:3:4 should be valid", validator.isValidInet6Address("::2:3:4"));
assertTrue("IPV6 ::2:3 should be valid", validator.isValidInet6Address("::2:3"));
assertTrue("IPV6 ::8 should be valid", validator.isValidInet6Address("::8"));
assertTrue("IPV6 1:2:3:4:5:6:: should be valid", validator.isValidInet6Address("1:2:3:4:5:6::"));
assertTrue("IPV6 1:2:3:4:5:: should be valid", validator.isValidInet6Address("1:2:3:4:5::"));
assertTrue("IPV6 1:2:3:4:: should be valid", validator.isValidInet6Address("1:2:3:4::"));
assertTrue("IPV6 1:2:3:: should be valid", validator.isValidInet6Address("1:2:3::"));
assertTrue("IPV6 1:2:: should be valid", validator.isValidInet6Address("1:2::"));
assertTrue("IPV6 1:: should be valid", validator.isValidInet6Address("1::"));
assertTrue("IPV6 1:2:3:4:5::7:8 should be valid", validator.isValidInet6Address("1:2:3:4:5::7:8"));
assertFalse("IPV6 1:2:3::4:5::7:8 should be invalid", validator.isValidInet6Address("1:2:3::4:5::7:8")); // Double "::"
assertFalse("IPV6 12345::6:7:8 should be invalid", validator.isValidInet6Address("12345::6:7:8"));
assertTrue("IPV6 1:2:3:4::7:8 should be valid", validator.isValidInet6Address("1:2:3:4::7:8"));
assertTrue("IPV6 1:2:3::7:8 should be valid", validator.isValidInet6Address("1:2:3::7:8"));
assertTrue("IPV6 1:2::7:8 should be valid", validator.isValidInet6Address("1:2::7:8"));
assertTrue("IPV6 1::7:8 should be valid", validator.isValidInet6Address("1::7:8"));
// IPv4 addresses as dotted-quads
assertTrue("IPV6 1:2:3:4:5:6:1.2.3.4 should be valid", validator.isValidInet6Address("1:2:3:4:5:6:1.2.3.4"));
assertTrue("IPV6 1:2:3:4:5::1.2.3.4 should be valid", validator.isValidInet6Address("1:2:3:4:5::1.2.3.4"));
assertTrue("IPV6 1:2:3:4::1.2.3.4 should be valid", validator.isValidInet6Address("1:2:3:4::1.2.3.4"));
assertTrue("IPV6 1:2:3::1.2.3.4 should be valid", validator.isValidInet6Address("1:2:3::1.2.3.4"));
assertTrue("IPV6 1:2::1.2.3.4 should be valid", validator.isValidInet6Address("1:2::1.2.3.4"));
assertTrue("IPV6 1::1.2.3.4 should be valid", validator.isValidInet6Address("1::1.2.3.4"));
assertTrue("IPV6 1:2:3:4::5:1.2.3.4 should be valid", validator.isValidInet6Address("1:2:3:4::5:1.2.3.4"));
assertTrue("IPV6 1:2:3::5:1.2.3.4 should be valid", validator.isValidInet6Address("1:2:3::5:1.2.3.4"));
assertTrue("IPV6 1:2::5:1.2.3.4 should be valid", validator.isValidInet6Address("1:2::5:1.2.3.4"));
assertTrue("IPV6 1::5:1.2.3.4 should be valid", validator.isValidInet6Address("1::5:1.2.3.4"));
assertTrue("IPV6 1::5:11.22.33.44 should be valid", validator.isValidInet6Address("1::5:11.22.33.44"));
assertFalse("IPV6 1::5:400.2.3.4 should be invalid", validator.isValidInet6Address("1::5:400.2.3.4"));
assertFalse("IPV6 1::5:260.2.3.4 should be invalid", validator.isValidInet6Address("1::5:260.2.3.4"));
assertFalse("IPV6 1::5:256.2.3.4 should be invalid", validator.isValidInet6Address("1::5:256.2.3.4"));
assertFalse("IPV6 1::5:1.256.3.4 should be invalid", validator.isValidInet6Address("1::5:1.256.3.4"));
assertFalse("IPV6 1::5:1.2.256.4 should be invalid", validator.isValidInet6Address("1::5:1.2.256.4"));
assertFalse("IPV6 1::5:1.2.3.256 should be invalid", validator.isValidInet6Address("1::5:1.2.3.256"));
assertFalse("IPV6 1::5:300.2.3.4 should be invalid", validator.isValidInet6Address("1::5:300.2.3.4"));
assertFalse("IPV6 1::5:1.300.3.4 should be invalid", validator.isValidInet6Address("1::5:1.300.3.4"));
assertFalse("IPV6 1::5:1.2.300.4 should be invalid", validator.isValidInet6Address("1::5:1.2.300.4"));
assertFalse("IPV6 1::5:1.2.3.300 should be invalid", validator.isValidInet6Address("1::5:1.2.3.300"));
assertFalse("IPV6 1::5:900.2.3.4 should be invalid", validator.isValidInet6Address("1::5:900.2.3.4"));
assertFalse("IPV6 1::5:1.900.3.4 should be invalid", validator.isValidInet6Address("1::5:1.900.3.4"));
assertFalse("IPV6 1::5:1.2.900.4 should be invalid", validator.isValidInet6Address("1::5:1.2.900.4"));
assertFalse("IPV6 1::5:1.2.3.900 should be invalid", validator.isValidInet6Address("1::5:1.2.3.900"));
assertFalse("IPV6 1::5:300.300.300.300 should be invalid", validator.isValidInet6Address("1::5:300.300.300.300"));
assertFalse("IPV6 1::5:3000.30.30.30 should be invalid", validator.isValidInet6Address("1::5:3000.30.30.30"));
assertFalse("IPV6 1::400.2.3.4 should be invalid", validator.isValidInet6Address("1::400.2.3.4"));
assertFalse("IPV6 1::260.2.3.4 should be invalid", validator.isValidInet6Address("1::260.2.3.4"));
assertFalse("IPV6 1::256.2.3.4 should be invalid", validator.isValidInet6Address("1::256.2.3.4"));
assertFalse("IPV6 1::1.256.3.4 should be invalid", validator.isValidInet6Address("1::1.256.3.4"));
assertFalse("IPV6 1::1.2.256.4 should be invalid", validator.isValidInet6Address("1::1.2.256.4"));
assertFalse("IPV6 1::1.2.3.256 should be invalid", validator.isValidInet6Address("1::1.2.3.256"));
assertFalse("IPV6 1::300.2.3.4 should be invalid", validator.isValidInet6Address("1::300.2.3.4"));
assertFalse("IPV6 1::1.300.3.4 should be invalid", validator.isValidInet6Address("1::1.300.3.4"));
assertFalse("IPV6 1::1.2.300.4 should be invalid", validator.isValidInet6Address("1::1.2.300.4"));
assertFalse("IPV6 1::1.2.3.300 should be invalid", validator.isValidInet6Address("1::1.2.3.300"));
assertFalse("IPV6 1::900.2.3.4 should be invalid", validator.isValidInet6Address("1::900.2.3.4"));
assertFalse("IPV6 1::1.900.3.4 should be invalid", validator.isValidInet6Address("1::1.900.3.4"));
assertFalse("IPV6 1::1.2.900.4 should be invalid", validator.isValidInet6Address("1::1.2.900.4"));
assertFalse("IPV6 1::1.2.3.900 should be invalid", validator.isValidInet6Address("1::1.2.3.900"));
assertFalse("IPV6 1::300.300.300.300 should be invalid", validator.isValidInet6Address("1::300.300.300.300"));
assertFalse("IPV6 1::3000.30.30.30 should be invalid", validator.isValidInet6Address("1::3000.30.30.30"));
assertFalse("IPV6 ::400.2.3.4 should be invalid", validator.isValidInet6Address("::400.2.3.4"));
assertFalse("IPV6 ::260.2.3.4 should be invalid", validator.isValidInet6Address("::260.2.3.4"));
assertFalse("IPV6 ::256.2.3.4 should be invalid", validator.isValidInet6Address("::256.2.3.4"));
assertFalse("IPV6 ::1.256.3.4 should be invalid", validator.isValidInet6Address("::1.256.3.4"));
assertFalse("IPV6 ::1.2.256.4 should be invalid", validator.isValidInet6Address("::1.2.256.4"));
assertFalse("IPV6 ::1.2.3.256 should be invalid", validator.isValidInet6Address("::1.2.3.256"));
assertFalse("IPV6 ::300.2.3.4 should be invalid", validator.isValidInet6Address("::300.2.3.4"));
assertFalse("IPV6 ::1.300.3.4 should be invalid", validator.isValidInet6Address("::1.300.3.4"));
assertFalse("IPV6 ::1.2.300.4 should be invalid", validator.isValidInet6Address("::1.2.300.4"));
assertFalse("IPV6 ::1.2.3.300 should be invalid", validator.isValidInet6Address("::1.2.3.300"));
assertFalse("IPV6 ::900.2.3.4 should be invalid", validator.isValidInet6Address("::900.2.3.4"));
assertFalse("IPV6 ::1.900.3.4 should be invalid", validator.isValidInet6Address("::1.900.3.4"));
assertFalse("IPV6 ::1.2.900.4 should be invalid", validator.isValidInet6Address("::1.2.900.4"));
assertFalse("IPV6 ::1.2.3.900 should be invalid", validator.isValidInet6Address("::1.2.3.900"));
assertFalse("IPV6 ::300.300.300.300 should be invalid", validator.isValidInet6Address("::300.300.300.300"));
assertFalse("IPV6 ::3000.30.30.30 should be invalid", validator.isValidInet6Address("::3000.30.30.30"));
assertTrue("IPV6 fe80::217:f2ff:254.7.237.98 should be valid", validator.isValidInet6Address("fe80::217:f2ff:254.7.237.98"));
assertTrue("IPV6 ::ffff:192.168.1.26 should be valid", validator.isValidInet6Address("::ffff:192.168.1.26"));
assertFalse("IPV6 2001:1:1:1:1:1:255Z255X255Y255 should be invalid", validator.isValidInet6Address("2001:1:1:1:1:1:255Z255X255Y255")); // garbage instead of "." in IPv4
assertFalse("IPV6 ::ffff:192x168.1.26 should be invalid", validator.isValidInet6Address("::ffff:192x168.1.26")); // ditto
assertTrue("IPV6 ::ffff:192.168.1.1 should be valid", validator.isValidInet6Address("::ffff:192.168.1.1"));
assertTrue("IPV6 0:0:0:0:0:0:13.1.68.3 should be valid", validator.isValidInet6Address("0:0:0:0:0:0:13.1.68.3"));// IPv4-compatible IPv6 address, full, deprecated
assertTrue("IPV6 0:0:0:0:0:FFFF:129.144.52.38 should be valid", validator.isValidInet6Address("0:0:0:0:0:FFFF:129.144.52.38"));// IPv4-mapped IPv6 address, full
assertTrue("IPV6 ::13.1.68.3 should be valid", validator.isValidInet6Address("::13.1.68.3"));// IPv4-compatible IPv6 address, compressed, deprecated
assertTrue("IPV6 ::FFFF:129.144.52.38 should be valid", validator.isValidInet6Address("::FFFF:129.144.52.38"));// IPv4-mapped IPv6 address, compressed
assertTrue("IPV6 fe80:0:0:0:204:61ff:254.157.241.86 should be valid", validator.isValidInet6Address("fe80:0:0:0:204:61ff:254.157.241.86"));
assertTrue("IPV6 fe80::204:61ff:254.157.241.86 should be valid", validator.isValidInet6Address("fe80::204:61ff:254.157.241.86"));
assertTrue("IPV6 ::ffff:12.34.56.78 should be valid", validator.isValidInet6Address("::ffff:12.34.56.78"));
assertFalse("IPV6 ::ffff:2.3.4 should be invalid", validator.isValidInet6Address("::ffff:2.3.4"));
assertFalse("IPV6 ::ffff:257.1.2.3 should be invalid", validator.isValidInet6Address("::ffff:257.1.2.3"));
assertFalse("IPV6 1.2.3.4 should be invalid", validator.isValidInet6Address("1.2.3.4"));
assertFalse("IPV6 1.2.3.4:1111:2222:3333:4444::5555 should be invalid", validator.isValidInet6Address("1.2.3.4:1111:2222:3333:4444::5555"));
assertFalse("IPV6 1.2.3.4:1111:2222:3333::5555 should be invalid", validator.isValidInet6Address("1.2.3.4:1111:2222:3333::5555"));
assertFalse("IPV6 1.2.3.4:1111:2222::5555 should be invalid", validator.isValidInet6Address("1.2.3.4:1111:2222::5555"));
assertFalse("IPV6 1.2.3.4:1111::5555 should be invalid", validator.isValidInet6Address("1.2.3.4:1111::5555"));
assertFalse("IPV6 1.2.3.4::5555 should be invalid", validator.isValidInet6Address("1.2.3.4::5555"));
assertFalse("IPV6 1.2.3.4:: should be invalid", validator.isValidInet6Address("1.2.3.4::"));
// Testing IPv4 addresses represented as dotted-quads
// Leading zeroes in IPv4 addresses not allowed: some systems treat the leading "0" in ".086" as the start of an octal number
// Update: The BNF in RFC-3986 explicitly defines the dec-octet (for IPv4 addresses) not to have a leading zero
assertFalse("IPV6 fe80:0000:0000:0000:0204:61ff:254.157.241.086 should be invalid", validator.isValidInet6Address("fe80:0000:0000:0000:0204:61ff:254.157.241.086"));
assertTrue("IPV6 ::ffff:192.0.2.128 should be valid", validator.isValidInet6Address("::ffff:192.0.2.128")); // but this is OK, since there's a single digit
assertFalse("IPV6 XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:1.2.3.4 should be invalid", validator.isValidInet6Address("XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:1.2.3.4"));
assertFalse("IPV6 1111:2222:3333:4444:5555:6666:00.00.00.00 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:00.00.00.00"));
assertFalse("IPV6 1111:2222:3333:4444:5555:6666:000.000.000.000 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:000.000.000.000"));
assertFalse("IPV6 1111:2222:3333:4444:5555:6666:256.256.256.256 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:256.256.256.256"));
assertTrue("IPV6 fe80:0000:0000:0000:0204:61ff:fe9d:f156 should be valid", validator.isValidInet6Address("fe80:0000:0000:0000:0204:61ff:fe9d:f156"));
assertTrue("IPV6 fe80:0:0:0:204:61ff:fe9d:f156 should be valid", validator.isValidInet6Address("fe80:0:0:0:204:61ff:fe9d:f156"));
assertTrue("IPV6 fe80::204:61ff:fe9d:f156 should be valid", validator.isValidInet6Address("fe80::204:61ff:fe9d:f156"));
assertFalse("IPV6 : should be invalid", validator.isValidInet6Address(":"));
assertTrue("IPV6 ::ffff:c000:280 should be valid", validator.isValidInet6Address("::ffff:c000:280"));
assertFalse("IPV6 1111:2222:3333:4444::5555: should be invalid", validator.isValidInet6Address("1111:2222:3333:4444::5555:"));
assertFalse("IPV6 1111:2222:3333::5555: should be invalid", validator.isValidInet6Address("1111:2222:3333::5555:"));
assertFalse("IPV6 1111:2222::5555: should be invalid", validator.isValidInet6Address("1111:2222::5555:"));
assertFalse("IPV6 1111::5555: should be invalid", validator.isValidInet6Address("1111::5555:"));
assertFalse("IPV6 ::5555: should be invalid", validator.isValidInet6Address("::5555:"));
assertFalse("IPV6 ::: should be invalid", validator.isValidInet6Address(":::"));
assertFalse("IPV6 1111: should be invalid", validator.isValidInet6Address("1111:"));
assertFalse("IPV6 :1111:2222:3333:4444::5555 should be invalid", validator.isValidInet6Address(":1111:2222:3333:4444::5555"));
assertFalse("IPV6 :1111:2222:3333::5555 should be invalid", validator.isValidInet6Address(":1111:2222:3333::5555"));
assertFalse("IPV6 :1111:2222::5555 should be invalid", validator.isValidInet6Address(":1111:2222::5555"));
assertFalse("IPV6 :1111::5555 should be invalid", validator.isValidInet6Address(":1111::5555"));
assertFalse("IPV6 :::5555 should be invalid", validator.isValidInet6Address(":::5555"));
assertTrue("IPV6 2001:0db8:85a3:0000:0000:8a2e:0370:7334 should be valid", validator.isValidInet6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334"));
assertTrue("IPV6 2001:db8:85a3:0:0:8a2e:370:7334 should be valid", validator.isValidInet6Address("2001:db8:85a3:0:0:8a2e:370:7334"));
assertTrue("IPV6 2001:db8:85a3::8a2e:370:7334 should be valid", validator.isValidInet6Address("2001:db8:85a3::8a2e:370:7334"));
assertTrue("IPV6 2001:0db8:0000:0000:0000:0000:1428:57ab should be valid", validator.isValidInet6Address("2001:0db8:0000:0000:0000:0000:1428:57ab"));
assertTrue("IPV6 2001:0db8:0000:0000:0000::1428:57ab should be valid", validator.isValidInet6Address("2001:0db8:0000:0000:0000::1428:57ab"));
assertTrue("IPV6 2001:0db8:0:0:0:0:1428:57ab should be valid", validator.isValidInet6Address("2001:0db8:0:0:0:0:1428:57ab"));
assertTrue("IPV6 2001:0db8:0:0::1428:57ab should be valid", validator.isValidInet6Address("2001:0db8:0:0::1428:57ab"));
assertTrue("IPV6 2001:0db8::1428:57ab should be valid", validator.isValidInet6Address("2001:0db8::1428:57ab"));
assertTrue("IPV6 2001:db8::1428:57ab should be valid", validator.isValidInet6Address("2001:db8::1428:57ab"));
assertTrue("IPV6 ::ffff:0c22:384e should be valid", validator.isValidInet6Address("::ffff:0c22:384e"));
assertTrue("IPV6 2001:0db8:1234:0000:0000:0000:0000:0000 should be valid", validator.isValidInet6Address("2001:0db8:1234:0000:0000:0000:0000:0000"));
assertTrue("IPV6 2001:0db8:1234:ffff:ffff:ffff:ffff:ffff should be valid", validator.isValidInet6Address("2001:0db8:1234:ffff:ffff:ffff:ffff:ffff"));
assertTrue("IPV6 2001:db8:a::123 should be valid", validator.isValidInet6Address("2001:db8:a::123"));
assertFalse("IPV6 123 should be invalid", validator.isValidInet6Address("123"));
assertFalse("IPV6 ldkfj should be invalid", validator.isValidInet6Address("ldkfj"));
assertFalse("IPV6 2001::FFD3::57ab should be invalid", validator.isValidInet6Address("2001::FFD3::57ab"));
assertFalse("IPV6 2001:db8:85a3::8a2e:37023:7334 should be invalid", validator.isValidInet6Address("2001:db8:85a3::8a2e:37023:7334"));
assertFalse("IPV6 2001:db8:85a3::8a2e:370k:7334 should be invalid", validator.isValidInet6Address("2001:db8:85a3::8a2e:370k:7334"));
assertFalse("IPV6 1:2:3:4:5:6:7:8:9 should be invalid", validator.isValidInet6Address("1:2:3:4:5:6:7:8:9"));
assertFalse("IPV6 1::2::3 should be invalid", validator.isValidInet6Address("1::2::3"));
assertFalse("IPV6 1:::3:4:5 should be invalid", validator.isValidInet6Address("1:::3:4:5"));
assertFalse("IPV6 1:2:3::4:5:6:7:8:9 should be invalid", validator.isValidInet6Address("1:2:3::4:5:6:7:8:9"));
assertTrue("IPV6 1111:2222:3333:4444:5555:6666:7777:8888 should be valid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:7777:8888"));
assertTrue("IPV6 1111:2222:3333:4444:5555:6666:7777:: should be valid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:7777::"));
assertTrue("IPV6 1111:2222:3333:4444:5555:6666:: should be valid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666::"));
assertTrue("IPV6 1111:2222:3333:4444:5555:: should be valid", validator.isValidInet6Address("1111:2222:3333:4444:5555::"));
assertTrue("IPV6 1111:2222:3333:4444:: should be valid", validator.isValidInet6Address("1111:2222:3333:4444::"));
assertTrue("IPV6 1111:2222:3333:: should be valid", validator.isValidInet6Address("1111:2222:3333::"));
assertTrue("IPV6 1111:2222:: should be valid", validator.isValidInet6Address("1111:2222::"));
assertTrue("IPV6 1111:: should be valid", validator.isValidInet6Address("1111::"));
assertTrue("IPV6 1111:2222:3333:4444:5555:6666::8888 should be valid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666::8888"));
assertTrue("IPV6 1111:2222:3333:4444:5555::8888 should be valid", validator.isValidInet6Address("1111:2222:3333:4444:5555::8888"));
assertTrue("IPV6 1111:2222:3333:4444::8888 should be valid", validator.isValidInet6Address("1111:2222:3333:4444::8888"));
assertTrue("IPV6 1111:2222:3333::8888 should be valid", validator.isValidInet6Address("1111:2222:3333::8888"));
assertTrue("IPV6 1111:2222::8888 should be valid", validator.isValidInet6Address("1111:2222::8888"));
assertTrue("IPV6 1111::8888 should be valid", validator.isValidInet6Address("1111::8888"));
assertTrue("IPV6 ::8888 should be valid", validator.isValidInet6Address("::8888"));
assertTrue("IPV6 1111:2222:3333:4444:5555::7777:8888 should be valid", validator.isValidInet6Address("1111:2222:3333:4444:5555::7777:8888"));
assertTrue("IPV6 1111:2222:3333:4444::7777:8888 should be valid", validator.isValidInet6Address("1111:2222:3333:4444::7777:8888"));
assertTrue("IPV6 1111:2222:3333::7777:8888 should be valid", validator.isValidInet6Address("1111:2222:3333::7777:8888"));
assertTrue("IPV6 1111:2222::7777:8888 should be valid", validator.isValidInet6Address("1111:2222::7777:8888"));
assertTrue("IPV6 1111::7777:8888 should be valid", validator.isValidInet6Address("1111::7777:8888"));
assertTrue("IPV6 ::7777:8888 should be valid", validator.isValidInet6Address("::7777:8888"));
assertTrue("IPV6 1111:2222:3333:4444::6666:7777:8888 should be valid", validator.isValidInet6Address("1111:2222:3333:4444::6666:7777:8888"));
assertTrue("IPV6 1111:2222:3333::6666:7777:8888 should be valid", validator.isValidInet6Address("1111:2222:3333::6666:7777:8888"));
assertTrue("IPV6 1111:2222::6666:7777:8888 should be valid", validator.isValidInet6Address("1111:2222::6666:7777:8888"));
assertTrue("IPV6 1111::6666:7777:8888 should be valid", validator.isValidInet6Address("1111::6666:7777:8888"));
assertTrue("IPV6 ::6666:7777:8888 should be valid", validator.isValidInet6Address("::6666:7777:8888"));
assertTrue("IPV6 1111:2222:3333::5555:6666:7777:8888 should be valid", validator.isValidInet6Address("1111:2222:3333::5555:6666:7777:8888"));
assertTrue("IPV6 1111:2222::5555:6666:7777:8888 should be valid", validator.isValidInet6Address("1111:2222::5555:6666:7777:8888"));
assertTrue("IPV6 1111::5555:6666:7777:8888 should be valid", validator.isValidInet6Address("1111::5555:6666:7777:8888"));
assertTrue("IPV6 ::5555:6666:7777:8888 should be valid", validator.isValidInet6Address("::5555:6666:7777:8888"));
assertTrue("IPV6 1111:2222::4444:5555:6666:7777:8888 should be valid", validator.isValidInet6Address("1111:2222::4444:5555:6666:7777:8888"));
assertTrue("IPV6 1111::4444:5555:6666:7777:8888 should be valid", validator.isValidInet6Address("1111::4444:5555:6666:7777:8888"));
assertTrue("IPV6 ::4444:5555:6666:7777:8888 should be valid", validator.isValidInet6Address("::4444:5555:6666:7777:8888"));
assertTrue("IPV6 1111::3333:4444:5555:6666:7777:8888 should be valid", validator.isValidInet6Address("1111::3333:4444:5555:6666:7777:8888"));
assertTrue("IPV6 ::3333:4444:5555:6666:7777:8888 should be valid", validator.isValidInet6Address("::3333:4444:5555:6666:7777:8888"));
assertTrue("IPV6 ::2222:3333:4444:5555:6666:7777:8888 should be valid", validator.isValidInet6Address("::2222:3333:4444:5555:6666:7777:8888"));
assertTrue("IPV6 1111:2222:3333:4444:5555:6666:123.123.123.123 should be valid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:123.123.123.123"));
assertTrue("IPV6 1111:2222:3333:4444:5555::123.123.123.123 should be valid", validator.isValidInet6Address("1111:2222:3333:4444:5555::123.123.123.123"));
assertTrue("IPV6 1111:2222:3333:4444::123.123.123.123 should be valid", validator.isValidInet6Address("1111:2222:3333:4444::123.123.123.123"));
assertTrue("IPV6 1111:2222:3333::123.123.123.123 should be valid", validator.isValidInet6Address("1111:2222:3333::123.123.123.123"));
assertTrue("IPV6 1111:2222::123.123.123.123 should be valid", validator.isValidInet6Address("1111:2222::123.123.123.123"));
assertTrue("IPV6 1111::123.123.123.123 should be valid", validator.isValidInet6Address("1111::123.123.123.123"));
assertTrue("IPV6 ::123.123.123.123 should be valid", validator.isValidInet6Address("::123.123.123.123"));
assertTrue("IPV6 1111:2222:3333:4444::6666:123.123.123.123 should be valid", validator.isValidInet6Address("1111:2222:3333:4444::6666:123.123.123.123"));
assertTrue("IPV6 1111:2222:3333::6666:123.123.123.123 should be valid", validator.isValidInet6Address("1111:2222:3333::6666:123.123.123.123"));
assertTrue("IPV6 1111:2222::6666:123.123.123.123 should be valid", validator.isValidInet6Address("1111:2222::6666:123.123.123.123"));
assertTrue("IPV6 1111::6666:123.123.123.123 should be valid", validator.isValidInet6Address("1111::6666:123.123.123.123"));
assertTrue("IPV6 ::6666:123.123.123.123 should be valid", validator.isValidInet6Address("::6666:123.123.123.123"));
assertTrue("IPV6 1111:2222:3333::5555:6666:123.123.123.123 should be valid", validator.isValidInet6Address("1111:2222:3333::5555:6666:123.123.123.123"));
assertTrue("IPV6 1111:2222::5555:6666:123.123.123.123 should be valid", validator.isValidInet6Address("1111:2222::5555:6666:123.123.123.123"));
assertTrue("IPV6 1111::5555:6666:123.123.123.123 should be valid", validator.isValidInet6Address("1111::5555:6666:123.123.123.123"));
assertTrue("IPV6 ::5555:6666:123.123.123.123 should be valid", validator.isValidInet6Address("::5555:6666:123.123.123.123"));
assertTrue("IPV6 1111:2222::4444:5555:6666:123.123.123.123 should be valid", validator.isValidInet6Address("1111:2222::4444:5555:6666:123.123.123.123"));
assertTrue("IPV6 1111::4444:5555:6666:123.123.123.123 should be valid", validator.isValidInet6Address("1111::4444:5555:6666:123.123.123.123"));
assertTrue("IPV6 ::4444:5555:6666:123.123.123.123 should be valid", validator.isValidInet6Address("::4444:5555:6666:123.123.123.123"));
assertTrue("IPV6 1111::3333:4444:5555:6666:123.123.123.123 should be valid", validator.isValidInet6Address("1111::3333:4444:5555:6666:123.123.123.123"));
assertTrue("IPV6 ::2222:3333:4444:5555:6666:123.123.123.123 should be valid", validator.isValidInet6Address("::2222:3333:4444:5555:6666:123.123.123.123"));
// Trying combinations of "0" and "::"
// These are all syntactically correct, but are bad form
// because "0" adjacent to "::" should be combined into "::"
assertTrue("IPV6 ::0:0:0:0:0:0:0 should be valid", validator.isValidInet6Address("::0:0:0:0:0:0:0"));
assertTrue("IPV6 ::0:0:0:0:0:0 should be valid", validator.isValidInet6Address("::0:0:0:0:0:0"));
assertTrue("IPV6 ::0:0:0:0:0 should be valid", validator.isValidInet6Address("::0:0:0:0:0"));
assertTrue("IPV6 ::0:0:0:0 should be valid", validator.isValidInet6Address("::0:0:0:0"));
assertTrue("IPV6 ::0:0:0 should be valid", validator.isValidInet6Address("::0:0:0"));
assertTrue("IPV6 ::0:0 should be valid", validator.isValidInet6Address("::0:0"));
assertTrue("IPV6 ::0 should be valid", validator.isValidInet6Address("::0"));
assertTrue("IPV6 0:0:0:0:0:0:0:: should be valid", validator.isValidInet6Address("0:0:0:0:0:0:0::"));
assertTrue("IPV6 0:0:0:0:0:0:: should be valid", validator.isValidInet6Address("0:0:0:0:0:0::"));
assertTrue("IPV6 0:0:0:0:0:: should be valid", validator.isValidInet6Address("0:0:0:0:0::"));
assertTrue("IPV6 0:0:0:0:: should be valid", validator.isValidInet6Address("0:0:0:0::"));
assertTrue("IPV6 0:0:0:: should be valid", validator.isValidInet6Address("0:0:0::"));
assertTrue("IPV6 0:0:: should be valid", validator.isValidInet6Address("0:0::"));
assertTrue("IPV6 0:: should be valid", validator.isValidInet6Address("0::"));
// Invalid data
assertFalse("IPV6 XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX should be invalid", validator.isValidInet6Address("XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX"));
// Too many components
assertFalse("IPV6 1111:2222:3333:4444:5555:6666:7777:8888:9999 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:7777:8888:9999"));
assertFalse("IPV6 1111:2222:3333:4444:5555:6666:7777:8888:: should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:7777:8888::"));
assertFalse("IPV6 ::2222:3333:4444:5555:6666:7777:8888:9999 should be invalid", validator.isValidInet6Address("::2222:3333:4444:5555:6666:7777:8888:9999"));
// Too few components
assertFalse("IPV6 1111:2222:3333:4444:5555:6666:7777 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:7777"));
assertFalse("IPV6 1111:2222:3333:4444:5555:6666 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666"));
assertFalse("IPV6 1111:2222:3333:4444:5555 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555"));
assertFalse("IPV6 1111:2222:3333:4444 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444"));
assertFalse("IPV6 1111:2222:3333 should be invalid", validator.isValidInet6Address("1111:2222:3333"));
assertFalse("IPV6 1111:2222 should be invalid", validator.isValidInet6Address("1111:2222"));
assertFalse("IPV6 1111 should be invalid", validator.isValidInet6Address("1111"));
// Missing :
assertFalse("IPV6 11112222:3333:4444:5555:6666:7777:8888 should be invalid", validator.isValidInet6Address("11112222:3333:4444:5555:6666:7777:8888"));
assertFalse("IPV6 1111:22223333:4444:5555:6666:7777:8888 should be invalid", validator.isValidInet6Address("1111:22223333:4444:5555:6666:7777:8888"));
assertFalse("IPV6 1111:2222:33334444:5555:6666:7777:8888 should be invalid", validator.isValidInet6Address("1111:2222:33334444:5555:6666:7777:8888"));
assertFalse("IPV6 1111:2222:3333:44445555:6666:7777:8888 should be invalid", validator.isValidInet6Address("1111:2222:3333:44445555:6666:7777:8888"));
assertFalse("IPV6 1111:2222:3333:4444:55556666:7777:8888 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:55556666:7777:8888"));
assertFalse("IPV6 1111:2222:3333:4444:5555:66667777:8888 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:66667777:8888"));
assertFalse("IPV6 1111:2222:3333:4444:5555:6666:77778888 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:77778888"));
// Missing : intended for ::
assertFalse("IPV6 1111:2222:3333:4444:5555:6666:7777:8888: should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:7777:8888:"));
assertFalse("IPV6 1111:2222:3333:4444:5555:6666:7777: should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:7777:"));
assertFalse("IPV6 1111:2222:3333:4444:5555:6666: should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:"));
assertFalse("IPV6 1111:2222:3333:4444:5555: should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:"));
assertFalse("IPV6 1111:2222:3333:4444: should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:"));
assertFalse("IPV6 1111:2222:3333: should be invalid", validator.isValidInet6Address("1111:2222:3333:"));
assertFalse("IPV6 1111:2222: should be invalid", validator.isValidInet6Address("1111:2222:"));
assertFalse("IPV6 :8888 should be invalid", validator.isValidInet6Address(":8888"));
assertFalse("IPV6 :7777:8888 should be invalid", validator.isValidInet6Address(":7777:8888"));
assertFalse("IPV6 :6666:7777:8888 should be invalid", validator.isValidInet6Address(":6666:7777:8888"));
assertFalse("IPV6 :5555:6666:7777:8888 should be invalid", validator.isValidInet6Address(":5555:6666:7777:8888"));
assertFalse("IPV6 :4444:5555:6666:7777:8888 should be invalid", validator.isValidInet6Address(":4444:5555:6666:7777:8888"));
assertFalse("IPV6 :3333:4444:5555:6666:7777:8888 should be invalid", validator.isValidInet6Address(":3333:4444:5555:6666:7777:8888"));
assertFalse("IPV6 :2222:3333:4444:5555:6666:7777:8888 should be invalid", validator.isValidInet6Address(":2222:3333:4444:5555:6666:7777:8888"));
assertFalse("IPV6 :1111:2222:3333:4444:5555:6666:7777:8888 should be invalid", validator.isValidInet6Address(":1111:2222:3333:4444:5555:6666:7777:8888"));
// :::
assertFalse("IPV6 :::2222:3333:4444:5555:6666:7777:8888 should be invalid", validator.isValidInet6Address(":::2222:3333:4444:5555:6666:7777:8888"));
assertFalse("IPV6 1111:::3333:4444:5555:6666:7777:8888 should be invalid", validator.isValidInet6Address("1111:::3333:4444:5555:6666:7777:8888"));
assertFalse("IPV6 1111:2222:::4444:5555:6666:7777:8888 should be invalid", validator.isValidInet6Address("1111:2222:::4444:5555:6666:7777:8888"));
assertFalse("IPV6 1111:2222:3333:::5555:6666:7777:8888 should be invalid", validator.isValidInet6Address("1111:2222:3333:::5555:6666:7777:8888"));
assertFalse("IPV6 1111:2222:3333:4444:::6666:7777:8888 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:::6666:7777:8888"));
assertFalse("IPV6 1111:2222:3333:4444:5555:::7777:8888 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:::7777:8888"));
assertFalse("IPV6 1111:2222:3333:4444:5555:6666:::8888 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:::8888"));
assertFalse("IPV6 1111:2222:3333:4444:5555:6666:7777::: should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:7777:::"));
// Double ::
assertFalse("IPV6 ::2222::4444:5555:6666:7777:8888 should be invalid", validator.isValidInet6Address("::2222::4444:5555:6666:7777:8888"));
assertFalse("IPV6 ::2222:3333::5555:6666:7777:8888 should be invalid", validator.isValidInet6Address("::2222:3333::5555:6666:7777:8888"));
assertFalse("IPV6 ::2222:3333:4444::6666:7777:8888 should be invalid", validator.isValidInet6Address("::2222:3333:4444::6666:7777:8888"));
assertFalse("IPV6 ::2222:3333:4444:5555::7777:8888 should be invalid", validator.isValidInet6Address("::2222:3333:4444:5555::7777:8888"));
assertFalse("IPV6 ::2222:3333:4444:5555:7777::8888 should be invalid", validator.isValidInet6Address("::2222:3333:4444:5555:7777::8888"));
assertFalse("IPV6 ::2222:3333:4444:5555:7777:8888:: should be invalid", validator.isValidInet6Address("::2222:3333:4444:5555:7777:8888::"));
assertFalse("IPV6 1111::3333::5555:6666:7777:8888 should be invalid", validator.isValidInet6Address("1111::3333::5555:6666:7777:8888"));
assertFalse("IPV6 1111::3333:4444::6666:7777:8888 should be invalid", validator.isValidInet6Address("1111::3333:4444::6666:7777:8888"));
assertFalse("IPV6 1111::3333:4444:5555::7777:8888 should be invalid", validator.isValidInet6Address("1111::3333:4444:5555::7777:8888"));
assertFalse("IPV6 1111::3333:4444:5555:6666::8888 should be invalid", validator.isValidInet6Address("1111::3333:4444:5555:6666::8888"));
assertFalse("IPV6 1111::3333:4444:5555:6666:7777:: should be invalid", validator.isValidInet6Address("1111::3333:4444:5555:6666:7777::"));
assertFalse("IPV6 1111:2222::4444::6666:7777:8888 should be invalid", validator.isValidInet6Address("1111:2222::4444::6666:7777:8888"));
assertFalse("IPV6 1111:2222::4444:5555::7777:8888 should be invalid", validator.isValidInet6Address("1111:2222::4444:5555::7777:8888"));
assertFalse("IPV6 1111:2222::4444:5555:6666::8888 should be invalid", validator.isValidInet6Address("1111:2222::4444:5555:6666::8888"));
assertFalse("IPV6 1111:2222::4444:5555:6666:7777:: should be invalid", validator.isValidInet6Address("1111:2222::4444:5555:6666:7777::"));
assertFalse("IPV6 1111:2222:3333::5555::7777:8888 should be invalid", validator.isValidInet6Address("1111:2222:3333::5555::7777:8888"));
assertFalse("IPV6 1111:2222:3333::5555:6666::8888 should be invalid", validator.isValidInet6Address("1111:2222:3333::5555:6666::8888"));
assertFalse("IPV6 1111:2222:3333::5555:6666:7777:: should be invalid", validator.isValidInet6Address("1111:2222:3333::5555:6666:7777::"));
assertFalse("IPV6 1111:2222:3333:4444::6666::8888 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444::6666::8888"));
assertFalse("IPV6 1111:2222:3333:4444::6666:7777:: should be invalid", validator.isValidInet6Address("1111:2222:3333:4444::6666:7777::"));
assertFalse("IPV6 1111:2222:3333:4444:5555::7777:: should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555::7777::"));
// Too many components"
assertFalse("IPV6 1111:2222:3333:4444:5555:6666:7777:8888:1.2.3.4 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:7777:8888:1.2.3.4"));
assertFalse("IPV6 1111:2222:3333:4444:5555:6666:7777:1.2.3.4 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:7777:1.2.3.4"));
assertFalse("IPV6 1111:2222:3333:4444:5555:6666::1.2.3.4 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666::1.2.3.4"));
assertFalse("IPV6 ::2222:3333:4444:5555:6666:7777:1.2.3.4 should be invalid", validator.isValidInet6Address("::2222:3333:4444:5555:6666:7777:1.2.3.4"));
assertFalse("IPV6 1111:2222:3333:4444:5555:6666:1.2.3.4.5 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:1.2.3.4.5"));
// Too few components
assertFalse("IPV6 1111:2222:3333:4444:5555:1.2.3.4 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:1.2.3.4"));
assertFalse("IPV6 1111:2222:3333:4444:1.2.3.4 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:1.2.3.4"));
assertFalse("IPV6 1111:2222:3333:1.2.3.4 should be invalid", validator.isValidInet6Address("1111:2222:3333:1.2.3.4"));
assertFalse("IPV6 1111:2222:1.2.3.4 should be invalid", validator.isValidInet6Address("1111:2222:1.2.3.4"));
assertFalse("IPV6 1111:1.2.3.4 should be invalid", validator.isValidInet6Address("1111:1.2.3.4"));
assertFalse("IPV6 1.2.3.4 should be invalid", validator.isValidInet6Address("1.2.3.4"));
// Missing :
assertFalse("IPV6 11112222:3333:4444:5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address("11112222:3333:4444:5555:6666:1.2.3.4"));
assertFalse("IPV6 1111:22223333:4444:5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address("1111:22223333:4444:5555:6666:1.2.3.4"));
assertFalse("IPV6 1111:2222:33334444:5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address("1111:2222:33334444:5555:6666:1.2.3.4"));
assertFalse("IPV6 1111:2222:3333:44445555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address("1111:2222:3333:44445555:6666:1.2.3.4"));
assertFalse("IPV6 1111:2222:3333:4444:55556666:1.2.3.4 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:55556666:1.2.3.4"));
assertFalse("IPV6 1111:2222:3333:4444:5555:66661.2.3.4 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:66661.2.3.4"));
// Missing .
assertFalse("IPV6 1111:2222:3333:4444:5555:6666:255255.255.255 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:255255.255.255"));
assertFalse("IPV6 1111:2222:3333:4444:5555:6666:255.255255.255 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:255.255255.255"));
assertFalse("IPV6 1111:2222:3333:4444:5555:6666:255.255.255255 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:255.255.255255"));
// Missing : intended for ::
assertFalse("IPV6 :1.2.3.4 should be invalid", validator.isValidInet6Address(":1.2.3.4"));
assertFalse("IPV6 :6666:1.2.3.4 should be invalid", validator.isValidInet6Address(":6666:1.2.3.4"));
assertFalse("IPV6 :5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address(":5555:6666:1.2.3.4"));
assertFalse("IPV6 :4444:5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address(":4444:5555:6666:1.2.3.4"));
assertFalse("IPV6 :3333:4444:5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address(":3333:4444:5555:6666:1.2.3.4"));
assertFalse("IPV6 :2222:3333:4444:5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address(":2222:3333:4444:5555:6666:1.2.3.4"));
assertFalse("IPV6 :1111:2222:3333:4444:5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address(":1111:2222:3333:4444:5555:6666:1.2.3.4"));
// :::
assertFalse("IPV6 :::2222:3333:4444:5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address(":::2222:3333:4444:5555:6666:1.2.3.4"));
assertFalse("IPV6 1111:::3333:4444:5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address("1111:::3333:4444:5555:6666:1.2.3.4"));
assertFalse("IPV6 1111:2222:::4444:5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address("1111:2222:::4444:5555:6666:1.2.3.4"));
assertFalse("IPV6 1111:2222:3333:::5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address("1111:2222:3333:::5555:6666:1.2.3.4"));
assertFalse("IPV6 1111:2222:3333:4444:::6666:1.2.3.4 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:::6666:1.2.3.4"));
assertFalse("IPV6 1111:2222:3333:4444:5555:::1.2.3.4 should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:::1.2.3.4"));
// Double ::
assertFalse("IPV6 ::2222::4444:5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address("::2222::4444:5555:6666:1.2.3.4"));
assertFalse("IPV6 ::2222:3333::5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address("::2222:3333::5555:6666:1.2.3.4"));
assertFalse("IPV6 ::2222:3333:4444::6666:1.2.3.4 should be invalid", validator.isValidInet6Address("::2222:3333:4444::6666:1.2.3.4"));
assertFalse("IPV6 ::2222:3333:4444:5555::1.2.3.4 should be invalid", validator.isValidInet6Address("::2222:3333:4444:5555::1.2.3.4"));
assertFalse("IPV6 1111::3333::5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address("1111::3333::5555:6666:1.2.3.4"));
assertFalse("IPV6 1111::3333:4444::6666:1.2.3.4 should be invalid", validator.isValidInet6Address("1111::3333:4444::6666:1.2.3.4"));
assertFalse("IPV6 1111::3333:4444:5555::1.2.3.4 should be invalid", validator.isValidInet6Address("1111::3333:4444:5555::1.2.3.4"));
assertFalse("IPV6 1111:2222::4444::6666:1.2.3.4 should be invalid", validator.isValidInet6Address("1111:2222::4444::6666:1.2.3.4"));
assertFalse("IPV6 1111:2222::4444:5555::1.2.3.4 should be invalid", validator.isValidInet6Address("1111:2222::4444:5555::1.2.3.4"));
assertFalse("IPV6 1111:2222:3333::5555::1.2.3.4 should be invalid", validator.isValidInet6Address("1111:2222:3333::5555::1.2.3.4"));
// Missing parts
assertFalse("IPV6 ::. should be invalid", validator.isValidInet6Address("::."));
assertFalse("IPV6 ::.. should be invalid", validator.isValidInet6Address("::.."));
assertFalse("IPV6 ::... should be invalid", validator.isValidInet6Address("::..."));
assertFalse("IPV6 ::1... should be invalid", validator.isValidInet6Address("::1..."));
assertFalse("IPV6 ::1.2.. should be invalid", validator.isValidInet6Address("::1.2.."));
assertFalse("IPV6 ::1.2.3. should be invalid", validator.isValidInet6Address("::1.2.3."));
assertFalse("IPV6 ::.2.. should be invalid", validator.isValidInet6Address("::.2.."));
assertFalse("IPV6 ::.2.3. should be invalid", validator.isValidInet6Address("::.2.3."));
assertFalse("IPV6 ::.2.3.4 should be invalid", validator.isValidInet6Address("::.2.3.4"));
assertFalse("IPV6 ::..3. should be invalid", validator.isValidInet6Address("::..3."));
assertFalse("IPV6 ::..3.4 should be invalid", validator.isValidInet6Address("::..3.4"));
assertFalse("IPV6 ::...4 should be invalid", validator.isValidInet6Address("::...4"));
// Extra : in front
assertFalse("IPV6 :1111:2222:3333:4444:5555:6666:7777:: should be invalid", validator.isValidInet6Address(":1111:2222:3333:4444:5555:6666:7777::"));
assertFalse("IPV6 :1111:2222:3333:4444:5555:6666:: should be invalid", validator.isValidInet6Address(":1111:2222:3333:4444:5555:6666::"));
assertFalse("IPV6 :1111:2222:3333:4444:5555:: should be invalid", validator.isValidInet6Address(":1111:2222:3333:4444:5555::"));
assertFalse("IPV6 :1111:2222:3333:4444:: should be invalid", validator.isValidInet6Address(":1111:2222:3333:4444::"));
assertFalse("IPV6 :1111:2222:3333:: should be invalid", validator.isValidInet6Address(":1111:2222:3333::"));
assertFalse("IPV6 :1111:2222:: should be invalid", validator.isValidInet6Address(":1111:2222::"));
assertFalse("IPV6 :1111:: should be invalid", validator.isValidInet6Address(":1111::"));
assertFalse("IPV6 :1111:2222:3333:4444:5555:6666::8888 should be invalid", validator.isValidInet6Address(":1111:2222:3333:4444:5555:6666::8888"));
assertFalse("IPV6 :1111:2222:3333:4444:5555::8888 should be invalid", validator.isValidInet6Address(":1111:2222:3333:4444:5555::8888"));
assertFalse("IPV6 :1111:2222:3333:4444::8888 should be invalid", validator.isValidInet6Address(":1111:2222:3333:4444::8888"));
assertFalse("IPV6 :1111:2222:3333::8888 should be invalid", validator.isValidInet6Address(":1111:2222:3333::8888"));
assertFalse("IPV6 :1111:2222::8888 should be invalid", validator.isValidInet6Address(":1111:2222::8888"));
assertFalse("IPV6 :1111::8888 should be invalid", validator.isValidInet6Address(":1111::8888"));
assertFalse("IPV6 :::8888 should be invalid", validator.isValidInet6Address(":::8888"));
assertFalse("IPV6 :1111:2222:3333:4444:5555::7777:8888 should be invalid", validator.isValidInet6Address(":1111:2222:3333:4444:5555::7777:8888"));
assertFalse("IPV6 :1111:2222:3333:4444::7777:8888 should be invalid", validator.isValidInet6Address(":1111:2222:3333:4444::7777:8888"));
assertFalse("IPV6 :1111:2222:3333::7777:8888 should be invalid", validator.isValidInet6Address(":1111:2222:3333::7777:8888"));
assertFalse("IPV6 :1111:2222::7777:8888 should be invalid", validator.isValidInet6Address(":1111:2222::7777:8888"));
assertFalse("IPV6 :1111::7777:8888 should be invalid", validator.isValidInet6Address(":1111::7777:8888"));
assertFalse("IPV6 :::7777:8888 should be invalid", validator.isValidInet6Address(":::7777:8888"));
assertFalse("IPV6 :1111:2222:3333:4444::6666:7777:8888 should be invalid", validator.isValidInet6Address(":1111:2222:3333:4444::6666:7777:8888"));
assertFalse("IPV6 :1111:2222:3333::6666:7777:8888 should be invalid", validator.isValidInet6Address(":1111:2222:3333::6666:7777:8888"));
assertFalse("IPV6 :1111:2222::6666:7777:8888 should be invalid", validator.isValidInet6Address(":1111:2222::6666:7777:8888"));
assertFalse("IPV6 :1111::6666:7777:8888 should be invalid", validator.isValidInet6Address(":1111::6666:7777:8888"));
assertFalse("IPV6 :::6666:7777:8888 should be invalid", validator.isValidInet6Address(":::6666:7777:8888"));
assertFalse("IPV6 :1111:2222:3333::5555:6666:7777:8888 should be invalid", validator.isValidInet6Address(":1111:2222:3333::5555:6666:7777:8888"));
assertFalse("IPV6 :1111:2222::5555:6666:7777:8888 should be invalid", validator.isValidInet6Address(":1111:2222::5555:6666:7777:8888"));
assertFalse("IPV6 :1111::5555:6666:7777:8888 should be invalid", validator.isValidInet6Address(":1111::5555:6666:7777:8888"));
assertFalse("IPV6 :::5555:6666:7777:8888 should be invalid", validator.isValidInet6Address(":::5555:6666:7777:8888"));
assertFalse("IPV6 :1111:2222::4444:5555:6666:7777:8888 should be invalid", validator.isValidInet6Address(":1111:2222::4444:5555:6666:7777:8888"));
assertFalse("IPV6 :1111::4444:5555:6666:7777:8888 should be invalid", validator.isValidInet6Address(":1111::4444:5555:6666:7777:8888"));
assertFalse("IPV6 :::4444:5555:6666:7777:8888 should be invalid", validator.isValidInet6Address(":::4444:5555:6666:7777:8888"));
assertFalse("IPV6 :1111::3333:4444:5555:6666:7777:8888 should be invalid", validator.isValidInet6Address(":1111::3333:4444:5555:6666:7777:8888"));
assertFalse("IPV6 :::3333:4444:5555:6666:7777:8888 should be invalid", validator.isValidInet6Address(":::3333:4444:5555:6666:7777:8888"));
assertFalse("IPV6 :::2222:3333:4444:5555:6666:7777:8888 should be invalid", validator.isValidInet6Address(":::2222:3333:4444:5555:6666:7777:8888"));
assertFalse("IPV6 :1111:2222:3333:4444:5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address(":1111:2222:3333:4444:5555:6666:1.2.3.4"));
assertFalse("IPV6 :1111:2222:3333:4444:5555::1.2.3.4 should be invalid", validator.isValidInet6Address(":1111:2222:3333:4444:5555::1.2.3.4"));
assertFalse("IPV6 :1111:2222:3333:4444::1.2.3.4 should be invalid", validator.isValidInet6Address(":1111:2222:3333:4444::1.2.3.4"));
assertFalse("IPV6 :1111:2222:3333::1.2.3.4 should be invalid", validator.isValidInet6Address(":1111:2222:3333::1.2.3.4"));
assertFalse("IPV6 :1111:2222::1.2.3.4 should be invalid", validator.isValidInet6Address(":1111:2222::1.2.3.4"));
assertFalse("IPV6 :1111::1.2.3.4 should be invalid", validator.isValidInet6Address(":1111::1.2.3.4"));
assertFalse("IPV6 :::1.2.3.4 should be invalid", validator.isValidInet6Address(":::1.2.3.4"));
assertFalse("IPV6 :1111:2222:3333:4444::6666:1.2.3.4 should be invalid", validator.isValidInet6Address(":1111:2222:3333:4444::6666:1.2.3.4"));
assertFalse("IPV6 :1111:2222:3333::6666:1.2.3.4 should be invalid", validator.isValidInet6Address(":1111:2222:3333::6666:1.2.3.4"));
assertFalse("IPV6 :1111:2222::6666:1.2.3.4 should be invalid", validator.isValidInet6Address(":1111:2222::6666:1.2.3.4"));
assertFalse("IPV6 :1111::6666:1.2.3.4 should be invalid", validator.isValidInet6Address(":1111::6666:1.2.3.4"));
assertFalse("IPV6 :::6666:1.2.3.4 should be invalid", validator.isValidInet6Address(":::6666:1.2.3.4"));
assertFalse("IPV6 :1111:2222:3333::5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address(":1111:2222:3333::5555:6666:1.2.3.4"));
assertFalse("IPV6 :1111:2222::5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address(":1111:2222::5555:6666:1.2.3.4"));
assertFalse("IPV6 :1111::5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address(":1111::5555:6666:1.2.3.4"));
assertFalse("IPV6 :::5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address(":::5555:6666:1.2.3.4"));
assertFalse("IPV6 :1111:2222::4444:5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address(":1111:2222::4444:5555:6666:1.2.3.4"));
assertFalse("IPV6 :1111::4444:5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address(":1111::4444:5555:6666:1.2.3.4"));
assertFalse("IPV6 :::4444:5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address(":::4444:5555:6666:1.2.3.4"));
assertFalse("IPV6 :1111::3333:4444:5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address(":1111::3333:4444:5555:6666:1.2.3.4"));
assertFalse("IPV6 :::2222:3333:4444:5555:6666:1.2.3.4 should be invalid", validator.isValidInet6Address(":::2222:3333:4444:5555:6666:1.2.3.4"));
// Extra : at end
assertFalse("IPV6 1111:2222:3333:4444:5555:6666:7777::: should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:7777:::"));
assertFalse("IPV6 1111:2222:3333:4444:5555:6666::: should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666:::"));
assertFalse("IPV6 1111:2222:3333:4444:5555::: should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:::"));
assertFalse("IPV6 1111:2222:3333:4444::: should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:::"));
assertFalse("IPV6 1111:2222:3333::: should be invalid", validator.isValidInet6Address("1111:2222:3333:::"));
assertFalse("IPV6 1111:2222::: should be invalid", validator.isValidInet6Address("1111:2222:::"));
assertFalse("IPV6 1111::: should be invalid", validator.isValidInet6Address("1111:::"));
assertFalse("IPV6 1111:2222:3333:4444:5555:6666::8888: should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555:6666::8888:"));
assertFalse("IPV6 1111:2222:3333:4444:5555::8888: should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555::8888:"));
assertFalse("IPV6 1111:2222:3333:4444::8888: should be invalid", validator.isValidInet6Address("1111:2222:3333:4444::8888:"));
assertFalse("IPV6 1111:2222:3333::8888: should be invalid", validator.isValidInet6Address("1111:2222:3333::8888:"));
assertFalse("IPV6 1111:2222::8888: should be invalid", validator.isValidInet6Address("1111:2222::8888:"));
assertFalse("IPV6 1111::8888: should be invalid", validator.isValidInet6Address("1111::8888:"));
assertFalse("IPV6 ::8888: should be invalid", validator.isValidInet6Address("::8888:"));
assertFalse("IPV6 1111:2222:3333:4444:5555::7777:8888: should be invalid", validator.isValidInet6Address("1111:2222:3333:4444:5555::7777:8888:"));
assertFalse("IPV6 1111:2222:3333:4444::7777:8888: should be invalid", validator.isValidInet6Address("1111:2222:3333:4444::7777:8888:"));
assertFalse("IPV6 1111:2222:3333::7777:8888: should be invalid", validator.isValidInet6Address("1111:2222:3333::7777:8888:"));
assertFalse("IPV6 1111:2222::7777:8888: should be invalid", validator.isValidInet6Address("1111:2222::7777:8888:"));
assertFalse("IPV6 1111::7777:8888: should be invalid", validator.isValidInet6Address("1111::7777:8888:"));
assertFalse("IPV6 ::7777:8888: should be invalid", validator.isValidInet6Address("::7777:8888:"));
assertFalse("IPV6 1111:2222:3333:4444::6666:7777:8888: should be invalid", validator.isValidInet6Address("1111:2222:3333:4444::6666:7777:8888:"));
assertFalse("IPV6 1111:2222:3333::6666:7777:8888: should be invalid", validator.isValidInet6Address("1111:2222:3333::6666:7777:8888:"));
assertFalse("IPV6 1111:2222::6666:7777:8888: should be invalid", validator.isValidInet6Address("1111:2222::6666:7777:8888:"));
assertFalse("IPV6 1111::6666:7777:8888: should be invalid", validator.isValidInet6Address("1111::6666:7777:8888:"));
assertFalse("IPV6 ::6666:7777:8888: should be invalid", validator.isValidInet6Address("::6666:7777:8888:"));
assertFalse("IPV6 1111:2222:3333::5555:6666:7777:8888: should be invalid", validator.isValidInet6Address("1111:2222:3333::5555:6666:7777:8888:"));
assertFalse("IPV6 1111:2222::5555:6666:7777:8888: should be invalid", validator.isValidInet6Address("1111:2222::5555:6666:7777:8888:"));
assertFalse("IPV6 1111::5555:6666:7777:8888: should be invalid", validator.isValidInet6Address("1111::5555:6666:7777:8888:"));
assertFalse("IPV6 ::5555:6666:7777:8888: should be invalid", validator.isValidInet6Address("::5555:6666:7777:8888:"));
assertFalse("IPV6 1111:2222::4444:5555:6666:7777:8888: should be invalid", validator.isValidInet6Address("1111:2222::4444:5555:6666:7777:8888:"));
assertFalse("IPV6 1111::4444:5555:6666:7777:8888: should be invalid", validator.isValidInet6Address("1111::4444:5555:6666:7777:8888:"));
assertFalse("IPV6 ::4444:5555:6666:7777:8888: should be invalid", validator.isValidInet6Address("::4444:5555:6666:7777:8888:"));
assertFalse("IPV6 1111::3333:4444:5555:6666:7777:8888: should be invalid", validator.isValidInet6Address("1111::3333:4444:5555:6666:7777:8888:"));
assertFalse("IPV6 ::3333:4444:5555:6666:7777:8888: should be invalid", validator.isValidInet6Address("::3333:4444:5555:6666:7777:8888:"));
assertFalse("IPV6 ::2222:3333:4444:5555:6666:7777:8888: should be invalid", validator.isValidInet6Address("::2222:3333:4444:5555:6666:7777:8888:"));
assertTrue("IPV6 0:a:b:c:d:e:f:: should be valid", validator.isValidInet6Address("0:a:b:c:d:e:f::"));
assertTrue("IPV6 ::0:a:b:c:d:e:f should be valid", validator.isValidInet6Address("::0:a:b:c:d:e:f")); // syntactically correct, but bad form (::0:... could be combined)
assertTrue("IPV6 a:b:c:d:e:f:0:: should be valid", validator.isValidInet6Address("a:b:c:d:e:f:0::"));
assertFalse("IPV6 ':10.0.0.1 should be invalid", validator.isValidInet6Address("':10.0.0.1"));
}
}
| 7,925 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/EmailValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.validator.ResultPair;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
/**
* Performs Validation Test for e-mail validations.
*/
public class EmailValidatorTest {
/**
* The key used to retrieve the set of validation
* rules from the xml file.
*/
protected static String FORM_KEY = "emailForm";
/**
* The key used to retrieve the validator action.
*/
protected static String ACTION = "email";
private EmailValidator validator;
@Before
public void setUp() {
validator = EmailValidator.getInstance();
}
/**
* Tests the e-mail validation.
*/
@Test
public void testEmail() {
assertTrue(validator.isValid("jsmith@apache.org"));
}
/**
* Tests the email validation with numeric domains.
*/
@Test
public void testEmailWithNumericAddress() {
assertTrue(validator.isValid("someone@[216.109.118.76]"));
assertTrue(validator.isValid("someone@yahoo.com"));
}
/**
* Tests the e-mail validation.
*/
@Test
public void testEmailExtension() {
assertTrue(validator.isValid("jsmith@apache.org"));
assertTrue(validator.isValid("jsmith@apache.com"));
assertTrue(validator.isValid("jsmith@apache.net"));
assertTrue(validator.isValid("jsmith@apache.info"));
assertFalse(validator.isValid("jsmith@apache."));
assertFalse(validator.isValid("jsmith@apache.c"));
assertTrue(validator.isValid("someone@yahoo.museum"));
assertFalse(validator.isValid("someone@yahoo.mu-seum"));
}
/**
* <p>Tests the e-mail validation with a dash in
* the address.</p>
*/
@Test
public void testEmailWithDash() {
assertTrue(validator.isValid("andy.noble@data-workshop.com"));
assertFalse(validator.isValid("andy-noble@data-workshop.-com"));
assertFalse(validator.isValid("andy-noble@data-workshop.c-om"));
assertFalse(validator.isValid("andy-noble@data-workshop.co-m"));
}
/**
* Tests the e-mail validation with a dot at the end of
* the address.
*/
@Test
public void testEmailWithDotEnd() {
assertFalse(validator.isValid("andy.noble@data-workshop.com."));
}
/**
* Tests the e-mail validation with an RCS-noncompliant character in
* the address.
*/
@Test
public void testEmailWithBogusCharacter() {
assertFalse(validator.isValid("andy.noble@\u008fdata-workshop.com"));
// The ' character is valid in an email username.
assertTrue(validator.isValid("andy.o'reilly@data-workshop.com"));
// But not in the domain name.
assertFalse(validator.isValid("andy@o'reilly.data-workshop.com"));
// The + character is valid in an email username.
assertTrue(validator.isValid("foo+bar@i.am.not.in.us.example.com"));
// But not in the domain name
assertFalse(validator.isValid("foo+bar@example+3.com"));
// Domains with only special characters aren't allowed (VALIDATOR-286)
assertFalse(validator.isValid("test@%*.com"));
assertFalse(validator.isValid("test@^&#.com"));
}
@Test
public void testVALIDATOR_315() {
assertFalse(validator.isValid("me@at&t.net"));
assertTrue(validator.isValid("me@att.net")); // Make sure TLD is not the cause of the failure
}
@Test
public void testVALIDATOR_278() {
assertFalse(validator.isValid("someone@-test.com"));// hostname starts with dash/hyphen
assertFalse(validator.isValid("someone@test-.com"));// hostname ends with dash/hyphen
}
@Test
public void testValidator235() {
final String version = System.getProperty("java.version");
if (version.compareTo("1.6") < 0) {
System.out.println("Cannot run Unicode IDN tests");
return; // Cannot run the test
}
assertTrue("xn--d1abbgf6aiiy.xn--p1ai should validate", validator.isValid("someone@xn--d1abbgf6aiiy.xn--p1ai"));
assertTrue("президент.рф should validate", validator.isValid("someone@президент.рф"));
assertTrue("www.b\u00fccher.ch should validate", validator.isValid("someone@www.b\u00fccher.ch"));
assertFalse("www.\uFFFD.ch FFFD should fail", validator.isValid("someone@www.\uFFFD.ch"));
assertTrue("www.b\u00fccher.ch should validate", validator.isValid("someone@www.b\u00fccher.ch"));
assertFalse("www.\uFFFD.ch FFFD should fail", validator.isValid("someone@www.\uFFFD.ch"));
}
/**
* Tests the email validation with commas.
*/
@Test
public void testEmailWithCommas() {
assertFalse(validator.isValid("joeblow@apa,che.org"));
assertFalse(validator.isValid("joeblow@apache.o,rg"));
assertFalse(validator.isValid("joeblow@apache,org"));
}
/**
* Tests the email validation with spaces.
*/
@Test
public void testEmailWithSpaces() {
assertFalse(validator.isValid("joeblow @apache.org"));
assertFalse(validator.isValid("joeblow@ apache.org"));
assertFalse(validator.isValid(" joeblow@apache.org"));
assertFalse(validator.isValid("joeblow@apache.org "));
assertFalse(validator.isValid("joe blow@apache.org "));
assertFalse(validator.isValid("joeblow@apa che.org "));
assertTrue(validator.isValid("\"joeblow \"@apache.org"));
assertTrue(validator.isValid("\" joeblow\"@apache.org"));
assertTrue(validator.isValid("\" joe blow \"@apache.org"));
}
/**
* Tests the email validation with ASCII control characters.
* (i.e. ASCII chars 0 - 31 and 127)
*/
@Test
public void testEmailWithControlChars() {
for (char c = 0; c < 32; c++) {
assertFalse("Test control char " + (int)c, validator.isValid("foo" + c + "bar@domain.com"));
}
assertFalse("Test control char 127", validator.isValid("foo" + (char)127 + "bar@domain.com"));
}
/**
* Test that @localhost and @localhost.localdomain
* addresses are declared as valid when requested.
*/
@Test
public void testEmailLocalhost() {
// Check the default is not to allow
final EmailValidator noLocal = EmailValidator.getInstance(false);
final EmailValidator allowLocal = EmailValidator.getInstance(true);
assertEquals(validator, noLocal);
// Depends on the validator
assertTrue(
"@localhost.localdomain should be accepted but wasn't",
allowLocal.isValid("joe@localhost.localdomain")
);
assertTrue(
"@localhost should be accepted but wasn't",
allowLocal.isValid("joe@localhost")
);
assertFalse(
"@localhost.localdomain should be accepted but wasn't",
noLocal.isValid("joe@localhost.localdomain")
);
assertFalse(
"@localhost should be accepted but wasn't",
noLocal.isValid("joe@localhost")
);
}
/**
* VALIDATOR-296 - A / or a ! is valid in the user part,
* but not in the domain part
*/
@Test
public void testEmailWithSlashes() {
assertTrue(
"/ and ! valid in username",
validator.isValid("joe!/blow@apache.org")
);
assertFalse(
"/ not valid in domain",
validator.isValid("joe@ap/ache.org")
);
assertFalse(
"! not valid in domain",
validator.isValid("joe@apac!he.org")
);
}
/**
* Write this test according to parts of RFC, as opposed to the type of character
* that is being tested.
*/
@Test
public void testEmailUserName() {
assertTrue(validator.isValid("joe1blow@apache.org"));
assertTrue(validator.isValid("joe$blow@apache.org"));
assertTrue(validator.isValid("joe-@apache.org"));
assertTrue(validator.isValid("joe_@apache.org"));
assertTrue(validator.isValid("joe+@apache.org")); // + is valid unquoted
assertTrue(validator.isValid("joe!@apache.org")); // ! is valid unquoted
assertTrue(validator.isValid("joe*@apache.org")); // * is valid unquoted
assertTrue(validator.isValid("joe'@apache.org")); // ' is valid unquoted
assertTrue(validator.isValid("joe%45@apache.org")); // % is valid unquoted
assertTrue(validator.isValid("joe?@apache.org")); // ? is valid unquoted
assertTrue(validator.isValid("joe&@apache.org")); // & ditto
assertTrue(validator.isValid("joe=@apache.org")); // = ditto
assertTrue(validator.isValid("+joe@apache.org")); // + is valid unquoted
assertTrue(validator.isValid("!joe@apache.org")); // ! is valid unquoted
assertTrue(validator.isValid("*joe@apache.org")); // * is valid unquoted
assertTrue(validator.isValid("'joe@apache.org")); // ' is valid unquoted
assertTrue(validator.isValid("%joe45@apache.org")); // % is valid unquoted
assertTrue(validator.isValid("?joe@apache.org")); // ? is valid unquoted
assertTrue(validator.isValid("&joe@apache.org")); // & ditto
assertTrue(validator.isValid("=joe@apache.org")); // = ditto
assertTrue(validator.isValid("+@apache.org")); // + is valid unquoted
assertTrue(validator.isValid("!@apache.org")); // ! is valid unquoted
assertTrue(validator.isValid("*@apache.org")); // * is valid unquoted
assertTrue(validator.isValid("'@apache.org")); // ' is valid unquoted
assertTrue(validator.isValid("%@apache.org")); // % is valid unquoted
assertTrue(validator.isValid("?@apache.org")); // ? is valid unquoted
assertTrue(validator.isValid("&@apache.org")); // & ditto
assertTrue(validator.isValid("=@apache.org")); // = ditto
//UnQuoted Special characters are invalid
assertFalse(validator.isValid("joe.@apache.org")); // . not allowed at end of local part
assertFalse(validator.isValid(".joe@apache.org")); // . not allowed at start of local part
assertFalse(validator.isValid(".@apache.org")); // . not allowed alone
assertTrue(validator.isValid("joe.ok@apache.org")); // . allowed embedded
assertFalse(validator.isValid("joe..ok@apache.org")); // .. not allowed embedded
assertFalse(validator.isValid("..@apache.org")); // .. not allowed alone
assertFalse(validator.isValid("joe(@apache.org"));
assertFalse(validator.isValid("joe)@apache.org"));
assertFalse(validator.isValid("joe,@apache.org"));
assertFalse(validator.isValid("joe;@apache.org"));
//Quoted Special characters are valid
assertTrue(validator.isValid("\"joe.\"@apache.org"));
assertTrue(validator.isValid("\".joe\"@apache.org"));
assertTrue(validator.isValid("\"joe+\"@apache.org"));
assertTrue(validator.isValid("\"joe@\"@apache.org"));
assertTrue(validator.isValid("\"joe!\"@apache.org"));
assertTrue(validator.isValid("\"joe*\"@apache.org"));
assertTrue(validator.isValid("\"joe'\"@apache.org"));
assertTrue(validator.isValid("\"joe(\"@apache.org"));
assertTrue(validator.isValid("\"joe)\"@apache.org"));
assertTrue(validator.isValid("\"joe,\"@apache.org"));
assertTrue(validator.isValid("\"joe%45\"@apache.org"));
assertTrue(validator.isValid("\"joe;\"@apache.org"));
assertTrue(validator.isValid("\"joe?\"@apache.org"));
assertTrue(validator.isValid("\"joe&\"@apache.org"));
assertTrue(validator.isValid("\"joe=\"@apache.org"));
assertTrue(validator.isValid("\"..\"@apache.org"));
// escaped quote character valid in quoted string
assertTrue(validator.isValid("\"john\\\"doe\"@apache.org"));
assertTrue(validator.isValid("john56789.john56789.john56789.john56789.john56789.john56789.john@example.com"));
assertFalse(validator.isValid("john56789.john56789.john56789.john56789.john56789.john56789.john5@example.com"));
assertTrue(validator.isValid("\\>escape\\\\special\\^characters\\<@example.com"));
assertTrue(validator.isValid("Abc\\@def@example.com"));
assertFalse(validator.isValid("Abc@def@example.com"));
assertTrue(validator.isValid("space\\ monkey@example.com"));
}
/**
* These test values derive directly from RFC 822 &
* Mail::RFC822::Address & RFC::RFC822::Address perl test.pl
* For traceability don't combine these test values with other tests.
*/
private static final ResultPair[] testEmailFromPerl = {
new ResultPair("abigail@example.com", true),
new ResultPair("abigail@example.com ", true),
new ResultPair(" abigail@example.com", true),
new ResultPair("abigail @example.com ", true),
new ResultPair("*@example.net", true),
new ResultPair("\"\\\"\"@foo.bar", true),
new ResultPair("fred&barny@example.com", true),
new ResultPair("---@example.com", true),
new ResultPair("foo-bar@example.net", true),
new ResultPair("\"127.0.0.1\"@[127.0.0.1]", true),
new ResultPair("Abigail <abigail@example.com>", true),
new ResultPair("Abigail<abigail@example.com>", true),
new ResultPair("Abigail<@a,@b,@c:abigail@example.com>", true),
new ResultPair("\"This is a phrase\"<abigail@example.com>", true),
new ResultPair("\"Abigail \"<abigail@example.com>", true),
new ResultPair("\"Joe & J. Harvey\" <example @Org>", true),
new ResultPair("Abigail <abigail @ example.com>", true),
new ResultPair("Abigail made this < abigail @ example . com >", true),
new ResultPair("Abigail(the bitch)@example.com", true),
new ResultPair("Abigail <abigail @ example . (bar) com >", true),
new ResultPair("Abigail < (one) abigail (two) @(three)example . (bar) com (quz) >", true),
new ResultPair("Abigail (foo) (((baz)(nested) (comment)) ! ) < (one) abigail (two) @(three)example . (bar) com (quz) >", true),
new ResultPair("Abigail <abigail(fo\\(o)@example.com>", true),
new ResultPair("Abigail <abigail(fo\\)o)@example.com> ", true),
new ResultPair("(foo) abigail@example.com", true),
new ResultPair("abigail@example.com (foo)", true),
new ResultPair("\"Abi\\\"gail\" <abigail@example.com>", true),
new ResultPair("abigail@[example.com]", true),
new ResultPair("abigail@[exa\\[ple.com]", true),
new ResultPair("abigail@[exa\\]ple.com]", true),
new ResultPair("\":sysmail\"@ Some-Group. Some-Org", true),
new ResultPair("Muhammed.(I am the greatest) Ali @(the)Vegas.WBA", true),
new ResultPair("mailbox.sub1.sub2@this-domain", true),
new ResultPair("sub-net.mailbox@sub-domain.domain", true),
new ResultPair("name:;", true),
new ResultPair("':;", true),
new ResultPair("name: ;", true),
new ResultPair("Alfred Neuman <Neuman@BBN-TENEXA>", true),
new ResultPair("Neuman@BBN-TENEXA", true),
new ResultPair("\"George, Ted\" <Shared@Group.Arpanet>", true),
new ResultPair("Wilt . (the Stilt) Chamberlain@NBA.US", true),
new ResultPair("Cruisers: Port@Portugal, Jones@SEA;", true),
new ResultPair("$@[]", true),
new ResultPair("*()@[]", true),
new ResultPair("\"quoted ( brackets\" ( a comment )@example.com", true),
new ResultPair("\"Joe & J. Harvey\"\\x0D\\x0A <ddd\\@ Org>", true),
new ResultPair("\"Joe &\\x0D\\x0A J. Harvey\" <ddd \\@ Org>", true),
new ResultPair("Gourmets: Pompous Person <WhoZiWhatZit\\@Cordon-Bleu>,\\x0D\\x0A" +
" Childs\\@WGBH.Boston, \"Galloping Gourmet\"\\@\\x0D\\x0A" +
" ANT.Down-Under (Australian National Television),\\x0D\\x0A" +
" Cheapie\\@Discount-Liquors;", true),
new ResultPair(" Just a string", false),
new ResultPair("string", false),
new ResultPair("(comment)", false),
new ResultPair("()@example.com", false),
new ResultPair("fred(&)barny@example.com", false),
new ResultPair("fred\\ barny@example.com", false),
new ResultPair("Abigail <abi gail @ example.com>", false),
new ResultPair("Abigail <abigail(fo(o)@example.com>", false),
new ResultPair("Abigail <abigail(fo)o)@example.com>", false),
new ResultPair("\"Abi\"gail\" <abigail@example.com>", false),
new ResultPair("abigail@[exa]ple.com]", false),
new ResultPair("abigail@[exa[ple.com]", false),
new ResultPair("abigail@[exaple].com]", false),
new ResultPair("abigail@", false),
new ResultPair("@example.com", false),
new ResultPair("phrase: abigail@example.com abigail@example.com ;", false),
new ResultPair("invalid�char@example.com", false)
};
/**
* Write this test based on perl Mail::RFC822::Address
* which takes its example email address directly from RFC822
*
* This test fails so disable it
* The real solution is to fix the email parsing.
*/
@Ignore("VALIDATOR-267")
@Test
public void testEmailFromPerl() {
int errors = 0;
for (final ResultPair element : testEmailFromPerl) {
final String item = element.item;
final boolean exp = element.valid;
final boolean act = validator.isValid(item);
if (act != exp) {
System.out.printf("%s: expected %s actual %s%n", item, exp, act);
errors += 1;
}
}
assertEquals("Expected 0 errors", 0, errors);
}
@Test
public void testValidator293(){
assertTrue(validator.isValid("abc-@abc.com"));
assertTrue(validator.isValid("abc_@abc.com"));
assertTrue(validator.isValid("abc-def@abc.com"));
assertTrue(validator.isValid("abc_def@abc.com"));
assertFalse(validator.isValid("abc@abc_def.com"));
}
@Test
public void testValidator365() {
assertFalse(validator.isValid(
"Loremipsumdolorsitametconsecteturadipiscingelit.Nullavitaeligulamattisrhoncusnuncegestasmattisleo."+
"Donecnonsapieninmagnatristiquedictumaacturpis.Fusceorciduifacilisisutsapieneuconsequatpharetralectus."+
"Quisqueenimestpulvinarutquamvitaeportamattisex.Nullamquismaurisplaceratconvallisjustoquisportamauris."+
"Innullalacusconvalliseufringillautvenenatissitametdiam.Maecenasluctusligulascelerisquepulvinarfeugiat."+
"Sedmolestienullaaliquetorciluctusidpharetranislfinibus.Suspendissemalesuadatinciduntduisitametportaarcusollicitudinnec."+
"Donecetmassamagna.Curabitururnadiampretiumveldignissimporttitorfringillaeuneque."+
"Duisantetelluspharetraidtinciduntinterdummolestiesitametfelis.Utquisquamsitametantesagittisdapibusacnonodio."+
"Namrutrummolestiediamidmattis.Cumsociisnatoquepenatibusetmagnisdisparturientmontesnasceturridiculusmus."+
"Morbiposueresedmetusacconsectetur.Etiamquisipsumvitaejustotempusmaximus.Sedultriciesplaceratvolutpat."+
"Integerlacuslectusmaximusacornarequissagittissitametjusto."+
"Cumsociisnatoquepenatibusetmagnisdisparturientmontesnasceturridiculusmus.Maecenasindictumpurussedrutrumex.Nullafacilisi."+
"Integerfinibusfinibusmietpharetranislfaucibusvel.Maecenasegetdolorlacinialobortisjustovelullamcorpersem."+
"Vivamusaliquetpurusidvariusornaresapienrisusrutrumnisitinciduntmollissemnequeidmetus."+
"Etiamquiseleifendpurus.Nuncfelisnuncscelerisqueiddignissimnecfinibusalibero."+
"Nuncsemperenimnequesitamethendreritpurusfacilisisac.Maurisdapibussemperfelisdignissimgravida."+
"Aeneanultricesblanditnequealiquamfinibusodioscelerisqueac.Aliquamnecmassaeumaurisfaucibusfringilla."+
"Etiamconsequatligulanisisitametaliquamnibhtemporquis.Nuncinterdumdignissimnullaatsodalesarcusagittiseu."+
"Proinpharetrametusneclacuspulvinarsedvolutpatliberoornare.Sedligulanislpulvinarnonlectuseublanditfacilisisante."+
"Sedmollisnislalacusauctorsuscipit.Inhachabitasseplateadictumst.Phasellussitametvelittemporvenenatisfeliseuegestasrisus."+
"Aliquameteratsitametnibhcommodofinibus.Morbiefficiturodiovelpulvinariaculis."+
"Aeneantemporipsummassaaconsecteturturpisfaucibusultrices.Praesentsodalesmaurisquisportafermentum."+
"Etiamnisinislvenenatisvelauctorutullamcorperinjusto.Proinvelligulaerat.Phasellusvestibulumgravidamassanonfeugiat."+
"Maecenaspharetraeuismodmetusegetefficitur.Suspendisseamet@gmail.com"));
}
/**
* Tests the e-mail validation with a user at a TLD
*
* http://tools.ietf.org/html/rfc5321#section-2.3.5
* (In the case of a top-level domain used by itself in an
* email address, a single string is used without any dots)
*/
@Test
public void testEmailAtTLD() {
final EmailValidator val = EmailValidator.getInstance(false, true);
assertTrue(val.isValid("test@com"));
}
@Test
public void testValidator359() {
final EmailValidator val = EmailValidator.getInstance(false, true);
assertFalse(val.isValid("test@.com"));
}
@Test
public void testValidator374() {
assertTrue(validator.isValid("abc@school.school"));
}
@Test
public void testValidator473_1() { // reject null DomainValidator
final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () ->
new EmailValidator(false, false, null));
assertThat(thrown.getMessage(), is(equalTo("DomainValidator cannot be null")));
}
@Test
public void testValidator473_2() { // reject null DomainValidator with mismatched allowLocal
final List<DomainValidator.Item> items = new ArrayList<>();
final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () ->
new EmailValidator(false, false, DomainValidator.getInstance(true, items)));
assertThat(thrown.getMessage(), is(equalTo("DomainValidator must agree with allowLocal setting")));
}
@Test
public void testValidator473_3() { // reject null DomainValidator with mismatched allowLocal
final List<DomainValidator.Item> items = new ArrayList<>();
final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () ->
new EmailValidator(true, false, DomainValidator.getInstance(false, items)));
assertThat(thrown.getMessage(), is(equalTo("DomainValidator must agree with allowLocal setting")));
}
@Test
public void testValidator473_4() { // Show that can override domain validation
assertFalse(validator.isValidDomain("test.local"));
final List<DomainValidator.Item> items = new ArrayList<>();
items.add(new DomainValidator.Item(DomainValidator.ArrayType.GENERIC_PLUS, "local"));
final EmailValidator val = new EmailValidator(true, false, DomainValidator.getInstance(true, items));
assertTrue(val.isValidDomain("test.local"));
}
public static void main(final String[] args) {
final EmailValidator validator = EmailValidator.getInstance();
for(final String arg : args) {
System.out.printf("%s: %s%n", arg, validator.isValid(arg));
}
}
}
| 7,926 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/DateValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* Test Case for DateValidator.
*/
public class DateValidatorTest extends AbstractCalendarValidatorTest {
private DateValidator dateValidator;
/**
* Constructor
* @param name test name
*/
public DateValidatorTest(final String name) {
super(name);
}
/**
* Sets up test fixtures.
*/
@Override
protected void setUp() {
dateValidator = new DateValidator();
validator = dateValidator;
}
/**
* Check that locale providers are set up correctly
* If not, the parse will fail
*/
public void testLocaleProviders() throws Exception {
final String localeProviders = System.getProperty("java.locale.providers");
if (localeProviders != null) { // may be null before Java 9
assertTrue("java.locale.providers must start with COMPAT", localeProviders.startsWith("COMPAT"));
}
final String txt = "3/20/15 10:59:00 PM"; // This relies on the locale format prior to Java 9 to parse correctly
final DateFormat dateformat= DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, Locale.US);
dateformat.setTimeZone(TimeZone.getTimeZone("GMT"));
final Date date = dateformat.parse(txt);
assertNotNull(date);
}
/**
* Test DateValidator validate Methods
*/
public void testDateValidatorMethods() {
Locale.setDefault(Locale.US);
final Locale locale = Locale.GERMAN;
final String pattern = "yyyy-MM-dd";
final String patternVal = "2005-12-31";
final String germanVal = "31 Dez 2005";
final String germanPattern = "dd MMM yyyy";
final String localeVal = "31.12.2005";
final String defaultVal = "12/31/05";
final String XXXX = "XXXX";
final Date expected = createCalendar(null, 20051231, 0).getTime();
assertEquals("validate(A) default", expected, DateValidator.getInstance().validate(defaultVal));
assertEquals("validate(A) locale ", expected, DateValidator.getInstance().validate(localeVal, locale));
assertEquals("validate(A) pattern", expected, DateValidator.getInstance().validate(patternVal, pattern));
assertEquals("validate(A) both", expected, DateValidator.getInstance().validate(germanVal, germanPattern, Locale.GERMAN));
assertTrue("isValid(A) default", DateValidator.getInstance().isValid(defaultVal));
assertTrue("isValid(A) locale ", DateValidator.getInstance().isValid(localeVal, locale));
assertTrue("isValid(A) pattern", DateValidator.getInstance().isValid(patternVal, pattern));
assertTrue("isValid(A) both", DateValidator.getInstance().isValid(germanVal, germanPattern, Locale.GERMAN));
assertNull("validate(B) default", DateValidator.getInstance().validate(XXXX));
assertNull("validate(B) locale ", DateValidator.getInstance().validate(XXXX, locale));
assertNull("validate(B) pattern", DateValidator.getInstance().validate(XXXX, pattern));
assertNull("validate(B) both", DateValidator.getInstance().validate("31 Dec 2005", germanPattern, Locale.GERMAN));
assertFalse("isValid(B) default", DateValidator.getInstance().isValid(XXXX));
assertFalse("isValid(B) locale ", DateValidator.getInstance().isValid(XXXX, locale));
assertFalse("isValid(B) pattern", DateValidator.getInstance().isValid(XXXX, pattern));
assertFalse("isValid(B) both", DateValidator.getInstance().isValid("31 Dec 2005", germanPattern, Locale.GERMAN));
// Test Time Zone
final TimeZone zone = TimeZone.getDefault().getRawOffset() == EET.getRawOffset() ? EST : EET;
final Date expectedZone = createCalendar(zone, 20051231, 0).getTime();
assertFalse("default/zone same "+zone, expected.getTime() == expectedZone.getTime());
assertEquals("validate(C) default", expectedZone, DateValidator.getInstance().validate(defaultVal, zone));
assertEquals("validate(C) locale ", expectedZone, DateValidator.getInstance().validate(localeVal, locale, zone));
assertEquals("validate(C) pattern", expectedZone, DateValidator.getInstance().validate(patternVal, pattern, zone));
assertEquals("validate(C) both", expectedZone, DateValidator.getInstance().validate(germanVal, germanPattern, Locale.GERMAN, zone));
}
/**
* Test compare date methods
*/
public void testCompare() {
final int sameTime = 124522;
final int testDate = 20050823;
final Date diffHour = createDate(GMT, testDate, 115922); // same date, different time
final Date value = createDate(GMT, testDate, sameTime); // test value
final Date date20050824 = createDate(GMT, 20050824, sameTime); // +1 day
final Date date20050822 = createDate(GMT, 20050822, sameTime); // -1 day
final Date date20050830 = createDate(GMT, 20050830, sameTime); // +1 week
final Date date20050816 = createDate(GMT, 20050816, sameTime); // -1 week
final Date date20050901 = createDate(GMT, 20050901, sameTime); // +1 month
final Date date20050801 = createDate(GMT, 20050801, sameTime); // same month
final Date date20050731 = createDate(GMT, 20050731, sameTime); // -1 month
final Date date20051101 = createDate(GMT, 20051101, sameTime); // +1 quarter (Feb Start)
final Date date20051001 = createDate(GMT, 20051001, sameTime); // +1 quarter
final Date date20050701 = createDate(GMT, 20050701, sameTime); // same quarter
final Date date20050630 = createDate(GMT, 20050630, sameTime); // -1 quarter
final Date date20050110 = createDate(GMT, 20050110, sameTime); // Previous Year qtr (Fen start)
final Date date20060101 = createDate(GMT, 20060101, sameTime); // +1 year
final Date date20050101 = createDate(GMT, 20050101, sameTime); // same year
final Date date20041231 = createDate(GMT, 20041231, sameTime); // -1 year
assertEquals("date LT", -1, dateValidator.compareDates(value, date20050824, GMT)); // +1 day
assertEquals("date EQ", 0, dateValidator.compareDates(value, diffHour, GMT)); // same day, diff hour
assertEquals("date GT", 1, dateValidator.compareDates(value, date20050822, GMT)); // -1 day
assertEquals("week LT", -1, dateValidator.compareWeeks(value, date20050830, GMT)); // +1 week
assertEquals("week =1", 0, dateValidator.compareWeeks(value, date20050824, GMT)); // +1 day
assertEquals("week =2", 0, dateValidator.compareWeeks(value, date20050822, GMT)); // same week
assertEquals("week =3", 0, dateValidator.compareWeeks(value, date20050822, GMT)); // -1 day
assertEquals("week GT", 1, dateValidator.compareWeeks(value, date20050816, GMT)); // -1 week
assertEquals("mnth LT", -1, dateValidator.compareMonths(value, date20050901, GMT)); // +1 month
assertEquals("mnth =1", 0, dateValidator.compareMonths(value, date20050830, GMT)); // +1 week
assertEquals("mnth =2", 0, dateValidator.compareMonths(value, date20050801, GMT)); // same month
assertEquals("mnth =3", 0, dateValidator.compareMonths(value, date20050816, GMT)); // -1 week
assertEquals("mnth GT", 1, dateValidator.compareMonths(value, date20050731, GMT)); // -1 month
assertEquals("qtrA <1", -1, dateValidator.compareQuarters(value, date20051101, GMT)); // +1 quarter (Feb)
assertEquals("qtrA <2", -1, dateValidator.compareQuarters(value, date20051001, GMT)); // +1 quarter
assertEquals("qtrA =1", 0, dateValidator.compareQuarters(value, date20050901, GMT)); // +1 month
assertEquals("qtrA =2", 0, dateValidator.compareQuarters(value, date20050701, GMT)); // same quarter
assertEquals("qtrA =3", 0, dateValidator.compareQuarters(value, date20050731, GMT)); // -1 month
assertEquals("qtrA GT", 1, dateValidator.compareQuarters(value, date20050630, GMT)); // -1 quarter
// Change quarter 1 to start in Feb
assertEquals("qtrB LT", -1, dateValidator.compareQuarters(value, date20051101, GMT, 2)); // +1 quarter (Feb)
assertEquals("qtrB =1", 0, dateValidator.compareQuarters(value, date20051001, GMT, 2)); // same quarter
assertEquals("qtrB =2", 0, dateValidator.compareQuarters(value, date20050901, GMT, 2)); // +1 month
assertEquals("qtrB =3", 1, dateValidator.compareQuarters(value, date20050701, GMT, 2)); // same quarter
assertEquals("qtrB =4", 1, dateValidator.compareQuarters(value, date20050731, GMT, 2)); // -1 month
assertEquals("qtrB GT", 1, dateValidator.compareQuarters(value, date20050630, GMT, 2)); // -1 quarter
assertEquals("qtrB prev", 1, dateValidator.compareQuarters(value, date20050110, GMT, 2)); // Jan Prev year qtr
assertEquals("year LT", -1, dateValidator.compareYears(value, date20060101, GMT)); // +1 year
assertEquals("year EQ", 0, dateValidator.compareYears(value, date20050101, GMT)); // same year
assertEquals("year GT", 1, dateValidator.compareYears(value, date20041231, GMT)); // -1 year
// Compare using alternative TimeZone
final Date sameDayTwoAm = createDate(GMT, testDate, 20000);
assertEquals("date LT", -1, dateValidator.compareDates(value, date20050824, EST)); // +1 day
assertEquals("date EQ", 0, dateValidator.compareDates(value, diffHour, EST)); // same day, diff hour
assertEquals("date EQ", 1, dateValidator.compareDates(value, sameDayTwoAm, EST)); // same day, diff hour
assertEquals("date GT", 1, dateValidator.compareDates(value, date20050822, EST)); // -1 day
}
}
| 7,927 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/ShortValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.util.Locale;
/**
* Test Case for ShortValidator.
*/
public class ShortValidatorTest extends AbstractNumberValidatorTest {
/**
* Constructor
* @param name test name
*/
public ShortValidatorTest(final String name) {
super(name);
}
@Override
protected void setUp() {
super.setUp();
validator = new ShortValidator(false, 0);
strictValidator = new ShortValidator();
testPattern = "#,###";
// testValidateMinMax()
max = Short.valueOf(Short.MAX_VALUE);
maxPlusOne = Long.valueOf(max.longValue() + 1);
min = Short.valueOf(Short.MIN_VALUE);
minMinusOne = Long.valueOf(min.longValue() - 1);
// testInvalidStrict()
invalidStrict = new String[] {null, "", "X", "X12", "12X", "1X2", "1.2"};
// testInvalidNotStrict()
invalid = new String[] {null, "", "X", "X12"};
// testValid()
testNumber = Short.valueOf((short)1234);
testZero = Short.valueOf((short)0);
validStrict = new String[] {"0", "1234", "1,234"};
validStrictCompare = new Number[] {testZero, testNumber, testNumber};
valid = new String[] {"0", "1234", "1,234", "1,234.5", "1234X"};
validCompare = new Number[] {testZero, testNumber, testNumber, testNumber, testNumber};
testStringUS = "1,234";
testStringDE = "1.234";
// Localized Pattern test
localeValue = testStringDE;
localePattern = "#.###";
testLocale = Locale.GERMANY;
localeExpected = testNumber;
}
/**
* Test ShortValidator validate Methods
*/
public void testShortValidatorMethods() {
final Locale locale = Locale.GERMAN;
final String pattern = "0,00,00";
final String patternVal = "1,23,45";
final String germanPatternVal = "1.23.45";
final String localeVal = "12.345";
final String defaultVal = "12,345";
final String XXXX = "XXXX";
final Short expected = Short.valueOf((short)12345);
assertEquals("validate(A) default", expected, ShortValidator.getInstance().validate(defaultVal));
assertEquals("validate(A) locale ", expected, ShortValidator.getInstance().validate(localeVal, locale));
assertEquals("validate(A) pattern", expected, ShortValidator.getInstance().validate(patternVal, pattern));
assertEquals("validate(A) both", expected, ShortValidator.getInstance().validate(germanPatternVal, pattern, Locale.GERMAN));
assertTrue("isValid(A) default", ShortValidator.getInstance().isValid(defaultVal));
assertTrue("isValid(A) locale ", ShortValidator.getInstance().isValid(localeVal, locale));
assertTrue("isValid(A) pattern", ShortValidator.getInstance().isValid(patternVal, pattern));
assertTrue("isValid(A) both", ShortValidator.getInstance().isValid(germanPatternVal, pattern, Locale.GERMAN));
assertNull("validate(B) default", ShortValidator.getInstance().validate(XXXX));
assertNull("validate(B) locale ", ShortValidator.getInstance().validate(XXXX, locale));
assertNull("validate(B) pattern", ShortValidator.getInstance().validate(XXXX, pattern));
assertNull("validate(B) both", ShortValidator.getInstance().validate(patternVal, pattern, Locale.GERMAN));
assertFalse("isValid(B) default", ShortValidator.getInstance().isValid(XXXX));
assertFalse("isValid(B) locale ", ShortValidator.getInstance().isValid(XXXX, locale));
assertFalse("isValid(B) pattern", ShortValidator.getInstance().isValid(XXXX, pattern));
assertFalse("isValid(B) both", ShortValidator.getInstance().isValid(patternVal, pattern, Locale.GERMAN));
}
/**
* Test Short Range/Min/Max
*/
public void testShortRangeMinMax() {
final ShortValidator validator = (ShortValidator)strictValidator;
final Short number9 = validator.validate("9", "#");
final Short number10 = validator.validate("10", "#");
final Short number11 = validator.validate("11", "#");
final Short number19 = validator.validate("19", "#");
final Short number20 = validator.validate("20", "#");
final Short number21 = validator.validate("21", "#");
final short min = (short)10;
final short max = (short)20;
// Test isInRange()
assertFalse("isInRange() < min", validator.isInRange(number9, min, max));
assertTrue("isInRange() = min", validator.isInRange(number10, min, max));
assertTrue("isInRange() in range", validator.isInRange(number11, min, max));
assertTrue("isInRange() = max", validator.isInRange(number20, min, max));
assertFalse("isInRange() > max", validator.isInRange(number21, min, max));
// Test minValue()
assertFalse("minValue() < min", validator.minValue(number9, min));
assertTrue("minValue() = min", validator.minValue(number10, min));
assertTrue("minValue() > min", validator.minValue(number11, min));
// Test minValue()
assertTrue("maxValue() < max", validator.maxValue(number19, max));
assertTrue("maxValue() = max", validator.maxValue(number20, max));
assertFalse("maxValue() > max", validator.maxValue(number21, max));
}
}
| 7,928 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/PercentValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.math.BigDecimal;
import java.util.Locale;
import junit.framework.TestCase;
/**
* Test Case for PercentValidator.
*/
public class PercentValidatorTest extends TestCase {
protected PercentValidator validator;
/**
* Constructor
* @param name test name
*/
public PercentValidatorTest(final String name) {
super(name);
}
@Override
protected void setUp() {
validator = new PercentValidator();
}
/**
* Tear down
*/
@Override
protected void tearDown() {
validator = null;
}
/**
* Test Format Type
*/
public void testFormatType() {
assertEquals("Format Type A", 2, PercentValidator.getInstance().getFormatType());
assertEquals("Format Type B", AbstractNumberValidator.PERCENT_FORMAT, PercentValidator.getInstance().getFormatType());
}
/**
* Test Valid percentage values
*/
public void testValid() {
// Set the default Locale
final Locale origDefault = Locale.getDefault();
Locale.setDefault(Locale.UK);
final BigDecimalValidator validator = PercentValidator.getInstance();
final BigDecimal expected = new BigDecimal("0.12");
final BigDecimal negative = new BigDecimal("-0.12");
final BigDecimal hundred = new BigDecimal("1.00");
assertEquals("Default locale", expected, validator.validate("12%"));
assertEquals("Default negtve", negative, validator.validate("-12%"));
// Invalid UK
assertEquals("UK locale", expected, validator.validate("12%", Locale.UK));
assertEquals("UK negative", negative, validator.validate("-12%", Locale.UK));
assertEquals("UK No symbol", expected, validator.validate("12", Locale.UK));
// Invalid US - can't find a Locale with different symbols!
assertEquals("US locale", expected, validator.validate("12%", Locale.US));
assertEquals("US negative", negative, validator.validate("-12%", Locale.US));
assertEquals("US No symbol", expected, validator.validate("12", Locale.US));
assertEquals("100%", hundred, validator.validate("100%"));
// Restore the original default
Locale.setDefault(origDefault);
}
/**
* Test Invalid percentage values
*/
public void testInvalid() {
final BigDecimalValidator validator = PercentValidator.getInstance();
// Invalid Missing
assertFalse("isValid() Null Value", validator.isValid(null));
assertFalse("isValid() Empty Value", validator.isValid(""));
assertNull("validate() Null Value", validator.validate(null));
assertNull("validate() Empty Value", validator.validate(""));
// Invalid UK
assertFalse("UK wrong symbol", validator.isValid("12@", Locale.UK)); // ???
assertFalse("UK wrong negative", validator.isValid("(12%)", Locale.UK));
// Invalid US - can't find a Locale with different symbols!
assertFalse("US wrong symbol", validator.isValid("12@", Locale.US)); // ???
assertFalse("US wrong negative", validator.isValid("(12%)", Locale.US));
}
}
| 7,929 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/CalendarValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.text.DateFormat;
import java.text.Format;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* Test Case for CalendarValidator.
*/
public class CalendarValidatorTest extends AbstractCalendarValidatorTest {
private static final int DATE_2005_11_23 = 20051123;
private static final int TIME_12_03_45 = 120345;
private CalendarValidator calValidator;
/**
* Constructor
* @param name test name
*/
public CalendarValidatorTest(final String name) {
super(name);
}
@Override
protected void setUp() {
calValidator = new CalendarValidator();
validator = calValidator;
}
/**
* Test CalendarValidator validate Methods
*/
public void testCalendarValidatorMethods() {
Locale.setDefault(Locale.US);
final Locale locale = Locale.GERMAN;
final String pattern = "yyyy-MM-dd";
final String patternVal = "2005-12-31";
final String germanVal = "31 Dez 2005";
final String germanPattern = "dd MMM yyyy";
final String localeVal = "31.12.2005";
final String defaultVal = "12/31/05";
final String XXXX = "XXXX";
final Date expected = createCalendar(null, 20051231, 0).getTime();
assertEquals("validate(A) default", expected, CalendarValidator.getInstance().validate(defaultVal).getTime());
assertEquals("validate(A) locale ", expected, CalendarValidator.getInstance().validate(localeVal, locale).getTime());
assertEquals("validate(A) pattern", expected, CalendarValidator.getInstance().validate(patternVal, pattern).getTime());
assertEquals("validate(A) both", expected, CalendarValidator.getInstance().validate(germanVal, germanPattern, Locale.GERMAN).getTime());
assertTrue("isValid(A) default", CalendarValidator.getInstance().isValid(defaultVal));
assertTrue("isValid(A) locale ", CalendarValidator.getInstance().isValid(localeVal, locale));
assertTrue("isValid(A) pattern", CalendarValidator.getInstance().isValid(patternVal, pattern));
assertTrue("isValid(A) both", CalendarValidator.getInstance().isValid(germanVal, germanPattern, Locale.GERMAN));
assertNull("validate(B) default", CalendarValidator.getInstance().validate(XXXX));
assertNull("validate(B) locale ", CalendarValidator.getInstance().validate(XXXX, locale));
assertNull("validate(B) pattern", CalendarValidator.getInstance().validate(XXXX, pattern));
assertNull("validate(B) both", CalendarValidator.getInstance().validate("31 Dec 2005", germanPattern, Locale.GERMAN));
assertFalse("isValid(B) default", CalendarValidator.getInstance().isValid(XXXX));
assertFalse("isValid(B) locale ", CalendarValidator.getInstance().isValid(XXXX, locale));
assertFalse("isValid(B) pattern", CalendarValidator.getInstance().isValid(XXXX, pattern));
assertFalse("isValid(B) both", CalendarValidator.getInstance().isValid("31 Dec 2005", germanPattern, Locale.GERMAN));
// Test Time Zone
final TimeZone zone = TimeZone.getDefault().getRawOffset() == EET.getRawOffset() ? EST : EET;
final Date expectedZone = createCalendar(zone, 20051231, 0).getTime();
assertFalse("default/EET same ", expected.getTime() == expectedZone.getTime());
assertEquals("validate(C) default", expectedZone, CalendarValidator.getInstance().validate(defaultVal, zone).getTime());
assertEquals("validate(C) locale ", expectedZone, CalendarValidator.getInstance().validate(localeVal, locale, zone).getTime());
assertEquals("validate(C) pattern", expectedZone, CalendarValidator.getInstance().validate(patternVal, pattern, zone).getTime());
assertEquals("validate(C) both", expectedZone, CalendarValidator.getInstance().validate(germanVal, germanPattern, Locale.GERMAN, zone).getTime());
}
/**
* Test compare date methods
*/
public void testCompare() {
final int sameTime = 124522;
final int testDate = 20050823;
final Calendar diffHour = createCalendar(GMT, testDate, 115922); // same date, different time
final Calendar diffMin = createCalendar(GMT, testDate, 124422); // same date, different time
final Calendar diffSec = createCalendar(GMT, testDate, 124521); // same date, different time
final Calendar value = createCalendar(GMT, testDate, sameTime); // test value
final Calendar cal20050824 = createCalendar(GMT, 20050824, sameTime); // +1 day
final Calendar cal20050822 = createCalendar(GMT, 20050822, sameTime); // -1 day
final Calendar cal20050830 = createCalendar(GMT, 20050830, sameTime); // +1 week
final Calendar cal20050816 = createCalendar(GMT, 20050816, sameTime); // -1 week
final Calendar cal20050901 = createCalendar(GMT, 20050901, sameTime); // +1 month
final Calendar cal20050801 = createCalendar(GMT, 20050801, sameTime); // same month
final Calendar cal20050731 = createCalendar(GMT, 20050731, sameTime); // -1 month
final Calendar cal20051101 = createCalendar(GMT, 20051101, sameTime); // +1 quarter (Feb Start)
final Calendar cal20051001 = createCalendar(GMT, 20051001, sameTime); // +1 quarter
final Calendar cal20050701 = createCalendar(GMT, 20050701, sameTime); // same quarter
final Calendar cal20050630 = createCalendar(GMT, 20050630, sameTime); // -1 quarter
final Calendar cal20060101 = createCalendar(GMT, 20060101, sameTime); // +1 year
final Calendar cal20050101 = createCalendar(GMT, 20050101, sameTime); // same year
final Calendar cal20041231 = createCalendar(GMT, 20041231, sameTime); // -1 year
assertEquals("hour GT", 1, calValidator.compare(value, diffHour, Calendar.HOUR_OF_DAY));
assertEquals("hour EQ", 0, calValidator.compare(value, diffMin, Calendar.HOUR_OF_DAY));
assertEquals("mins GT", 1, calValidator.compare(value, diffMin, Calendar.MINUTE));
assertEquals("mins EQ", 0, calValidator.compare(value, diffSec, Calendar.MINUTE));
assertEquals("secs GT", 1, calValidator.compare(value, diffSec, Calendar.SECOND));
assertEquals("date LT", -1, calValidator.compareDates(value, cal20050824)); // +1 day
assertEquals("date EQ", 0, calValidator.compareDates(value, diffHour)); // same day, diff hour
assertEquals("date(B)", 0, calValidator.compare(value, diffHour, Calendar.DAY_OF_YEAR)); // same day, diff hour
assertEquals("date GT", 1, calValidator.compareDates(value, cal20050822)); // -1 day
assertEquals("week LT", -1, calValidator.compareWeeks(value, cal20050830)); // +1 week
assertEquals("week =1", 0, calValidator.compareWeeks(value, cal20050824)); // +1 day
assertEquals("week =2", 0, calValidator.compareWeeks(value, cal20050822)); // same week
assertEquals("week =3", 0, calValidator.compare(value, cal20050822, Calendar.WEEK_OF_MONTH)); // same week
assertEquals("week =4", 0, calValidator.compareWeeks(value, cal20050822)); // -1 day
assertEquals("week GT", 1, calValidator.compareWeeks(value, cal20050816)); // -1 week
assertEquals("mnth LT", -1, calValidator.compareMonths(value, cal20050901)); // +1 month
assertEquals("mnth =1", 0, calValidator.compareMonths(value, cal20050830)); // +1 week
assertEquals("mnth =2", 0, calValidator.compareMonths(value, cal20050801)); // same month
assertEquals("mnth =3", 0, calValidator.compareMonths(value, cal20050816)); // -1 week
assertEquals("mnth GT", 1, calValidator.compareMonths(value, cal20050731)); // -1 month
assertEquals("qtrA <1", -1, calValidator.compareQuarters(value, cal20051101)); // +1 quarter (Feb)
assertEquals("qtrA <2", -1, calValidator.compareQuarters(value, cal20051001)); // +1 quarter
assertEquals("qtrA =1", 0, calValidator.compareQuarters(value, cal20050901)); // +1 month
assertEquals("qtrA =2", 0, calValidator.compareQuarters(value, cal20050701)); // same quarter
assertEquals("qtrA =3", 0, calValidator.compareQuarters(value, cal20050731)); // -1 month
assertEquals("qtrA GT", 1, calValidator.compareQuarters(value, cal20050630)); // -1 quarter
// Change quarter 1 to start in Feb
assertEquals("qtrB LT", -1, calValidator.compareQuarters(value, cal20051101, 2)); // +1 quarter (Feb)
assertEquals("qtrB =1", 0, calValidator.compareQuarters(value, cal20051001, 2)); // same quarter
assertEquals("qtrB =2", 0, calValidator.compareQuarters(value, cal20050901, 2)); // +1 month
assertEquals("qtrB =3", 1, calValidator.compareQuarters(value, cal20050701, 2)); // same quarter
assertEquals("qtrB =4", 1, calValidator.compareQuarters(value, cal20050731, 2)); // -1 month
assertEquals("qtrB GT", 1, calValidator.compareQuarters(value, cal20050630, 2)); // -1 quarter
assertEquals("year LT", -1, calValidator.compareYears(value, cal20060101)); // +1 year
assertEquals("year EQ", 0, calValidator.compareYears(value, cal20050101)); // same year
assertEquals("year GT", 1, calValidator.compareYears(value, cal20041231)); // -1 year
// invalid compare
try {
calValidator.compare(value, value, -1);
fail("Invalid Compare field - expected IllegalArgumentException to be thrown");
} catch (final IllegalArgumentException e) {
assertEquals("check message", "Invalid field: -1", e.getMessage());
}
}
/**
* Test Date/Time style Validator (there isn't an implementation for this)
*/
public void testDateTimeStyle() {
// Set the default Locale
final Locale origDefault = Locale.getDefault();
Locale.setDefault(Locale.UK);
final AbstractCalendarValidator dateTimeValidator =
new AbstractCalendarValidator(true, DateFormat.SHORT, DateFormat.SHORT) {
private static final long serialVersionUID = 1L;
@Override
protected Object processParsedValue(final Object value, final Format formatter) {
return value;
}
};
assertTrue("validate(A) default", dateTimeValidator.isValid("31/12/05 14:23"));
assertTrue("validate(A) locale ", dateTimeValidator.isValid("12/31/05 2:23 PM", Locale.US));
// Restore the original default
Locale.setDefault(origDefault);
}
/**
* Test format methods
*/
@Override
public void testFormat() {
// Set the default Locale
final Locale origDefault = Locale.getDefault();
Locale.setDefault(Locale.UK);
final Calendar cal20050101 = createCalendar(GMT, 20051231, 11500);
assertNull("null", calValidator.format(null));
assertEquals("default", "31/12/05", calValidator.format(cal20050101));
assertEquals("locale", "12/31/05", calValidator.format(cal20050101, Locale.US));
assertEquals("patternA", "2005-12-31 01:15", calValidator.format(cal20050101, "yyyy-MM-dd HH:mm"));
assertEquals("patternB", "2005-12-31 GMT", calValidator.format(cal20050101, "yyyy-MM-dd z"));
assertEquals("both", "31 Dez 2005", calValidator.format(cal20050101, "dd MMM yyyy", Locale.GERMAN));
// EST Time Zone
assertEquals("EST default", "30/12/05", calValidator.format(cal20050101, EST));
assertEquals("EST locale", "12/30/05", calValidator.format(cal20050101, Locale.US, EST));
assertEquals("EST patternA", "2005-12-30 20:15", calValidator.format(cal20050101, "yyyy-MM-dd HH:mm", EST));
assertEquals("EST patternB", "2005-12-30 EST", calValidator.format(cal20050101, "yyyy-MM-dd z", EST));
assertEquals("EST both", "30 Dez 2005", calValidator.format(cal20050101, "dd MMM yyyy", Locale.GERMAN, EST));
// Restore the original default
Locale.setDefault(origDefault);
}
/**
* Test adjustToTimeZone() method
*/
public void testAdjustToTimeZone() {
final Calendar calEST = createCalendar(EST, DATE_2005_11_23, TIME_12_03_45);
final Date dateEST = calEST.getTime();
final Calendar calGMT = createCalendar(GMT, DATE_2005_11_23, TIME_12_03_45);
final Date dateGMT = calGMT.getTime();
final Calendar calCET = createCalendar(EET, DATE_2005_11_23, TIME_12_03_45);
final Date dateCET = calCET.getTime();
// Check the dates don't match
assertFalse("Check GMT != CET", dateGMT.getTime() == dateCET.getTime());
assertFalse("Check GMT != EST", dateGMT.getTime() == dateEST.getTime());
assertFalse("Check CET != EST", dateCET.getTime() == dateEST.getTime());
// EST to GMT and back
CalendarValidator.adjustToTimeZone(calEST, GMT);
assertEquals("EST to GMT", dateGMT, calEST.getTime());
assertFalse("Check EST = GMT", dateEST == calEST.getTime());
CalendarValidator.adjustToTimeZone(calEST, EST);
assertEquals("back to EST", dateEST, calEST.getTime());
assertFalse("Check EST != GMT", dateGMT == calEST.getTime());
// CET to GMT and back
CalendarValidator.adjustToTimeZone(calCET, GMT);
assertEquals("CET to GMT", dateGMT, calCET.getTime());
assertFalse("Check CET = GMT", dateCET == calCET.getTime());
CalendarValidator.adjustToTimeZone(calCET, EET);
assertEquals("back to CET", dateCET, calCET.getTime());
assertFalse("Check CET != GMT", dateGMT == calCET.getTime());
// Adjust to TimeZone with Same rules
final Calendar calUTC = createCalendar(UTC, DATE_2005_11_23, TIME_12_03_45);
assertTrue("SAME: UTC = GMT", UTC.hasSameRules(GMT));
assertEquals("SAME: Check time (A)", calUTC.getTime(), calGMT.getTime());
assertFalse("SAME: Check GMT(A)", GMT.equals(calUTC.getTimeZone()));
assertTrue("SAME: Check UTC(A)", UTC.equals(calUTC.getTimeZone()));
CalendarValidator.adjustToTimeZone(calUTC, GMT);
assertEquals("SAME: Check time (B)", calUTC.getTime(), calGMT.getTime());
assertTrue("SAME: Check GMT(B)", GMT.equals(calUTC.getTimeZone()));
assertFalse("SAME: Check UTC(B)", UTC.equals(calUTC.getTimeZone()));
}
}
| 7,930 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/CodeValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import org.apache.commons.validator.routines.checkdigit.CheckDigit;
import org.apache.commons.validator.routines.checkdigit.EAN13CheckDigit;
import junit.framework.TestCase;
/**
* CodeValidatorTest.java.
*
* @since 1.4
*/
public class CodeValidatorTest extends TestCase {
/**
* Constructs a test with the specified name.
* @param name The name of the test
*/
public CodeValidatorTest(final String name) {
super(name);
}
/**
* Test Check Digit.
*/
public void testCheckDigit() {
CodeValidator validator = new CodeValidator((String)null, -1, -1, (CheckDigit)null);
final String invalidEAN = "9781930110992";
final String validEAN = "9781930110991";
// Test no CheckDigit (i.e. null)
assertNull("No CheckDigit", validator.getCheckDigit());
assertEquals("No CheckDigit invalid", invalidEAN, validator.validate(invalidEAN));
assertEquals("No CheckDigit valid", validEAN, validator.validate(validEAN));
assertEquals("No CheckDigit (is) invalid", true, validator.isValid(invalidEAN));
assertEquals("No CheckDigit (is) valid", true, validator.isValid(validEAN));
// Use the EAN-13 check digit routine
validator = new CodeValidator((String)null, -1, EAN13CheckDigit.EAN13_CHECK_DIGIT);
assertNotNull("EAN CheckDigit", validator.getCheckDigit());
assertEquals("EAN CheckDigit invalid", null, validator.validate(invalidEAN));
assertEquals("EAN CheckDigit valid", validEAN, validator.validate(validEAN));
assertEquals("EAN CheckDigit (is) invalid", false, validator.isValid(invalidEAN));
assertEquals("EAN CheckDigit (is) valid", true, validator.isValid(validEAN));
assertEquals("EAN CheckDigit ex", null, validator.validate("978193011099X"));
}
/**
* Test the minimum/maximum length
*/
public void testLength() {
CodeValidator validator = new CodeValidator((String)null, -1, -1, (CheckDigit)null);
final String length_10 = "1234567890";
final String length_11 = "12345678901";
final String length_12 = "123456789012";
final String length_20 = "12345678901234567890";
final String length_21 = "123456789012345678901";
final String length_22 = "1234567890123456789012";
assertEquals("No min", -1, validator.getMinLength());
assertEquals("No max", -1, validator.getMaxLength());
assertEquals("No Length 10", length_10, validator.validate(length_10));
assertEquals("No Length 11", length_11, validator.validate(length_11));
assertEquals("No Length 12", length_12, validator.validate(length_12));
assertEquals("No Length 20", length_20, validator.validate(length_20));
assertEquals("No Length 21", length_21, validator.validate(length_21));
assertEquals("No Length 22", length_22, validator.validate(length_22));
validator = new CodeValidator((String)null, 11, -1, (CheckDigit)null);
assertEquals("Min 11 - min", 11, validator.getMinLength());
assertEquals("Min 11 - max", -1, validator.getMaxLength());
assertEquals("Min 11 - 10", null, validator.validate(length_10));
assertEquals("Min 11 - 11", length_11, validator.validate(length_11));
assertEquals("Min 11 - 12", length_12, validator.validate(length_12));
assertEquals("Min 11 - 20", length_20, validator.validate(length_20));
assertEquals("Min 11 - 21", length_21, validator.validate(length_21));
assertEquals("Min 11 - 22", length_22, validator.validate(length_22));
validator = new CodeValidator((String)null, -1, 21, (CheckDigit)null);
assertEquals("Max 21 - min", -1, validator.getMinLength());
assertEquals("Max 21 - max", 21, validator.getMaxLength());
assertEquals("Max 21 - 10", length_10, validator.validate(length_10));
assertEquals("Max 21 - 11", length_11, validator.validate(length_11));
assertEquals("Max 21 - 12", length_12, validator.validate(length_12));
assertEquals("Max 21 - 20", length_20, validator.validate(length_20));
assertEquals("Max 21 - 21", length_21, validator.validate(length_21));
assertEquals("Max 21 - 22", null, validator.validate(length_22));
validator = new CodeValidator((String)null, 11, 21, (CheckDigit)null);
assertEquals("Min 11 / Max 21 - min", 11, validator.getMinLength());
assertEquals("Min 11 / Max 21 - max", 21, validator.getMaxLength());
assertEquals("Min 11 / Max 21 - 10", null, validator.validate(length_10));
assertEquals("Min 11 / Max 21 - 11", length_11, validator.validate(length_11));
assertEquals("Min 11 / Max 21 - 12", length_12, validator.validate(length_12));
assertEquals("Min 11 / Max 21 - 20", length_20, validator.validate(length_20));
assertEquals("Min 11 / Max 21 - 21", length_21, validator.validate(length_21));
assertEquals("Min 11 / Max 21 - 22", null, validator.validate(length_22));
validator = new CodeValidator((String)null, 11, 11, (CheckDigit)null);
assertEquals("Exact 11 - min", 11, validator.getMinLength());
assertEquals("Exact 11 - max", 11, validator.getMaxLength());
assertEquals("Exact 11 - 10", null, validator.validate(length_10));
assertEquals("Exact 11 - 11", length_11, validator.validate(length_11));
assertEquals("Exact 11 - 12", null, validator.validate(length_12));
}
/**
* Test Regular Expression.
*/
public void testRegex() {
CodeValidator validator = new CodeValidator((String)null, -1, -1, (CheckDigit)null);
final String value2 = "12";
final String value3 = "123";
final String value4 = "1234";
final String value5 = "12345";
final String invalid = "12a4";
// No Regular Expression
assertNull("No Regex", validator.getRegexValidator());
assertEquals("No Regex 2", value2, validator.validate(value2));
assertEquals("No Regex 3", value3, validator.validate(value3));
assertEquals("No Regex 4", value4, validator.validate(value4));
assertEquals("No Regex 5", value5, validator.validate(value5));
assertEquals("No Regex invalid", invalid, validator.validate(invalid));
// Regular Expression
String regex = "^([0-9]{3,4})$";
validator = new CodeValidator(regex, -1, -1, (CheckDigit)null);
assertNotNull("No Regex", validator.getRegexValidator());
assertEquals("Regex 2", null, validator.validate(value2));
assertEquals("Regex 3", value3, validator.validate(value3));
assertEquals("Regex 4", value4, validator.validate(value4));
assertEquals("Regex 5", null, validator.validate(value5));
assertEquals("Regex invalid", null, validator.validate(invalid));
// Reformatted
regex = "^([0-9]{3})(?:[-\\s])([0-9]{3})$";
validator = new CodeValidator(new RegexValidator(regex), 6, (CheckDigit)null);
assertEquals("Reformat 123-456", "123456", validator.validate("123-456"));
assertEquals("Reformat 123 456", "123456", validator.validate("123 456"));
assertEquals("Reformat 123456", null, validator.validate("123456"));
assertEquals("Reformat 123.456", null, validator.validate("123.456"));
regex = "^(?:([0-9]{3})(?:[-\\s])([0-9]{3}))|([0-9]{6})$";
validator = new CodeValidator(new RegexValidator(regex), 6, (CheckDigit)null);
assertEquals("Reformat 2 Regex", "RegexValidator{" + regex + "}", validator.getRegexValidator().toString());
assertEquals("Reformat 2 123-456", "123456", validator.validate("123-456"));
assertEquals("Reformat 2 123 456", "123456", validator.validate("123 456"));
assertEquals("Reformat 2 123456", "123456", validator.validate("123456"));
}
/**
* Test Regular Expression.
*/
public void testNoInput() {
final CodeValidator validator = new CodeValidator((String)null, -1, -1, (CheckDigit)null);
assertEquals("Null", null, validator.validate(null));
assertEquals("Zero Length", null, validator.validate(""));
assertEquals("Spaces", null, validator.validate(" "));
assertEquals("Trimmed", "A", validator.validate(" A "));
}
public void testValidator294_1() {
CodeValidator validator = new CodeValidator((String)null, 0, -1, (CheckDigit)null);
assertEquals("Null", null, validator.validate(null));
validator = new CodeValidator((String)null, -1, 0, (CheckDigit)null);
assertEquals("Null", null, validator.validate(null));
}
public void testValidator294_2() {
final CodeValidator validator = new CodeValidator((String)null, -1, 0, (CheckDigit)null);
assertEquals("Null", null, validator.validate(null));
}
/**
* Test Regular Expression.
*/
public void testConstructors() {
CodeValidator validator;
final RegexValidator regex = new RegexValidator("^[0-9]*$");
// Constructor 1
validator = new CodeValidator(regex, EAN13CheckDigit.EAN13_CHECK_DIGIT);
assertEquals("Constructor 1 - regex", regex, validator.getRegexValidator());
assertEquals("Constructor 1 - min length", -1, validator.getMinLength());
assertEquals("Constructor 1 - max length", -1, validator.getMaxLength());
assertEquals("Constructor 1 - check digit", EAN13CheckDigit.EAN13_CHECK_DIGIT, validator.getCheckDigit());
// Constructor 2
validator = new CodeValidator(regex, 13, EAN13CheckDigit.EAN13_CHECK_DIGIT);
assertEquals("Constructor 2 - regex", regex, validator.getRegexValidator());
assertEquals("Constructor 2 - min length", 13, validator.getMinLength());
assertEquals("Constructor 2 - max length", 13, validator.getMaxLength());
assertEquals("Constructor 2 - check digit", EAN13CheckDigit.EAN13_CHECK_DIGIT, validator.getCheckDigit());
// Constructor 3
validator = new CodeValidator(regex, 10, 20, EAN13CheckDigit.EAN13_CHECK_DIGIT);
assertEquals("Constructor 3 - regex", regex, validator.getRegexValidator());
assertEquals("Constructor 3 - min length", 10, validator.getMinLength());
assertEquals("Constructor 3 - max length", 20, validator.getMaxLength());
assertEquals("Constructor 3 - check digit", EAN13CheckDigit.EAN13_CHECK_DIGIT, validator.getCheckDigit());
// Constructor 4
validator = new CodeValidator("^[0-9]*$", EAN13CheckDigit.EAN13_CHECK_DIGIT);
assertEquals("Constructor 4 - regex", "RegexValidator{^[0-9]*$}", validator.getRegexValidator().toString());
assertEquals("Constructor 4 - min length", -1, validator.getMinLength());
assertEquals("Constructor 4 - max length", -1, validator.getMaxLength());
assertEquals("Constructor 4 - check digit", EAN13CheckDigit.EAN13_CHECK_DIGIT, validator.getCheckDigit());
// Constructor 5
validator = new CodeValidator("^[0-9]*$", 13, EAN13CheckDigit.EAN13_CHECK_DIGIT);
assertEquals("Constructor 5 - regex", "RegexValidator{^[0-9]*$}", validator.getRegexValidator().toString());
assertEquals("Constructor 5 - min length", 13, validator.getMinLength());
assertEquals("Constructor 5 - max length", 13, validator.getMaxLength());
assertEquals("Constructor 5 - check digit", EAN13CheckDigit.EAN13_CHECK_DIGIT, validator.getCheckDigit());
// Constructor 6
validator = new CodeValidator("^[0-9]*$", 10, 20, EAN13CheckDigit.EAN13_CHECK_DIGIT);
assertEquals("Constructor 6 - regex", "RegexValidator{^[0-9]*$}", validator.getRegexValidator().toString());
assertEquals("Constructor 6 - min length", 10, validator.getMinLength());
assertEquals("Constructor 6 - max length", 20, validator.getMaxLength());
assertEquals("Constructor 6 - check digit", EAN13CheckDigit.EAN13_CHECK_DIGIT, validator.getCheckDigit());
}
}
| 7,931 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/CurrencyValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.math.BigDecimal;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
import junit.framework.TestCase;
/**
* Test Case for CurrencyValidator.
*/
public class CurrencyValidatorTest extends TestCase {
private static final char CURRENCY_SYMBOL = '\u00A4';
private String US_DOLLAR;
private String UK_POUND;
/**
* Constructor
* @param name test name
*/
public CurrencyValidatorTest(final String name) {
super(name);
}
@Override
protected void setUp() {
US_DOLLAR = new DecimalFormatSymbols(Locale.US).getCurrencySymbol();
UK_POUND = new DecimalFormatSymbols(Locale.UK).getCurrencySymbol();
}
/**
* Test Format Type
*/
public void testFormatType() {
assertEquals("Format Type A", 1, CurrencyValidator.getInstance().getFormatType());
assertEquals("Format Type B", AbstractNumberValidator.CURRENCY_FORMAT, CurrencyValidator.getInstance().getFormatType());
}
/**
* Test Valid currency values
*/
public void testValid() {
// Set the default Locale
final Locale origDefault = Locale.getDefault();
Locale.setDefault(Locale.UK);
final BigDecimalValidator validator = CurrencyValidator.getInstance();
final BigDecimal expected = new BigDecimal("1234.56");
final BigDecimal negative = new BigDecimal("-1234.56");
final BigDecimal noDecimal = new BigDecimal("1234.00");
final BigDecimal oneDecimal = new BigDecimal("1234.50");
assertEquals("Default locale", expected, validator.validate(UK_POUND + "1,234.56"));
assertEquals("UK locale", expected, validator.validate(UK_POUND + "1,234.56", Locale.UK));
assertEquals("UK negative", negative, validator.validate("-" + UK_POUND + "1,234.56", Locale.UK));
assertEquals("UK no decimal", noDecimal, validator.validate(UK_POUND + "1,234", Locale.UK));
assertEquals("UK 1 decimal", oneDecimal, validator.validate(UK_POUND + "1,234.5", Locale.UK));
assertEquals("UK 3 decimal", expected, validator.validate(UK_POUND + "1,234.567", Locale.UK));
assertEquals("UK no symbol", expected, validator.validate("1,234.56", Locale.UK));
assertEquals("US locale", expected, validator.validate(US_DOLLAR + "1,234.56", Locale.US));
assertEquals("US negative", negative, validator.validate("(" + US_DOLLAR + "1,234.56)", Locale.US));
assertEquals("US no decimal", noDecimal, validator.validate(US_DOLLAR + "1,234", Locale.US));
assertEquals("US 1 decimal", oneDecimal, validator.validate(US_DOLLAR + "1,234.5", Locale.US));
assertEquals("US 3 decimal", expected, validator.validate(US_DOLLAR + "1,234.567", Locale.US));
assertEquals("US no symbol", expected, validator.validate("1,234.56", Locale.US));
// Restore the original default
Locale.setDefault(origDefault);
}
/**
* Test Invalid currency values
*/
public void testInvalid() {
final BigDecimalValidator validator = CurrencyValidator.getInstance();
// Invalid Missing
assertFalse("isValid() Null Value", validator.isValid(null));
assertFalse("isValid() Empty Value", validator.isValid(""));
assertNull("validate() Null Value", validator.validate(null));
assertNull("validate() Empty Value", validator.validate(""));
// Invalid UK
assertFalse("UK wrong symbol", validator.isValid(US_DOLLAR + "1,234.56", Locale.UK));
assertFalse("UK wrong negative", validator.isValid("(" + UK_POUND + "1,234.56)", Locale.UK));
// Invalid US
assertFalse("US wrong symbol", validator.isValid(UK_POUND + "1,234.56", Locale.US));
assertFalse("US wrong negative", validator.isValid("-" + US_DOLLAR + "1,234.56", Locale.US));
}
/**
* Test Valid integer (non-decimal) currency values
*/
public void testIntegerValid() {
// Set the default Locale
final Locale origDefault = Locale.getDefault();
Locale.setDefault(Locale.UK);
final CurrencyValidator validator = new CurrencyValidator();
final BigDecimal expected = new BigDecimal("1234.00");
final BigDecimal negative = new BigDecimal("-1234.00");
assertEquals("Default locale", expected, validator.validate(UK_POUND +"1,234"));
assertEquals("UK locale", expected, validator.validate(UK_POUND + "1,234", Locale.UK));
assertEquals("UK negative", negative, validator.validate("-" + UK_POUND + "1,234", Locale.UK));
assertEquals("US locale", expected, validator.validate(US_DOLLAR + "1,234", Locale.US));
assertEquals("US negative", negative, validator.validate("(" + US_DOLLAR + "1,234)", Locale.US));
// Restore the original default
Locale.setDefault(origDefault);
}
/**
* Test Invalid integer (non decimal) currency values
*/
public void testIntegerInvalid() {
final CurrencyValidator validator = new CurrencyValidator(true, false);
// Invalid UK - has decimals
assertFalse("UK positive", validator.isValid(UK_POUND + "1,234.56", Locale.UK));
assertFalse("UK negative", validator.isValid("-" + UK_POUND + "1,234.56", Locale.UK));
// Invalid US - has decimals
assertFalse("US positive", validator.isValid(US_DOLLAR + "1,234.56", Locale.US));
assertFalse("US negative", validator.isValid("(" + US_DOLLAR + "1,234.56)", Locale.US));
}
/**
* Test currency values with a pattern
*/
public void testPattern() {
// Set the default Locale
final Locale origDefault = Locale.getDefault();
Locale.setDefault(Locale.UK);
final BigDecimalValidator validator = CurrencyValidator.getInstance();
final String basicPattern = CURRENCY_SYMBOL + "#,##0.000";
final String pattern = basicPattern + ";[" + basicPattern +"]";
final BigDecimal expected = new BigDecimal("1234.567");
final BigDecimal negative = new BigDecimal("-1234.567");
// Test Pattern
assertEquals("default", expected, validator.validate(UK_POUND + "1,234.567", pattern));
assertEquals("negative", negative, validator.validate("[" + UK_POUND + "1,234.567]", pattern));
assertEquals("no symbol +ve", expected, validator.validate("1,234.567", pattern));
assertEquals("no symbol -ve", negative, validator.validate("[1,234.567]", pattern));
// Test Pattern & Locale
assertEquals("default", expected, validator.validate(US_DOLLAR + "1,234.567", pattern, Locale.US));
assertEquals("negative", negative, validator.validate("[" + US_DOLLAR + "1,234.567]", pattern, Locale.US));
assertEquals("no symbol +ve", expected, validator.validate("1,234.567", pattern, Locale.US));
assertEquals("no symbol -ve", negative, validator.validate("[1,234.567]", pattern, Locale.US));
// invalid
assertFalse("invalid symbol", validator.isValid(US_DOLLAR + "1,234.567", pattern));
assertFalse("invalid symbol", validator.isValid(UK_POUND + "1,234.567", pattern, Locale.US));
// Restore the original default
Locale.setDefault(origDefault);
}
}
| 7,932 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/BigDecimalValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.math.BigDecimal;
import java.util.Locale;
/**
* Test Case for BigDecimalValidator.
*/
public class BigDecimalValidatorTest extends AbstractNumberValidatorTest {
/**
* Constructor
* @param name test name
*/
public BigDecimalValidatorTest(final String name) {
super(name);
}
@Override
protected void setUp() {
super.setUp();
validator = new BigDecimalValidator(false);
strictValidator = new BigDecimalValidator();
testPattern = "#,###.###";
// testValidateMinMax()
max = null;
maxPlusOne = null;
min = null;
minMinusOne = null;
// testInvalidStrict()
invalidStrict = new String[] {null, "", "X", "X12", "12X", "1X2", "1.234X"};
// testInvalidNotStrict()
invalid = new String[] {null, "", "X", "X12"};
// testValid()
testNumber = new BigDecimal("1234.5");
final Number testNumber2 = new BigDecimal(".1");
final Number testNumber3 = new BigDecimal("12345.67899");
testZero = new BigDecimal("0");
validStrict = new String[] {"0", "1234.5", "1,234.5", ".1", "12345.678990"};
validStrictCompare = new Number[] {testZero, testNumber, testNumber, testNumber2, testNumber3};
valid = new String[] {"0", "1234.5", "1,234.5", "1,234.5", "1234.5X"};
validCompare = new Number[] {testZero, testNumber, testNumber, testNumber, testNumber};
testStringUS = "1,234.5";
testStringDE = "1.234,5";
// Localized Pattern test
localeValue = testStringDE;
localePattern = "#.###,#";
testLocale = Locale.GERMANY;
localeExpected = testNumber;
}
/**
* Test BigDecimalValidator validate Methods
*/
public void testBigDecimalValidatorMethods() {
final Locale locale = Locale.GERMAN;
final String pattern = "0,00,00";
final String patternVal = "1,23,45";
final String germanPatternVal = "1.23.45";
final String localeVal = "12.345";
final String defaultVal = "12,345";
final String XXXX = "XXXX";
final BigDecimal expected = new BigDecimal(12345);
assertEquals("validate(A) default", expected, BigDecimalValidator.getInstance().validate(defaultVal));
assertEquals("validate(A) locale ", expected, BigDecimalValidator.getInstance().validate(localeVal, locale));
assertEquals("validate(A) pattern", expected, BigDecimalValidator.getInstance().validate(patternVal, pattern));
assertEquals("validate(A) both", expected, BigDecimalValidator.getInstance().validate(germanPatternVal, pattern, Locale.GERMAN));
assertTrue("isValid(A) default", BigDecimalValidator.getInstance().isValid(defaultVal));
assertTrue("isValid(A) locale ", BigDecimalValidator.getInstance().isValid(localeVal, locale));
assertTrue("isValid(A) pattern", BigDecimalValidator.getInstance().isValid(patternVal, pattern));
assertTrue("isValid(A) both", BigDecimalValidator.getInstance().isValid(germanPatternVal, pattern, Locale.GERMAN));
assertNull("validate(B) default", BigDecimalValidator.getInstance().validate(XXXX));
assertNull("validate(B) locale ", BigDecimalValidator.getInstance().validate(XXXX, locale));
assertNull("validate(B) pattern", BigDecimalValidator.getInstance().validate(XXXX, pattern));
assertNull("validate(B) both", BigDecimalValidator.getInstance().validate(patternVal, pattern, Locale.GERMAN));
assertFalse("isValid(B) default", BigDecimalValidator.getInstance().isValid(XXXX));
assertFalse("isValid(B) locale ", BigDecimalValidator.getInstance().isValid(XXXX, locale));
assertFalse("isValid(B) pattern", BigDecimalValidator.getInstance().isValid(XXXX, pattern));
assertFalse("isValid(B) both", BigDecimalValidator.getInstance().isValid(patternVal, pattern, Locale.GERMAN));
}
/**
* Test BigDecimal Range/Min/Max
*/
public void testBigDecimalRangeMinMax() {
final BigDecimalValidator validator = new BigDecimalValidator(true, AbstractNumberValidator.STANDARD_FORMAT, true);
final BigDecimal number9 = new BigDecimal("9");
final BigDecimal number10 = new BigDecimal("10");
final BigDecimal number11 = new BigDecimal("11");
final BigDecimal number19 = new BigDecimal("19");
final BigDecimal number20 = new BigDecimal("20");
final BigDecimal number21 = new BigDecimal("21");
final float min = 10;
final float max = 20;
// Test isInRange()
assertFalse("isInRange(A) < min", validator.isInRange(number9, min, max));
assertTrue("isInRange(A) = min", validator.isInRange(number10, min, max));
assertTrue("isInRange(A) in range", validator.isInRange(number11, min, max));
assertTrue("isInRange(A) = max", validator.isInRange(number20, min, max));
assertFalse("isInRange(A) > max", validator.isInRange(number21, min, max));
// Test minValue()
assertFalse("minValue(A) < min", validator.minValue(number9, min));
assertTrue("minValue(A) = min", validator.minValue(number10, min));
assertTrue("minValue(A) > min", validator.minValue(number11, min));
// Test minValue()
assertTrue("maxValue(A) < max", validator.maxValue(number19, max));
assertTrue("maxValue(A) = max", validator.maxValue(number20, max));
assertFalse("maxValue(A) > max", validator.maxValue(number21, max));
}
}
| 7,933 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/AbstractNumberValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Locale;
import junit.framework.TestCase;
/**
* Base Number Test Case.
*/
public abstract class AbstractNumberValidatorTest extends TestCase {
protected AbstractNumberValidator validator;
protected AbstractNumberValidator strictValidator;
protected Number max;
protected Number maxPlusOne;
protected Number min;
protected Number minMinusOne;
protected String[] invalid;
protected String[] valid;
protected Number[] validCompare;
protected String[] invalidStrict;
protected String[] validStrict;
protected Number[] validStrictCompare;
protected String testPattern;
protected Number testNumber;
protected Number testZero;
protected String testStringUS;
protected String testStringDE;
protected String localeValue;
protected String localePattern;
protected Locale testLocale;
protected Number localeExpected;
/**
* Constructor
* @param name test name
*/
public AbstractNumberValidatorTest(final String name) {
super(name);
}
@Override
protected void setUp() {
Locale.setDefault(Locale.US);
}
/**
* Tear down
*/
@Override
protected void tearDown() {
validator = null;
strictValidator = null;
}
/**
* Test Format Type
*/
public void testFormatType() {
assertEquals("Format Type A", 0, validator.getFormatType());
assertEquals("Format Type B", AbstractNumberValidator.STANDARD_FORMAT, validator.getFormatType());
}
/**
* Test Min/Max values allowed
*/
public void testValidateMinMax() {
final DecimalFormat fmt = new DecimalFormat("#");
if (max != null) {
assertEquals("Test Max", max, validator.parse(fmt.format(max), "#", null));
assertNull("Test Max + 1", validator.parse(fmt.format(maxPlusOne), "#", null));
assertEquals("Test Min", min, validator.parse(fmt.format(min), "#", null));
assertNull("Test min - 1", validator.parse(fmt.format(minMinusOne), "#", null));
}
}
/**
* Test Invalid, strict=true
*/
public void testInvalidStrict() {
for (int i = 0; i < invalidStrict.length; i++) {
final String text = "idx=["+i+"] value=[" + invalidStrict[i] + "]";
assertNull("(A) " + text, strictValidator.parse(invalidStrict[i], null, Locale.US));
assertFalse("(B) " + text, strictValidator.isValid(invalidStrict[i], null, Locale.US));
assertNull("(C) " + text, strictValidator.parse(invalidStrict[i], testPattern, null));
assertFalse("(D) " + text, strictValidator.isValid(invalidStrict[i], testPattern, null));
}
}
/**
* Test Invalid, strict=false
*/
public void testInvalidNotStrict() {
for (int i = 0; i < invalid.length; i++) {
final String text = "idx=["+i+"] value=[" + invalid[i] + "]";
assertNull("(A) " + text, validator.parse(invalid[i], null, Locale.US));
assertFalse("(B) " + text, validator.isValid(invalid[i], null, Locale.US));
assertNull("(C) " + text, validator.parse(invalid[i], testPattern, null));
assertFalse("(D) " + text, validator.isValid(invalid[i], testPattern, null));
}
}
/**
* Test Valid, strict=true
*/
public void testValidStrict() {
for (int i = 0; i < validStrict.length; i++) {
final String text = "idx=["+i+"] value=[" + validStrictCompare[i] + "]";
assertEquals("(A) " + text, validStrictCompare[i], strictValidator.parse(validStrict[i], null, Locale.US));
assertTrue("(B) " + text, strictValidator.isValid(validStrict[i], null, Locale.US));
assertEquals("(C) " + text, validStrictCompare[i], strictValidator.parse(validStrict[i], testPattern, null));
assertTrue("(D) " + text, strictValidator.isValid(validStrict[i], testPattern, null));
}
}
/**
* Test Valid, strict=false
*/
public void testValidNotStrict() {
for (int i = 0; i < valid.length; i++) {
final String text = "idx=["+i+"] value=[" + validCompare[i] + "]";
assertEquals("(A) " + text, validCompare[i], validator.parse(valid[i], null, Locale.US));
assertTrue("(B) " + text, validator.isValid(valid[i], null, Locale.US));
assertEquals("(C) " + text, validCompare[i], validator.parse(valid[i], testPattern, null));
assertTrue("(D) " + text, validator.isValid(valid[i], testPattern, null));
}
}
/**
* Test different Locale
*/
public void testValidateLocale() {
assertEquals("US Locale, US Format", testNumber, strictValidator.parse(testStringUS, null, Locale.US));
assertNull("US Locale, DE Format", strictValidator.parse(testStringDE, null, Locale.US));
// Default German Locale
assertEquals("DE Locale, DE Format", testNumber, strictValidator.parse(testStringDE, null, Locale.GERMAN));
assertNull("DE Locale, US Format", strictValidator.parse(testStringUS, null, Locale.GERMAN));
// Default Locale has been set to Locale.US in setup()
assertEquals("Default Locale, US Format", testNumber, strictValidator.parse(testStringUS, null, null));
assertNull("Default Locale, DE Format", strictValidator.parse(testStringDE, null, null));
}
/**
* Test format() methods
*/
public void testFormat() {
final Number number = new BigDecimal("1234.5");
assertEquals("US Locale, US Format", "1,234.5", strictValidator.format(number, Locale.US));
assertEquals("DE Locale, DE Format", "1.234,5", strictValidator.format(number, Locale.GERMAN));
assertEquals("Pattern #,#0.00", "12,34.50", strictValidator.format(number, "#,#0.00"));
}
/**
* Test Range/Min/Max
*/
public void testRangeMinMax() {
final Number number9 = Integer.valueOf(9);
final Number number10 = Integer.valueOf(10);
final Number number11 = Integer.valueOf(11);
final Number number19 = Integer.valueOf(19);
final Number number20 = Integer.valueOf(20);
final Number number21 = Integer.valueOf(21);
// Test isInRange()
assertFalse("isInRange() < min", strictValidator.isInRange(number9 , number10, number20));
assertTrue("isInRange() = min", strictValidator.isInRange(number10 , number10, number20));
assertTrue("isInRange() in range", strictValidator.isInRange(number11 , number10, number20));
assertTrue("isInRange() = max", strictValidator.isInRange(number20 , number10, number20));
assertFalse("isInRange() > max", strictValidator.isInRange(number21 , number10, number20));
// Test minValue()
assertFalse("minValue() < min", strictValidator.minValue(number9 , number10));
assertTrue("minValue() = min", strictValidator.minValue(number10 , number10));
assertTrue("minValue() > min", strictValidator.minValue(number11 , number10));
// Test minValue()
assertTrue("maxValue() < max", strictValidator.maxValue(number19 , number20));
assertTrue("maxValue() = max", strictValidator.maxValue(number20 , number20));
assertFalse("maxValue() > max", strictValidator.maxValue(number21 , number20));
}
/**
* Test validator serialization.
*/
public void testSerialization() {
// Serialize the check digit routine
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
final ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(validator);
oos.flush();
oos.close();
} catch (final Exception e) {
fail(validator.getClass().getName() + " error during serialization: " + e);
}
// Deserialize the test object
Object result = null;
try {
final ByteArrayInputStream bais =
new ByteArrayInputStream(baos.toByteArray());
final ObjectInputStream ois = new ObjectInputStream(bais);
result = ois.readObject();
bais.close();
} catch (final Exception e) {
fail(validator.getClass().getName() + " error during deserialization: " + e);
}
assertNotNull(result);
}
}
| 7,934 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/checkdigit/ISBNCheckDigitTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines.checkdigit;
/**
* ISBN-10/ISBN-13 Check Digit Test.
*
* @since 1.4
*/
public class ISBNCheckDigitTest extends AbstractCheckDigitTest {
/**
* Constructor
* @param name test name
*/
public ISBNCheckDigitTest(final String name) {
super(name);
}
/**
* Sets up routine & valid codes.
*/
@Override
protected void setUp() {
routine = ISBNCheckDigit.ISBN_CHECK_DIGIT;
valid = new String[] {
"9780072129519",
"9780764558313",
"1930110995",
"020163385X",
"1590596277", // ISBN-10 Ubuntu Book
"9781590596272" // ISBN-13 Ubuntu Book
};
missingMessage = "ISBN Code is missing";
zeroSum = "000000000000";
}
/**
* Sets up routine & valid codes.
*/
public void testInvalidLength() {
assertFalse("isValid() Lth 9 ", routine.isValid("123456789"));
assertFalse("isValid() Lth 11", routine.isValid("12345678901"));
assertFalse("isValid() Lth 12", routine.isValid("123456789012"));
assertFalse("isValid() Lth 14", routine.isValid("12345678901234"));
try {
routine.calculate("12345678");
fail("calculate() Lth 8 - expected exception");
} catch (final Exception e) {
assertEquals("calculate() Lth 8", "Invalid ISBN Length = 8", e.getMessage());
}
try {
routine.calculate("1234567890");
fail("calculate() Lth 10 - expected exception");
} catch (final Exception e) {
assertEquals("calculate() Lth 10", "Invalid ISBN Length = 10", e.getMessage());
}
try {
routine.calculate("12345678901");
fail("calculate() Lth 11 - expected exception");
} catch (final Exception e) {
assertEquals("calculate() Lth 11", "Invalid ISBN Length = 11", e.getMessage());
}
try {
routine.calculate("1234567890123");
fail("calculate() Lth 13 - expected exception");
} catch (final Exception e) {
assertEquals("calculate() Lth 13", "Invalid ISBN Length = 13", e.getMessage());
}
}
}
| 7,935 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/checkdigit/SedolCheckDigitTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines.checkdigit;
/**
* ISIN Check Digit Test.
*
* @since 1.4
*/
public class SedolCheckDigitTest extends AbstractCheckDigitTest {
/**
* Constructor
* @param name test name
*/
public SedolCheckDigitTest(final String name) {
super(name);
}
/**
* Sets up routine & valid codes.
*/
@Override
protected void setUp() {
routine = SedolCheckDigit.SEDOL_CHECK_DIGIT;
valid = new String[] {
"0263494",
"0870612",
"B06LQ97",
"3437575",
"B07LF55",
};
invalid = new String[] {"123#567"};
zeroSum = "0000000";
}
private static final String[] INVALID_CHECK_DIGITS = {
"026349E", // proper check digit is '4', see above
"087061C", // proper check digit is '2', see above
"B06LQ9H", // proper check digit is '7', see above
"343757F", // proper check digit is '5', see above
"B07LF5F", // proper check digit is '5', see above
};
public void testVALIDATOR_346() {
for (final String invalidCheckDigit : INVALID_CHECK_DIGITS) {
assertFalse("Should fail: " + invalidCheckDigit, routine.isValid(invalidCheckDigit));
}
}
}
| 7,936 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/checkdigit/ISSNCheckDigitTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines.checkdigit;
/**
* ISSN Check Digit Test.
*
* @since 1.5.0
*/
public class ISSNCheckDigitTest extends AbstractCheckDigitTest {
/**
* Constructor
* @param name test name
*/
public ISSNCheckDigitTest(final String name) {
super(name);
}
/**
* Sets up routine & valid codes.
*/
@Override
protected void setUp() {
routine = ISSNCheckDigit.ISSN_CHECK_DIGIT;
valid = new String[] {
"03178471",
"1050124X",
"15626865",
"10637710",
"17487188",
"02642875",
"17500095",
"11881534",
"19111479",
"19111460",
"00016772",
"1365201X",
};
invalid = new String[] {
"03178472", // wrong check
"1050-124X", // format char
" 1365201X",
"1365201X ",
" 1365201X ",
};
missingMessage = "Code is missing";
zeroSum = "00000000";
}
}
| 7,937 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/checkdigit/ModulusTenSedolCheckDigitTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines.checkdigit;
/**
* ModulusTenCheckDigit SEDOL Test.
*/
public class ModulusTenSedolCheckDigitTest extends AbstractCheckDigitTest {
/**
* Constructor
* @param name test name
*/
public ModulusTenSedolCheckDigitTest(final String name) {
super(name);
}
/**
* Sets up routine & valid codes.
*/
@Override
protected void setUp() {
routine = new ModulusTenCheckDigit(new int[] { 1, 3, 1, 7, 3, 9, 1 });
valid = new String[] {
"0263494",
"0870612",
"B06LQ97",
"3437575",
"B07LF55",
};
invalid = new String[] {"123#567"};
zeroSum = "0000000";
}
private static final String[] INVALID_CHECK_DIGITS = {
"026349E", // proper check digit is '4', see above
"087061C", // proper check digit is '2', see above
"B06LQ9H", // proper check digit is '7', see above
"343757F", // proper check digit is '5', see above
"B07LF5F", // proper check digit is '5', see above
};
public void testVALIDATOR_346() {
for (final String invalidCheckDigit : INVALID_CHECK_DIGITS) {
assertFalse("Should fail: " + invalidCheckDigit, routine.isValid(invalidCheckDigit));
}
}
}
| 7,938 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/checkdigit/ISBN10CheckDigitTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines.checkdigit;
/**
* ISBN-10 Check Digit Test.
*
* @since 1.4
*/
public class ISBN10CheckDigitTest extends AbstractCheckDigitTest {
/**
* Constructor
* @param name test name
*/
public ISBN10CheckDigitTest(final String name) {
super(name);
}
/**
* Sets up routine & valid codes.
*/
@Override
protected void setUp() {
routine = ISBN10CheckDigit.ISBN10_CHECK_DIGIT;
valid = new String[] {
"1930110995",
"020163385X",
"1932394354",
"1590596277"
};
}
}
| 7,939 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/checkdigit/IBANCheckDigitTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines.checkdigit;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
/**
* IBAN Check Digit Test.
*
* @since 1.4
*/
public class IBANCheckDigitTest extends AbstractCheckDigitTest {
/**
* Constructor
* @param name test name
*/
public IBANCheckDigitTest(final String name) {
super(name);
checkDigitLth = 2;
}
/**
* Sets up routine & valid codes.
*/
@Override
protected void setUp() {
routine = IBANCheckDigit.IBAN_CHECK_DIGIT;
valid = new String[] {
"AD1200012030200359100100", // Andorra
"AE070331234567890123456", // United Arab Emirates
"AL47212110090000000235698741", // Albania
"AT611904300234573201", // Austria
"AZ21NABZ00000000137010001944", // Azerbaijan
"BA391290079401028494", // Bosnia and Herzegovina
"BE62510007547061", // Belgium
"BE68539007547034", // Belgium
"BG80BNBG96611020345678", // Bulgaria
"BH67BMAG00001299123456", // Bahrain
"BI4210000100010000332045181", // Burundi
"BR1800000000141455123924100C2", // Brazil
"BY13NBRB3600900000002Z00AB00", // Belarus
"CH3900700115201849173", // Switzerland
"CH9300762011623852957", // Switzerland
"CR05015202001026284066", // Costa Rica
"CY17002001280000001200527600", // Cyprus
"CZ6508000000192000145399", // Czechoslovakia
"DE89370400440532013000", // Germany
"DJ2110002010010409943020008", // Djibouti
"DK5000400440116243", // Denmark
"DO28BAGR00000001212453611324", // Dominican Republic
"EE382200221020145685", // Estonia
"ES8023100001180000012345", // Spain
"FI2112345600000785", // Finland
"FO6264600001631634", // Denmark (Faroes)
"FR1420041010050500013M02606", // France
"GB29NWBK60161331926819", // UK
"GI75NWBK000000007099453", // Gibraltar
"GL8964710001000206", // Denmark (Greenland)
"GR1601101250000000012300695", // Greece
"GT82TRAJ01020000001210029690", // Guatemala
"HR1210010051863000160", // Croatia
"HU42117730161111101800000000", // Hungary
"IE29AIBK93115212345678", // Ireland
"IL620108000000099999999", // Israel
"IQ98NBIQ850123456789012", // Iraq
"IS140159260076545510730339", // Iceland
"IT60X0542811101000000123456", // Italy
"JO94CBJO0010000000000131000302",// Jordan
"KW81CBKU0000000000001234560101",// Kuwait
"KZ86125KZT5004100100", // Kazakhstan
"LB62099900000001001901229114", // Lebanon
"LC55HEMM000100010012001200023015",//Saint Lucia
"LI21088100002324013AA", // Liechtenstein (Principality of)
"LT121000011101001000", // Lithuania
"LU280019400644750000", // Luxembourg
"LV80BANK0000435195001", // Latvia
"MC5811222000010123456789030", // Monaco
"MD24AG000225100013104168", // Moldova
"ME25505000012345678951", // Montenegro
"MK07250120000058984", // Macedonia, Former Yugoslav Republic of
"MR1300020001010000123456753", // Mauritania
"MT84MALT011000012345MTLCAST001S",// Malta
"MU17BOMM0101101030300200000MUR",// Mauritius
"NL39RABO0300065264", // Netherlands
"NL91ABNA0417164300", // Netherlands
"NO9386011117947", // Norway
"PK36SCBL0000001123456702", // Pakistan
"PL27114020040000300201355387", // Poland
"PL60102010260000042270201111", // Poland
"PS92PALS000000000400123456702", // Palestine, State of
"PT50000201231234567890154", // Portugal
"QA58DOHB00001234567890ABCDEFG", // Qatar
"RO49AAAA1B31007593840000", // Romania
"RS35260005601001611379", // Serbia
"RU0204452560040702810412345678901",// Russia
"SA0380000000608010167519", // Saudi Arabia
"SC18SSCB11010000000000001497USD",// Seychelles
"SD8811123456789012", // Sudan
"SE3550000000054910000003", // Sweden
"SD2129010501234001", // Sudan
"SI56191000000123438", // Slovenia
"SK3112000000198742637541", // Slovak Republic
"SM86U0322509800000000270100", // San Marino
"ST68000100010051845310112", // Sao Tome and Principe
"SV62CENR00000000000000700025", // El Salvador
"TL380080012345678910157", // Timor-Leste
"TN5910006035183598478831", // Tunisia
"TR330006100519786457841326", // Turkey
"UA213223130000026007233566001", // Ukraine
"VA59001123000012345678", // Vatican City State
"VG96VPVG0000012345678901", // Virgin Islands, British
"XK051212012345678906", // Republic of Kosovo
// Codes AA and ZZ will never be used as ISO countries nor in IBANs
// add some dummy calculated codes to test the limits
// Current minimum length is Norway = 15
// Current maximum length is Malta = 31
// N.B. These codes will fail online checkers which validate the IBAN format
//234567890123456789012345678901
"AA0200000000053",
"AA9700000000089",
"AA9800000000071",
"ZZ02ZZZZZZZZZZZZZZZZZZZZZZZZZ04",
"ZZ97ZZZZZZZZZZZZZZZZZZZZZZZZZ40",
"ZZ98ZZZZZZZZZZZZZZZZZZZZZZZZZ22",
};
/*
* sources
* https://intranet.birmingham.ac.uk/finance/documents/public/IBAN.pdf
* http://www.paymentscouncil.org.uk/resources_and_publications/ibans_in_europe/
*/
invalid = new String[] {
"510007+47061BE63",
"IE01AIBK93118702569045",
"AA0000000000089",
"AA9900000000053",
};
zeroSum = null;
missingMessage = "Invalid Code length=0";
}
/**
* Test zero sum
*/
@Override
public void testZeroSum() {
// ignore, don't run this test
// example code used to create dummy IBANs
// try {
// for(int i=0; i<97;i++) {
// String check = String.format("ZZ00ZZZZZZZZZZZZZZZZZZZZZZZZZ%02d", new Object[]{Integer.valueOf(i)});
// String chk = routine.calculate(check);
// if (chk.equals("97")||chk.equals("98")||chk.equals("02")) {
// System.out.println(check+ " "+chk);
// }
// }
// } catch (CheckDigitException e) {
// e.printStackTrace();
// }
}
/**
* Returns an array of codes with invalid check digits.
*
* @param codes Codes with valid check digits
* @return Codes with invalid check digits
*/
@Override
protected String[] createInvalidCodes(final String[] codes) {
final List<String> list = new ArrayList<>();
// create invalid check digit values
for (final String code2 : codes) {
final String code = removeCheckDigit(code2);
final String check = checkDigit(code2);
for (int j = 2; j <= 98; j++) { // check digits can be from 02-98 (00 and 01 are not possible)
final String curr = j > 9 ? "" + j : "0" + j;
if (!curr.equals(check)) {
list.add(code.substring(0, 2) + curr + code.substring(4));
}
}
}
return list.toArray(new String[0]);
}
/**
* Returns a code with the Check Digits (i.e. characters 3&4) set to "00".
*
* @param code The code
* @return The code with the zeroed check digits
*/
@Override
protected String removeCheckDigit(final String code) {
return code.substring(0, 2) + "00" + code.substring(4);
}
/**
* Returns the check digit (i.e. last character) for a code.
*
* @param code The code
* @return The check digit
*/
@Override
protected String checkDigit(final String code) {
if (code == null || code.length() <= checkDigitLth) {
return "";
}
return code.substring(2, 4);
}
public void testOther() throws Exception {
try (BufferedReader rdr = new BufferedReader(
new InputStreamReader(
this.getClass().getResourceAsStream("IBANtests.txt"),"ASCII"))) {
String line;
while((line=rdr.readLine()) != null) {
if (!line.startsWith("#") && !line.isEmpty()) {
if (line.startsWith("-")) {
line = line.substring(1);
Assert.assertFalse(line, routine.isValid(line.replace(" ", "")));
} else {
Assert.assertTrue(line, routine.isValid(line.replace(" ", "")));
}
}
}
}
}
}
| 7,940 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/checkdigit/ISINCheckDigitTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines.checkdigit;
/**
* ISIN Check Digit Test.
*
* @since 1.4
*/
public class ISINCheckDigitTest extends AbstractCheckDigitTest {
/**
* Constructor
* @param name test name
*/
public ISINCheckDigitTest(final String name) {
super(name);
}
/**
* Sets up routine & valid codes.
*/
@Override
protected void setUp() {
routine = ISINCheckDigit.ISIN_CHECK_DIGIT;
valid = new String[] {"US0378331005",
"BMG8571G1096",
"AU0000XVGZA3",
"GB0002634946",
"FR0004026250",
"3133EHHF3", // see VALIDATOR-422 Valid check-digit, but not valid ISIN
"DK0009763344",
"dk0009763344", // TODO lowercase is currently accepted, but is this valid?
"AU0000xvgza3", // lowercase NSIN
"EZ0000000003", // Invented; for use in ISINValidatorTest
"XS0000000009", // ditto
"AA0000000006", // ditto
};
invalid = new String[] {"0378#3100"};
}
private static final String[] INVALID_CHECK_DIGITS =
{"US037833100O", // proper check digit is '5', see above
"BMG8571G109D", // proper check digit is '6', see above
"AU0000XVGZAD", // proper check digit is '3', see above
"GB000263494I", // proper check digit is '6', see above
"FR000402625C", // proper check digit is '0', see above
"DK000976334H", // proper check digit is '4', see above
};
public void testVALIDATOR_345() {
for (final String invalidCheckDigit : INVALID_CHECK_DIGITS) {
assertFalse("Should fail: " + invalidCheckDigit, routine.isValid(invalidCheckDigit));
}
}
}
| 7,941 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/checkdigit/ModulusTenEAN13CheckDigitTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines.checkdigit;
/**
* ModulusTenCheckDigit EAN-13 Test.
*/
public class ModulusTenEAN13CheckDigitTest extends AbstractCheckDigitTest {
/**
* Constructor
* @param name test name
*/
public ModulusTenEAN13CheckDigitTest(final String name) {
super(name);
}
/**
* Sets up routine & valid codes.
*/
@Override
protected void setUp() {
routine = new ModulusTenCheckDigit(new int[] { 1, 3 }, true);
valid = new String[] {
"9780072129519",
"9780764558313",
"4025515373438",
"0095673400332"};
}
}
| 7,942 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/checkdigit/EAN13CheckDigitTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines.checkdigit;
/**
* EAN-13 Check Digit Test.
*
* @since 1.4
*/
public class EAN13CheckDigitTest extends AbstractCheckDigitTest {
/**
* Constructor
* @param name test name
*/
public EAN13CheckDigitTest(final String name) {
super(name);
}
/**
* Sets up routine & valid codes.
*/
@Override
protected void setUp() {
routine = EAN13CheckDigit.EAN13_CHECK_DIGIT;
valid = new String[] {
"9780072129519",
"9780764558313",
"4025515373438",
"0095673400332"};
}
}
| 7,943 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/checkdigit/LuhnCheckDigitTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines.checkdigit;
/**
* Luhn Check Digit Test.
*
* @since 1.4
*/
public class LuhnCheckDigitTest extends AbstractCheckDigitTest {
private static final String VALID_VISA = "4417123456789113";
private static final String VALID_SHORT_VISA = "4222222222222";
private static final String VALID_AMEX = "378282246310005";
private static final String VALID_MASTERCARD = "5105105105105100";
private static final String VALID_DISCOVER = "6011000990139424";
private static final String VALID_DINERS = "30569309025904";
/**
* Constructor
* @param name test name
*/
public LuhnCheckDigitTest(final String name) {
super(name);
}
/**
* Sets up routine & valid codes.
*/
@Override
protected void setUp() {
routine = LuhnCheckDigit.LUHN_CHECK_DIGIT;
valid = new String[] {
VALID_VISA,
VALID_SHORT_VISA,
VALID_AMEX,
VALID_MASTERCARD,
VALID_DISCOVER,
VALID_DINERS};
}
}
| 7,944 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/checkdigit/ABANumberCheckDigitTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines.checkdigit;
/**
* ABA Number Check Digit Test.
*
* @since 1.4
*/
public class ABANumberCheckDigitTest extends AbstractCheckDigitTest {
/**
* Constructor
* @param name test name
*/
public ABANumberCheckDigitTest(final String name) {
super(name);
}
/**
* Sets up routine & valid codes.
*/
@Override
protected void setUp() {
routine = ABANumberCheckDigit.ABAN_CHECK_DIGIT;
valid = new String[] {
"123456780",
"123123123",
"011000015",
"111000038",
"231381116",
"121181976"
};
}
}
| 7,945 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/checkdigit/CUSIPCheckDigitTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines.checkdigit;
/**
* CUSIP Check Digit Test.
*
* @since 1.4
*/
public class CUSIPCheckDigitTest extends AbstractCheckDigitTest {
/**
* Constructs a new test.
* @param name test name
*/
public CUSIPCheckDigitTest(final String name) {
super(name);
}
/**
* Sets up routine & valid codes.
*/
@Override
protected void setUp() {
routine = CUSIPCheckDigit.CUSIP_CHECK_DIGIT;
valid = new String[] {"037833100",
"931142103",
"837649128",
"392690QT3",
"594918104",
"86770G101",
"Y8295N109",
"G8572F100"
};
invalid = new String[] {"0378#3100"};
}
private static final String[] INVALID_CHECK_DIGITS = {"DUS0421CW",
"DUS0421CN",
"DUS0421CE"
};
public void testVALIDATOR_336_InvalidCheckDigits() {
for (final String invalidCheckDigit : INVALID_CHECK_DIGITS) {
assertFalse("Should fail: " + invalidCheckDigit, routine.isValid(invalidCheckDigit));
}
}
private static final String[] VALID_CHECK_DIGITS = {"DUS0421C5"};
public void testVALIDATOR_336_ValidCheckDigits() {
for (final String validCheckDigit : VALID_CHECK_DIGITS) {
assertTrue("Should fail: " + validCheckDigit, routine.isValid(validCheckDigit));
}
}
}
| 7,946 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/checkdigit/ModulusTenCUSIPCheckDigitTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines.checkdigit;
/**
* ModulusTenCheckDigit CUSIP Test.
*/
public class ModulusTenCUSIPCheckDigitTest extends AbstractCheckDigitTest {
/**
* Constructs a new test.
* @param name test name
*/
public ModulusTenCUSIPCheckDigitTest(final String name) {
super(name);
}
/**
* Sets up routine & valid codes.
*/
@Override
protected void setUp() {
routine = new ModulusTenCheckDigit(new int[] { 1, 2}, true, true);
valid = new String[] {"037833100",
"931142103",
"837649128",
"392690QT3",
"594918104",
"86770G101",
"Y8295N109",
"G8572F100"
};
invalid = new String[] {"0378#3100"};
}
private static final String[] INVALID_CHECK_DIGITS = {"DUS0421CW",
"DUS0421CN",
"DUS0421CE"
};
public void testVALIDATOR_336_InvalidCheckDigits() {
for (final String invalidCheckDigit : INVALID_CHECK_DIGITS) {
assertFalse("Should fail: " + invalidCheckDigit, routine.isValid(invalidCheckDigit));
}
}
private static final String[] VALID_CHECK_DIGITS = {"DUS0421C5"};
public void testVALIDATOR_336_ValidCheckDigits() {
for (final String validCheckDigit : VALID_CHECK_DIGITS) {
assertTrue("Should fail: " + validCheckDigit, routine.isValid(validCheckDigit));
}
}
}
| 7,947 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/checkdigit/ModulusTenLuhnCheckDigitTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines.checkdigit;
/**
* ModulusTenCheckDigit Luhn Test.
*/
public class ModulusTenLuhnCheckDigitTest extends AbstractCheckDigitTest {
private static final String VALID_VISA = "4417123456789113";
private static final String VALID_SHORT_VISA = "4222222222222";
private static final String VALID_AMEX = "378282246310005";
private static final String VALID_MASTERCARD = "5105105105105100";
private static final String VALID_DISCOVER = "6011000990139424";
private static final String VALID_DINERS = "30569309025904";
/**
* Constructor
* @param name test name
*/
public ModulusTenLuhnCheckDigitTest(final String name) {
super(name);
}
/**
* Sets up routine & valid codes.
*/
@Override
protected void setUp() {
routine = new ModulusTenCheckDigit(new int[] {1, 2}, true, true);
valid = new String[] {
VALID_VISA,
VALID_SHORT_VISA,
VALID_AMEX,
VALID_MASTERCARD,
VALID_DISCOVER,
VALID_DINERS};
}
}
| 7,948 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/checkdigit/VerhoeffCheckDigitTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines.checkdigit;
/**
* Verhoeff Check Digit Test.
*
* @since 1.4
*/
public class VerhoeffCheckDigitTest extends AbstractCheckDigitTest {
/**
* Constructs a new test.
* @param name test name
*/
public VerhoeffCheckDigitTest(final String name) {
super(name);
}
/**
* Sets up routine & valid codes.
*/
@Override
protected void setUp() {
routine = VerhoeffCheckDigit.VERHOEFF_CHECK_DIGIT;
valid = new String[] {
"15",
"1428570",
"12345678902"
};
}
/**
* Test zero sum
*/
@Override
public void testZeroSum() {
// ignore, don't run this test
}
}
| 7,949 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/checkdigit/AbstractCheckDigitTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines.checkdigit;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import junit.framework.TestCase;
/**
* Luhn Check Digit Test.
*
* @since 1.4
*/
public abstract class AbstractCheckDigitTest extends TestCase {
/** logging instance */
protected Log log = LogFactory.getLog(getClass());
/** Check digit routine being tested */
protected int checkDigitLth = 1;
/** Check digit routine being tested */
protected CheckDigit routine;
/**
* Array of valid code values
* These must contain valid strings *including* the check digit.
*
* They are passed to:
* CheckDigit.isValid(expects string including checkdigit)
* which is expected to return true
* and
* AbstractCheckDigitTest.createInvalidCodes() which
* mangles the last character to check that the result is now invalid.
* and
* the truncated string is passed to
* CheckDigit.calculate(expects string without checkdigit)
* the result is compared with the last character
*/
protected String[] valid;
/**
* Array of invalid code values
*
* These are currently passed to both
* CheckDigit.calculate(expects a string without checkdigit)
* which is expected to throw an exception
* However that only applies if the string is syntactically incorrect;
* and
* CheckDigit.isValid(expects a string including checkdigit)
* which is expected to return false
*
* See https://issues.apache.org/jira/browse/VALIDATOR-344 for some dicussion on this
*/
protected String[] invalid = {"12345678A"};
/** code value which sums to zero */
protected String zeroSum = "0000000000";
/** Prefix for error messages */
protected String missingMessage = "Code is missing";
/**
* Constructor
* @param name test name
*/
public AbstractCheckDigitTest(final String name) {
super(name);
}
/**
* Tear Down - clears routine and valid codes.
*/
@Override
protected void tearDown() {
valid = null;
routine = null;
}
/**
* Test isValid() for valid values.
*/
public void testIsValidTrue() {
if (log.isDebugEnabled()) {
log.debug("testIsValidTrue() for " + routine.getClass().getName());
}
// test valid values
for (int i = 0; i < valid.length; i++) {
if (log.isDebugEnabled()) {
log.debug(" " + i + " Testing Valid Code=[" + valid[i] + "]");
}
assertTrue("valid[" + i +"]: " + valid[i], routine.isValid(valid[i]));
}
}
/**
* Test isValid() for invalid values.
*/
public void testIsValidFalse() {
if (log.isDebugEnabled()) {
log.debug("testIsValidFalse() for " + routine.getClass().getName());
}
// test invalid code values
for (int i = 0; i < invalid.length; i++) {
if (log.isDebugEnabled()) {
log.debug(" " + i + " Testing Invalid Code=[" + invalid[i] + "]");
}
assertFalse("invalid[" + i +"]: " + invalid[i], routine.isValid(invalid[i]));
}
// test invalid check digit values
final String[] invalidCheckDigits = createInvalidCodes(valid);
for (int i = 0; i < invalidCheckDigits.length; i++) {
if (log.isDebugEnabled()) {
log.debug(" " + i + " Testing Invalid Check Digit, Code=[" + invalidCheckDigits[i] + "]");
}
assertFalse("invalid check digit[" + i +"]: " + invalidCheckDigits[i], routine.isValid(invalidCheckDigits[i]));
}
}
/**
* Test calculate() for valid values.
*/
public void testCalculateValid() {
if (log.isDebugEnabled()) {
log.debug("testCalculateValid() for " + routine.getClass().getName());
}
// test valid values
for (int i = 0; i < valid.length; i++) {
final String code = removeCheckDigit(valid[i]);
final String expected = checkDigit(valid[i]);
try {
if (log.isDebugEnabled()) {
log.debug(" " + i + " Testing Valid Check Digit, Code=[" + code + "] expected=[" + expected + "]");
}
assertEquals("valid[" + i +"]: " + valid[i], expected, routine.calculate(code));
} catch (final Exception e) {
fail("valid[" + i +"]=" + valid[i] + " threw " + e);
}
}
}
/**
* Test calculate() for invalid values.
*/
public void testCalculateInvalid() {
if (log.isDebugEnabled()) {
log.debug("testCalculateInvalid() for " + routine.getClass().getName());
}
// test invalid code values
for (int i = 0; i < invalid.length; i++) {
try {
final String code = invalid[i];
if (log.isDebugEnabled()) {
log.debug(" " + i + " Testing Invalid Check Digit, Code=[" + code + "]");
}
final String expected = checkDigit(code);
final String actual = routine.calculate(removeCheckDigit(code));
// If exception not thrown, check that the digit is incorrect instead
if (expected.equals(actual)) {
fail("Expected mismatch for " + code + " expected " + expected + " actual " + actual);
}
} catch (final CheckDigitException e) {
// possible failure messages:
// Invalid ISBN Length ...
// Invalid Character[ ...
// Are there any others?
assertTrue("Invalid Character[" +i +"]=" + e.getMessage(), e.getMessage().startsWith("Invalid "));
// WAS assertTrue("Invalid Character[" +i +"]=" + e.getMessage(), e.getMessage().startsWith("Invalid Character["));
}
}
}
/**
* Test missing code
*/
public void testMissingCode() {
// isValid() null
assertFalse("isValid() Null", routine.isValid(null));
// isValid() zero length
assertFalse("isValid() Zero Length", routine.isValid(""));
// isValid() length 1
// Don't use 0, because that passes for Verhoef (not sure why yet)
assertFalse("isValid() Length 1", routine.isValid("9"));
// calculate() null
try {
routine.calculate(null);
fail("calculate() Null - expected exception");
} catch (final Exception e) {
assertEquals("calculate() Null", missingMessage, e.getMessage());
}
// calculate() zero length
try {
routine.calculate("");
fail("calculate() Zero Length - expected exception");
} catch (final Exception e) {
assertEquals("calculate() Zero Length", missingMessage, e.getMessage());
}
}
/**
* Test zero sum
*/
public void testZeroSum() {
assertFalse("isValid() Zero Sum", routine.isValid(zeroSum));
try {
routine.calculate(zeroSum);
fail("Zero Sum - expected exception");
} catch (final Exception e) {
assertEquals("isValid() Zero Sum", "Invalid code, sum is zero", e.getMessage());
}
}
/**
* Test check digit serialization.
*/
public void testSerialization() {
// Serialize the check digit routine
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
final ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(routine);
oos.flush();
oos.close();
} catch (final Exception e) {
fail(routine.getClass().getName() + " error during serialization: " + e);
}
// Deserialize the test object
Object result = null;
try {
final ByteArrayInputStream bais =
new ByteArrayInputStream(baos.toByteArray());
final ObjectInputStream ois = new ObjectInputStream(bais);
result = ois.readObject();
bais.close();
} catch (final Exception e) {
fail(routine.getClass().getName() + " error during deserialization: " + e);
}
assertNotNull(result);
}
private static final String POSSIBLE_CHECK_DIGITS = "0123456789 ABCDEFHIJKLMNOPQRSTUVWXYZ\tabcdefghijklmnopqrstuvwxyz!@£$%^&*()_+";
// private static final String POSSIBLE_CHECK_DIGITS = "0123456789";
/**
* Returns an array of codes with invalid check digits.
*
* @param codes Codes with valid check digits
* @return Codes with invalid check digits
*/
protected String[] createInvalidCodes(final String[] codes) {
final List<String> list = new ArrayList<>();
// create invalid check digit values
for (final String fullCode : codes) {
final String code = removeCheckDigit(fullCode);
final String check = checkDigit(fullCode);
for (int j = 0; j < POSSIBLE_CHECK_DIGITS.length(); j++) {
final String curr = POSSIBLE_CHECK_DIGITS.substring(j, j + 1);//"" + Character.forDigit(j, 10);
if (!curr.equals(check)) {
list.add(code + curr);
}
}
}
return list.toArray(new String[0]);
}
/**
* Returns a code with the Check Digit (i.e. last character) removed.
*
* @param code The code
* @return The code without the check digit
*/
protected String removeCheckDigit(final String code) {
if (code == null || code.length() <= checkDigitLth) {
return null;
}
return code.substring(0, code.length() - checkDigitLth);
}
/**
* Returns the check digit (i.e. last character) for a code.
*
* @param code The code
* @return The check digit
*/
protected String checkDigit(final String code) {
if (code == null || code.length() <= checkDigitLth) {
return "";
}
final int start = code.length() - checkDigitLth;
return code.substring(start);
}
}
| 7,950 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/routines/checkdigit/ModulusTenABACheckDigitTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines.checkdigit;
/**
* ModulusTenCheckDigit ABA Number Check Digit Test.
*/
public class ModulusTenABACheckDigitTest extends AbstractCheckDigitTest {
/**
* Constructor
* @param name test name
*/
public ModulusTenABACheckDigitTest(final String name) {
super(name);
}
/**
* Sets up routine & valid codes.
*/
@Override
protected void setUp() {
routine = new ModulusTenCheckDigit(new int[] { 1, 7, 3 }, true);
valid = new String[] {
"123456780",
"123123123",
"011000015",
"111000038",
"231381116",
"121181976"
};
}
}
| 7,951 |
0 | Create_ds/commons-validator/src/test/java/org/apache/commons/validator | Create_ds/commons-validator/src/test/java/org/apache/commons/validator/custom/CustomValidatorResources.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.custom;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.validator.ValidatorResources;
import org.xml.sax.SAXException;
/**
* Custom ValidatorResources implementation.
*/
public class CustomValidatorResources extends ValidatorResources {
private static final long serialVersionUID = 1272843199141974642L;
/**
* Create a custom ValidatorResources object from an uri
*
* @param in InputStream for the validation.xml configuration file.
* @throws SAXException if the validation XML files are not valid or well formed.
* @throws IOException if an I/O error occurs processing the XML files
*/
public CustomValidatorResources(final InputStream in) throws IOException, SAXException {
super(in);
}
} | 7,952 |
0 | Create_ds/commons-validator/src/example/org/apache/commons/validator | Create_ds/commons-validator/src/example/org/apache/commons/validator/example/ValidateExample.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.example;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Iterator;
import java.util.Locale;
import java.util.ResourceBundle;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.Form;
import org.apache.commons.validator.Validator;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.ValidatorException;
import org.apache.commons.validator.ValidatorResources;
import org.apache.commons.validator.ValidatorResult;
import org.apache.commons.validator.ValidatorResults;
import org.xml.sax.SAXException;
/**
* <p>A simple example of setting up and using the Validator.</p>
*
* This simple example shows all the steps needed to set up and use
* the Validator. Note that in most cases, some kind of framework
* would be wrapped around the Validator, such as is the case with
* the Struts Validator Framework. However, should you wish to use
* the Validator against raw Beans in a pure Java application, you
* can see everything you need to know to get it working here.
*/
public class ValidateExample {
/**
* We need a resource bundle to get our field names and errors messages
* from. Note that this is not strictly required to make the Validator
* work, but is a good coding practice.
*/
private static ResourceBundle apps =
ResourceBundle.getBundle(
"org.apache.commons.validator.example.applicationResources");
/**
* This is the main method that will be called to initialize the Validator, create some sample beans, and
* run the Validator against them.
*/
public static void main(String[] args)
throws ValidatorException, IOException, SAXException {
InputStream in = null;
ValidatorResources resources = null;
try {
// Create a new instance of a ValidatorResource, then get a stream
// handle on the XML file with the actions in it, and initialize the
// resources from it. This would normally be done by a servlet
// run during JSP initialization or some other application-startup
// routine.
in = ValidateExample.class.getResourceAsStream("validator-example.xml");
resources = new ValidatorResources(in);
} finally {
// Make sure we close the input stream.
if (in != null) {
in.close();
}
}
// Create a test bean to validate against.
ValidateBean bean = new ValidateBean();
// Create a validator with the ValidateBean actions for the bean
// we're interested in.
Validator validator = new Validator(resources, "ValidateBean");
// Tell the validator which bean to validate against.
validator.setParameter(Validator.BEAN_PARAM, bean);
ValidatorResults results = null;
// Run the validation actions against the bean. Since all of the properties
// are null, we expect them all to error out except for street2, which has
// no validations (it's an optional property)
results = validator.validate();
printResults(bean, results, resources);
// Now set all the required properties, but make the age a non-integer.
// You'll notice that age will pass the required test, but fail the int
// test.
bean.setLastName("Tester");
bean.setFirstName("John");
bean.setStreet1("1 Test Street");
bean.setCity("Testville");
bean.setState("TE");
bean.setPostalCode("12345");
bean.setAge("Too Old");
results = validator.validate();
printResults(bean, results, resources);
// Now only report failed fields
validator.setOnlyReturnErrors(true);
results = validator.validate();
printResults(bean, results, resources);
// Now everything should pass.
validator.setOnlyReturnErrors(false);
bean.setAge("123");
results = validator.validate();
printResults(bean, results, resources);
}
/**
* Dumps out the Bean in question and the results of validating it.
*/
public static void printResults(
ValidateBean bean,
ValidatorResults results,
ValidatorResources resources) {
boolean success = true;
// Start by getting the form for the current locale and Bean.
Form form = resources.getForm(Locale.getDefault(), "ValidateBean");
System.out.println("\n\nValidating:");
System.out.println(bean);
// Iterate over each of the properties of the Bean which had messages.
Iterator<String> propertyNames = results.getPropertyNames().iterator();
while (propertyNames.hasNext()) {
String propertyName = propertyNames.next();
// Get the Field associated with that property in the Form
Field field = form.getField(propertyName);
// Look up the formatted name of the field from the Field arg0
String prettyFieldName = apps.getString(field.getArg(0).getKey());
// Get the result of validating the property.
ValidatorResult result = results.getValidatorResult(propertyName);
// Get all the actions run against the property, and iterate over their names.
Iterator<String> keys = result.getActions();
while (keys.hasNext()) {
String actName = keys.next();
// Get the Action for that name.
ValidatorAction action = resources.getValidatorAction(actName);
// If the result is valid, print PASSED, otherwise print FAILED
System.out.println(
propertyName
+ "["
+ actName
+ "] ("
+ (result.isValid(actName) ? "PASSED" : "FAILED")
+ ")");
//If the result failed, format the Action's message against the formatted field name
if (!result.isValid(actName)) {
success = false;
String message = apps.getString(action.getMsg());
Object[] args = { prettyFieldName };
System.out.println(
" Error message will be: "
+ MessageFormat.format(message, args));
}
}
}
if (success) {
System.out.println("FORM VALIDATION PASSED");
} else {
System.out.println("FORM VALIDATION FAILED");
}
}
}
| 7,953 |
0 | Create_ds/commons-validator/src/example/org/apache/commons/validator | Create_ds/commons-validator/src/example/org/apache/commons/validator/example/ValidateBean.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.example;
/**
* A simple bean to use with the Validator Example.
*/
public class ValidateBean {
String lastName, firstName, street1, street2, city, state, postalCode, age;
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setStreet1(String street1) {
this.street1 = street1;
}
public void setStreet2(String street2) {
this.street2 = street2;
}
public void setCity(String city) {
this.city = city;
}
public void setState(String state) {
this.state = state;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public void setAge(String age) {
this.age = age;
}
public String getLastName() {
return this.lastName;
}
public String getFirstName() {
return this.firstName;
}
public String getStreet1() {
return this.street1;
}
public String getStreet2() {
return this.street2;
}
public String getCity() {
return this.city;
}
public String getState() {
return this.state;
}
public String getPostalCode() {
return this.postalCode;
}
public String getAge() {
return this.age;
}
public String toString() {
return "{lastname="
+ this.lastName
+ ", firstname="
+ this.firstName
+ ", street1="
+ this.street1
+ ",\n street2="
+ this.street2
+ ", "
+ "city="
+ this.city
+ ", state="
+ this.state
+ ",\n postalcode="
+ this.postalCode
+ ", age="
+ this.age
+ "}";
}
}
| 7,954 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/Arg.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import java.io.Serializable;
/**
* <p>
* A default argument or an argument for a
* specific validator definition (ex: required)
* can be stored to pass into a message as parameters. This can be used in a
* pluggable validator for constructing locale
* sensitive messages by using <code>java.text.MessageFormat</code>
* or an equivalent class. The resource field can be
* used to determine if the value stored in the argument
* is a value to be retrieved from a locale sensitive
* message retrieval system like <code>java.util.PropertyResourceBundle</code>.
* The resource field defaults to 'true'.
* </p>
* <p>Instances of this class are configured with an <arg> xml element.</p>
*/
//TODO mutable non-private fields
public class Arg implements Cloneable, Serializable {
private static final long serialVersionUID = -8922606779669839294L;
/**
* The resource bundle name that this Arg's <code>key</code> should be
* resolved in (optional).
* @since 1.1
*/
protected String bundle;
/**
* The key or value of the argument.
*/
protected String key;
/**
* The name dependency that this argument goes with (optional).
*/
protected String name;
/**
* This argument's position in the message. Set postion=0 to
* make a replacement in this string: "some msg {0}".
* @since 1.1
*/
protected int position = -1;
/**
* Whether or not the key is a message resource (optional). Defaults to
* true. If it is 'true', the value will try to be resolved as a message
* resource.
*/
protected boolean resource = true;
/**
* Creates and returns a copy of this object.
* @return A copy of this object.
*/
@Override
public Object clone() {
try {
return super.clone();
} catch (final CloneNotSupportedException e) {
throw new UnsupportedOperationException(e.toString(), e);
}
}
/**
* Returns the resource bundle name.
* @return the bundle name.
* @since 1.1
*/
public String getBundle() {
return this.bundle;
}
/**
* Gets the key/value.
* @return the key value.
*/
public String getKey() {
return this.key;
}
/**
* Gets the name of the dependency.
* @return the name of the dependency.
*/
public String getName() {
return this.name;
}
/**
* Argument's replacement position.
* @return This argument's replacement position.
*/
public int getPosition() {
return this.position;
}
/**
* Tests whether or not the key is a resource key or literal value.
* @return {@code true} if key is a resource key.
*/
public boolean isResource() {
return this.resource;
}
/**
* Sets the resource bundle name.
* @param bundle The new bundle name.
* @since 1.1
*/
public void setBundle(final String bundle) {
this.bundle = bundle;
}
/**
* Sets the key/value.
* @param key They to access the argument.
*/
public void setKey(final String key) {
this.key = key;
}
/**
* Sets the name of the dependency.
* @param name the name of the dependency.
*/
public void setName(final String name) {
this.name = name;
}
/**
* Sets this argument's replacement position.
* @param position set this argument's replacement position.
*/
public void setPosition(final int position) {
this.position = position;
}
/**
* Sets whether or not the key is a resource.
* @param resource If true indicates the key is a resource.
*/
public void setResource(final boolean resource) {
this.resource = resource;
}
/**
* Returns a string representation of the object.
* @return a string representation of the object.
*/
@Override
public String toString() {
final StringBuilder results = new StringBuilder();
results.append("Arg: name=");
results.append(name);
results.append(" key=");
results.append(key);
results.append(" position=");
results.append(position);
results.append(" bundle=");
results.append(bundle);
results.append(" resource=");
results.append(resource);
results.append("\n");
return results.toString();
}
} | 7,955 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/FormSet.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Holds a set of <code>Form</code>s stored associated with a <code>Locale</code>
* based on the country, language, and variant specified. Instances of this
* class are configured with a <formset> xml element.
*/
public class FormSet implements Serializable {
private static final long serialVersionUID = -8936513232763306055L;
/** Logging */
private transient Log log = LogFactory.getLog(FormSet.class);
/**
* Whether or not the this <code>FormSet</code> was processed for replacing
* variables in strings with their values.
*/
private boolean processed;
/** Language component of <code>Locale</code> (required). */
private String language;
/** Country component of <code>Locale</code> (optional). */
private String country;
/** Variant component of <code>Locale</code> (optional). */
private String variant;
/**
* A <code>Map</code> of <code>Form</code>s using the name field of the
* <code>Form</code> as the key.
*/
private final Map<String, Form> forms = new HashMap<>();
/**
* A <code>Map</code> of <code>Constant</code>s using the name field of the
* <code>Constant</code> as the key.
*/
private final Map<String, String> constants = new HashMap<>();
/**
* This is the type of <code>FormSet</code>s where no locale is specified.
*/
protected final static int GLOBAL_FORMSET = 1;
/**
* This is the type of <code>FormSet</code>s where only language locale is
* specified.
*/
protected final static int LANGUAGE_FORMSET = 2;
/**
* This is the type of <code>FormSet</code>s where only language and country
* locale are specified.
*/
protected final static int COUNTRY_FORMSET = 3;
/**
* This is the type of <code>FormSet</code>s where full locale has been set.
*/
protected final static int VARIANT_FORMSET = 4;
/**
* Flag indicating if this formSet has been merged with its parent (higher
* rank in Locale hierarchy).
*/
private boolean merged;
/**
* Has this formSet been merged?
*
* @return true if it has been merged
* @since 1.2.0
*/
protected boolean isMerged() {
return merged;
}
/**
* Returns the type of <code>FormSet</code>:<code>GLOBAL_FORMSET</code>,
* <code>LANGUAGE_FORMSET</code>,<code>COUNTRY_FORMSET</code> or <code>VARIANT_FORMSET</code>
* .
*
* @return The type value
* @since 1.2.0
* @throws NullPointerException if there is inconsistency in the locale
* definition (not sure about this)
*/
protected int getType() {
if (getVariant() != null) {
if (getLanguage() == null || getCountry() == null) {
throw new NullPointerException(
"When variant is specified, country and language must be specified.");
}
return VARIANT_FORMSET;
}
if (getCountry() != null) {
if (getLanguage() == null) {
throw new NullPointerException(
"When country is specified, language must be specified.");
}
return COUNTRY_FORMSET;
}
if (getLanguage() != null) {
return LANGUAGE_FORMSET;
}
return GLOBAL_FORMSET;
}
/**
* Merges the given <code>FormSet</code> into this one. If any of <code>depends</code>
* s <code>Forms</code> are not in this <code>FormSet</code> then, include
* them, else merge both <code>Forms</code>. Theoretically we should only
* merge a "parent" formSet.
*
* @param depends FormSet to be merged
* @since 1.2.0
*/
protected void merge(final FormSet depends) {
if (depends != null) {
final Map<String, Form> pForms = getForms();
final Map<String, Form> dForms = depends.getForms();
for (final Entry<String, Form> entry : dForms.entrySet()) {
final String key = entry.getKey();
final Form pForm = pForms.get(key);
if (pForm != null) {//merge, but principal 'rules', don't overwrite
// anything
pForm.merge(entry.getValue());
}
else {//just add
addForm(entry.getValue());
}
}
}
merged = true;
}
/**
* Whether or not the this <code>FormSet</code> was processed for replacing
* variables in strings with their values.
*
* @return The processed value
*/
public boolean isProcessed() {
return processed;
}
/**
* Gets the equivalent of the language component of <code>Locale</code>.
*
* @return The language value
*/
public String getLanguage() {
return language;
}
/**
* Sets the equivalent of the language component of <code>Locale</code>.
*
* @param language The new language value
*/
public void setLanguage(final String language) {
this.language = language;
}
/**
* Gets the equivalent of the country component of <code>Locale</code>.
*
* @return The country value
*/
public String getCountry() {
return country;
}
/**
* Sets the equivalent of the country component of <code>Locale</code>.
*
* @param country The new country value
*/
public void setCountry(final String country) {
this.country = country;
}
/**
* Gets the equivalent of the variant component of <code>Locale</code>.
*
* @return The variant value
*/
public String getVariant() {
return variant;
}
/**
* Sets the equivalent of the variant component of <code>Locale</code>.
*
* @param variant The new variant value
*/
public void setVariant(final String variant) {
this.variant = variant;
}
/**
* Add a <code>Constant</code> to the locale level.
*
* @param name The constant name
* @param value The constant value
*/
public void addConstant(final String name, final String value) {
if (constants.containsKey(name)) {
getLog().error("Constant '" + name + "' already exists in FormSet["
+ this.displayKey() + "] - ignoring.");
} else {
constants.put(name, value);
}
}
/**
* Add a <code>Form</code> to the <code>FormSet</code>.
*
* @param f The form
*/
public void addForm(final Form f) {
final String formName = f.getName();
if (forms.containsKey(formName)) {
getLog().error("Form '" + formName + "' already exists in FormSet["
+ this.displayKey() + "] - ignoring.");
} else {
forms.put(f.getName(), f);
}
}
/**
* Retrieve a <code>Form</code> based on the form name.
*
* @param formName The form name
* @return The form
*/
public Form getForm(final String formName) {
return this.forms.get(formName);
}
/**
* A <code>Map</code> of <code>Form</code>s is returned as an unmodifiable
* <code>Map</code> with the key based on the form name.
*
* @return The forms map
*/
public Map<String, Form> getForms() {
return Collections.unmodifiableMap(forms);
}
/**
* Processes all of the <code>Form</code>s.
*
* @param globalConstants Global constants
*/
synchronized void process(final Map<String, String> globalConstants) {
for (final Form f : forms.values()) {
f.process(globalConstants, constants, forms);
}
processed = true;
}
/**
* Returns a string representation of the object's key.
*
* @return A string representation of the key
*/
public String displayKey() {
final StringBuilder results = new StringBuilder();
if (language != null && !language.isEmpty()) {
results.append("language=");
results.append(language);
}
if (country != null && !country.isEmpty()) {
if (results.length() > 0) {
results.append(", ");
}
results.append("country=");
results.append(country);
}
if (variant != null && !variant.isEmpty()) {
if (results.length() > 0) {
results.append(", ");
}
results.append("variant=");
results.append(variant );
}
if (results.length() == 0) {
results.append("default");
}
return results.toString();
}
/**
* Returns a string representation of the object.
*
* @return A string representation
*/
@Override
public String toString() {
final StringBuilder results = new StringBuilder();
results.append("FormSet: language=");
results.append(language);
results.append(" country=");
results.append(country);
results.append(" variant=");
results.append(variant);
results.append("\n");
for (final Object name : getForms().values()) {
results.append(" ");
results.append(name);
results.append("\n");
}
return results.toString();
}
/**
* Accessor method for Log instance.
*
* The Log instance variable is transient and
* accessing it through this method ensures it
* is re-initialized when this instance is
* de-serialized.
*
* @return The Log instance.
*/
private Log getLog() {
if (log == null) {
log = LogFactory.getLog(FormSet.class);
}
return log;
}
}
| 7,956 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/Form.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.FastHashMap;// DEPRECATED
/**
* <p>
* This contains a set of validation rules for a form/JavaBean. The information
* is contained in a list of <code>Field</code> objects. Instances of this class
* are configured with a <form> xml element.
* </p>
* <p>
* The use of FastHashMap is deprecated and will be replaced in a future
* release.
* </p>
*/
//TODO mutable non-private fields
public class Form implements Serializable {
private static final long serialVersionUID = 6445211789563796371L;
/** The name/key the set of validation rules is stored under. */
protected String name;
/**
* List of <code>Field</code>s. Used to maintain the order they were added
* in although individual <code>Field</code>s can be retrieved using <code>Map</code>
* of <code>Field</code>s.
*/
protected List<Field> lFields = new ArrayList<>();
/**
* Map of <code>Field</code>s keyed on their property value.
*
* @deprecated Subclasses should use getFieldMap() instead.
*/
@Deprecated
protected FastHashMap hFields = new FastHashMap(); // <String, Field>
/**
* The name/key of the form which this form extends from.
*
* @since 1.2.0
*/
protected String inherit;
/**
* Whether or not the this <code>Form</code> was processed for replacing
* variables in strings with their values.
*/
private boolean processed;
/**
* Gets the name/key of the set of validation rules.
*
* @return The name value
*/
public String getName() {
return name;
}
/**
* Sets the name/key of the set of validation rules.
*
* @param name The new name value
*/
public void setName(final String name) {
this.name = name;
}
/**
* Add a <code>Field</code> to the <code>Form</code>.
*
* @param f The field
*/
public void addField(final Field f) {
this.lFields.add(f);
getFieldMap().put(f.getKey(), f);
}
/**
* A <code>List</code> of <code>Field</code>s is returned as an unmodifiable
* <code>List</code>.
*
* @return The fields value
*/
public List<Field> getFields() {
return Collections.unmodifiableList(lFields);
}
/**
* Returns the Field with the given name or null if this Form has no such
* field.
*
* @param fieldName The field name
* @return The field value
* @since 1.1
*/
public Field getField(final String fieldName) {
return getFieldMap().get(fieldName);
}
/**
* Returns true if this Form contains a Field with the given name.
*
* @param fieldName The field name
* @return True if this form contains the field by the given name
* @since 1.1
*/
public boolean containsField(final String fieldName) {
return getFieldMap().containsKey(fieldName);
}
/**
* Merges the given form into this one. For any field in <code>depends</code>
* not present in this form, include it. <code>depends</code> has precedence
* in the way the fields are ordered.
*
* @param depends the form we want to merge
* @since 1.2.0
*/
protected void merge(final Form depends) {
final List<Field> templFields = new ArrayList<>();
@SuppressWarnings("unchecked") // FastHashMap is not generic
final
Map<String, Field> temphFields = new FastHashMap();
for (final Field defaultField : depends.getFields()) {
if (defaultField != null) {
final String fieldKey = defaultField.getKey();
if (!this.containsField(fieldKey)) {
templFields.add(defaultField);
temphFields.put(fieldKey, defaultField);
}
else {
final Field old = getField(fieldKey);
getFieldMap().remove(fieldKey);
lFields.remove(old);
templFields.add(old);
temphFields.put(fieldKey, old);
}
}
}
lFields.addAll(0, templFields);
getFieldMap().putAll(temphFields);
}
/**
* Processes all of the <code>Form</code>'s <code>Field</code>s.
*
* @param globalConstants A map of global constants
* @param constants Local constants
* @param forms Map of forms
* @since 1.2.0
*/
protected void process(final Map<String, String> globalConstants, final Map<String, String> constants, final Map<String, Form> forms) {
if (isProcessed()) {
return;
}
int n = 0;//we want the fields from its parent first
if (isExtending()) {
final Form parent = forms.get(inherit);
if (parent != null) {
if (!parent.isProcessed()) {
//we want to go all the way up the tree
parent.process(constants, globalConstants, forms);
}
for (final Field f : parent.getFields()) {
//we want to be able to override any fields we like
if (getFieldMap().get(f.getKey()) == null) {
lFields.add(n, f);
getFieldMap().put(f.getKey(), f);
n++;
}
}
}
}
hFields.setFast(true);
//no need to reprocess parent's fields, we iterate from 'n'
for (final Iterator<Field> i = lFields.listIterator(n); i.hasNext(); ) {
final Field f = i.next();
f.process(globalConstants, constants);
}
processed = true;
}
/**
* Returns a string representation of the object.
*
* @return string representation
*/
@Override
public String toString() {
final StringBuilder results = new StringBuilder();
results.append("Form: ");
results.append(name);
results.append("\n");
for (final Field lField : lFields) {
results.append("\tField: \n");
results.append(lField);
results.append("\n");
}
return results.toString();
}
/**
* Validate all Fields in this Form on the given page and below.
*
* @param params A Map of parameter class names to parameter
* values to pass into validation methods.
* @param actions A Map of validator names to ValidatorAction
* objects.
* @param page Fields on pages higher than this will not be
* validated.
* @return A ValidatorResults object containing all
* validation messages.
* @throws ValidatorException
*/
ValidatorResults validate(final Map<String, Object> params, final Map<String, ValidatorAction> actions, final int page)
throws ValidatorException {
return validate(params, actions, page, null);
}
/**
* Validate all Fields in this Form on the given page and below.
*
* @param params A Map of parameter class names to parameter
* values to pass into validation methods.
* @param actions A Map of validator names to ValidatorAction
* objects.
* @param page Fields on pages higher than this will not be
* validated.
* @return A ValidatorResults object containing all
* validation messages.
* @throws ValidatorException
* @since 1.2.0
*/
ValidatorResults validate(final Map<String, Object> params, final Map<String, ValidatorAction> actions, final int page, final String fieldName)
throws ValidatorException {
final ValidatorResults results = new ValidatorResults();
params.put(Validator.VALIDATOR_RESULTS_PARAM, results);
// Only validate a single field if specified
if (fieldName != null) {
final Field field = getFieldMap().get(fieldName);
if (field == null) {
throw new ValidatorException("Unknown field "+fieldName+" in form "+getName());
}
params.put(Validator.FIELD_PARAM, field);
if (field.getPage() <= page) {
results.merge(field.validate(params, actions));
}
} else {
for (final Field field : this.lFields) {
params.put(Validator.FIELD_PARAM, field);
if (field.getPage() <= page) {
results.merge(field.validate(params, actions));
}
}
}
return results;
}
/**
* Whether or not the this <code>Form</code> was processed for replacing
* variables in strings with their values.
*
* @return The processed value
* @since 1.2.0
*/
public boolean isProcessed() {
return processed;
}
/**
* Gets the name/key of the parent set of validation rules.
*
* @return The extends value
* @since 1.2.0
*/
public String getExtends() {
return inherit;
}
/**
* Sets the name/key of the parent set of validation rules.
*
* @param inherit The new extends value
* @since 1.2.0
*/
public void setExtends(final String inherit) {
this.inherit = inherit;
}
/**
* Gets extends flag.
*
* @return The extending value
* @since 1.2.0
*/
public boolean isExtending() {
return inherit != null;
}
/**
* Returns a Map of String field keys to Field objects.
*
* @return The fieldMap value
* @since 1.2.0
*/
@SuppressWarnings("unchecked") // FastHashMap is not generic
protected Map<String, Field> getFieldMap() {
return hFields;
}
}
| 7,957 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/ValidatorResources.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.collections.FastHashMap; // DEPRECATED
import org.apache.commons.digester.Digester;
import org.apache.commons.digester.Rule;
import org.apache.commons.digester.xmlrules.DigesterLoader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
/**
* <p>
* General purpose class for storing <code>FormSet</code> objects based
* on their associated <code>Locale</code>. Instances of this class are usually
* configured through a validation.xml file that is parsed in a constructor.
* </p>
*
* <p><strong>Note</strong> - Classes that extend this class
* must be Serializable so that instances may be used in distributable
* application server environments.</p>
*
* <p>
* The use of FastHashMap is deprecated and will be replaced in a future
* release.
* </p>
*/
//TODO mutable non-private fields
public class ValidatorResources implements Serializable {
private static final long serialVersionUID = -8203745881446239554L;
/** Name of the digester validator rules file */
private static final String VALIDATOR_RULES = "digester-rules.xml";
/**
* The set of public identifiers, and corresponding resource names, for
* the versions of the configuration file DTDs that we know about. There
* <strong>MUST</strong> be an even number of Strings in this list!
*/
private static final String[] REGISTRATIONS = {
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0//EN",
"/org/apache/commons/validator/resources/validator_1_0.dtd",
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0.1//EN",
"/org/apache/commons/validator/resources/validator_1_0_1.dtd",
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1//EN",
"/org/apache/commons/validator/resources/validator_1_1.dtd",
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN",
"/org/apache/commons/validator/resources/validator_1_1_3.dtd",
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.2.0//EN",
"/org/apache/commons/validator/resources/validator_1_2_0.dtd",
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.3.0//EN",
"/org/apache/commons/validator/resources/validator_1_3_0.dtd",
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.4.0//EN",
"/org/apache/commons/validator/resources/validator_1_4_0.dtd"
};
private transient Log log = LogFactory.getLog(ValidatorResources.class);
/**
* <code>Map</code> of <code>FormSet</code>s stored under
* a <code>Locale</code> key (expressed as a String).
* @deprecated Subclasses should use getFormSets() instead.
*/
@Deprecated
protected FastHashMap hFormSets = new FastHashMap(); // <String, FormSet>
/**
* <code>Map</code> of global constant values with
* the name of the constant as the key.
* @deprecated Subclasses should use getConstants() instead.
*/
@Deprecated
protected FastHashMap hConstants = new FastHashMap(); // <String, String>
/**
* <code>Map</code> of <code>ValidatorAction</code>s with
* the name of the <code>ValidatorAction</code> as the key.
* @deprecated Subclasses should use getActions() instead.
*/
@Deprecated
protected FastHashMap hActions = new FastHashMap(); // <String, ValidatorAction>
/**
* The default locale on our server.
*/
protected static Locale defaultLocale = Locale.getDefault();
/**
* Create an empty ValidatorResources object.
*/
public ValidatorResources() {
}
/**
* This is the default <code>FormSet</code> (without locale). (We probably don't need
* the defaultLocale anymore.)
*/
protected FormSet defaultFormSet;
/**
* Create a ValidatorResources object from an InputStream.
*
* @param in InputStream to a validation.xml configuration file. It's the client's
* responsibility to close this stream.
* @throws SAXException if the validation XML files are not valid or well
* formed.
* @throws IOException if an I/O error occurs processing the XML files
* @since 1.1
*/
public ValidatorResources(final InputStream in) throws IOException, SAXException {
this(new InputStream[]{in});
}
/**
* Create a ValidatorResources object from an InputStream.
*
* @param streams An array of InputStreams to several validation.xml
* configuration files that will be read in order and merged into this object.
* It's the client's responsibility to close these streams.
* @throws SAXException if the validation XML files are not valid or well
* formed.
* @throws IOException if an I/O error occurs processing the XML files
* @since 1.1
*/
public ValidatorResources(final InputStream[] streams)
throws IOException, SAXException {
final Digester digester = initDigester();
for (int i = 0; i < streams.length; i++) {
if (streams[i] == null) {
throw new IllegalArgumentException("Stream[" + i + "] is null");
}
digester.push(this);
digester.parse(streams[i]);
}
this.process();
}
/**
* Create a ValidatorResources object from an uri
*
* @param uri The location of a validation.xml configuration file.
* @throws SAXException if the validation XML files are not valid or well
* formed.
* @throws IOException if an I/O error occurs processing the XML files
* @since 1.2
*/
public ValidatorResources(final String uri) throws IOException, SAXException {
this(new String[] { uri });
}
/**
* Create a ValidatorResources object from several uris
*
* @param uris An array of uris to several validation.xml
* configuration files that will be read in order and merged into this object.
* @throws SAXException if the validation XML files are not valid or well
* formed.
* @throws IOException if an I/O error occurs processing the XML files
* @since 1.2
*/
public ValidatorResources(final String... uris)
throws IOException, SAXException {
final Digester digester = initDigester();
for (final String element : uris) {
digester.push(this);
digester.parse(element);
}
this.process();
}
/**
* Create a ValidatorResources object from a URL.
*
* @param url The URL for the validation.xml
* configuration file that will be read into this object.
* @throws SAXException if the validation XML file are not valid or well
* formed.
* @throws IOException if an I/O error occurs processing the XML files
* @since 1.3.1
*/
public ValidatorResources(final URL url)
throws IOException, SAXException {
this(new URL[]{url});
}
/**
* Create a ValidatorResources object from several URL.
*
* @param urls An array of URL to several validation.xml
* configuration files that will be read in order and merged into this object.
* @throws SAXException if the validation XML files are not valid or well
* formed.
* @throws IOException if an I/O error occurs processing the XML files
* @since 1.3.1
*/
public ValidatorResources(final URL[] urls)
throws IOException, SAXException {
final Digester digester = initDigester();
for (final URL url : urls) {
digester.push(this);
digester.parse(url);
}
this.process();
}
/**
* Initialize the digester.
*/
private Digester initDigester() {
URL rulesUrl = this.getClass().getResource(VALIDATOR_RULES);
if (rulesUrl == null) {
// Fix for Issue# VALIDATOR-195
rulesUrl = ValidatorResources.class.getResource(VALIDATOR_RULES);
}
if (getLog().isDebugEnabled()) {
getLog().debug("Loading rules from '" + rulesUrl + "'");
}
final Digester digester = DigesterLoader.createDigester(rulesUrl);
digester.setNamespaceAware(true);
digester.setValidating(true);
digester.setUseContextClassLoader(true);
// Add rules for arg0-arg3 elements
addOldArgRules(digester);
// register DTDs
for (int i = 0; i < REGISTRATIONS.length; i += 2) {
final URL url = this.getClass().getResource(REGISTRATIONS[i + 1]);
if (url != null) {
digester.register(REGISTRATIONS[i], url.toString());
}
}
return digester;
}
private static final String ARGS_PATTERN
= "form-validation/formset/form/field/arg";
/**
* Create a <code>Rule</code> to handle <code>arg0-arg3</code>
* elements. This will allow validation.xml files that use the
* versions of the DTD prior to Validator 1.2.0 to continue
* working.
*/
private void addOldArgRules(final Digester digester) {
// Create a new rule to process args elements
final Rule rule = new Rule() {
@Override
public void begin(final String namespace, final String name, final Attributes attributes) {
// Create the Arg
final Arg arg = new Arg();
arg.setKey(attributes.getValue("key"));
arg.setName(attributes.getValue("name"));
if ("false".equalsIgnoreCase(attributes.getValue("resource"))) {
arg.setResource(false);
}
try {
final int length = "arg".length(); // skip the arg prefix
arg.setPosition(Integer.parseInt(name.substring(length)));
} catch (final Exception ex) {
getLog().error("Error parsing Arg position: " + name + " " + arg + " " + ex);
}
// Add the arg to the parent field
((Field) getDigester().peek(0)).addArg(arg);
}
};
// Add the rule for each of the arg elements
digester.addRule(ARGS_PATTERN + "0", rule);
digester.addRule(ARGS_PATTERN + "1", rule);
digester.addRule(ARGS_PATTERN + "2", rule);
digester.addRule(ARGS_PATTERN + "3", rule);
}
/**
* Add a <code>FormSet</code> to this <code>ValidatorResources</code>
* object. It will be associated with the <code>Locale</code> of the
* <code>FormSet</code>.
* @param fs The form set to add.
* @since 1.1
*/
public void addFormSet(final FormSet fs) {
final String key = this.buildKey(fs);
if (key.isEmpty()) {// there can only be one default formset
if (getLog().isWarnEnabled() && defaultFormSet != null) {
// warn the user he might not get the expected results
getLog().warn("Overriding default FormSet definition.");
}
defaultFormSet = fs;
} else {
final FormSet formset = getFormSets().get(key);
if (formset == null) {// it hasn't been included yet
if (getLog().isDebugEnabled()) {
getLog().debug("Adding FormSet '" + fs + "'.");
}
} else if (getLog().isWarnEnabled()) {// warn the user he might not
// get the expected results
getLog()
.warn("Overriding FormSet definition. Duplicate for locale: "
+ key);
}
getFormSets().put(key, fs);
}
}
/**
* Add a global constant to the resource.
* @param name The constant name.
* @param value The constant value.
*/
public void addConstant(final String name, final String value) {
if (getLog().isDebugEnabled()) {
getLog().debug("Adding Global Constant: " + name + "," + value);
}
this.hConstants.put(name, value);
}
/**
* Add a <code>ValidatorAction</code> to the resource. It also creates an
* instance of the class based on the <code>ValidatorAction</code>s
* class name and retrieves the <code>Method</code> instance and sets them
* in the <code>ValidatorAction</code>.
* @param va The validator action.
*/
public void addValidatorAction(final ValidatorAction va) {
va.init();
getActions().put(va.getName(), va);
if (getLog().isDebugEnabled()) {
getLog().debug("Add ValidatorAction: " + va.getName() + "," + va.getClassname());
}
}
/**
* Gets a <code>ValidatorAction</code> based on it's name.
* @param key The validator action key.
* @return The validator action.
*/
public ValidatorAction getValidatorAction(final String key) {
return getActions().get(key);
}
/**
* Gets an unmodifiable <code>Map</code> of the <code>ValidatorAction</code>s.
* @return Map of validator actions.
*/
public Map<String, ValidatorAction> getValidatorActions() {
return Collections.unmodifiableMap(getActions());
}
/**
* Builds a key to store the <code>FormSet</code> under based on it's
* language, country, and variant values.
* @param fs The Form Set.
* @return generated key for a formset.
*/
protected String buildKey(final FormSet fs) {
return
this.buildLocale(fs.getLanguage(), fs.getCountry(), fs.getVariant());
}
/**
* Assembles a Locale code from the given parts.
*/
private String buildLocale(final String lang, final String country, final String variant) {
String key = lang != null && !lang.isEmpty() ? lang : "";
key += country != null && !country.isEmpty() ? "_" + country : "";
key += variant != null && !variant.isEmpty() ? "_" + variant : "";
return key;
}
/**
* <p>Gets a <code>Form</code> based on the name of the form and the
* <code>Locale</code> that most closely matches the <code>Locale</code>
* passed in. The order of <code>Locale</code> matching is:</p>
* <ol>
* <li>language + country + variant</li>
* <li>language + country</li>
* <li>language</li>
* <li>default locale</li>
* </ol>
* @param locale The Locale.
* @param formKey The key for the Form.
* @return The validator Form.
* @since 1.1
*/
public Form getForm(final Locale locale, final String formKey) {
return this.getForm(locale.getLanguage(), locale.getCountry(), locale
.getVariant(), formKey);
}
/**
* <p>Gets a <code>Form</code> based on the name of the form and the
* <code>Locale</code> that most closely matches the <code>Locale</code>
* passed in. The order of <code>Locale</code> matching is:</p>
* <ol>
* <li>language + country + variant</li>
* <li>language + country</li>
* <li>language</li>
* <li>default locale</li>
* </ol>
* @param language The locale's language.
* @param country The locale's country.
* @param variant The locale's language variant.
* @param formKey The key for the Form.
* @return The validator Form.
* @since 1.1
*/
public Form getForm(final String language, final String country, final String variant,
final String formKey) {
Form form = null;
// Try language/country/variant
String key = this.buildLocale(language, country, variant);
if (!key.isEmpty()) {
final FormSet formSet = getFormSets().get(key);
if (formSet != null) {
form = formSet.getForm(formKey);
}
}
final String localeKey = key;
// Try language/country
if (form == null) {
key = buildLocale(language, country, null);
if (!key.isEmpty()) {
final FormSet formSet = getFormSets().get(key);
if (formSet != null) {
form = formSet.getForm(formKey);
}
}
}
// Try language
if (form == null) {
key = buildLocale(language, null, null);
if (!key.isEmpty()) {
final FormSet formSet = getFormSets().get(key);
if (formSet != null) {
form = formSet.getForm(formKey);
}
}
}
// Try default formset
if (form == null) {
form = defaultFormSet.getForm(formKey);
key = "default";
}
if (form == null) {
if (getLog().isWarnEnabled()) {
getLog().warn("Form '" + formKey + "' not found for locale '" +
localeKey + "'");
}
} else if (getLog().isDebugEnabled()) {
getLog().debug("Form '" + formKey + "' found in formset '" +
key + "' for locale '" + localeKey + "'");
}
return form;
}
/**
* Process the <code>ValidatorResources</code> object. Currently sets the
* <code>FastHashMap</code> s to the 'fast' mode and call the processes
* all other resources. <strong>Note </strong>: The framework calls this
* automatically when ValidatorResources is created from an XML file. If you
* create an instance of this class by hand you <strong>must </strong> call
* this method when finished.
*/
public void process() {
hFormSets.setFast(true);
hConstants.setFast(true);
hActions.setFast(true);
this.processForms();
}
/**
* <p>Process the <code>Form</code> objects. This clones the <code>Field</code>s
* that don't exist in a <code>FormSet</code> compared to its parent
* <code>FormSet</code>.</p>
*/
private void processForms() {
if (defaultFormSet == null) {// it isn't mandatory to have a
// default formset
defaultFormSet = new FormSet();
}
defaultFormSet.process(getConstants());
// Loop through FormSets and merge if necessary
for (final String key : getFormSets().keySet()) {
final FormSet fs = getFormSets().get(key);
fs.merge(getParent(fs));
}
// Process Fully Constructed FormSets
for (final FormSet fs : getFormSets().values()) {
if (!fs.isProcessed()) {
fs.process(getConstants());
}
}
}
/**
* Finds the given formSet's parent. ex: A formSet with locale en_UK_TEST1
* has a direct parent in the formSet with locale en_UK. If it doesn't
* exist, find the formSet with locale en, if no found get the
* defaultFormSet.
*
* @param fs
* the formSet we want to get the parent from
* @return fs's parent
*/
private FormSet getParent(final FormSet fs) {
FormSet parent = null;
if (fs.getType() == FormSet.LANGUAGE_FORMSET) {
parent = defaultFormSet;
} else if (fs.getType() == FormSet.COUNTRY_FORMSET) {
parent = getFormSets().get(buildLocale(fs.getLanguage(),
null, null));
if (parent == null) {
parent = defaultFormSet;
}
} else if (fs.getType() == FormSet.VARIANT_FORMSET) {
parent = getFormSets().get(buildLocale(fs.getLanguage(), fs
.getCountry(), null));
if (parent == null) {
parent = getFormSets().get(buildLocale(fs.getLanguage(),
null, null));
if (parent == null) {
parent = defaultFormSet;
}
}
}
return parent;
}
/**
* <p>Gets a <code>FormSet</code> based on the language, country
* and variant.</p>
* @param language The locale's language.
* @param country The locale's country.
* @param variant The locale's language variant.
* @return The FormSet for a locale.
* @since 1.2
*/
FormSet getFormSet(final String language, final String country, final String variant) {
final String key = buildLocale(language, country, variant);
if (key.isEmpty()) {
return defaultFormSet;
}
return getFormSets().get(key);
}
/**
* Returns a Map of String locale keys to Lists of their FormSets.
* @return Map of Form sets
* @since 1.2.0
*/
@SuppressWarnings("unchecked") // FastHashMap is not generic
protected Map<String, FormSet> getFormSets() {
return hFormSets;
}
/**
* Returns a Map of String constant names to their String values.
* @return Map of Constants
* @since 1.2.0
*/
@SuppressWarnings("unchecked") // FastHashMap is not generic
protected Map<String, String> getConstants() {
return hConstants;
}
/**
* Returns a Map of String ValidatorAction names to their ValidatorAction.
* @return Map of Validator Actions
* @since 1.2.0
*/
@SuppressWarnings("unchecked") // FastHashMap is not generic
protected Map<String, ValidatorAction> getActions() {
return hActions;
}
/**
* Accessor method for Log instance.
*
* The Log instance variable is transient and
* accessing it through this method ensures it
* is re-initialized when this instance is
* de-serialized.
*
* @return The Log instance.
*/
private Log getLog() {
if (log == null) {
log = LogFactory.getLog(ValidatorResources.class);
}
return log;
}
}
| 7,958 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/GenericValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import java.io.Serializable;
import java.util.Locale;
import java.util.regex.Pattern;
import org.apache.commons.validator.routines.CreditCardValidator;
import org.apache.commons.validator.routines.DateValidator;
import org.apache.commons.validator.routines.EmailValidator;
import org.apache.commons.validator.routines.UrlValidator;
/**
* This class contains basic methods for performing validations.
*/
public class GenericValidator implements Serializable {
private static final long serialVersionUID = -7212095066891517618L;
/**
* UrlValidator used in wrapper method.
*/
private static final UrlValidator URL_VALIDATOR = new UrlValidator();
/**
* CreditCardValidator used in wrapper method.
*/
private static final CreditCardValidator CREDIT_CARD_VALIDATOR =
new CreditCardValidator();
/**
* <p>Checks if the field isn't null and length of the field is greater
* than zero not including whitespace.</p>
*
* @param value The value validation is being performed on.
* @return true if blank or null.
*/
public static boolean isBlankOrNull(final String value) {
return value == null || value.trim().isEmpty();
}
/**
* <p>Checks if the value matches the regular expression.</p>
*
* @param value The value validation is being performed on.
* @param regexp The regular expression.
* @return true if matches the regular expression.
*/
public static boolean matchRegexp(final String value, final String regexp) {
if (regexp == null || regexp.isEmpty()) {
return false;
}
return Pattern.matches(regexp, value);
}
/**
* <p>Checks if the value can safely be converted to a byte primitive.</p>
*
* @param value The value validation is being performed on.
* @return true if the value can be converted to a Byte.
*/
public static boolean isByte(final String value) {
return GenericTypeValidator.formatByte(value) != null;
}
/**
* <p>Checks if the value can safely be converted to a short primitive.</p>
*
* @param value The value validation is being performed on.
* @return true if the value can be converted to a Short.
*/
public static boolean isShort(final String value) {
return GenericTypeValidator.formatShort(value) != null;
}
/**
* <p>Checks if the value can safely be converted to a int primitive.</p>
*
* @param value The value validation is being performed on.
* @return true if the value can be converted to an Integer.
*/
public static boolean isInt(final String value) {
return GenericTypeValidator.formatInt(value) != null;
}
/**
* <p>Checks if the value can safely be converted to a long primitive.</p>
*
* @param value The value validation is being performed on.
* @return true if the value can be converted to a Long.
*/
public static boolean isLong(final String value) {
return GenericTypeValidator.formatLong(value) != null;
}
/**
* <p>Checks if the value can safely be converted to a float primitive.</p>
*
* @param value The value validation is being performed on.
* @return true if the value can be converted to a Float.
*/
public static boolean isFloat(final String value) {
return GenericTypeValidator.formatFloat(value) != null;
}
/**
* <p>Checks if the value can safely be converted to a double primitive.</p>
*
* @param value The value validation is being performed on.
* @return true if the value can be converted to a Double.
*/
public static boolean isDouble(final String value) {
return GenericTypeValidator.formatDouble(value) != null;
}
/**
* <p>Checks if the field is a valid date. The <code>Locale</code> is
* used with <code>java.text.DateFormat</code>. The setLenient method
* is set to {@code false} for all.</p>
*
* @param value The value validation is being performed on.
* @param locale The locale to use for the date format, defaults to the
* system default if null.
* @return true if the value can be converted to a Date.
*/
public static boolean isDate(final String value, final Locale locale) {
return DateValidator.getInstance().isValid(value, locale);
}
/**
* <p>Checks if the field is a valid date. The pattern is used with
* <code>java.text.SimpleDateFormat</code>. If strict is true, then the
* length will be checked so '2/12/1999' will not pass validation with
* the format 'MM/dd/yyyy' because the month isn't two digits.
* The setLenient method is set to {@code false} for all.</p>
*
* @param value The value validation is being performed on.
* @param datePattern The pattern passed to <code>SimpleDateFormat</code>.
* @param strict Whether or not to have an exact match of the datePattern.
* @return true if the value can be converted to a Date.
*/
public static boolean isDate(final String value, final String datePattern, final boolean strict) {
// TODO method isValid() not yet supported in routines version
return org.apache.commons.validator.DateValidator.getInstance().isValid(value, datePattern, strict);
}
/**
* <p>Checks if a value is within a range (min & max specified
* in the vars attribute).</p>
*
* @param value The value validation is being performed on.
* @param min The minimum value of the range.
* @param max The maximum value of the range.
* @return true if the value is in the specified range.
*/
public static boolean isInRange(final byte value, final byte min, final byte max) {
return value >= min && value <= max;
}
/**
* <p>Checks if a value is within a range (min & max specified
* in the vars attribute).</p>
*
* @param value The value validation is being performed on.
* @param min The minimum value of the range.
* @param max The maximum value of the range.
* @return true if the value is in the specified range.
*/
public static boolean isInRange(final int value, final int min, final int max) {
return value >= min && value <= max;
}
/**
* <p>Checks if a value is within a range (min & max specified
* in the vars attribute).</p>
*
* @param value The value validation is being performed on.
* @param min The minimum value of the range.
* @param max The maximum value of the range.
* @return true if the value is in the specified range.
*/
public static boolean isInRange(final float value, final float min, final float max) {
return value >= min && value <= max;
}
/**
* <p>Checks if a value is within a range (min & max specified
* in the vars attribute).</p>
*
* @param value The value validation is being performed on.
* @param min The minimum value of the range.
* @param max The maximum value of the range.
* @return true if the value is in the specified range.
*/
public static boolean isInRange(final short value, final short min, final short max) {
return value >= min && value <= max;
}
/**
* <p>Checks if a value is within a range (min & max specified
* in the vars attribute).</p>
*
* @param value The value validation is being performed on.
* @param min The minimum value of the range.
* @param max The maximum value of the range.
* @return true if the value is in the specified range.
*/
public static boolean isInRange(final long value, final long min, final long max) {
return value >= min && value <= max;
}
/**
* <p>Checks if a value is within a range (min & max specified
* in the vars attribute).</p>
*
* @param value The value validation is being performed on.
* @param min The minimum value of the range.
* @param max The maximum value of the range.
* @return true if the value is in the specified range.
*/
public static boolean isInRange(final double value, final double min, final double max) {
return value >= min && value <= max;
}
/**
* Checks if the field is a valid credit card number.
* @param value The value validation is being performed on.
* @return true if the value is valid Credit Card Number.
*/
public static boolean isCreditCard(final String value) {
return CREDIT_CARD_VALIDATOR.isValid(value);
}
/**
* <p>Checks if a field has a valid e-mail address.</p>
*
* @param value The value validation is being performed on.
* @return true if the value is valid Email Address.
*/
public static boolean isEmail(final String value) {
return EmailValidator.getInstance().isValid(value);
}
/**
* <p>Checks if a field is a valid URL address.</p>
* If you need to modify what is considered valid then
* consider using the UrlValidator directly.
*
* @param value The value validation is being performed on.
* @return true if the value is valid Url.
*/
public static boolean isUrl(final String value) {
return URL_VALIDATOR.isValid(value);
}
/**
* <p>Checks if the value's length is less than or equal to the max.</p>
*
* @param value The value validation is being performed on.
* @param max The maximum length.
* @return true if the value's length is less than the specified maximum.
*/
public static boolean maxLength(final String value, final int max) {
return value.length() <= max;
}
/**
* <p>Checks if the value's adjusted length is less than or equal to the max.</p>
*
* @param value The value validation is being performed on.
* @param max The maximum length.
* @param lineEndLength The length to use for line endings.
* @return true if the value's length is less than the specified maximum.
*/
public static boolean maxLength(final String value, final int max, final int lineEndLength) {
final int adjustAmount = adjustForLineEnding(value, lineEndLength);
return value.length() + adjustAmount <= max;
}
/**
* <p>Checks if the value's length is greater than or equal to the min.</p>
*
* @param value The value validation is being performed on.
* @param min The minimum length.
* @return true if the value's length is more than the specified minimum.
*/
public static boolean minLength(final String value, final int min) {
return value.length() >= min;
}
/**
* <p>Checks if the value's adjusted length is greater than or equal to the min.</p>
*
* @param value The value validation is being performed on.
* @param min The minimum length.
* @param lineEndLength The length to use for line endings.
* @return true if the value's length is more than the specified minimum.
*/
public static boolean minLength(final String value, final int min, final int lineEndLength) {
final int adjustAmount = adjustForLineEnding(value, lineEndLength);
return value.length() + adjustAmount >= min;
}
/**
* Calculate an adjustment amount for line endings.
*
* See Bug 37962 for the rational behind this.
*
* @param value The value validation is being performed on.
* @param lineEndLength The length to use for line endings.
* @return the adjustment amount.
*/
private static int adjustForLineEnding(final String value, final int lineEndLength) {
int nCount = 0;
int rCount = 0;
for (int i = 0; i < value.length(); i++) {
if (value.charAt(i) == '\n') {
nCount++;
}
if (value.charAt(i) == '\r') {
rCount++;
}
}
return nCount * lineEndLength - (rCount + nCount);
}
// See http://issues.apache.org/bugzilla/show_bug.cgi?id=29015 WRT the "value" methods
/**
* <p>Checks if the value is greater than or equal to the min.</p>
*
* @param value The value validation is being performed on.
* @param min The minimum numeric value.
* @return true if the value is >= the specified minimum.
*/
public static boolean minValue(final int value, final int min) {
return value >= min;
}
/**
* <p>Checks if the value is greater than or equal to the min.</p>
*
* @param value The value validation is being performed on.
* @param min The minimum numeric value.
* @return true if the value is >= the specified minimum.
*/
public static boolean minValue(final long value, final long min) {
return value >= min;
}
/**
* <p>Checks if the value is greater than or equal to the min.</p>
*
* @param value The value validation is being performed on.
* @param min The minimum numeric value.
* @return true if the value is >= the specified minimum.
*/
public static boolean minValue(final double value, final double min) {
return value >= min;
}
/**
* <p>Checks if the value is greater than or equal to the min.</p>
*
* @param value The value validation is being performed on.
* @param min The minimum numeric value.
* @return true if the value is >= the specified minimum.
*/
public static boolean minValue(final float value, final float min) {
return value >= min;
}
/**
* <p>Checks if the value is less than or equal to the max.</p>
*
* @param value The value validation is being performed on.
* @param max The maximum numeric value.
* @return true if the value is <= the specified maximum.
*/
public static boolean maxValue(final int value, final int max) {
return value <= max;
}
/**
* <p>Checks if the value is less than or equal to the max.</p>
*
* @param value The value validation is being performed on.
* @param max The maximum numeric value.
* @return true if the value is <= the specified maximum.
*/
public static boolean maxValue(final long value, final long max) {
return value <= max;
}
/**
* <p>Checks if the value is less than or equal to the max.</p>
*
* @param value The value validation is being performed on.
* @param max The maximum numeric value.
* @return true if the value is <= the specified maximum.
*/
public static boolean maxValue(final double value, final double max) {
return value <= max;
}
/**
* <p>Checks if the value is less than or equal to the max.</p>
*
* @param value The value validation is being performed on.
* @param max The maximum numeric value.
* @return true if the value is <= the specified maximum.
*/
public static boolean maxValue(final float value, final float max) {
return value <= max;
}
}
| 7,959 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/FormSetFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import org.apache.commons.digester.AbstractObjectCreationFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.Attributes;
/**
* Factory class used by Digester to create FormSet's.
*
* @since 1.2
*/
public class FormSetFactory extends AbstractObjectCreationFactory {
/** Logging */
private transient Log log = LogFactory.getLog(FormSetFactory.class);
/**
* <p>Create or retrieve a <code>FormSet</code> for the specified
* attributes.</p>
*
* @param attributes The sax attributes for the formset element.
* @return The FormSet for a locale.
* @throws Exception If an error occurs creating the FormSet.
*/
@Override
public Object createObject(final Attributes attributes) throws Exception {
final ValidatorResources resources = (ValidatorResources) digester.peek(0);
final String language = attributes.getValue("language");
final String country = attributes.getValue("country");
final String variant = attributes.getValue("variant");
return createFormSet(resources, language, country, variant);
}
/**
* <p>Create or retrieve a <code>FormSet</code> based on the language, country
* and variant.</p>
*
* @param resources The validator resources.
* @param language The locale's language.
* @param country The locale's country.
* @param variant The locale's language variant.
* @return The FormSet for a locale.
* @since 1.2
*/
private FormSet createFormSet(final ValidatorResources resources,
final String language,
final String country,
final String variant) {
// Retrieve existing FormSet for the language/country/variant
FormSet formSet = resources.getFormSet(language, country, variant);
if (formSet != null) {
if (getLog().isDebugEnabled()) {
getLog().debug("FormSet[" + formSet.displayKey() + "] found - merging.");
}
return formSet;
}
// Create a new FormSet for the language/country/variant
formSet = new FormSet();
formSet.setLanguage(language);
formSet.setCountry(country);
formSet.setVariant(variant);
// Add the FormSet to the validator resources
resources.addFormSet(formSet);
if (getLog().isDebugEnabled()) {
getLog().debug("FormSet[" + formSet.displayKey() + "] created.");
}
return formSet;
}
/**
* Accessor method for Log instance.
*
* The Log instance variable is transient and
* accessing it through this method ensures it
* is re-initialized when this instance is
* de-serialized.
*
* @return The Log instance.
*/
private Log getLog() {
if (log == null) {
log = LogFactory.getLog(FormSetFactory.class);
}
return log;
}
}
| 7,960 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/DateValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
/**
* <p>Perform date validations.</p>
* <p>
* This class is a Singleton; you can retrieve the instance via the
* getInstance() method.
* </p>
*
* @since 1.1
* @deprecated Use the new DateValidator, CalendarValidator or TimeValidator in the
* routines package. This class will be removed in a future release.
*/
@Deprecated
public class DateValidator {
/**
* Singleton instance of this class.
*/
private static final DateValidator DATE_VALIDATOR = new DateValidator();
/**
* Returns the Singleton instance of this validator.
* @return A singleton instance of the DateValidator.
*/
public static DateValidator getInstance() {
return DATE_VALIDATOR;
}
/**
* Protected constructor for subclasses to use.
*/
protected DateValidator() {
}
/**
* <p>Checks if the field is a valid date. The pattern is used with
* <code>java.text.SimpleDateFormat</code>. If strict is true, then the
* length will be checked so '2/12/1999' will not pass validation with
* the format 'MM/dd/yyyy' because the month isn't two digits.
* The setLenient method is set to {@code false} for all.</p>
*
* @param value The value validation is being performed on.
* @param datePattern The pattern passed to <code>SimpleDateFormat</code>.
* @param strict Whether or not to have an exact match of the datePattern.
* @return true if the date is valid.
*/
public boolean isValid(final String value, final String datePattern, final boolean strict) {
if (value == null
|| datePattern == null
|| datePattern.isEmpty()) {
return false;
}
final SimpleDateFormat formatter = new SimpleDateFormat(datePattern);
formatter.setLenient(false);
try {
formatter.parse(value);
} catch (final ParseException e) {
return false;
}
if (strict && datePattern.length() != value.length()) {
return false;
}
return true;
}
/**
* <p>Checks if the field is a valid date. The <code>Locale</code> is
* used with <code>java.text.DateFormat</code>. The setLenient method
* is set to {@code false} for all.</p>
*
* @param value The value validation is being performed on.
* @param locale The locale to use for the date format, defaults to the default
* system default if null.
* @return true if the date is valid.
*/
public boolean isValid(final String value, final Locale locale) {
if (value == null) {
return false;
}
DateFormat formatter;
if (locale != null) {
formatter = DateFormat.getDateInstance(DateFormat.SHORT, locale);
} else {
formatter =
DateFormat.getDateInstance(
DateFormat.SHORT,
Locale.getDefault());
}
formatter.setLenient(false);
try {
formatter.parse(value);
} catch (final ParseException e) {
return false;
}
return true;
}
}
| 7,961 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/Msg.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import java.io.Serializable;
/**
* An alternative message can be associated with a <code>Field</code>
* and a pluggable validator instead of using the default message
* stored in the <code>ValidatorAction</code> (aka pluggable validator).
* Instances of this class are configured with a <msg> xml element.
*/
//TODO mutable non-private fields
public class Msg implements Cloneable, Serializable {
private static final long serialVersionUID = 5690015734364127124L;
/**
* The resource bundle name that this Msg's <code>key</code> should be
* resolved in (optional).
* @since 1.1
*/
protected String bundle;
/**
* The key or value of the argument.
*/
protected String key;
/**
* The name dependency that this argument goes with (optional).
*/
protected String name;
/**
* Whether or not the key is a message resource (optional). Defaults to
* true. If it is 'true', the value will try to be resolved as a message
* resource.
* @since 1.1.4
*/
protected boolean resource = true;
/**
* Returns the resource bundle name.
* @return The bundle name.
* @since 1.1
*/
public String getBundle() {
return this.bundle;
}
/**
* Sets the resource bundle name.
* @param bundle The new bundle name.
* @since 1.1
*/
public void setBundle(final String bundle) {
this.bundle = bundle;
}
/**
* Gets the name of the dependency.
* @return The dependency name.
*/
public String getName() {
return name;
}
/**
* Sets the name of the dependency.
* @param name The dependency name.
*/
public void setName(final String name) {
this.name = name;
}
/**
* Gets the key/value.
* @return The message key/value.
*/
public String getKey() {
return key;
}
/**
* Sets the key/value.
* @param key The message key/value.
*/
public void setKey(final String key) {
this.key = key;
}
/**
* Tests whether or not the key is a resource key or literal value.
* @return {@code true} if key is a resource key.
* @since 1.1.4
*/
public boolean isResource() {
return this.resource;
}
/**
* Sets whether or not the key is a resource.
* @param resource If true indicates the key is a resource.
* @since 1.1.4
*/
public void setResource(final boolean resource) {
this.resource = resource;
}
/**
* Creates and returns a copy of this object.
* @return A copy of the Msg.
*/
@Override
public Object clone() {
try {
return super.clone();
} catch (final CloneNotSupportedException e) {
throw new UnsupportedOperationException(e.toString(), e);
}
}
/**
* Returns a string representation of the object.
* @return Msg String representation.
*/
@Override
public String toString() {
final StringBuilder results = new StringBuilder();
results.append("Msg: name=");
results.append(name);
results.append(" key=");
results.append(key);
results.append(" resource=");
results.append(resource);
results.append(" bundle=");
results.append(bundle);
results.append("\n");
return results.toString();
}
} | 7,962 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/ValidatorResult.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* This contains the results of a set of validation rules processed
* on a JavaBean.
*/
//TODO mutable non-private fields
public class ValidatorResult implements Serializable {
private static final long serialVersionUID = -3713364681647250531L;
/**
* Map of results. The key is the name of the <code>ValidatorAction</code>
* and the value is whether or not this field passed or not.
*/
protected Map<String, ResultStatus> hAction = new HashMap<>();
/**
* <code>Field</code> being validated.
* TODO This variable is not used. Need to investigate removing it.
*/
protected Field field;
/**
* Constructs a <code>ValidatorResult</code> with the associated field being
* validated.
* @param field Field that was validated.
*/
public ValidatorResult(final Field field) {
this.field = field;
}
/**
* Add the result of a validator action.
* @param validatorName Name of the validator.
* @param result Whether the validation passed or failed.
*/
public void add(final String validatorName, final boolean result) {
this.add(validatorName, result, null);
}
/**
* Add the result of a validator action.
* @param validatorName Name of the validator.
* @param result Whether the validation passed or failed.
* @param value Value returned by the validator.
*/
public void add(final String validatorName, final boolean result, final Object value) {
hAction.put(validatorName, new ResultStatus(result, value));
}
/**
* Indicate whether a specified validator is in the Result.
* @param validatorName Name of the validator.
* @return true if the validator is in the result.
*/
public boolean containsAction(final String validatorName) {
return hAction.containsKey(validatorName);
}
/**
* Indicate whether a specified validation passed.
* @param validatorName Name of the validator.
* @return true if the validation passed.
*/
public boolean isValid(final String validatorName) {
final ResultStatus status = hAction.get(validatorName);
return status == null ? false : status.isValid();
}
/**
* Return the result of a validation.
* @param validatorName Name of the validator.
* @return The validation result.
*/
public Object getResult(final String validatorName) {
final ResultStatus status = hAction.get(validatorName);
return status == null ? null : status.getResult();
}
/**
* Return an Iterator of the action names contained in this Result.
* @return The set of action names.
*/
public Iterator<String> getActions() {
return Collections.unmodifiableMap(hAction).keySet().iterator();
}
/**
* Return a Map of the validator actions in this Result.
* @return Map of validator actions.
* @deprecated Use getActions() to return the set of actions
* the isValid(name) and getResult(name) methods
* to determine the contents of ResultStatus.
*
*/
@Deprecated
public Map<String, ResultStatus> getActionMap() {
return Collections.unmodifiableMap(hAction);
}
/**
* Returns the Field that was validated.
* @return The Field associated with this result.
*/
public Field getField() {
return this.field;
}
/**
* Contains the status of the validation.
*/
protected static class ResultStatus implements Serializable {
private static final long serialVersionUID = 4076665918535320007L;
private boolean valid;
private Object result;
/**
* Constructs a Result status.
* @param valid Whether the validator passed or failed.
* @param result Value returned by the validator.
*/
public ResultStatus(final boolean valid, final Object result) {
this.valid = valid;
this.result = result;
}
/**
* Provided for backwards binary compatibility only.
*
* @param ignored ignored by this method
* @param valid Whether the validator passed or failed.
* @param result Value returned by the validator.
*
* @deprecated Use {@code ResultStatus(boolean, Object)} instead
*/
@Deprecated
public ResultStatus(final ValidatorResult ignored, final boolean valid, final Object result) {
this(valid, result);
}
/**
* Tests whether or not the validation passed.
* @return true if the result was good.
*/
public boolean isValid() {
return valid;
}
/**
* Sets whether or not the validation passed.
* @param valid Whether the validation passed.
*/
public void setValid(final boolean valid) {
this.valid = valid;
}
/**
* Gets the result returned by a validation method.
* This can be used to retrieve to the correctly
* typed value of a date validation for example.
* @return The value returned by the validation.
*/
public Object getResult() {
return result;
}
/**
* Sets the result returned by a validation method.
* This can be used to retrieve to the correctly
* typed value of a date validation for example.
* @param result The value returned by the validation.
*/
public void setResult(final Object result) {
this.result = result;
}
}
} | 7,963 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/Validator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* Validations are processed by the validate method. An instance of
* <code>ValidatorResources</code> is used to define the validators
* (validation methods) and the validation rules for a JavaBean.
*/
// TODO mutable fields should be made private and accessed via suitable methods only
public class Validator implements Serializable {
private static final long serialVersionUID = -7119418755208731611L;
/**
* Resources key the JavaBean is stored to perform validation on.
*/
public static final String BEAN_PARAM = "java.lang.Object";
/**
* Resources key the <code>ValidatorAction</code> is stored under.
* This will be automatically passed into a validation method
* with the current <code>ValidatorAction</code> if it is
* specified in the method signature.
*/
public static final String VALIDATOR_ACTION_PARAM =
"org.apache.commons.validator.ValidatorAction";
/**
* Resources key the <code>ValidatorResults</code> is stored under.
* This will be automatically passed into a validation method
* with the current <code>ValidatorResults</code> if it is
* specified in the method signature.
*/
public static final String VALIDATOR_RESULTS_PARAM =
"org.apache.commons.validator.ValidatorResults";
/**
* Resources key the <code>Form</code> is stored under.
* This will be automatically passed into a validation method
* with the current <code>Form</code> if it is
* specified in the method signature.
*/
public static final String FORM_PARAM = "org.apache.commons.validator.Form";
/**
* Resources key the <code>Field</code> is stored under.
* This will be automatically passed into a validation method
* with the current <code>Field</code> if it is
* specified in the method signature.
*/
public static final String FIELD_PARAM = "org.apache.commons.validator.Field";
/**
* Resources key the <code>Validator</code> is stored under.
* This will be automatically passed into a validation method
* with the current <code>Validator</code> if it is
* specified in the method signature.
*/
public static final String VALIDATOR_PARAM =
"org.apache.commons.validator.Validator";
/**
* Resources key the <code>Locale</code> is stored.
* This will be used to retrieve the appropriate
* <code>FormSet</code> and <code>Form</code> to be
* processed.
*/
public static final String LOCALE_PARAM = "java.util.Locale";
/**
* The Validator Resources.
*/
protected ValidatorResources resources;
/**
* The name of the form to validate
*/
protected String formName;
/**
* The name of the field on the form to validate
* @since 1.2.0
*/
protected String fieldName;
/**
* Maps validation method parameter class names to the objects to be passed
* into the method.
*/
protected Map<String, Object> parameters = new HashMap<>(); // <String, Object>
/**
* The current page number to validate.
*/
protected int page;
/**
* The class loader to use for instantiating application objects.
* If not specified, the context class loader, or the class loader
* used to load Digester itself, is used, based on the value of the
* <code>useContextClassLoader</code> variable.
*/
protected transient ClassLoader classLoader;
/**
* Whether or not to use the Context ClassLoader when loading classes
* for instantiating new objects. Default is {@code false}.
*/
protected boolean useContextClassLoader;
/**
* Sets this to true to not return Fields that pass validation. Only return failures.
*/
protected boolean onlyReturnErrors;
/**
* Constructs a <code>Validator</code> that will
* use the <code>ValidatorResources</code>
* passed in to retrieve pluggable validators
* the different sets of validation rules.
*
* @param resources <code>ValidatorResources</code> to use during validation.
*/
public Validator(final ValidatorResources resources) {
this(resources, null);
}
/**
* Constructs a <code>Validator</code> that will
* use the <code>ValidatorResources</code>
* passed in to retrieve pluggable validators
* the different sets of validation rules.
*
* @param resources <code>ValidatorResources</code> to use during validation.
* @param formName Key used for retrieving the set of validation rules.
*/
public Validator(final ValidatorResources resources, final String formName) {
if (resources == null) {
throw new IllegalArgumentException("Resources cannot be null.");
}
this.resources = resources;
this.formName = formName;
}
/**
* Constructs a <code>Validator</code> that will
* use the <code>ValidatorResources</code>
* passed in to retrieve pluggable validators
* the different sets of validation rules.
*
* @param resources <code>ValidatorResources</code> to use during validation.
* @param formName Key used for retrieving the set of validation rules.
* @param fieldName Key used for retrieving the set of validation rules for a field
* @since 1.2.0
*/
public Validator(final ValidatorResources resources, final String formName, final String fieldName) {
if (resources == null) {
throw new IllegalArgumentException("Resources cannot be null.");
}
this.resources = resources;
this.formName = formName;
this.fieldName = fieldName;
}
/**
* Sets a parameter of a pluggable validation method.
*
* @param parameterClassName The full class name of the parameter of the
* validation method that corresponds to the value/instance passed in with it.
*
* @param parameterValue The instance that will be passed into the
* validation method.
*/
public void setParameter(final String parameterClassName, final Object parameterValue) {
this.parameters.put(parameterClassName, parameterValue);
}
/**
* Returns the value of the specified parameter that will be used during the
* processing of validations.
*
* @param parameterClassName The full class name of the parameter of the
* validation method that corresponds to the value/instance passed in with it.
* @return value of the specified parameter.
*/
public Object getParameterValue(final String parameterClassName) {
return this.parameters.get(parameterClassName);
}
/**
* Gets the form name which is the key to a set of validation rules.
* @return the name of the form.
*/
public String getFormName() {
return formName;
}
/**
* Sets the form name which is the key to a set of validation rules.
* @param formName the name of the form.
*/
public void setFormName(final String formName) {
this.formName = formName;
}
/**
* Sets the name of the field to validate in a form (optional)
*
* @param fieldName The name of the field in a form set
* @since 1.2.0
*/
public void setFieldName(final String fieldName) {
this.fieldName = fieldName;
}
/**
* Gets the page.
*
* <p>
* This in conjunction with the page property of
* a {@code Field} can control the processing of fields. If the field's
* page is less than or equal to this page value, it will be processed.
* </p>
*
* @return the page number.
*/
public int getPage() {
return page;
}
/**
* Sets the page.
* <p>
* This in conjunction with the page property of
* a {@code Field} can control the processing of fields. If the field's page
* is less than or equal to this page value, it will be processed.
* </p>
*
* @param page the page number.
*/
public void setPage(final int page) {
this.page = page;
}
/**
* Clears the form name, resources that were added, and the page that was
* set (if any). This can be called to reinitialize the Validator instance
* so it can be reused. The form name (key to set of validation rules) and any
* resources needed, like the JavaBean being validated, will need to
* set and/or added to this instance again. The
* <code>ValidatorResources</code> will not be removed since it can be used
* again and is thread safe.
*/
public void clear() {
this.formName = null;
this.fieldName = null;
this.parameters = new HashMap<>();
this.page = 0;
}
/**
* Return the boolean as to whether the context classloader should be used.
* @return whether the context classloader should be used.
*/
public boolean getUseContextClassLoader() {
return this.useContextClassLoader;
}
/**
* Determine whether to use the Context ClassLoader (the one found by
* calling <code>Thread.currentThread().getContextClassLoader()</code>)
* to resolve/load classes that are defined in various rules. If not
* using Context ClassLoader, then the class-loading defaults to
* using the calling-class' ClassLoader.
*
* @param use determines whether to use Context ClassLoader.
*/
public void setUseContextClassLoader(final boolean use) {
this.useContextClassLoader = use;
}
/**
* Return the class loader to be used for instantiating application objects
* when required. This is determined based upon the following rules:
* <ul>
* <li>The class loader set by <code>setClassLoader()</code>, if any</li>
* <li>The thread context class loader, if it exists and the
* <code>useContextClassLoader</code> property is set to true</li>
* <li>The class loader used to load the Digester class itself.
* </ul>
* @return the class loader.
*/
public ClassLoader getClassLoader() {
if (this.classLoader != null) {
return this.classLoader;
}
if (this.useContextClassLoader) {
final ClassLoader contextLoader = Thread.currentThread().getContextClassLoader();
if (contextLoader != null) {
return contextLoader;
}
}
return this.getClass().getClassLoader();
}
/**
* Sets the class loader to be used for instantiating application objects
* when required.
*
* @param classLoader The new class loader to use, or <code>null</code>
* to revert to the standard rules
*/
public void setClassLoader(final ClassLoader classLoader) {
this.classLoader = classLoader;
}
/**
* Performs validations based on the configured resources.
*
* @return The <code>Map</code> returned uses the property of the
* <code>Field</code> for the key and the value is the number of error the
* field had.
* @throws ValidatorException If an error occurs during validation
*/
public ValidatorResults validate() throws ValidatorException {
Locale locale = (Locale) this.getParameterValue(LOCALE_PARAM);
if (locale == null) {
locale = Locale.getDefault();
}
this.setParameter(VALIDATOR_PARAM, this);
final Form form = this.resources.getForm(locale, this.formName);
if (form != null) {
this.setParameter(FORM_PARAM, form);
return form.validate(
this.parameters,
this.resources.getValidatorActions(),
this.page,
this.fieldName);
}
return new ValidatorResults();
}
/**
* Returns true if the Validator is only returning Fields that fail validation.
* @return whether only failed fields are returned.
*/
public boolean getOnlyReturnErrors() {
return onlyReturnErrors;
}
/**
* Configures which Fields the Validator returns from the validate() method. Set this
* to true to only return Fields that failed validation. By default, validate() returns
* all fields.
* @param onlyReturnErrors whether only failed fields are returned.
*/
public void setOnlyReturnErrors(final boolean onlyReturnErrors) {
this.onlyReturnErrors = onlyReturnErrors;
}
}
| 7,964 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/ValidatorAction.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.util.ValidatorUtils;
/**
* Contains the information to dynamically create and run a validation
* method. This is the class representation of a pluggable validator that can
* be defined in an xml file with the <validator> element.
*
* <strong>Note</strong>: The validation method is assumed to be thread safe.
*/
public class ValidatorAction implements Serializable {
private static final long serialVersionUID = 1339713700053204597L;
/**
* Logger.
*/
private transient Log log = LogFactory.getLog(ValidatorAction.class);
/**
* The name of the validation.
*/
private String name;
/**
* The full class name of the class containing
* the validation method associated with this action.
*/
private String className;
/**
* The Class object loaded from the class name.
*/
private Class<?> validationClass;
/**
* The full method name of the validation to be performed. The method
* must be thread safe.
*/
private String method;
/**
* The Method object loaded from the method name.
*/
private Method validationMethod;
/**
* <p>
* The method signature of the validation method. This should be a comma
* delimited list of the full class names of each parameter in the correct
* order that the method takes.
* </p>
* <p>
* Note: <code>java.lang.Object</code> is reserved for the
* JavaBean that is being validated. The <code>ValidatorAction</code>
* and <code>Field</code> that are associated with a field's
* validation will automatically be populated if they are
* specified in the method signature.
* </p>
*/
private String methodParams =
Validator.BEAN_PARAM
+ ","
+ Validator.VALIDATOR_ACTION_PARAM
+ ","
+ Validator.FIELD_PARAM;
/**
* The Class objects for each entry in methodParameterList.
*/
private Class<?>[] parameterClasses;
/**
* The other <code>ValidatorAction</code>s that this one depends on. If
* any errors occur in an action that this one depends on, this action will
* not be processsed.
*/
private String depends;
/**
* The default error message associated with this action.
*/
private String msg;
/**
* An optional field to contain the name to be used if JavaScript is
* generated.
*/
private String jsFunctionName;
/**
* An optional field to contain the class path to be used to retrieve the
* JavaScript function.
*/
private String jsFunction;
/**
* An optional field to containing a JavaScript representation of the
* java method assocated with this action.
*/
private String javascript;
/**
* If the java method matching the correct signature isn't static, the
* instance is stored in the action. This assumes the method is thread
* safe.
*/
private Object instance;
/**
* An internal List representation of the other <code>ValidatorAction</code>s
* this one depends on (if any). This List gets updated
* whenever setDepends() gets called. This is synchronized so a call to
* setDepends() (which clears the List) won't interfere with a call to
* isDependency().
*/
private final List<String> dependencyList = Collections.synchronizedList(new ArrayList<>());
/**
* An internal List representation of all the validation method's
* parameters defined in the methodParams String.
*/
private final List<String> methodParameterList = new ArrayList<>();
/**
* Gets the name of the validator action.
* @return Validator Action name.
*/
public String getName() {
return name;
}
/**
* Sets the name of the validator action.
* @param name Validator Action name.
*/
public void setName(final String name) {
this.name = name;
}
/**
* Gets the class of the validator action.
* @return Class name of the validator Action.
*/
public String getClassname() {
return className;
}
/**
* Sets the class of the validator action.
* @param className Class name of the validator Action.
* @deprecated Use {@link #setClassName(String)}.
*/
@Deprecated
public void setClassname(final String className) {
this.className = className;
}
/**
* Sets the class of the validator action.
* @param className Class name of the validator Action.
*/
public void setClassName(final String className) {
this.className = className;
}
/**
* Gets the name of method being called for the validator action.
* @return The method name.
*/
public String getMethod() {
return method;
}
/**
* Sets the name of method being called for the validator action.
* @param method The method name.
*/
public void setMethod(final String method) {
this.method = method;
}
/**
* Gets the method parameters for the method.
* @return Method's parameters.
*/
public String getMethodParams() {
return methodParams;
}
/**
* Sets the method parameters for the method.
* @param methodParams A comma separated list of parameters.
*/
public void setMethodParams(final String methodParams) {
this.methodParams = methodParams;
this.methodParameterList.clear();
final StringTokenizer st = new StringTokenizer(methodParams, ",");
while (st.hasMoreTokens()) {
final String value = st.nextToken().trim();
if (value != null && !value.isEmpty()) {
this.methodParameterList.add(value);
}
}
}
/**
* Gets the dependencies of the validator action as a comma separated list
* of validator names.
* @return The validator action's dependencies.
*/
public String getDepends() {
return this.depends;
}
/**
* Sets the dependencies of the validator action.
* @param depends A comma separated list of validator names.
*/
public void setDepends(final String depends) {
this.depends = depends;
this.dependencyList.clear();
final StringTokenizer st = new StringTokenizer(depends, ",");
while (st.hasMoreTokens()) {
final String depend = st.nextToken().trim();
if (depend != null && !depend.isEmpty()) {
this.dependencyList.add(depend);
}
}
}
/**
* Gets the message associated with the validator action.
* @return The message for the validator action.
*/
public String getMsg() {
return msg;
}
/**
* Sets the message associated with the validator action.
* @param msg The message for the validator action.
*/
public void setMsg(final String msg) {
this.msg = msg;
}
/**
* Gets the Javascript function name. This is optional and can
* be used instead of validator action name for the name of the
* Javascript function/object.
* @return The Javascript function name.
*/
public String getJsFunctionName() {
return jsFunctionName;
}
/**
* Sets the Javascript function name. This is optional and can
* be used instead of validator action name for the name of the
* Javascript function/object.
* @param jsFunctionName The Javascript function name.
*/
public void setJsFunctionName(final String jsFunctionName) {
this.jsFunctionName = jsFunctionName;
}
/**
* Sets the fully qualified class path of the Javascript function.
* <p>
* This is optional and can be used <strong>instead</strong> of the setJavascript().
* Attempting to call both <code>setJsFunction</code> and <code>setJavascript</code>
* will result in an <code>IllegalStateException</code> being thrown.
* </p>
* <p>
* If <strong>neither</strong> setJsFunction or setJavascript is set then
* validator will attempt to load the default javascript definition.
* </p>
* <pre>
* <b>Examples</b>
* If in the validator.xml :
* #1:
* <validator name="tire"
* jsFunction="com.yourcompany.project.tireFuncion">
* Validator will attempt to load com.yourcompany.project.validateTireFunction.js from
* its class path.
* #2:
* <validator name="tire">
* Validator will use the name attribute to try and load
* org.apache.commons.validator.javascript.validateTire.js
* which is the default javascript definition.
* </pre>
* @param jsFunction The Javascript function's fully qualified class path.
*/
public void setJsFunction(final String jsFunction) {
if (javascript != null) {
throw new IllegalStateException("Cannot call setJsFunction() after calling setJavascript()");
}
this.jsFunction = jsFunction;
}
/**
* Gets the Javascript equivalent of the java class and method
* associated with this action.
* @return The Javascript validation.
*/
public String getJavascript() {
return javascript;
}
/**
* Sets the Javascript equivalent of the java class and method
* associated with this action.
* @param javascript The Javascript validation.
*/
public void setJavascript(final String javascript) {
if (jsFunction != null) {
throw new IllegalStateException("Cannot call setJavascript() after calling setJsFunction()");
}
this.javascript = javascript;
}
/**
* Initialize based on set.
*/
protected void init() {
this.loadJavascriptFunction();
}
/**
* Load the javascript function specified by the given path. For this
* implementation, the <code>jsFunction</code> property should contain a
* fully qualified package and script name, separated by periods, to be
* loaded from the class loader that created this instance.
*
* TODO if the path begins with a '/' the path will be intepreted as
* absolute, and remain unchanged. If this fails then it will attempt to
* treat the path as a file path. It is assumed the script ends with a
* '.js'.
*/
protected synchronized void loadJavascriptFunction() {
if (this.javascriptAlreadyLoaded()) {
return;
}
if (getLog().isTraceEnabled()) {
getLog().trace(" Loading function begun");
}
if (this.jsFunction == null) {
this.jsFunction = this.generateJsFunction();
}
final String javascriptFileName = this.formatJavascriptFileName();
if (getLog().isTraceEnabled()) {
getLog().trace(" Loading js function '" + javascriptFileName + "'");
}
this.javascript = this.readJavascriptFile(javascriptFileName);
if (getLog().isTraceEnabled()) {
getLog().trace(" Loading javascript function completed");
}
}
/**
* Read a javascript function from a file.
* @param javascriptFileName The file containing the javascript.
* @return The javascript function or null if it could not be loaded.
*/
private String readJavascriptFile(final String javascriptFileName) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
classLoader = this.getClass().getClassLoader();
}
InputStream is = classLoader.getResourceAsStream(javascriptFileName);
if (is == null) {
is = this.getClass().getResourceAsStream(javascriptFileName);
}
if (is == null) {
getLog().debug(" Unable to read javascript name "+javascriptFileName);
return null;
}
final StringBuilder buffer = new StringBuilder();
final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // TODO encoding
try {
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line).append("\n");
}
} catch (final IOException e) {
getLog().error("Error reading javascript file.", e);
} finally {
try {
reader.close();
} catch (final IOException e) {
getLog().error("Error closing stream to javascript file.", e);
}
}
final String function = buffer.toString();
return function.equals("") ? null : function;
}
/**
* @return A file name suitable for passing to a
* ClassLoader.getResourceAsStream() method.
*/
private String formatJavascriptFileName() {
String fname = this.jsFunction.substring(1);
if (!this.jsFunction.startsWith("/")) {
fname = jsFunction.replace('.', '/') + ".js";
}
return fname;
}
/**
* @return true if the javascript for this action has already been loaded.
*/
private boolean javascriptAlreadyLoaded() {
return this.javascript != null;
}
/**
* Used to generate the javascript name when it is not specified.
*/
private String generateJsFunction() {
final StringBuilder jsName =
new StringBuilder("org.apache.commons.validator.javascript");
jsName.append(".validate");
jsName.append(name.substring(0, 1).toUpperCase());
jsName.append(name.substring(1));
return jsName.toString();
}
/**
* Checks whether or not the value passed in is in the depends field.
* @param validatorName Name of the dependency to check.
* @return Whether the named validator is a dependant.
*/
public boolean isDependency(final String validatorName) {
return this.dependencyList.contains(validatorName);
}
/**
* Returns the dependent validator names as an unmodifiable
* <code>List</code>.
* @return List of the validator action's depedents.
*/
public List<String> getDependencyList() {
return Collections.unmodifiableList(this.dependencyList);
}
/**
* Returns a string representation of the object.
* @return a string representation.
*/
@Override
public String toString() {
final StringBuilder results = new StringBuilder("ValidatorAction: ");
results.append(name);
results.append("\n");
return results.toString();
}
/**
* Dynamically runs the validation method for this validator and returns
* true if the data is valid.
* @param field
* @param params A Map of class names to parameter values.
* @param results
* @param pos The index of the list property to validate if it's indexed.
* @throws ValidatorException
*/
boolean executeValidationMethod(
final Field field,
// TODO What is this the correct value type?
// both ValidatorAction and Validator are added as parameters
final Map<String, Object> params,
final ValidatorResults results,
final int pos)
throws ValidatorException {
params.put(Validator.VALIDATOR_ACTION_PARAM, this);
try {
if (this.validationMethod == null) {
synchronized(this) {
final ClassLoader loader = this.getClassLoader(params);
this.loadValidationClass(loader);
this.loadParameterClasses(loader);
this.loadValidationMethod();
}
}
final Object[] paramValues = this.getParameterValues(params);
if (field.isIndexed()) {
this.handleIndexedField(field, pos, paramValues);
}
Object result = null;
try {
result =
validationMethod.invoke(
getValidationClassInstance(),
paramValues);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new ValidatorException(e.getMessage());
} catch (final InvocationTargetException e) {
if (e.getTargetException() instanceof Exception) {
throw (Exception) e.getTargetException();
}
if (e.getTargetException() instanceof Error) {
throw (Error) e.getTargetException();
}
}
final boolean valid = this.isValid(result);
if (!valid || valid && !onlyReturnErrors(params)) {
results.add(field, this.name, valid, result);
}
if (!valid) {
return false;
}
// TODO This catch block remains for backward compatibility. Remove
// this for Validator 2.0 when exception scheme changes.
} catch (final Exception e) {
if (e instanceof ValidatorException) {
throw (ValidatorException) e;
}
getLog().error(
"Unhandled exception thrown during validation: " + e.getMessage(),
e);
results.add(field, this.name, false);
return false;
}
return true;
}
/**
* Load the Method object for the configured validation method name.
* @throws ValidatorException
*/
private void loadValidationMethod() throws ValidatorException {
if (this.validationMethod != null) {
return;
}
try {
this.validationMethod =
this.validationClass.getMethod(this.method, this.parameterClasses);
} catch (final NoSuchMethodException e) {
throw new ValidatorException("No such validation method: " +
e.getMessage());
}
}
/**
* Load the Class object for the configured validation class name.
* @param loader The ClassLoader used to load the Class object.
* @throws ValidatorException
*/
private void loadValidationClass(final ClassLoader loader)
throws ValidatorException {
if (this.validationClass != null) {
return;
}
try {
this.validationClass = loader.loadClass(this.className);
} catch (final ClassNotFoundException e) {
throw new ValidatorException(e.toString());
}
}
/**
* Converts a List of parameter class names into their Class objects.
* Stores the output in {@link #parameterClasses}. This
* array is in the same order as the given List and is suitable for passing
* to the validation method.
* @throws ValidatorException if a class cannot be loaded.
*/
private void loadParameterClasses(final ClassLoader loader)
throws ValidatorException {
if (this.parameterClasses != null) {
return;
}
final Class<?>[] parameterClasses = new Class[this.methodParameterList.size()];
for (int i = 0; i < this.methodParameterList.size(); i++) {
final String paramClassName = this.methodParameterList.get(i);
try {
parameterClasses[i] = loader.loadClass(paramClassName);
} catch (final ClassNotFoundException e) {
throw new ValidatorException(e.getMessage());
}
}
this.parameterClasses = parameterClasses;
}
/**
* Converts a List of parameter class names into their values contained in
* the parameters Map.
* @param params A Map of class names to parameter values.
* @return An array containing the value object for each parameter. This
* array is in the same order as the given List and is suitable for passing
* to the validation method.
*/
private Object[] getParameterValues(final Map<String, ? super Object> params) {
final Object[] paramValue = new Object[this.methodParameterList.size()];
for (int i = 0; i < this.methodParameterList.size(); i++) {
final String paramClassName = this.methodParameterList.get(i);
paramValue[i] = params.get(paramClassName);
}
return paramValue;
}
/**
* Return an instance of the validation class or null if the validation
* method is static so does not require an instance to be executed.
*/
private Object getValidationClassInstance() throws ValidatorException {
if (Modifier.isStatic(this.validationMethod.getModifiers())) {
this.instance = null;
} else if (this.instance == null) {
try {
this.instance = this.validationClass.getConstructor().newInstance();
} catch (ReflectiveOperationException e) {
final String msg1 =
"Couldn't create instance of "
+ this.className
+ ". "
+ e.getMessage();
throw new ValidatorException(msg1);
}
}
return this.instance;
}
/**
* Modifies the paramValue array with indexed fields.
*
* @param field
* @param pos
* @param paramValues
*/
private void handleIndexedField(final Field field, final int pos, final Object[] paramValues)
throws ValidatorException {
final int beanIndex = this.methodParameterList.indexOf(Validator.BEAN_PARAM);
final int fieldIndex = this.methodParameterList.indexOf(Validator.FIELD_PARAM);
final Object[] indexedList = field.getIndexedProperty(paramValues[beanIndex]);
// Set current iteration object to the parameter array
paramValues[beanIndex] = indexedList[pos];
// Set field clone with the key modified to represent
// the current field
final Field indexedField = (Field) field.clone();
indexedField.setKey(
ValidatorUtils.replace(
indexedField.getKey(),
Field.TOKEN_INDEXED,
"[" + pos + "]"));
paramValues[fieldIndex] = indexedField;
}
/**
* If the result object is a <code>Boolean</code>, it will return its
* value. If not it will return {@code false} if the object is
* <code>null</code> and {@code true} if it isn't.
*/
private boolean isValid(final Object result) {
if (result instanceof Boolean) {
final Boolean valid = (Boolean) result;
return valid.booleanValue();
}
return result != null;
}
/**
* Returns the ClassLoader set in the Validator contained in the parameter
* Map.
*/
private ClassLoader getClassLoader(final Map<String, Object> params) {
final Validator v = (Validator) params.get(Validator.VALIDATOR_PARAM);
return v.getClassLoader();
}
/**
* Returns the onlyReturnErrors setting in the Validator contained in the
* parameter Map.
*/
private boolean onlyReturnErrors(final Map<String, Object> params) {
final Validator v = (Validator) params.get(Validator.VALIDATOR_PARAM);
return v.getOnlyReturnErrors();
}
/**
* Accessor method for Log instance.
*
* The Log instance variable is transient and
* accessing it through this method ensures it
* is re-initialized when this instance is
* de-serialized.
*
* @return The Log instance.
*/
private Log getLog() {
if (log == null) {
log = LogFactory.getLog(ValidatorAction.class);
}
return log;
}
}
| 7,965 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/Var.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import java.io.Serializable;
/**
* A variable that can be associated with a <code>Field</code> for
* passing in information to a pluggable validator. Instances of this class are
* configured with a <var> xml element.
*/
public class Var implements Cloneable, Serializable {
private static final long serialVersionUID = -684185211548420224L;
/**
* Int Constant for JavaScript type. This can be used
* when auto-generating JavaScript.
*/
public static final String JSTYPE_INT = "int";
/**
* String Constant for JavaScript type. This can be used
* when auto-generating JavaScript.
*/
public static final String JSTYPE_STRING = "string";
/**
* Regular Expression Constant for JavaScript type. This can be used
* when auto-generating JavaScript.
*/
public static final String JSTYPE_REGEXP = "regexp";
/**
* The name of the variable.
*/
private String name;
/**
* The key or value the variable.
*/
private String value;
/**
* The optional JavaScript type of the variable.
*/
private String jsType;
/**
* Whether the variable is a resource [false]
*/
private boolean resource;
/**
* The bundle for a variable (when resource = 'true').
*/
private String bundle;
/**
* Default Constructor.
*/
public Var() {
}
/**
* Constructs a variable with a specified name, value
* and Javascript type.
* @param name Variable name.
* @param value Variable value.
* @param jsType Variable Javascript type.
*/
public Var(final String name, final String value, final String jsType) {
this.name = name;
this.value = value;
this.jsType = jsType;
}
/**
* Gets the name of the variable.
* @return The name of the variable.
*/
public String getName() {
return this.name;
}
/**
* Sets the name of the variable.
* @param name The name of the variable.
*/
public void setName(final String name) {
this.name = name;
}
/**
* Gets the value of the variable.
* @return The value of the variable.
*/
public String getValue() {
return this.value;
}
/**
* Sets the value of the variable.
* @param value The value of the variable.
*/
public void setValue(final String value) {
this.value = value;
}
/**
* Tests whether or not the value is a resource key or literal value.
* @return {@code true} if value is a resource key.
* @since 1.2.0
*/
public boolean isResource() {
return this.resource;
}
/**
* Sets whether or not the value is a resource.
* @param resource If true indicates the value is a resource.
* @since 1.2.0
*/
public void setResource(final boolean resource) {
this.resource = resource;
}
/**
* Returns the resource bundle name.
* @return The bundle name.
* @since 1.2.0
*/
public String getBundle() {
return this.bundle;
}
/**
* Sets the resource bundle name.
* @param bundle The new bundle name.
* @since 1.2.0
*/
public void setBundle(final String bundle) {
this.bundle = bundle;
}
/**
* Gets the JavaScript type of the variable.
* @return The Javascript type of the variable.
*/
public String getJsType() {
return this.jsType;
}
/**
* Sets the JavaScript type of the variable.
* @param jsType The Javascript type of the variable.
*/
public void setJsType(final String jsType) {
this.jsType = jsType;
}
/**
* Creates and returns a copy of this object.
* @return A copy of the variable.
*/
@Override
public Object clone() {
try {
return super.clone();
} catch (final CloneNotSupportedException e) {
throw new UnsupportedOperationException(e.toString(), e);
}
}
/**
* Returns a string representation of the object.
* @return A string representation of the variable.
*/
@Override
public String toString() {
final StringBuilder results = new StringBuilder();
results.append("Var: name=");
results.append(name);
results.append(" value=");
results.append(value);
results.append(" resource=");
results.append(resource);
if (resource) {
results.append(" bundle=");
results.append(bundle);
}
results.append(" jsType=");
results.append(jsType);
results.append("\n");
return results.toString();
}
} | 7,966 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/GenericTypeValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* This class contains basic methods for performing validations that return the
* correctly typed class based on the validation performed.
*/
public class GenericTypeValidator implements Serializable {
private static final long serialVersionUID = 5487162314134261703L;
private static final Log LOG = LogFactory.getLog(GenericTypeValidator.class);
/**
* Checks if the value can safely be converted to a byte primitive.
*
* @param value The value validation is being performed on.
* @return the converted Byte value.
*/
public static Byte formatByte(final String value) {
if (value == null) {
return null;
}
try {
return Byte.valueOf(value);
} catch (final NumberFormatException e) {
return null;
}
}
/**
* Checks if the value can safely be converted to a byte primitive.
*
* @param value The value validation is being performed on.
* @param locale The locale to use to parse the number (system default if
* null)
* @return the converted Byte value.
*/
public static Byte formatByte(final String value, final Locale locale) {
Byte result = null;
if (value != null) {
NumberFormat formatter = null;
if (locale != null) {
formatter = NumberFormat.getNumberInstance(locale);
} else {
formatter = NumberFormat.getNumberInstance(Locale.getDefault());
}
formatter.setParseIntegerOnly(true);
final ParsePosition pos = new ParsePosition(0);
final Number num = formatter.parse(value, pos);
// If there was no error and we used the whole string
if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length() &&
num.doubleValue() >= Byte.MIN_VALUE &&
num.doubleValue() <= Byte.MAX_VALUE) {
result = Byte.valueOf(num.byteValue());
}
}
return result;
}
/**
* Checks if the value can safely be converted to a short primitive.
*
* @param value The value validation is being performed on.
* @return the converted Short value.
*/
public static Short formatShort(final String value) {
if (value == null) {
return null;
}
try {
return Short.valueOf(value);
} catch (final NumberFormatException e) {
return null;
}
}
/**
* Checks if the value can safely be converted to a short primitive.
*
* @param value The value validation is being performed on.
* @param locale The locale to use to parse the number (system default if
* null)
* @return the converted Short value.
*/
public static Short formatShort(final String value, final Locale locale) {
Short result = null;
if (value != null) {
NumberFormat formatter = null;
if (locale != null) {
formatter = NumberFormat.getNumberInstance(locale);
} else {
formatter = NumberFormat.getNumberInstance(Locale.getDefault());
}
formatter.setParseIntegerOnly(true);
final ParsePosition pos = new ParsePosition(0);
final Number num = formatter.parse(value, pos);
// If there was no error and we used the whole string
if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length() &&
num.doubleValue() >= Short.MIN_VALUE &&
num.doubleValue() <= Short.MAX_VALUE) {
result = Short.valueOf(num.shortValue());
}
}
return result;
}
/**
* Checks if the value can safely be converted to a int primitive.
*
* @param value The value validation is being performed on.
* @return the converted Integer value.
*/
public static Integer formatInt(final String value) {
if (value == null) {
return null;
}
try {
return Integer.valueOf(value);
} catch (final NumberFormatException e) {
return null;
}
}
/**
* Checks if the value can safely be converted to an int primitive.
*
* @param value The value validation is being performed on.
* @param locale The locale to use to parse the number (system default if
* null)
* @return the converted Integer value.
*/
public static Integer formatInt(final String value, final Locale locale) {
Integer result = null;
if (value != null) {
NumberFormat formatter = null;
if (locale != null) {
formatter = NumberFormat.getNumberInstance(locale);
} else {
formatter = NumberFormat.getNumberInstance(Locale.getDefault());
}
formatter.setParseIntegerOnly(true);
final ParsePosition pos = new ParsePosition(0);
final Number num = formatter.parse(value, pos);
// If there was no error and we used the whole string
if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length() &&
num.doubleValue() >= Integer.MIN_VALUE &&
num.doubleValue() <= Integer.MAX_VALUE) {
result = Integer.valueOf(num.intValue());
}
}
return result;
}
/**
* Checks if the value can safely be converted to a long primitive.
*
* @param value The value validation is being performed on.
* @return the converted Long value.
*/
public static Long formatLong(final String value) {
if (value == null) {
return null;
}
try {
return Long.valueOf(value);
} catch (final NumberFormatException e) {
return null;
}
}
/**
* Checks if the value can safely be converted to a long primitive.
*
* @param value The value validation is being performed on.
* @param locale The locale to use to parse the number (system default if
* null)
* @return the converted Long value.
*/
public static Long formatLong(final String value, final Locale locale) {
Long result = null;
if (value != null) {
NumberFormat formatter = null;
if (locale != null) {
formatter = NumberFormat.getNumberInstance(locale);
} else {
formatter = NumberFormat.getNumberInstance(Locale.getDefault());
}
formatter.setParseIntegerOnly(true);
final ParsePosition pos = new ParsePosition(0);
final Number num = formatter.parse(value, pos);
// If there was no error and we used the whole string
if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length() &&
num.doubleValue() >= Long.MIN_VALUE &&
num.doubleValue() <= Long.MAX_VALUE) {
result = Long.valueOf(num.longValue());
}
}
return result;
}
/**
* Checks if the value can safely be converted to a float primitive.
*
* @param value The value validation is being performed on.
* @return the converted Float value.
*/
public static Float formatFloat(final String value) {
if (value == null) {
return null;
}
try {
return Float.valueOf(value);
} catch (final NumberFormatException e) {
return null;
}
}
/**
* Checks if the value can safely be converted to a float primitive.
*
* @param value The value validation is being performed on.
* @param locale The locale to use to parse the number (system default if
* null)
* @return the converted Float value.
*/
public static Float formatFloat(final String value, final Locale locale) {
Float result = null;
if (value != null) {
NumberFormat formatter = null;
if (locale != null) {
formatter = NumberFormat.getInstance(locale);
} else {
formatter = NumberFormat.getInstance(Locale.getDefault());
}
final ParsePosition pos = new ParsePosition(0);
final Number num = formatter.parse(value, pos);
// If there was no error and we used the whole string
if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length() &&
num.doubleValue() >= Float.MAX_VALUE * -1 &&
num.doubleValue() <= Float.MAX_VALUE) {
result = Float.valueOf(num.floatValue());
}
}
return result;
}
/**
* Checks if the value can safely be converted to a double primitive.
*
* @param value The value validation is being performed on.
* @return the converted Double value.
*/
public static Double formatDouble(final String value) {
if (value == null) {
return null;
}
try {
return Double.valueOf(value);
} catch (final NumberFormatException e) {
return null;
}
}
/**
* Checks if the value can safely be converted to a double primitive.
*
* @param value The value validation is being performed on.
* @param locale The locale to use to parse the number (system default if
* null)
* @return the converted Double value.
*/
public static Double formatDouble(final String value, final Locale locale) {
Double result = null;
if (value != null) {
NumberFormat formatter = null;
if (locale != null) {
formatter = NumberFormat.getInstance(locale);
} else {
formatter = NumberFormat.getInstance(Locale.getDefault());
}
final ParsePosition pos = new ParsePosition(0);
final Number num = formatter.parse(value, pos);
// If there was no error and we used the whole string
if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length() &&
num.doubleValue() >= Double.MAX_VALUE * -1 &&
num.doubleValue() <= Double.MAX_VALUE) {
result = Double.valueOf(num.doubleValue());
}
}
return result;
}
/**
* Checks if the field is a valid date.
*
* <p>The {@code Locale} is used with {@code java.text.DateFormat}. The {@link java.text.DateFormat#setLenient(boolean)}
* method is set to {@code false} for all.
* </p>
*
* @param value The value validation is being performed on.
* @param locale The Locale to use to parse the date (system default if null)
* @return the converted Date value.
*/
public static Date formatDate(final String value, final Locale locale) {
Date date = null;
if (value == null) {
return null;
}
try {
// Get the formatters to check against
DateFormat formatterShort = null;
DateFormat formatterDefault = null;
if (locale != null) {
formatterShort =
DateFormat.getDateInstance(DateFormat.SHORT, locale);
formatterDefault =
DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
} else {
formatterShort =
DateFormat.getDateInstance(
DateFormat.SHORT,
Locale.getDefault());
formatterDefault =
DateFormat.getDateInstance(
DateFormat.DEFAULT,
Locale.getDefault());
}
// Turn off lenient parsing
formatterShort.setLenient(false);
formatterDefault.setLenient(false);
// Firstly, try with the short form
try {
date = formatterShort.parse(value);
} catch (final ParseException e) {
// Fall back on the default one
date = formatterDefault.parse(value);
}
} catch (final ParseException e) {
// Bad date, so LOG and return null
if (LOG.isDebugEnabled()) {
LOG.debug("Date parse failed value=[" + value + "], " +
"locale=[" + locale + "] " + e);
}
}
return date;
}
/**
* Checks if the field is a valid date.
*
* <p>The pattern is used with {@code java.text.SimpleDateFormat}.
* If strict is true, then the length will be checked so '2/12/1999' will
* not pass validation with the format 'MM/dd/yyyy' because the month isn't
* two digits. The {@link java.text.SimpleDateFormat#setLenient(boolean)}
* method is set to {@code false} for all.
* </p>
*
* @param value The value validation is being performed on.
* @param datePattern The pattern passed to {@code SimpleDateFormat}.
* @param strict Whether or not to have an exact match of the
* datePattern.
* @return the converted Date value.
*/
public static Date formatDate(final String value, final String datePattern, final boolean strict) {
Date date = null;
if (value == null
|| datePattern == null
|| datePattern.isEmpty()) {
return null;
}
try {
final SimpleDateFormat formatter = new SimpleDateFormat(datePattern);
formatter.setLenient(false);
date = formatter.parse(value);
if (strict && datePattern.length() != value.length()) {
date = null;
}
} catch (final ParseException e) {
// Bad date so return null
if (LOG.isDebugEnabled()) {
LOG.debug("Date parse failed value=[" + value + "], " +
"pattern=[" + datePattern + "], " +
"strict=[" + strict + "] " + e);
}
}
return date;
}
/**
* Checks if the field is a valid credit card number.
*
* <p>Reference Sean M. Burke's <a href="http://www.ling.nwu.edu/~sburke/pub/luhn_lib.pl">
* script</a>.</p>
*
* @param value The value validation is being performed on.
* @return the converted Credit Card number.
*/
public static Long formatCreditCard(final String value) {
return GenericValidator.isCreditCard(value) ? Long.valueOf(value) : null;
}
}
| 7,967 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/ValidatorResults.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* This contains the results of a set of validation rules processed
* on a JavaBean.
*/
//TODO mutable non-private fields
public class ValidatorResults implements Serializable {
private static final long serialVersionUID = -2709911078904924839L;
/**
* Map of validation results.
*/
protected Map<String, ValidatorResult> hResults = new HashMap<>();
/**
* Merge another ValidatorResults into mine.
*
* @param results ValidatorResults to merge.
*/
public void merge(final ValidatorResults results) {
this.hResults.putAll(results.hResults);
}
/**
* Add a the result of a validator action.
*
* @param field The field validated.
* @param validatorName The name of the validator.
* @param result The result of the validation.
*/
public void add(final Field field, final String validatorName, final boolean result) {
this.add(field, validatorName, result, null);
}
/**
* Add a the result of a validator action.
*
* @param field The field validated.
* @param validatorName The name of the validator.
* @param result The result of the validation.
* @param value The value returned by the validator.
*/
public void add(
final Field field,
final String validatorName,
final boolean result,
final Object value) {
ValidatorResult validatorResult = this.getValidatorResult(field.getKey());
if (validatorResult == null) {
validatorResult = new ValidatorResult(field);
this.hResults.put(field.getKey(), validatorResult);
}
validatorResult.add(validatorName, result, value);
}
/**
* Clear all results recorded by this object.
*/
public void clear() {
this.hResults.clear();
}
/**
* Return {@code true} if there are no messages recorded
* in this collection, or {@code false} otherwise.
*
* @return Whether these results are empty.
*/
public boolean isEmpty() {
return this.hResults.isEmpty();
}
/**
* Gets the <code>ValidatorResult</code> associated
* with the key passed in. The key the <code>ValidatorResult</code>
* is stored under is the <code>Field</code>'s getKey method.
*
* @param key The key generated from <code>Field</code> (this is often just
* the field name).
*
* @return The result of a specified key.
*/
public ValidatorResult getValidatorResult(final String key) {
return this.hResults.get(key);
}
/**
* Return the set of property names for which at least one message has
* been recorded.
* @return An unmodifiable Set of the property names.
*/
public Set<String> getPropertyNames() {
return Collections.unmodifiableSet(this.hResults.keySet());
}
/**
* Gets a <code>Map</code> of any <code>Object</code>s returned from
* validation routines.
*
* @return Map of objections returned by validators.
*/
public Map<String, Object> getResultValueMap() {
final Map<String, Object> results = new HashMap<>();
for (final String propertyKey : hResults.keySet()) {
final ValidatorResult vr = this.getValidatorResult(propertyKey);
for (final Iterator<String> x = vr.getActions(); x.hasNext();) {
final String actionKey = x.next();
final Object result = vr.getResult(actionKey);
if (result != null && !(result instanceof Boolean)) {
results.put(propertyKey, result);
}
}
}
return results;
}
}
| 7,968 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/EmailValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.validator.routines.InetAddressValidator;
/**
* <p>Perform email validations.</p>
* <p>
* This class is a Singleton; you can retrieve the instance via the getInstance() method.
* </p>
* <p>
* Based on a script by <a href="mailto:stamhankar@hotmail.com">Sandeep V. Tamhankar</a>
* http://javascript.internet.com
* </p>
* <p>
* This implementation is not guaranteed to catch all possible errors in an email address.
* For example, an address like nobody@noplace.somedog will pass validator, even though there
* is no TLD "somedog"
* </p>.
*
* @since 1.1
* @deprecated Use the new EmailValidator in the routines package. This class
* will be removed in a future release.
*/
@Deprecated
public class EmailValidator {
private static final String SPECIAL_CHARS = "\\p{Cntrl}\\(\\)<>@,;:'\\\\\\\"\\.\\[\\]";
private static final String VALID_CHARS = "[^\\s" + SPECIAL_CHARS + "]";
private static final String QUOTED_USER = "(\"[^\"]*\")";
private static final String ATOM = VALID_CHARS + '+';
private static final String WORD = "((" + VALID_CHARS + "|')+|" + QUOTED_USER + ")";
// NOT USED private static final Pattern LEGAL_ASCII_PATTERN = Pattern.compile("^\\p{ASCII}+$");
// NOT USED private static final Pattern EMAIL_PATTERN = Pattern.compile("^(.+)@(.+)$");
private static final Pattern IP_DOMAIN_PATTERN = Pattern.compile("^\\[(.*)\\]$");
private static final Pattern TLD_PATTERN = Pattern.compile("^([a-zA-Z]+)$");
private static final Pattern USER_PATTERN = Pattern.compile("^\\s*" + WORD + "(\\." + WORD + ")*$");
private static final Pattern DOMAIN_PATTERN = Pattern.compile("^" + ATOM + "(\\." + ATOM + ")*\\s*$");
private static final Pattern ATOM_PATTERN = Pattern.compile("(" + ATOM + ")");
/**
* Singleton instance of this class.
*/
private static final EmailValidator EMAIL_VALIDATOR = new EmailValidator();
/**
* Returns the Singleton instance of this validator.
* @return singleton instance of this validator.
*/
public static EmailValidator getInstance() {
return EMAIL_VALIDATOR;
}
/**
* Protected constructor for subclasses to use.
*/
protected EmailValidator() {
}
/**
* <p>Checks if a field has a valid e-mail address.</p>
*
* @param email The value validation is being performed on. A <code>null</code>
* value is considered invalid.
* @return true if the email address is valid.
*/
public boolean isValid(final String email) {
return org.apache.commons.validator.routines.EmailValidator.getInstance().isValid(email);
}
/**
* Returns true if the domain component of an email address is valid.
* @param domain being validated.
* @return true if the email address's domain is valid.
*/
protected boolean isValidDomain(final String domain) {
boolean symbolic = false;
// see if domain is an IP address in brackets
final Matcher ipDomainMatcher = IP_DOMAIN_PATTERN.matcher(domain);
if (ipDomainMatcher.matches()) {
final InetAddressValidator inetAddressValidator =
InetAddressValidator.getInstance();
if (inetAddressValidator.isValid(ipDomainMatcher.group(1))) {
return true;
}
} else {
// Domain is symbolic name
symbolic = DOMAIN_PATTERN.matcher(domain).matches();
}
if (!symbolic) {
return false;
}
if (!isValidSymbolicDomain(domain)) {
return false;
}
return true;
}
/**
* Returns true if the user component of an email address is valid.
* @param user being validated
* @return true if the user name is valid.
*/
protected boolean isValidUser(final String user) {
return USER_PATTERN.matcher(user).matches();
}
/**
* Validates an IP address. Returns true if valid.
* @param ipAddress IP address
* @return true if the ip address is valid.
*/
protected boolean isValidIpAddress(final String ipAddress) {
final Matcher ipAddressMatcher = IP_DOMAIN_PATTERN.matcher(ipAddress);
for (int i = 1; i <= 4; i++) { // CHECKSTYLE IGNORE MagicNumber
final String ipSegment = ipAddressMatcher.group(i);
if (ipSegment == null || ipSegment.isEmpty()) {
return false;
}
int iIpSegment = 0;
try {
iIpSegment = Integer.parseInt(ipSegment);
} catch (final NumberFormatException e) {
return false;
}
if (iIpSegment > 255) { // CHECKSTYLE IGNORE MagicNumber
return false;
}
}
return true;
}
/**
* Validates a symbolic domain name. Returns true if it's valid.
* @param domain symbolic domain name
* @return true if the symbolic domain name is valid.
*/
protected boolean isValidSymbolicDomain(String domain) {
final String[] domainSegment = new String[10]; // CHECKSTYLE IGNORE MagicNumber
boolean match = true;
int i = 0;
final Matcher atomMatcher = ATOM_PATTERN.matcher(domain);
while (match) {
match = atomMatcher.matches();
if (match) {
domainSegment[i] = atomMatcher.group(1);
final int l = domainSegment[i].length() + 1;
domain =
l >= domain.length()
? ""
: domain.substring(l);
i++;
}
}
final int len = i;
// Make sure there's a host name preceding the domain.
if (len < 2) {
return false;
}
final String tld = domainSegment[len - 1];
if (tld.length() <= 1) {
return false;
}
if (! TLD_PATTERN.matcher(tld).matches()) {
return false;
}
return true;
}
/**
* Recursively remove comments, and replace with a single space. The simpler
* regexps in the Email Addressing FAQ are imperfect - they will miss escaped
* chars in atoms, for example.
* Derived From Mail::RFC822::Address
* @param emailStr The email address
* @return address with comments removed.
*/
protected String stripComments(final String emailStr) {
String result = emailStr;
final String commentPat = "^((?:[^\"\\\\]|\\\\.)*(?:\"(?:[^\"\\\\]|\\\\.)*\"(?:[^\"\\\\]|\111111\\\\.)*)*)\\((?:[^()\\\\]|\\\\.)*\\)/";
final Pattern commentMatcher = Pattern.compile(commentPat);
while (commentMatcher.matcher(result).matches()) {
result = result.replaceFirst(commentPat, "\1 ");
}
return result;
}
}
| 7,969 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/UrlValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.validator.routines.InetAddressValidator;
import org.apache.commons.validator.util.Flags;
/**
* <p>Validates URLs.</p>
* Behavour of validation is modified by passing in options:
* <ul>
* <li>ALLOW_2_SLASHES - [FALSE] Allows double '/' characters in the path
* component.</li>
* <li>NO_FRAGMENT- [FALSE] By default fragments are allowed, if this option is
* included then fragments are flagged as illegal.</li>
* <li>ALLOW_ALL_SCHEMES - [FALSE] By default only http, https, and ftp are
* considered valid schemes. Enabling this option will let any scheme pass validation.</li>
* </ul>
*
* <p>Originally based in on php script by Debbie Dyer, validation.php v1.2b, Date: 03/07/02,
* http://javascript.internet.com. However, this validation now bears little resemblance
* to the php original.</p>
* <pre>
* Example of usage:
* Construct a UrlValidator with valid schemes of "http", and "https".
*
* String[] schemes = {"http","https"}.
* UrlValidator urlValidator = new UrlValidator(schemes);
* if (urlValidator.isValid("ftp://foo.bar.com/")) {
* System.out.println("URL is valid");
* } else {
* System.out.println("URL is invalid");
* }
*
* prints "URL is invalid"
* If instead the default constructor is used.
*
* UrlValidator urlValidator = new UrlValidator();
* if (urlValidator.isValid("ftp://foo.bar.com/")) {
* System.out.println("URL is valid");
* } else {
* System.out.println("URL is invalid");
* }
*
* prints out "URL is valid"
* </pre>
*
* @see
* <a href="http://www.ietf.org/rfc/rfc2396.txt">
* Uniform Resource Identifiers (URI): Generic Syntax
* </a>
*
* @since 1.1
* @deprecated Use the new UrlValidator in the routines package. This class
* will be removed in a future release.
*/
@Deprecated
public class UrlValidator implements Serializable {
private static final long serialVersionUID = 24137157400029593L;
/**
* Allows all validly formatted schemes to pass validation instead of
* supplying a set of valid schemes.
*/
public static final int ALLOW_ALL_SCHEMES = 1 << 0;
/**
* Allow two slashes in the path component of the URL.
*/
public static final int ALLOW_2_SLASHES = 1 << 1;
/**
* Enabling this options disallows any URL fragments.
*/
public static final int NO_FRAGMENTS = 1 << 2;
private static final String ALPHA_CHARS = "a-zA-Z";
// NOT USED private static final String ALPHA_NUMERIC_CHARS = ALPHA_CHARS + "\\d";
private static final String SPECIAL_CHARS = ";/@&=,.?:+$";
private static final String VALID_CHARS = "[^\\s" + SPECIAL_CHARS + "]";
// Drop numeric, and "+-." for now
private static final String AUTHORITY_CHARS_REGEX = "\\p{Alnum}\\-\\.";
private static final String ATOM = VALID_CHARS + '+';
/**
* This expression derived/taken from the BNF for URI (RFC2396).
*/
private static final String URL_REGEX =
"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?";
// 12 3 4 5 6 7 8 9
private static final Pattern URL_PATTERN = Pattern.compile(URL_REGEX);
/**
* Schema/Protocol (ie. http:, ftp:, file:, etc).
*/
private static final int PARSE_URL_SCHEME = 2;
/**
* Includes hostname/ip and port number.
*/
private static final int PARSE_URL_AUTHORITY = 4;
private static final int PARSE_URL_PATH = 5;
private static final int PARSE_URL_QUERY = 7;
private static final int PARSE_URL_FRAGMENT = 9;
/**
* Protocol (ie. http:, ftp:,https:).
*/
private static final Pattern SCHEME_PATTERN = Pattern.compile("^\\p{Alpha}[\\p{Alnum}\\+\\-\\.]*");
private static final String AUTHORITY_REGEX =
"^([" + AUTHORITY_CHARS_REGEX + "]*)(:\\d*)?(.*)?";
// 1 2 3 4
private static final Pattern AUTHORITY_PATTERN = Pattern.compile(AUTHORITY_REGEX);
private static final int PARSE_AUTHORITY_HOST_IP = 1;
private static final int PARSE_AUTHORITY_PORT = 2;
/**
* Should always be empty.
*/
private static final int PARSE_AUTHORITY_EXTRA = 3;
private static final Pattern PATH_PATTERN = Pattern.compile("^(/[-\\w:@&?=+,.!/~*'%$_;]*)?$");
private static final Pattern QUERY_PATTERN = Pattern.compile("^(.*)$");
private static final Pattern LEGAL_ASCII_PATTERN = Pattern.compile("^\\p{ASCII}+$");
private static final Pattern DOMAIN_PATTERN =
Pattern.compile("^" + ATOM + "(\\." + ATOM + ")*$");
private static final Pattern PORT_PATTERN = Pattern.compile("^:(\\d{1,5})$");
private static final Pattern ATOM_PATTERN = Pattern.compile("^(" + ATOM + ").*?$");
private static final Pattern ALPHA_PATTERN = Pattern.compile("^[" + ALPHA_CHARS + "]");
/**
* Holds the set of current validation options.
*/
private final Flags options;
/**
* The set of schemes that are allowed to be in a URL.
*/
private final Set<String> allowedSchemes = new HashSet<>();
/**
* If no schemes are provided, default to this set.
*/
protected String[] defaultSchemes = {"http", "https", "ftp"};
/**
* Create a UrlValidator with default properties.
*/
public UrlValidator() {
this(null);
}
/**
* Behavior of validation is modified by passing in several strings options:
* @param schemes Pass in one or more URL schemes to consider valid, passing in
* a null will default to "http,https,ftp" being valid.
* If a non-null schemes is specified then all valid schemes must
* be specified. Setting the ALLOW_ALL_SCHEMES option will
* ignore the contents of schemes.
*/
public UrlValidator(final String[] schemes) {
this(schemes, 0);
}
/**
* Initialize a UrlValidator with the given validation options.
* @param options The options should be set using the public constants declared in
* this class. To set multiple options you simply add them together. For example,
* ALLOW_2_SLASHES + NO_FRAGMENTS enables both of those options.
*/
public UrlValidator(final int options) {
this(null, options);
}
/**
* Behavour of validation is modified by passing in options:
* @param schemes The set of valid schemes.
* @param options The options should be set using the public constants declared in
* this class. To set multiple options you simply add them together. For example,
* ALLOW_2_SLASHES + NO_FRAGMENTS enables both of those options.
*/
public UrlValidator(String[] schemes, final int options) {
this.options = new Flags(options);
if (this.options.isOn(ALLOW_ALL_SCHEMES)) {
return;
}
if (schemes == null) {
schemes = this.defaultSchemes;
}
this.allowedSchemes.addAll(Arrays.asList(schemes));
}
/**
* <p>Checks if a field has a valid URL address.</p>
*
* @param value The value validation is being performed on. A <code>null</code>
* value is considered invalid.
* @return true if the URL is valid.
*/
public boolean isValid(final String value) {
if (value == null) {
return false;
}
if (!LEGAL_ASCII_PATTERN.matcher(value).matches()) {
return false;
}
// Check the whole url address structure
final Matcher urlMatcher = URL_PATTERN.matcher(value);
if (!urlMatcher.matches()) {
return false;
}
if (!isValidScheme(urlMatcher.group(PARSE_URL_SCHEME))) {
return false;
}
if (!isValidAuthority(urlMatcher.group(PARSE_URL_AUTHORITY))) {
return false;
}
if (!isValidPath(urlMatcher.group(PARSE_URL_PATH))) {
return false;
}
if (!isValidQuery(urlMatcher.group(PARSE_URL_QUERY))) {
return false;
}
if (!isValidFragment(urlMatcher.group(PARSE_URL_FRAGMENT))) {
return false;
}
return true;
}
/**
* Validate scheme. If schemes[] was initialized to a non null,
* then only those scheme's are allowed. Note this is slightly different
* than for the constructor.
* @param scheme The scheme to validate. A <code>null</code> value is considered
* invalid.
* @return true if valid.
*/
protected boolean isValidScheme(final String scheme) {
if (scheme == null) {
return false;
}
if (!SCHEME_PATTERN.matcher(scheme).matches()) {
return false;
}
if (options.isOff(ALLOW_ALL_SCHEMES) && !allowedSchemes.contains(scheme)) {
return false;
}
return true;
}
/**
* Returns true if the authority is properly formatted. An authority is the combination
* of hostname and port. A <code>null</code> authority value is considered invalid.
* @param authority Authority value to validate.
* @return true if authority (hostname and port) is valid.
*/
protected boolean isValidAuthority(final String authority) {
if (authority == null) {
return false;
}
final InetAddressValidator inetAddressValidator =
InetAddressValidator.getInstance();
final Matcher authorityMatcher = AUTHORITY_PATTERN.matcher(authority);
if (!authorityMatcher.matches()) {
return false;
}
boolean hostname = false;
// check if authority is IP address or hostname
String hostIP = authorityMatcher.group(PARSE_AUTHORITY_HOST_IP);
final boolean ipV4Address = inetAddressValidator.isValid(hostIP);
if (!ipV4Address) {
// Domain is hostname name
hostname = DOMAIN_PATTERN.matcher(hostIP).matches();
}
//rightmost hostname will never start with a digit.
if (hostname) {
// LOW-TECH FIX FOR VALIDATOR-202
// TODO: Rewrite to use ArrayList and .add semantics: see VALIDATOR-203
final char[] chars = hostIP.toCharArray();
int size = 1;
for (final char element : chars) {
if (element == '.') {
size++;
}
}
final String[] domainSegment = new String[size];
boolean match = true;
int segmentCount = 0;
int segmentLength = 0;
while (match) {
final Matcher atomMatcher = ATOM_PATTERN.matcher(hostIP);
match = atomMatcher.matches();
if (match) {
domainSegment[segmentCount] = atomMatcher.group(1);
segmentLength = domainSegment[segmentCount].length() + 1;
hostIP =
segmentLength >= hostIP.length()
? ""
: hostIP.substring(segmentLength);
segmentCount++;
}
}
final String topLevel = domainSegment[segmentCount - 1];
if (topLevel.length() < 2 || topLevel.length() > 4) { // CHECKSTYLE IGNORE MagicNumber (deprecated code)
return false;
}
// First letter of top level must be a alpha
if (!ALPHA_PATTERN.matcher(topLevel.substring(0, 1)).matches()) {
return false;
}
// Make sure there's a host name preceding the authority.
if (segmentCount < 2) {
return false;
}
}
if (!hostname && !ipV4Address) {
return false;
}
final String port = authorityMatcher.group(PARSE_AUTHORITY_PORT);
if (port != null && !PORT_PATTERN.matcher(port).matches()) {
return false;
}
final String extra = authorityMatcher.group(PARSE_AUTHORITY_EXTRA);
if (!GenericValidator.isBlankOrNull(extra)) {
return false;
}
return true;
}
/**
* Returns true if the path is valid. A <code>null</code> value is considered invalid.
* @param path Path value to validate.
* @return true if path is valid.
*/
protected boolean isValidPath(final String path) {
if (path == null) {
return false;
}
if (!PATH_PATTERN.matcher(path).matches()) {
return false;
}
final int slash2Count = countToken("//", path);
if (options.isOff(ALLOW_2_SLASHES) && slash2Count > 0) {
return false;
}
final int slashCount = countToken("/", path);
final int dot2Count = countToken("..", path);
if (dot2Count > 0 && slashCount - slash2Count - 1 <= dot2Count){
return false;
}
return true;
}
/**
* Returns true if the query is null or it's a properly formatted query string.
* @param query Query value to validate.
* @return true if query is valid.
*/
protected boolean isValidQuery(final String query) {
if (query == null) {
return true;
}
return QUERY_PATTERN.matcher(query).matches();
}
/**
* Returns true if the given fragment is null or fragments are allowed.
* @param fragment Fragment value to validate.
* @return true if fragment is valid.
*/
protected boolean isValidFragment(final String fragment) {
if (fragment == null) {
return true;
}
return options.isOff(NO_FRAGMENTS);
}
/**
* Returns the number of times the token appears in the target.
* @param token Token value to be counted.
* @param target Target value to count tokens in.
* @return the number of tokens.
*/
protected int countToken(final String token, final String target) {
int tokenIndex = 0;
int count = 0;
while (tokenIndex != -1) {
tokenIndex = target.indexOf(token, tokenIndex);
if (tokenIndex > -1) {
tokenIndex++;
count++;
}
}
return count;
}
}
| 7,970 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/ValidatorException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
/**
* The base exception for the Validator Framework. All other
* <code>Exception</code>s thrown during calls to
* <code>Validator.validate()</code> are considered errors.
*/
public class ValidatorException extends Exception {
private static final long serialVersionUID = 1025759372615616964L;
/**
* Constructs an Exception with no specified detail message.
*/
public ValidatorException() {
}
/**
* Constructs an Exception with the specified detail message.
*
* @param message The error message.
*/
public ValidatorException(final String message) {
super(message);
}
} | 7,971 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/Field.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.FastHashMap; // DEPRECATED
import org.apache.commons.validator.util.ValidatorUtils;
/**
* This contains the list of pluggable validators to run on a field and any
* message information and variables to perform the validations and generate
* error messages. Instances of this class are configured with a
* <field> xml element.
* <p>
* The use of FastHashMap is deprecated and will be replaced in a future
* release.
* </p>
*
* @see org.apache.commons.validator.Form
*/
// TODO mutable non-private fields
public class Field implements Cloneable, Serializable {
private static final long serialVersionUID = -8502647722530192185L;
/**
* This is the value that will be used as a key if the <code>Arg</code>
* name field has no value.
*/
private static final String DEFAULT_ARG =
"org.apache.commons.validator.Field.DEFAULT";
/**
* This indicates an indexed property is being referenced.
*/
public static final String TOKEN_INDEXED = "[]";
/**
* The start of a token.
*/
protected static final String TOKEN_START = "${";
/**
* The end of a token.
*/
protected static final String TOKEN_END = "}";
/**
* A Vriable token.
*/
protected static final String TOKEN_VAR = "var:";
/**
* The Field's property name.
*/
protected String property;
/**
* The Field's indexed property name.
*/
protected String indexedProperty;
/**
* The Field's indexed list property name.
*/
protected String indexedListProperty;
/**
* The Field's unique key.
*/
protected String key;
/**
* A comma separated list of validator's this field depends on.
*/
protected String depends;
/**
* The Page Number
*/
protected int page;
/**
* The flag that indicates whether scripting should be generated
* by the client for client-side validation.
* @since 1.4
*/
protected boolean clientValidation = true;
/**
* The order of the Field in the Form.
*/
protected int fieldOrder;
/**
* Internal representation of this.depends String as a List. This List
* gets updated whenever setDepends() gets called. This List is
* synchronized so a call to setDepends() (which clears the List) won't
* interfere with a call to isDependency().
*/
private final List<String> dependencyList = Collections.synchronizedList(new ArrayList<>());
/**
* @deprecated Subclasses should use getVarMap() instead.
*/
@Deprecated
protected FastHashMap hVars = new FastHashMap(); // <String, Var>
/**
* @deprecated Subclasses should use getMsgMap() instead.
*/
@Deprecated
protected FastHashMap hMsgs = new FastHashMap(); // <String, Msg>
/**
* Holds Maps of arguments. args[0] returns the Map for the first
* replacement argument. Start with a 0 length array so that it will
* only grow to the size of the highest argument position.
* @since 1.1
*/
@SuppressWarnings("unchecked") // cannot instantiate generic array, so have to assume this is OK
protected Map<String, Arg>[] args = new Map[0];
/**
* Gets the page value that the Field is associated with for
* validation.
* @return The page number.
*/
public int getPage() {
return this.page;
}
/**
* Sets the page value that the Field is associated with for
* validation.
* @param page The page number.
*/
public void setPage(final int page) {
this.page = page;
}
/**
* Gets the position of the <code>Field</code> in the validation list.
* @return The field position.
*/
public int getFieldOrder() {
return this.fieldOrder;
}
/**
* Sets the position of the <code>Field</code> in the validation list.
* @param fieldOrder The field position.
*/
public void setFieldOrder(final int fieldOrder) {
this.fieldOrder = fieldOrder;
}
/**
* Gets the property name of the field.
* @return The field's property name.
*/
public String getProperty() {
return this.property;
}
/**
* Sets the property name of the field.
* @param property The field's property name.
*/
public void setProperty(final String property) {
this.property = property;
}
/**
* Gets the indexed property name of the field. This
* is the method name that can take an <code>int</code> as
* a parameter for indexed property value retrieval.
* @return The field's indexed property name.
*/
public String getIndexedProperty() {
return this.indexedProperty;
}
/**
* Sets the indexed property name of the field.
* @param indexedProperty The field's indexed property name.
*/
public void setIndexedProperty(final String indexedProperty) {
this.indexedProperty = indexedProperty;
}
/**
* Gets the indexed property name of the field. This
* is the method name that will return an array or a
* <code>Collection</code> used to retrieve the
* list and then loop through the list performing the specified
* validations.
* @return The field's indexed List property name.
*/
public String getIndexedListProperty() {
return this.indexedListProperty;
}
/**
* Sets the indexed property name of the field.
* @param indexedListProperty The field's indexed List property name.
*/
public void setIndexedListProperty(final String indexedListProperty) {
this.indexedListProperty = indexedListProperty;
}
/**
* Gets the validation rules for this field as a comma separated list.
* @return A comma separated list of validator names.
*/
public String getDepends() {
return this.depends;
}
/**
* Sets the validation rules for this field as a comma separated list.
* @param depends A comma separated list of validator names.
*/
public void setDepends(final String depends) {
this.depends = depends;
this.dependencyList.clear();
final StringTokenizer st = new StringTokenizer(depends, ",");
while (st.hasMoreTokens()) {
final String depend = st.nextToken().trim();
if (depend != null && !depend.isEmpty()) {
this.dependencyList.add(depend);
}
}
}
/**
* Add a <code>Msg</code> to the <code>Field</code>.
* @param msg A validation message.
*/
public void addMsg(final Msg msg) {
getMsgMap().put(msg.getName(), msg);
}
/**
* Retrieve a message value.
* @param key Validation key.
* @return A validation message for a specified validator.
*/
public String getMsg(final String key) {
final Msg msg = getMessage(key);
return msg == null ? null : msg.getKey();
}
/**
* Retrieve a message object.
* @since 1.1.4
* @param key Validation key.
* @return A validation message for a specified validator.
*/
public Msg getMessage(final String key) {
return getMsgMap().get(key);
}
/**
* The <code>Field</code>'s messages are returned as an
* unmodifiable <code>Map</code>.
* @since 1.1.4
* @return Map of validation messages for the field.
*/
public Map<String, Msg> getMessages() {
return Collections.unmodifiableMap(getMsgMap());
}
/**
* Determines whether client-side scripting should be generated
* for this field. The default is {@code true}
* @return {@code true} for scripting; otherwise false
* @see #setClientValidation(boolean)
* @since 1.4
*/
public boolean isClientValidation() {
return this.clientValidation;
}
/**
* Sets the flag that determines whether client-side scripting should
* be generated for this field.
* @param clientValidation the scripting flag
* @see #isClientValidation()
* @since 1.4
*/
public void setClientValidation(final boolean clientValidation) {
this.clientValidation = clientValidation;
}
/**
* Add an <code>Arg</code> to the replacement argument list.
* @since 1.1
* @param arg Validation message's argument.
*/
public void addArg(final Arg arg) {
// TODO this first if check can go away after arg0, etc. are removed from dtd
if (arg == null || arg.getKey() == null || arg.getKey().isEmpty()) {
return;
}
determineArgPosition(arg);
ensureArgsCapacity(arg);
Map<String, Arg> argMap = this.args[arg.getPosition()];
if (argMap == null) {
argMap = new HashMap<>();
this.args[arg.getPosition()] = argMap;
}
if (arg.getName() == null) {
argMap.put(DEFAULT_ARG, arg);
} else {
argMap.put(arg.getName(), arg);
}
}
/**
* Calculate the position of the Arg
*/
private void determineArgPosition(final Arg arg) {
final int position = arg.getPosition();
// position has been explicity set
if (position >= 0) {
return;
}
// first arg to be added
if (args == null || args.length == 0) {
arg.setPosition(0);
return;
}
// determine the position of the last argument with
// the same name or the last default argument
final String keyName = arg.getName() == null ? DEFAULT_ARG : arg.getName();
int lastPosition = -1;
int lastDefault = -1;
for (int i = 0; i < args.length; i++) {
if (args[i] != null && args[i].containsKey(keyName)) {
lastPosition = i;
}
if (args[i] != null && args[i].containsKey(DEFAULT_ARG)) {
lastDefault = i;
}
}
if (lastPosition < 0) {
lastPosition = lastDefault;
}
// allocate the next position
arg.setPosition(++lastPosition);
}
/**
* Ensures that the args array can hold the given arg. Resizes the array as
* necessary.
* @param arg Determine if the args array is long enough to store this arg's
* position.
*/
private void ensureArgsCapacity(final Arg arg) {
if (arg.getPosition() >= this.args.length) {
@SuppressWarnings("unchecked") // cannot check this at compile time, but it is OK
final
Map<String, Arg>[] newArgs = new Map[arg.getPosition() + 1];
System.arraycopy(this.args, 0, newArgs, 0, this.args.length);
this.args = newArgs;
}
}
/**
* Gets the default <code>Arg</code> object at the given position.
* @param position Validation message argument's position.
* @return The default Arg or null if not found.
* @since 1.1
*/
public Arg getArg(final int position) {
return this.getArg(DEFAULT_ARG, position);
}
/**
* Gets the <code>Arg</code> object at the given position. If the key
* finds a <code>null</code> value then the default value will be
* retrieved.
* @param key The name the Arg is stored under. If not found, the default
* Arg for the given position (if any) will be retrieved.
* @param position The Arg number to find.
* @return The Arg with the given name and position or null if not found.
* @since 1.1
*/
public Arg getArg(final String key, final int position) {
if (position >= this.args.length || this.args[position] == null) {
return null;
}
final Arg arg = args[position].get(key);
// Didn't find default arg so exit, otherwise we would get into
// infinite recursion
if (arg == null && key.equals(DEFAULT_ARG)) {
return null;
}
return arg == null ? this.getArg(position) : arg;
}
/**
* Retrieves the Args for the given validator name.
* @param key The validator's args to retrieve.
* @return An Arg[] sorted by the Args' positions (i.e. the Arg at index 0
* has a position of 0).
* @since 1.1.1
*/
public Arg[] getArgs(final String key){
final Arg[] argList = new Arg[this.args.length];
for (int i = 0; i < this.args.length; i++) {
argList[i] = this.getArg(key, i);
}
return argList;
}
/**
* Add a <code>Var</code> to the <code>Field</code>.
* @param v The Validator Argument.
*/
public void addVar(final Var v) {
this.getVarMap().put(v.getName(), v);
}
/**
* Add a <code>Var</code>, based on the values passed in, to the
* <code>Field</code>.
* @param name Name of the validation.
* @param value The Argument's value.
* @param jsType The Javascript type.
*/
public void addVar(final String name, final String value, final String jsType) {
this.addVar(new Var(name, value, jsType));
}
/**
* Retrieve a variable.
* @param mainKey The Variable's key
* @return the Variable
*/
public Var getVar(final String mainKey) {
return getVarMap().get(mainKey);
}
/**
* Retrieve a variable's value.
* @param mainKey The Variable's key
* @return the Variable's value
*/
public String getVarValue(final String mainKey) {
String value = null;
final Var v = getVarMap().get(mainKey);
if (v != null) {
value = v.getValue();
}
return value;
}
/**
* The <code>Field</code>'s variables are returned as an
* unmodifiable <code>Map</code>.
* @return the Map of Variable's for a Field.
*/
public Map<String, Var> getVars() {
return Collections.unmodifiableMap(getVarMap());
}
/**
* Gets a unique key based on the property and indexedProperty fields.
* @return a unique key for the field.
*/
public String getKey() {
if (this.key == null) {
this.generateKey();
}
return this.key;
}
/**
* Sets a unique key for the field. This can be used to change
* the key temporarily to have a unique key for an indexed field.
* @param key a unique key for the field
*/
public void setKey(final String key) {
this.key = key;
}
/**
* If there is a value specified for the indexedProperty field then
* {@code true} will be returned. Otherwise it will be
* {@code false}.
* @return Whether the Field is indexed.
*/
public boolean isIndexed() {
return indexedListProperty != null && !indexedListProperty.isEmpty();
}
/**
* Generate correct <code>key</code> value.
*/
public void generateKey() {
if (this.isIndexed()) {
this.key = this.indexedListProperty + TOKEN_INDEXED + "." + this.property;
} else {
this.key = this.property;
}
}
/**
* Replace constants with values in fields and process the depends field
* to create the dependency <code>Map</code>.
*/
void process(final Map<String, String> globalConstants, final Map<String, String> constants) {
this.hMsgs.setFast(false);
this.hVars.setFast(true);
this.generateKey();
// Process FormSet Constants
for (final Entry<String, String> entry : constants.entrySet()) {
final String key1 = entry.getKey();
final String key2 = TOKEN_START + key1 + TOKEN_END;
final String replaceValue = entry.getValue();
property = ValidatorUtils.replace(property, key2, replaceValue);
processVars(key2, replaceValue);
this.processMessageComponents(key2, replaceValue);
}
// Process Global Constants
for (final Entry<String, String> entry : globalConstants.entrySet()) {
final String key1 = entry.getKey();
final String key2 = TOKEN_START + key1 + TOKEN_END;
final String replaceValue = entry.getValue();
property = ValidatorUtils.replace(property, key2, replaceValue);
processVars(key2, replaceValue);
this.processMessageComponents(key2, replaceValue);
}
// Process Var Constant Replacement
for (final String key1 : getVarMap().keySet()) {
final String key2 = TOKEN_START + TOKEN_VAR + key1 + TOKEN_END;
final Var var = this.getVar(key1);
final String replaceValue = var.getValue();
this.processMessageComponents(key2, replaceValue);
}
hMsgs.setFast(true);
}
/**
* Replace the vars value with the key/value pairs passed in.
*/
private void processVars(final String key, final String replaceValue) {
for (final String varKey : getVarMap().keySet()) {
final Var var = this.getVar(varKey);
var.setValue(ValidatorUtils.replace(var.getValue(), key, replaceValue));
}
}
/**
* Replace the args key value with the key/value pairs passed in.
*/
private void processMessageComponents(final String key, final String replaceValue) {
final String varKey = TOKEN_START + TOKEN_VAR;
// Process Messages
if (key != null && !key.startsWith(varKey)) {
for (final Msg msg : getMsgMap().values()) {
msg.setKey(ValidatorUtils.replace(msg.getKey(), key, replaceValue));
}
}
this.processArg(key, replaceValue);
}
/**
* Replace the arg <code>Collection</code> key value with the key/value
* pairs passed in.
*/
private void processArg(final String key, final String replaceValue) {
for (final Map<String, Arg> argMap : this.args) {
if (argMap == null) {
continue;
}
for (final Arg arg : argMap.values()) {
if (arg != null) {
arg.setKey(ValidatorUtils.replace(arg.getKey(), key, replaceValue));
}
}
}
}
/**
* Checks if the validator is listed as a dependency.
* @param validatorName Name of the validator to check.
* @return Whether the field is dependant on a validator.
*/
public boolean isDependency(final String validatorName) {
return this.dependencyList.contains(validatorName);
}
/**
* Gets an unmodifiable <code>List</code> of the dependencies in the same
* order they were defined in parameter passed to the setDepends() method.
* @return A list of the Field's dependancies.
*/
public List<String> getDependencyList() {
return Collections.unmodifiableList(this.dependencyList);
}
/**
* Creates and returns a copy of this object.
* @return A copy of the Field.
*/
@Override
public Object clone() {
Field field = null;
try {
field = (Field) super.clone();
} catch (final CloneNotSupportedException e) {
throw new UnsupportedOperationException(e.toString(), e);
}
@SuppressWarnings("unchecked") // empty array always OK; cannot check this at compile time
final Map<String, Arg>[] tempMap = new Map[this.args.length];
field.args = tempMap;
for (int i = 0; i < this.args.length; i++) {
if (this.args[i] == null) {
continue;
}
final Map<String, Arg> argMap = new HashMap<>(this.args[i]);
argMap.forEach((validatorName, arg) -> argMap.put(validatorName, (Arg) arg.clone()));
field.args[i] = argMap;
}
field.hVars = ValidatorUtils.copyFastHashMap(hVars);
field.hMsgs = ValidatorUtils.copyFastHashMap(hMsgs);
return field;
}
/**
* Returns a string representation of the object.
* @return A string representation of the object.
*/
@Override
public String toString() {
final StringBuilder results = new StringBuilder();
results.append("\t\tkey = " + key + "\n");
results.append("\t\tproperty = " + property + "\n");
results.append("\t\tindexedProperty = " + indexedProperty + "\n");
results.append("\t\tindexedListProperty = " + indexedListProperty + "\n");
results.append("\t\tdepends = " + depends + "\n");
results.append("\t\tpage = " + page + "\n");
results.append("\t\tfieldOrder = " + fieldOrder + "\n");
if (hVars != null) {
results.append("\t\tVars:\n");
for (final Object key1 : getVarMap().keySet()) {
results.append("\t\t\t");
results.append(key1);
results.append("=");
results.append(getVarMap().get(key1));
results.append("\n");
}
}
return results.toString();
}
/**
* Returns an indexed property from the object we're validating.
*
* @param bean The bean to extract the indexed values from.
* @throws ValidatorException If there's an error looking up the property
* or, the property found is not indexed.
*/
Object[] getIndexedProperty(final Object bean) throws ValidatorException {
Object indexProp = null;
try {
indexProp =
PropertyUtils.getProperty(bean, this.getIndexedListProperty());
} catch (IllegalAccessException|InvocationTargetException|NoSuchMethodException e) {
throw new ValidatorException(e.getMessage());
}
if (indexProp instanceof Collection) {
return ((Collection<?>) indexProp).toArray();
}
if (indexProp.getClass().isArray()) {
return (Object[]) indexProp;
}
throw new ValidatorException(this.getKey() + " is not indexed");
}
/**
* Returns the size of an indexed property from the object we're validating.
*
* @param bean The bean to extract the indexed values from.
* @throws ValidatorException If there's an error looking up the property
* or, the property found is not indexed.
*/
private int getIndexedPropertySize(final Object bean) throws ValidatorException {
Object indexProp = null;
try {
indexProp =
PropertyUtils.getProperty(bean, this.getIndexedListProperty());
} catch (IllegalAccessException|InvocationTargetException|NoSuchMethodException e) {
throw new ValidatorException(e.getMessage());
}
if (indexProp == null) {
return 0;
}
if (indexProp instanceof Collection) {
return ((Collection<?>)indexProp).size();
}
if (indexProp.getClass().isArray()) {
return ((Object[])indexProp).length;
}
throw new ValidatorException(this.getKey() + " is not indexed");
}
/**
* Executes the given ValidatorAction and all ValidatorActions that it
* depends on.
* @return true if the validation succeeded.
*/
private boolean validateForRule(
final ValidatorAction va,
final ValidatorResults results,
final Map<String, ValidatorAction> actions,
final Map<String, Object> params,
final int pos)
throws ValidatorException {
final ValidatorResult result = results.getValidatorResult(this.getKey());
if (result != null && result.containsAction(va.getName())) {
return result.isValid(va.getName());
}
if (!this.runDependentValidators(va, results, actions, params, pos)) {
return false;
}
return va.executeValidationMethod(this, params, results, pos);
}
/**
* Calls all of the validators that this validator depends on.
* TODO ValidatorAction should know how to run its own dependencies.
* @param va Run dependent validators for this action.
* @param results
* @param actions
* @param pos
* @return true if all of the dependent validations passed.
* @throws ValidatorException If there's an error running a validator
*/
private boolean runDependentValidators(
final ValidatorAction va,
final ValidatorResults results,
final Map<String, ValidatorAction> actions,
final Map<String, Object> params,
final int pos)
throws ValidatorException {
final List<String> dependentValidators = va.getDependencyList();
if (dependentValidators.isEmpty()) {
return true;
}
for (final String depend : dependentValidators) {
final ValidatorAction action = actions.get(depend);
if (action == null) {
this.handleMissingAction(depend);
}
if (!this.validateForRule(action, results, actions, params, pos)) {
return false;
}
}
return true;
}
/**
* Run the configured validations on this field. Run all validations
* in the depends clause over each item in turn, returning when the first
* one fails.
* @param params A Map of parameter class names to parameter values to pass
* into validation methods.
* @param actions A Map of validator names to ValidatorAction objects.
* @return A ValidatorResults object containing validation messages for
* this field.
* @throws ValidatorException If an error occurs during validation.
*/
public ValidatorResults validate(final Map<String, Object> params, final Map<String, ValidatorAction> actions)
throws ValidatorException {
if (this.getDepends() == null) {
return new ValidatorResults();
}
final ValidatorResults allResults = new ValidatorResults();
final Object bean = params.get(Validator.BEAN_PARAM);
final int numberOfFieldsToValidate =
this.isIndexed() ? this.getIndexedPropertySize(bean) : 1;
for (int fieldNumber = 0; fieldNumber < numberOfFieldsToValidate; fieldNumber++) {
final ValidatorResults results = new ValidatorResults();
synchronized(dependencyList) {
for (final String depend : this.dependencyList) {
final ValidatorAction action = actions.get(depend);
if (action == null) {
this.handleMissingAction(depend);
}
final boolean good =
validateForRule(action, results, actions, params, fieldNumber);
if (!good) {
allResults.merge(results);
return allResults;
}
}
}
allResults.merge(results);
}
return allResults;
}
/**
* Called when a validator name is used in a depends clause but there is
* no know ValidatorAction configured for that name.
* @param name The name of the validator in the depends list.
* @throws ValidatorException
*/
private void handleMissingAction(final String name) throws ValidatorException {
throw new ValidatorException("No ValidatorAction named " + name
+ " found for field " + this.getProperty());
}
/**
* Returns a Map of String Msg names to Msg objects.
* @since 1.2.0
* @return A Map of the Field's messages.
*/
@SuppressWarnings("unchecked") // FastHashMap does not support generics
protected Map<String, Msg> getMsgMap() {
return hMsgs;
}
/**
* Returns a Map of String Var names to Var objects.
* @since 1.2.0
* @return A Map of the Field's variables.
*/
@SuppressWarnings("unchecked") // FastHashMap does not support generics
protected Map<String, Var> getVarMap() {
return hVars;
}
}
| 7,972 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/ISBNValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
/**
* A class for validating 10 digit ISBN codes.
* Based on this
* <a href="http://www.isbn.org/standards/home/isbn/international/html/usm4.htm">
* algorithm</a>
*
* <b>NOTE:</b> This has been replaced by the new
* {@link org.apache.commons.validator.routines.ISBNValidator}.
*
* @since 1.2.0
* @deprecated Use the new ISBNValidator in the routines package
*/
@Deprecated
public class ISBNValidator {
/**
* Default Constructor.
*/
public ISBNValidator() {
}
/**
* If the ISBN is formatted with space or dash separators its format is
* validated. Then the digits in the number are weighted, summed, and
* divided by 11 according to the ISBN algorithm. If the result is zero,
* the ISBN is valid. This method accepts formatted or raw ISBN codes.
*
* @param isbn Candidate ISBN number to be validated. <code>null</code> is
* considered invalid.
* @return true if the string is a valid ISBN code.
*/
public boolean isValid(final String isbn) {
return org.apache.commons.validator.routines.ISBNValidator.getInstance().isValidISBN10(isbn);
}
}
| 7,973 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/CreditCardValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.commons.validator.util.Flags;
/**
* Perform credit card validations.
*
* <p>
* By default, all supported card types are allowed. You can specify which
* cards should pass validation by configuring the validation options. For
* example,
* </p>
*
* <pre>
* <code>CreditCardValidator ccv = new CreditCardValidator(CreditCardValidator.AMEX + CreditCardValidator.VISA);</code>
* </pre>
*
* <p>
* configures the validator to only pass American Express and Visa cards.
* If a card type is not directly supported by this class, you can implement
* the CreditCardType interface and pass an instance into the
* <code>addAllowedCardType</code> method.
* </p>
*
* <p>
* For a similar implementation in Perl, reference Sean M. Burke's
* <a href="http://www.speech.cs.cmu.edu/~sburke/pub/luhn_lib.html">script</a>.
* More information is also available
* <a href="http://www.merriampark.com/anatomycc.htm">here</a>.
* </p>
*
* @since 1.1
* @deprecated Use the new CreditCardValidator in the routines package. This class
* will be removed in a future release.
*/
// CHECKSTYLE:OFF (deprecated code)
@Deprecated
public class CreditCardValidator {
/**
* Option specifying that no cards are allowed. This is useful if
* you want only custom card types to validate so you turn off the
* default cards with this option.
* <pre>
* <code>
* CreditCardValidator v = new CreditCardValidator(CreditCardValidator.NONE);
* v.addAllowedCardType(customType);
* v.isValid(aCardNumber);
* </code>
* </pre>
* @since 1.1.2
*/
public static final int NONE = 0;
/**
* Option specifying that American Express cards are allowed.
*/
public static final int AMEX = 1 << 0;
/**
* Option specifying that Visa cards are allowed.
*/
public static final int VISA = 1 << 1;
/**
* Option specifying that Mastercard cards are allowed.
*/
public static final int MASTERCARD = 1 << 2;
/**
* Option specifying that Discover cards are allowed.
*/
public static final int DISCOVER = 1 << 3;
/**
* The CreditCardTypes that are allowed to pass validation.
*/
private final Collection<CreditCardType> cardTypes = new ArrayList<>();
/**
* Create a new CreditCardValidator with default options.
*/
public CreditCardValidator() {
this(AMEX + VISA + MASTERCARD + DISCOVER);
}
/**
* Creates a new CreditCardValidator with the specified options.
* @param options Pass in
* CreditCardValidator.VISA + CreditCardValidator.AMEX to specify that
* those are the only valid card types.
*/
public CreditCardValidator(final int options) {
final Flags f = new Flags(options);
if (f.isOn(VISA)) {
this.cardTypes.add(new Visa());
}
if (f.isOn(AMEX)) {
this.cardTypes.add(new Amex());
}
if (f.isOn(MASTERCARD)) {
this.cardTypes.add(new Mastercard());
}
if (f.isOn(DISCOVER)) {
this.cardTypes.add(new Discover());
}
}
/**
* Checks if the field is a valid credit card number.
* @param card The card number to validate.
* @return Whether the card number is valid.
*/
public boolean isValid(final String card) {
if (card == null || card.length() < 13 || card.length() > 19) {
return false;
}
if (!this.luhnCheck(card)) {
return false;
}
for (final Object cardType : this.cardTypes) {
final CreditCardType type = (CreditCardType) cardType;
if (type.matches(card)) {
return true;
}
}
return false;
}
/**
* Adds an allowed CreditCardType that participates in the card
* validation algorithm.
* @param type The type that is now allowed to pass validation.
* @since 1.1.2
*/
public void addAllowedCardType(final CreditCardType type){
this.cardTypes.add(type);
}
/**
* Checks for a valid credit card number.
* @param cardNumber Credit Card Number.
* @return Whether the card number passes the luhnCheck.
*/
protected boolean luhnCheck(final String cardNumber) {
// number must be validated as 0..9 numeric first!!
final int digits = cardNumber.length();
final int oddOrEven = digits & 1;
long sum = 0;
for (int count = 0; count < digits; count++) {
int digit = 0;
try {
digit = Integer.parseInt(cardNumber.charAt(count) + "");
} catch (final NumberFormatException e) {
return false;
}
if ((count & 1 ^ oddOrEven) == 0) { // not
digit *= 2;
if (digit > 9) {
digit -= 9;
}
}
sum += digit;
}
return sum == 0 ? false : sum % 10 == 0;
}
/**
* CreditCardType implementations define how validation is performed
* for one type/brand of credit card.
* @since 1.1.2
*/
public interface CreditCardType {
/**
* Returns true if the card number matches this type of credit
* card. Note that this method is <strong>not</strong> responsible
* for analyzing the general form of the card number because
* <code>CreditCardValidator</code> performs those checks before
* calling this method. It is generally only required to valid the
* length and prefix of the number to determine if it's the correct
* type.
* @param card The card number, never null.
* @return true if the number matches.
*/
boolean matches(String card);
}
/**
* Change to support Visa Carte Blue used in France
* has been removed - see Bug 35926
*/
private static class Visa implements CreditCardType {
private static final String PREFIX = "4";
@Override
public boolean matches(final String card) {
return card.substring(0, 1).equals(PREFIX)
&& (card.length() == 13 || card.length() == 16);
}
}
private static class Amex implements CreditCardType {
private static final String PREFIX = "34,37,";
@Override
public boolean matches(final String card) {
final String prefix2 = card.substring(0, 2) + ",";
return PREFIX.contains(prefix2) && card.length() == 15;
}
}
private static class Discover implements CreditCardType {
private static final String PREFIX = "6011";
@Override
public boolean matches(final String card) {
return card.substring(0, 4).equals(PREFIX) && card.length() == 16;
}
}
private static class Mastercard implements CreditCardType {
private static final String PREFIX = "51,52,53,54,55,";
@Override
public boolean matches(final String card) {
final String prefix2 = card.substring(0, 2) + ",";
return PREFIX.contains(prefix2) && card.length() == 16;
}
}
}
| 7,974 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/package-info.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* The Validator package provides validation for JavaBeans based on an xml file.
*
* <a id="doc.Description"></a>
* <div>
* <a href="http://commons.apache.org/validator/dependencies.html">[Dependencies]</a>
* <a href="#doc.Intro">[Introduction]</a>
* <a href="#doc.Overview">[Overview]</a>
* <a href="#doc.Resources">[Resources]</a>
* <a href="#doc.Usage">[Usage Example]</a>
* </div>
* <a id="doc.Intro"></a>
* <h2>Introduction</h2>
* <p>A common issue when receiving data either electronically or from
* user input is verifying the integrity of the data. This work is
* repetitive and becomes even more complicated when different sets
* of validation rules need to be applied to the same set of data based
* on locale for example. Error messages may also vary by locale.
* This package attempts to address some of these issues and
* speed development and maintenance of validation rules.
* </p>
* <p>In order to use the Validator, the following basic steps are required:</p>
* <ul>
* <li>Create a new instance of the
* <code>org.apache.commons.validator.Validator</code> class. Currently
* Validator instances may be safely reused if the current ValidatorResources
* are the same, as long as
* you have completed any previous validation, and you do not try to utilize
* a particular Validator instance from more than one thread at a time.</li>
* <li>Add any <a href="#doc.Resources">resources</a>
* needed to perform the validations. Such as the JavaBean to validate.</li>
* <li>Call the validate method on <code>org.apache.commons.validator.Validator</code>.</li>
* </ul>
* <a id="doc.Overview"></a>
* <h2>Overview</h2>
* <p>
* The Commons Validator is a basic validation framework that
* lets you define validation rules for a JavaBean in an xml file.
* Validators, the validation definition, can also be defined in
* the xml file. An example of a validator would be defining
* what method and class will be called to perform the validation
* for a required field. Validation rules can be grouped together
* based on locale and a JavaBean/Form that the rules are associated
* with. The framework has basic support for user-defined constants
* which can be used in some field attributes.
* </p>
* <p>
* Validation rules can be defined in an xml file which keeps
* them abstracted from JavaBean you are validating. The
* property reference to a field supports nested properties
* using the Apache Commons BeanUtils
* (http://commons.apache.org/beanutils/) package.
* Error messages and the arguments for error messages can be
* associated with a fields validation.
* </p>
* <a id="doc.Resources"></a>
* <h2>Resources</h2>
* <p>
* After a Validator instance is created, instances of
* classes can be added to it to be passed into
* validation methods by calling the setParameter()
* method. Below is a list of reserved parameters (class names).
* </p>
* <table border="1">
* <caption>Reserved Parameters</caption>
* <tr>
* <th>Class Name</th>
* <th>Validator Contstant</th>
* <th>Description</th>
* </tr>
* <tr>
* <td>java.lang.Object</td>
* <td>Validator.BEAN_PARAM</td>
* <td>JavaBean that is being validated</td>
* </tr>
* <tr>
* <td>java.util.Locale</td>
* <td>Validator.LOCALE_PARAM</td>
* <td>
* Locale to use when retrieving a FormSet.
* The default locale will be used if one
* isn't specified.
* </td>
* </tr>
* <tr>
* <td>org.apache.commons.validator.ValidatorAction</td>
* <td>Validator.VALIDATOR_ACTION_PARAM</td>
* <td>
* This is automatically added to a Validator's
* resources as a validation is being processed.
* If this class name is used when defining
* a method signature for a pluggable validator,
* the current ValidatorAction will be passed into
* the validation method.
* </td>
* </tr>
* <tr>
* <td>org.apache.commons.validator.Field</td>
* <td>Validator.FIELD_PARAM</td>
* <td>
* This is automatically added to a Validator's
* resources as a validation is being processed.
* If this class name is used when defining
* a method signature for a pluggable validator,
* the current Field will be passed into
* the validation method.
* </td>
* </tr>
* </table>
* <a id="doc.Usage"></a>
* <h2>Usage Example</h2>
* <p>
* This is a basic example setting up a required validator for
* a name bean. This example is a working unit test (reference
* <code>org.apache.commons.validator.RequiredNameTest</code> and
* validator-name-required.xml located under validator/src/test).
* </p>
* <p>
* Create an xml file with your validator and validation rules.
* Setup your required validator in your xml file.<br>
* <br>
* <a href="#doc.Usage.xml">XML Example</a><br>
* <a href="#doc.Usage.validator">Validator Example</a><br>
* <a href="#doc.Usage.pluggableValidator">Pluggable Validator Example</a>
* </p>
* <a id="doc.Usage.xml"></a>
* <h2>XML Example</h2>
* <p>
* Definition of a 'required' pluggable validator.<br>
* <pre>
* <form-validation>
* <global>
* <validator name="required"
* classname="org.apache.commons.validator.TestValidator"
* method="validateRequired"
* methodParams="java.lang.Object, org.apache.commons.validator.Field"/>
* </global>
* <formset>
* </formset>
* </form-validation>
* </pre>
* <p>
* Add validation rules to require a first name and a last name.<br>
* <pre>
* <form-validation>
* <global>
* <validator name="required"
* classname="org.apache.commons.validator.TestValidator"
* method="validateRequired"
* methodParams="java.lang.Object, org.apache.commons.validator.Field"/>
* </global>
* <b>
* <formset>
* <form name="nameForm">
* <field property="firstName" depends="required">
* <arg0 key="nameForm.firstname.displayname"/>
* </field>
* <field property="lastName" depends="required">
* <arg0 key="nameForm.lastname.displayname"/>
* </field>
* </form>
* </formset>
* </b>
* </form-validation>
* </pre>
* <a id="doc.Usage.validator"></a>
* <h2>Validator Example</h2>
* <p>
* Excerpts from org.apache.commons.validator.RequiredNameTest
* </p>
* <pre>
* InputStream in = this.getClass().getResourceAsStream("validator-name-required.xml");
* // Create an instance of ValidatorResources to initialize from an xml file.
* ValidatorResources resources = new ValidatorResources(in);
* // Create bean to run test on.
* Name name = new Name();
* // Construct validator based on the loaded resources and the form key
* Validator validator = new Validator(resources, "nameForm");
* // add the name bean to the validator as a resource
* // for the validations to be performed on.
* validator.setParameter(Validator.BEAN_PARAM, name);
* // Get results of the validation.
* Map results;
* // throws ValidatorException (catch clause not shown here)
* results = validator.validate();
* if (results.get("firstName") == null) {
* // no error
* } else {
* // number of errors for first name
* int errors = ((Integer)results.get("firstName")).intValue();
* }
* </pre>
* <a id="doc.Usage.pluggableValidator"></a>
* <h2>Pluggable Validator Example</h2>
* <p>
* Validation method defined in the 'required' pluggable validator
* (excerpt from org.apache.commons.validator.TestValidator).
* </p>
* <pre>
* public static boolean validateRequired(Object bean, Field field) {
* String value = ValidatorUtil.getValueAsString(bean, field.getProperty());
* return GenericValidator.isBlankOrNull(value);
* }
* </pre>
*/
package org.apache.commons.validator;
| 7,975 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/util/Flags.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.util;
import java.io.Serializable;
/**
* Represents a collection of 64 boolean (on/off) flags. Individual flags
* are represented by powers of 2. For example,<br>
* Flag 1 = 1<br>
* Flag 2 = 2<br>
* Flag 3 = 4<br>
* Flag 4 = 8<br><br>
* or using shift operator to make numbering easier:<br>
* Flag 1 = 1 << 0<br>
* Flag 2 = 1 << 1<br>
* Flag 3 = 1 << 2<br>
* Flag 4 = 1 << 3<br>
*
* <p>
* There cannot be a flag with a value of 3 because that represents Flag 1
* and Flag 2 both being on/true.
* </p>
*/
public class Flags implements Serializable, Cloneable {
private static final long serialVersionUID = 8481587558770237995L;
/**
* Represents the current flag state.
*/
private long flags;
/**
* Create a new Flags object.
*/
public Flags() {
}
/**
* Initialize a new Flags object with the given flags.
*
* @param flags collection of boolean flags to represent.
*/
public Flags(final long flags) {
this.flags = flags;
}
/**
* Returns the current flags.
*
* @return collection of boolean flags represented.
*/
public long getFlags() {
return this.flags;
}
/**
* Tests whether the given flag is on. If the flag is not a power of 2
* (ie. 3) this tests whether the combination of flags is on.
*
* @param flag Flag value to check.
*
* @return whether the specified flag value is on.
*/
public boolean isOn(final long flag) {
return (this.flags & flag) == flag;
}
/**
* Tests whether the given flag is off. If the flag is not a power of 2
* (ie. 3) this tests whether the combination of flags is off.
*
* @param flag Flag value to check.
*
* @return whether the specified flag value is off.
*/
public boolean isOff(final long flag) {
return (this.flags & flag) == 0;
}
/**
* Turns on the given flag. If the flag is not a power of 2 (ie. 3) this
* turns on multiple flags.
*
* @param flag Flag value to turn on.
*/
public void turnOn(final long flag) {
this.flags |= flag;
}
/**
* Turns off the given flag. If the flag is not a power of 2 (ie. 3) this
* turns off multiple flags.
*
* @param flag Flag value to turn off.
*/
public void turnOff(final long flag) {
this.flags &= ~flag;
}
/**
* Turn off all flags.
*/
public void turnOffAll() {
this.flags = 0;
}
/**
* Turn off all flags. This is a synonym for <code>turnOffAll()</code>.
* @since 1.1.1
*/
public void clear() {
this.flags = 0;
}
/**
* Turn on all 64 flags.
*/
public void turnOnAll() {
this.flags = 0xFFFFFFFFFFFFFFFFL;
}
/**
* Clone this Flags object.
*
* @return a copy of this object.
* @see Object#clone()
*/
@Override
public Object clone() {
try {
return super.clone();
} catch (final CloneNotSupportedException e) {
throw new UnsupportedOperationException("Couldn't clone Flags object.", e);
}
}
/**
* Tests if two Flags objects are in the same state.
* @param obj object being tested
* @see Object#equals(Object)
*
* @return whether the objects are equal.
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Flags)) {
return false;
}
Flags other = (Flags) obj;
return flags == other.flags;
}
/**
* The hash code is based on the current state of the flags.
* @see Object#hashCode()
*
* @return the hash code for this object.
*/
@Override
public int hashCode() {
return (int) this.flags;
}
/**
* Returns a 64 length String with the first flag on the right and the
* 64th flag on the left. A 1 indicates the flag is on, a 0 means it's
* off.
*
* @return string representation of this object.
*/
@Override
public String toString() {
final StringBuilder bin = new StringBuilder(Long.toBinaryString(this.flags));
for (int i = 64 - bin.length(); i > 0; i--) { // CHECKSTYLE IGNORE MagicNumber
bin.insert(0, "0");
}
return bin.toString();
}
}
| 7,976 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/util/ValidatorUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.util;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.FastHashMap; // DEPRECATED
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.Arg;
import org.apache.commons.validator.Msg;
import org.apache.commons.validator.Var;
/**
* Basic utility methods.
* <p>
* The use of FastHashMap is deprecated and will be replaced in a future
* release.
* </p>
*/
public class ValidatorUtils {
private static final Log LOG = LogFactory.getLog(ValidatorUtils.class);
/**
* <p>Replace part of a <code>String</code> with another value.</p>
*
* @param value <code>String</code> to perform the replacement on.
* @param key The name of the constant.
* @param replaceValue The value of the constant.
*
* @return The modified value.
*/
public static String replace(String value, final String key, final String replaceValue) {
if (value == null || key == null || replaceValue == null) {
return value;
}
final int pos = value.indexOf(key);
if (pos < 0) {
return value;
}
final int length = value.length();
final int start = pos;
final int end = pos + key.length();
if (length == key.length()) {
value = replaceValue;
} else if (end == length) {
value = value.substring(0, start) + replaceValue;
} else {
value =
value.substring(0, start)
+ replaceValue
+ replace(value.substring(end), key, replaceValue);
}
return value;
}
/**
* Convenience method for getting a value from a bean property as a
* <code>String</code>. If the property is a <code>String[]</code> or
* <code>Collection</code> and it is empty, an empty <code>String</code>
* "" is returned. Otherwise, property.toString() is returned. This method
* may return <code>null</code> if there was an error retrieving the
* property.
*
* @param bean The bean object.
* @param property The name of the property to access.
*
* @return The value of the property.
*/
public static String getValueAsString(final Object bean, final String property) {
Object value = null;
try {
value = PropertyUtils.getProperty(bean, property);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
LOG.error(e.getMessage(), e);
}
if (value == null) {
return null;
}
if (value instanceof String[]) {
return ((String[]) value).length > 0 ? value.toString() : "";
}
if (value instanceof Collection) {
return ((Collection<?>) value).isEmpty() ? "" : value.toString();
}
return value.toString();
}
/**
* Makes a deep copy of a <code>FastHashMap</code> if the values
* are <code>Msg</code>, <code>Arg</code>,
* or <code>Var</code>. Otherwise it is a shallow copy.
*
* @param fastHashMap <code>FastHashMap</code> to copy.
* @return FastHashMap A copy of the <code>FastHashMap</code> that was
* passed in.
* @deprecated This method is not part of Validator's public API. Validator
* will use it internally until FastHashMap references are removed. Use
* copyMap() instead.
*/
@Deprecated
public static FastHashMap copyFastHashMap(final FastHashMap fastHashMap) {
final FastHashMap results = new FastHashMap();
@SuppressWarnings("unchecked") // FastHashMap is not generic
final HashMap<String, ?> map = fastHashMap;
map.forEach((key, value) -> {
if (value instanceof Msg) {
results.put(key, ((Msg) value).clone());
} else if (value instanceof Arg) {
results.put(key, ((Arg) value).clone());
} else if (value instanceof Var) {
results.put(key, ((Var) value).clone());
} else {
results.put(key, value);
}
});
results.setFast(true);
return results;
}
/**
* Makes a deep copy of a <code>Map</code> if the values are
* <code>Msg</code>, <code>Arg</code>, or <code>Var</code>. Otherwise,
* it is a shallow copy.
*
* @param map The source Map to copy.
*
* @return A copy of the <code>Map</code> that was passed in.
*/
public static Map<String, Object> copyMap(final Map<String, Object> map) {
final Map<String, Object> results = new HashMap<>();
map.forEach((key, value) -> {
if (value instanceof Msg) {
results.put(key, ((Msg) value).clone());
} else if (value instanceof Arg) {
results.put(key, ((Arg) value).clone());
} else if (value instanceof Var) {
results.put(key, ((Var) value).clone());
} else {
results.put(key, value);
}
});
return results;
}
}
| 7,977 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/util/package-info.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This package contains utility classes used by Commons Validator.
*/
package org.apache.commons.validator.util; | 7,978 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/routines/IBANValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.apache.commons.validator.routines.checkdigit.IBANCheckDigit;
/**
* IBAN Validator.
* <p>
* The validator includes a default set of formats derived from the IBAN registry at
* https://www.swift.com/standards/data-standards/iban.
* </p>
* <p>
* This can get out of date, but the set can be adjusted by creating a validator and using the
* {@link #setValidator(String, int, String)} or
* {@link #setValidator(Validator)}
* method to add (or remove) an entry.
* </p>
* <p>
* For example:
* </p>
* <pre>
* IBANValidator ibv = new IBANValidator();
* ibv.setValidator("XX", 12, "XX\\d{10}")
* </pre>
* <p>
* The singleton default instance cannot be modified in this way.
* </p>
* @since 1.5.0
*/
public class IBANValidator {
private static final int SHORT_CODE_LEN = 2;
private final ConcurrentMap<String, Validator> validatorMap;
/**
* The validation class
*/
public static class Validator {
/*
* The minimum length does not appear to be defined by the standard.
* Norway is currently the shortest at 15.
*
* There is no standard for BBANs; they vary between countries.
* But a BBAN must consist of a branch id and account number.
* Each of these must be at least 2 chars (generally more) so an absolute minimum is
* 4 characters for the BBAN and 8 for the IBAN.
*/
private static final int MIN_LEN = 8;
private static final int MAX_LEN = 34; // defined by [3]
final String countryCode;
final String[] otherCountryCodes;
final RegexValidator regexValidator;
final int ibanLength; // used to avoid unnecessary regex matching
/**
* Creates the validator.
* @param countryCode the country code
* @param ibanLength the length of the IBAN
* @param regexWithCC the regex to use to check the format, the regex MUST start with the country code.
*/
public Validator(final String countryCode, final int ibanLength, final String regexWithCC) {
this(countryCode, ibanLength, regexWithCC.substring(countryCode.length()), new String[] {});
}
/**
* Creates the validator.
* @param countryCode the country code
* @param ibanLength the length of the IBAN
* @param regexWithoutCC the regex to use to check the format, the regex MUST NOT start with the country code.
*/
Validator(final String countryCode, final int ibanLength, final String regexWithoutCC, final String... otherCountryCodes) {
if (!(countryCode.length() == 2 && Character.isUpperCase(countryCode.charAt(0)) && Character.isUpperCase(countryCode.charAt(1)))) {
throw new IllegalArgumentException("Invalid country Code; must be exactly 2 upper-case characters");
}
if (ibanLength > MAX_LEN || ibanLength < MIN_LEN) {
throw new IllegalArgumentException("Invalid length parameter, must be in range " + MIN_LEN + " to " + MAX_LEN + " inclusive: " + ibanLength);
}
final String regex = countryCode + regexWithoutCC;
if (!regex.startsWith(countryCode)) {
throw new IllegalArgumentException("countryCode '" + countryCode + "' does not agree with format: " + regex);
}
this.countryCode = countryCode;
this.otherCountryCodes = otherCountryCodes.clone();
final List<String> regexList = new ArrayList<>(this.otherCountryCodes.length + 1);
regexList.add(countryCode + regexWithoutCC);
for (String otherCc : otherCountryCodes) {
regexList.add(otherCc + regexWithoutCC);
}
this.ibanLength = ibanLength;
this.regexValidator = new RegexValidator(regexList);
}
/**
* Gets the RegexValidator.
*
* @return the RegexValidator.
* @since 1.8
*/
public RegexValidator getRegexValidator() {
return regexValidator;
}
}
/*
* Wikipedia [1] says that only uppercase is allowed.
* The SWIFT PDF file [2] implies that lower case is allowed.
* However there are no examples using lower-case.
* Unfortunately the relevant ISO documents (ISO 13616-1) are not available for free.
* The IBANCheckDigit code treats upper and lower case the same,
* so any case validation has to be done in this class.
*
* Note: the European Payments council has a document [3] which includes a description
* of the IBAN. Section 5 clearly states that only upper case is allowed.
* Also the maximum length is 34 characters (including the country code),
* and the length is fixed for each country.
*
* It looks like lower-case is permitted in BBANs, but they must be converted to
* upper case for IBANs.
*
* [1] https://en.wikipedia.org/wiki/International_Bank_Account_Number
* [2] http://www.swift.com/dsp/resources/documents/IBAN_Registry.pdf (404)
* => https://www.swift.com/sites/default/files/resources/iban_registry.pdf
* The above is an old version (62, Jan 2016)
* As of May 2020, the current IBAN standards are located at:
* https://www.swift.com/standards/data-standards/iban
* The above page contains links for the PDF and TXT (CSV) versions of the registry
* Warning: these may not agree -- in the past there have been discrepancies.
* The TXT file can be used to determine changes which can be cross-checked in the PDF file.
* [3] http://www.europeanpaymentscouncil.eu/documents/ECBS%20IBAN%20standard%20EBS204_V3.2.pdf
*/
private static final Validator[] DEFAULT_VALIDATORS = {
new Validator("AD", 24, "AD\\d{10}[A-Z0-9]{12}" ), // Andorra
new Validator("AE", 23, "AE\\d{21}" ), // United Arab Emirates (The)
new Validator("AL", 28, "AL\\d{10}[A-Z0-9]{16}" ), // Albania
new Validator("AT", 20, "AT\\d{18}" ), // Austria
new Validator("AZ", 28, "AZ\\d{2}[A-Z]{4}[A-Z0-9]{20}" ), // Azerbaijan
new Validator("BA", 20, "BA\\d{18}" ), // Bosnia and Herzegovina
new Validator("BE", 16, "BE\\d{14}" ), // Belgium
new Validator("BG", 22, "BG\\d{2}[A-Z]{4}\\d{6}[A-Z0-9]{8}" ), // Bulgaria
new Validator("BH", 22, "BH\\d{2}[A-Z]{4}[A-Z0-9]{14}" ), // Bahrain
new Validator("BI", 27, "BI\\d{25}" ), // Burundi
new Validator("BR", 29, "BR\\d{25}[A-Z]{1}[A-Z0-9]{1}" ), // Brazil
new Validator("BY", 28, "BY\\d{2}[A-Z0-9]{4}\\d{4}[A-Z0-9]{16}" ), // Republic of Belarus
new Validator("CH", 21, "CH\\d{7}[A-Z0-9]{12}" ), // Switzerland
new Validator("CR", 22, "CR\\d{20}" ), // Costa Rica
new Validator("CY", 28, "CY\\d{10}[A-Z0-9]{16}" ), // Cyprus
new Validator("CZ", 24, "CZ\\d{22}" ), // Czechia
new Validator("DE", 22, "DE\\d{20}" ), // Germany
new Validator("DJ", 27, "DJ\\d{25}" ), // Djibouti
new Validator("DK", 18, "DK\\d{16}" ), // Denmark
new Validator("DO", 28, "DO\\d{2}[A-Z0-9]{4}\\d{20}" ), // Dominican Republic
new Validator("EE", 20, "EE\\d{18}" ), // Estonia
new Validator("EG", 29, "EG\\d{27}" ), // Egypt
new Validator("ES", 24, "ES\\d{22}" ), // Spain
new Validator("FI", 18, "\\d{16}", "AX" ), // Finland
new Validator("FO", 18, "FO\\d{16}" ), // Faroe Islands
new Validator("FR", 27, "\\d{12}[A-Z0-9]{11}\\d{2}", "GF", "GP", "MQ", "RE", "PF", "TF", "YT", "NC", "BL", "MF", "PM", "WF"), // France
new Validator("GB", 22, "\\d{2}[A-Z]{4}\\d{14}", "IM", "JE", "GG"), // United Kingdom
new Validator("GE", 22, "GE\\d{2}[A-Z]{2}\\d{16}" ), // Georgia
new Validator("GI", 23, "GI\\d{2}[A-Z]{4}[A-Z0-9]{15}" ), // Gibraltar
new Validator("GL", 18, "GL\\d{16}" ), // Greenland
new Validator("GR", 27, "GR\\d{9}[A-Z0-9]{16}" ), // Greece
new Validator("GT", 28, "GT\\d{2}[A-Z0-9]{24}" ), // Guatemala
new Validator("HR", 21, "HR\\d{19}" ), // Croatia
new Validator("HU", 28, "HU\\d{26}" ), // Hungary
new Validator("IE", 22, "IE\\d{2}[A-Z]{4}\\d{14}" ), // Ireland
new Validator("IL", 23, "IL\\d{21}" ), // Israel
new Validator("IQ", 23, "IQ\\d{2}[A-Z]{4}\\d{15}" ), // Iraq
new Validator("IS", 26, "IS\\d{24}" ), // Iceland
new Validator("IT", 27, "IT\\d{2}[A-Z]{1}\\d{10}[A-Z0-9]{12}" ), // Italy
new Validator("JO", 30, "JO\\d{2}[A-Z]{4}\\d{4}[A-Z0-9]{18}" ), // Jordan
new Validator("KW", 30, "KW\\d{2}[A-Z]{4}[A-Z0-9]{22}" ), // Kuwait
new Validator("KZ", 20, "KZ\\d{5}[A-Z0-9]{13}" ), // Kazakhstan
new Validator("LB", 28, "LB\\d{6}[A-Z0-9]{20}" ), // Lebanon
new Validator("LC", 32, "LC\\d{2}[A-Z]{4}[A-Z0-9]{24}" ), // Saint Lucia
new Validator("LI", 21, "LI\\d{7}[A-Z0-9]{12}" ), // Liechtenstein
new Validator("LT", 20, "LT\\d{18}" ), // Lithuania
new Validator("LU", 20, "LU\\d{5}[A-Z0-9]{13}" ), // Luxembourg
new Validator("LV", 21, "LV\\d{2}[A-Z]{4}[A-Z0-9]{13}" ), // Latvia
new Validator("LY", 25, "LY\\d{23}" ), // Libya
new Validator("MC", 27, "MC\\d{12}[A-Z0-9]{11}\\d{2}" ), // Monaco
new Validator("MD", 24, "MD\\d{2}[A-Z0-9]{20}" ), // Moldova
new Validator("ME", 22, "ME\\d{20}" ), // Montenegro
new Validator("MK", 19, "MK\\d{5}[A-Z0-9]{10}\\d{2}" ), // Macedonia
new Validator("MR", 27, "MR\\d{25}" ), // Mauritania
new Validator("MT", 31, "MT\\d{2}[A-Z]{4}\\d{5}[A-Z0-9]{18}" ), // Malta
new Validator("MU", 30, "MU\\d{2}[A-Z]{4}\\d{19}[A-Z]{3}" ), // Mauritius
new Validator("NL", 18, "NL\\d{2}[A-Z]{4}\\d{10}" ), // Netherlands (The)
new Validator("NO", 15, "NO\\d{13}" ), // Norway
new Validator("PK", 24, "PK\\d{2}[A-Z]{4}[A-Z0-9]{16}" ), // Pakistan
new Validator("PL", 28, "PL\\d{26}" ), // Poland
new Validator("PS", 29, "PS\\d{2}[A-Z]{4}[A-Z0-9]{21}" ), // Palestine, State of
new Validator("PT", 25, "PT\\d{23}" ), // Portugal
new Validator("QA", 29, "QA\\d{2}[A-Z]{4}[A-Z0-9]{21}" ), // Qatar
new Validator("RO", 24, "RO\\d{2}[A-Z]{4}[A-Z0-9]{16}" ), // Romania
new Validator("RS", 22, "RS\\d{20}" ), // Serbia
new Validator("RU", 33, "RU\\d{31}" ), // Russia
new Validator("SA", 24, "SA\\d{4}[A-Z0-9]{18}" ), // Saudi Arabia
new Validator("SC", 31, "SC\\d{2}[A-Z]{4}\\d{20}[A-Z]{3}" ), // Seychelles
new Validator("SD", 18, "SD\\d{16}" ), // Sudan
new Validator("SE", 24, "SE\\d{22}" ), // Sweden
new Validator("SI", 19, "SI\\d{17}" ), // Slovenia
new Validator("SK", 24, "SK\\d{22}" ), // Slovakia
new Validator("SM", 27, "SM\\d{2}[A-Z]{1}\\d{10}[A-Z0-9]{12}" ), // San Marino
new Validator("ST", 25, "ST\\d{23}" ), // Sao Tome and Principe
new Validator("SV", 28, "SV\\d{2}[A-Z]{4}\\d{20}" ), // El Salvador
new Validator("TL", 23, "TL\\d{21}" ), // Timor-Leste
new Validator("TN", 24, "TN\\d{22}" ), // Tunisia
new Validator("TR", 26, "TR\\d{8}[A-Z0-9]{16}" ), // Turkey
new Validator("UA", 29, "UA\\d{8}[A-Z0-9]{19}" ), // Ukraine
new Validator("VA", 22, "VA\\d{20}" ), // Vatican City State
new Validator("VG", 24, "VG\\d{2}[A-Z]{4}\\d{16}" ), // Virgin Islands
new Validator("XK", 20, "XK\\d{18}" ), // Kosovo
};
/** The singleton instance which uses the default formats */
public static final IBANValidator DEFAULT_IBAN_VALIDATOR = new IBANValidator();
/**
* Return a singleton instance of the IBAN validator using the default formats
*
* @return A singleton instance of the IBAN validator
*/
public static IBANValidator getInstance() {
return DEFAULT_IBAN_VALIDATOR;
}
/**
* Create a default IBAN validator.
*/
public IBANValidator() {
this(DEFAULT_VALIDATORS);
}
/**
* Create an IBAN validator from the specified map of IBAN formats.
*
* @param validators map of IBAN formats
*/
public IBANValidator(final Validator[] validators) {
this.validatorMap = createValidators(validators);
}
private ConcurrentMap<String, Validator> createValidators(final Validator[] validators) {
final ConcurrentMap<String, Validator> map = new ConcurrentHashMap<>();
for (final Validator validator : validators) {
map.put(validator.countryCode, validator);
for (String otherCC : validator.otherCountryCodes) {
map.put(otherCC, validator);
}
}
return map;
}
/**
* Validate an IBAN Code
*
* @param code The value validation is being performed on
* @return {@code true} if the value is valid
*/
public boolean isValid(final String code) {
final Validator formatValidator = getValidator(code);
if (formatValidator == null || code.length() != formatValidator.ibanLength || !formatValidator.regexValidator.isValid(code)) {
return false;
}
return IBANCheckDigit.IBAN_CHECK_DIGIT.isValid(code);
}
/**
* Does the class have the required validator?
*
* @param code the code to check
* @return true if there is a validator
*/
public boolean hasValidator(final String code) {
return getValidator(code) != null;
}
/**
* Gets a copy of the default Validators.
*
* @return a copy of the default Validator array
*/
public Validator[] getDefaultValidators() {
return Arrays.copyOf(DEFAULT_VALIDATORS, DEFAULT_VALIDATORS.length);
}
/**
* Gets the Validator for a given IBAN
*
* @param code a string starting with the ISO country code (e.g. an IBAN)
*
* @return the validator or {@code null} if there is not one registered.
*/
public Validator getValidator(final String code) {
if (code == null || code.length() < SHORT_CODE_LEN) { // ensure we can extract the code
return null;
}
final String key = code.substring(0, SHORT_CODE_LEN);
return validatorMap.get(key);
}
/**
* Installs a validator.
* Will replace any existing entry which has the same countryCode
*
* @param validator the instance to install.
* @return the previous Validator, or {@code null} if there was none
* @throws IllegalStateException if an attempt is made to modify the singleton validator
*/
public Validator setValidator(final Validator validator) {
if (this == DEFAULT_IBAN_VALIDATOR) {
throw new IllegalStateException("The singleton validator cannot be modified");
}
return validatorMap.put(validator.countryCode, validator);
}
/**
* Installs a validator.
* Will replace any existing entry which has the same countryCode.
*
* @param countryCode the country code
* @param length the length of the IBAN. Must be ≥ 8 and ≤ 32.
* If the length is < 0, the validator is removed, and the format is not used.
* @param format the format of the IBAN (as a regular expression)
* @return the previous Validator, or {@code null} if there was none
* @throws IllegalArgumentException if there is a problem
* @throws IllegalStateException if an attempt is made to modify the singleton validator
*/
public Validator setValidator(final String countryCode, final int length, final String format) {
if (this == DEFAULT_IBAN_VALIDATOR) {
throw new IllegalStateException("The singleton validator cannot be modified");
}
if (length < 0) {
return validatorMap.remove(countryCode);
}
return setValidator(new Validator(countryCode, length, format));
}
}
| 7,979 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/routines/InetAddressValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
/**
* <p><b>InetAddress</b> validation and conversion routines (<code>java.net.InetAddress</code>).</p>
*
* <p>This class provides methods to validate a candidate IP address.
*
* <p>
* This class is a Singleton; you can retrieve the instance via the {@link #getInstance()} method.
* </p>
*
* @since 1.4
*/
public class InetAddressValidator implements Serializable {
private static final int MAX_BYTE = 128;
private static final int IPV4_MAX_OCTET_VALUE = 255;
private static final int MAX_UNSIGNED_SHORT = 0xffff;
private static final int BASE_16 = 16;
private static final long serialVersionUID = -919201640201914789L;
private static final String IPV4_REGEX =
"^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$";
// Max number of hex groups (separated by :) in an IPV6 address
private static final int IPV6_MAX_HEX_GROUPS = 8;
// Max hex digits in each IPv6 group
private static final int IPV6_MAX_HEX_DIGITS_PER_GROUP = 4;
/**
* Singleton instance of this class.
*/
private static final InetAddressValidator VALIDATOR = new InetAddressValidator();
/** IPv4 RegexValidator */
private final RegexValidator ipv4Validator = new RegexValidator(IPV4_REGEX);
private static final Pattern DIGITS_PATTERN = Pattern.compile("\\d{1,3}");
private static final Pattern ID_CHECK_PATTERN = Pattern.compile("[^\\s/%]+");
/**
* Returns the singleton instance of this validator.
* @return the singleton instance of this validator
*/
public static InetAddressValidator getInstance() {
return VALIDATOR;
}
/**
* Checks if the specified string is a valid IPv4 or IPv6 address.
* @param inetAddress the string to validate
* @return true if the string validates as an IP address
*/
public boolean isValid(final String inetAddress) {
return isValidInet4Address(inetAddress) || isValidInet6Address(inetAddress);
}
/**
* Validates an IPv4 address. Returns true if valid.
* @param inet4Address the IPv4 address to validate
* @return true if the argument contains a valid IPv4 address
*/
public boolean isValidInet4Address(final String inet4Address) {
// verify that address conforms to generic IPv4 format
final String[] groups = ipv4Validator.match(inet4Address);
if (groups == null) {
return false;
}
// verify that address subgroups are legal
for (final String ipSegment : groups) {
if (ipSegment == null || ipSegment.isEmpty()) {
return false;
}
int iIpSegment = 0;
try {
iIpSegment = Integer.parseInt(ipSegment);
} catch (final NumberFormatException e) {
return false;
}
if (iIpSegment > IPV4_MAX_OCTET_VALUE) {
return false;
}
if (ipSegment.length() > 1 && ipSegment.startsWith("0")) {
return false;
}
}
return true;
}
/**
* Validates an IPv6 address. Returns true if valid.
* @param inet6Address the IPv6 address to validate
* @return true if the argument contains a valid IPv6 address
*
* @since 1.4.1
*/
public boolean isValidInet6Address(String inet6Address) {
String[] parts;
// remove prefix size. This will appear after the zone id (if any)
parts = inet6Address.split("/", -1);
if (parts.length > 2) {
return false; // can only have one prefix specifier
}
if (parts.length == 2) {
if (!DIGITS_PATTERN.matcher(parts[1]).matches()) {
return false; // not a valid number
}
final int bits = Integer.parseInt(parts[1]); // cannot fail because of RE check
if (bits < 0 || bits > MAX_BYTE) {
return false; // out of range
}
}
// remove zone-id
parts = parts[0].split("%", -1);
if (parts.length > 2) {
return false;
}
// The id syntax is implementation independent, but it presumably cannot allow:
// whitespace, '/' or '%'
if (parts.length == 2 && !ID_CHECK_PATTERN.matcher(parts[1]).matches()) {
return false; // invalid id
}
inet6Address = parts[0];
final boolean containsCompressedZeroes = inet6Address.contains("::");
if (containsCompressedZeroes && inet6Address.indexOf("::") != inet6Address.lastIndexOf("::")) {
return false;
}
if (inet6Address.startsWith(":") && !inet6Address.startsWith("::")
|| inet6Address.endsWith(":") && !inet6Address.endsWith("::")) {
return false;
}
String[] octets = inet6Address.split(":");
if (containsCompressedZeroes) {
final List<String> octetList = new ArrayList<>(Arrays.asList(octets));
if (inet6Address.endsWith("::")) {
// String.split() drops ending empty segments
octetList.add("");
} else if (inet6Address.startsWith("::") && !octetList.isEmpty()) {
octetList.remove(0);
}
octets = octetList.toArray(new String[0]);
}
if (octets.length > IPV6_MAX_HEX_GROUPS) {
return false;
}
int validOctets = 0;
int emptyOctets = 0; // consecutive empty chunks
for (int index = 0; index < octets.length; index++) {
final String octet = octets[index];
if (octet.isEmpty()) {
emptyOctets++;
if (emptyOctets > 1) {
return false;
}
} else {
emptyOctets = 0;
// Is last chunk an IPv4 address?
if (index == octets.length - 1 && octet.contains(".")) {
if (!isValidInet4Address(octet)) {
return false;
}
validOctets += 2;
continue;
}
if (octet.length() > IPV6_MAX_HEX_DIGITS_PER_GROUP) {
return false;
}
int octetInt = 0;
try {
octetInt = Integer.parseInt(octet, BASE_16);
} catch (final NumberFormatException e) {
return false;
}
if (octetInt < 0 || octetInt > MAX_UNSIGNED_SHORT) {
return false;
}
}
validOctets++;
}
if (validOctets > IPV6_MAX_HEX_GROUPS || validOctets < IPV6_MAX_HEX_GROUPS && !containsCompressedZeroes) {
return false;
}
return true;
}
}
| 7,980 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/routines/AbstractNumberValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.Format;
import java.text.NumberFormat;
import java.util.Locale;
/**
* <p>Abstract class for Number Validation.</p>
*
* <p>This is a <i>base</i> class for building Number
* Validators using format parsing.</p>
*
* @since 1.3.0
*/
public abstract class AbstractNumberValidator extends AbstractFormatValidator {
private static final long serialVersionUID = -3088817875906765463L;
/** Standard <code>NumberFormat</code> type */
public static final int STANDARD_FORMAT = 0;
/** Currency <code>NumberFormat</code> type */
public static final int CURRENCY_FORMAT = 1;
/** Percent <code>NumberFormat</code> type */
public static final int PERCENT_FORMAT = 2;
private final boolean allowFractions;
private final int formatType;
/**
* Constructs an instance with specified <i>strict</i>
* and <i>decimal</i> parameters.
*
* @param strict {@code true} if strict
* <code>Format</code> parsing should be used.
* @param formatType The <code>NumberFormat</code> type to
* create for validation, default is STANDARD_FORMAT.
* @param allowFractions {@code true} if fractions are
* allowed or {@code false} if integers only.
*/
public AbstractNumberValidator(final boolean strict, final int formatType, final boolean allowFractions) {
super(strict);
this.allowFractions = allowFractions;
this.formatType = formatType;
}
/**
* <p>Indicates whether the number being validated is
* a decimal or integer.</p>
*
* @return {@code true} if decimals are allowed
* or {@code false} if the number is an integer.
*/
public boolean isAllowFractions() {
return allowFractions;
}
/**
* <p>Indicates the type of <code>NumberFormat</code> created
* by this validator instance.</p>
*
* @return the format type created.
*/
public int getFormatType() {
return formatType;
}
/**
* <p>Validate using the specified <code>Locale</code>.</p>
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against, or the
* default for the <code>Locale</code> if <code>null</code>.
* @param locale The locale to use for the date format, system default if null.
* @return {@code true} if the value is valid.
*/
@Override
public boolean isValid(final String value, final String pattern, final Locale locale) {
final Object parsedValue = parse(value, pattern, locale);
return parsedValue == null ? false : true;
}
/**
* Check if the value is within a specified range.
*
* @param value The value validation is being performed on.
* @param min The minimum value of the range.
* @param max The maximum value of the range.
* @return {@code true} if the value is within the
* specified range.
*/
public boolean isInRange(final Number value, final Number min, final Number max) {
return minValue(value, min) && maxValue(value, max);
}
/**
* Check if the value is greater than or equal to a minimum.
*
* @param value The value validation is being performed on.
* @param min The minimum value.
* @return {@code true} if the value is greater than
* or equal to the minimum.
*/
public boolean minValue(final Number value, final Number min) {
if (isAllowFractions()) {
return value.doubleValue() >= min.doubleValue();
}
return value.longValue() >= min.longValue();
}
/**
* Check if the value is less than or equal to a maximum.
*
* @param value The value validation is being performed on.
* @param max The maximum value.
* @return {@code true} if the value is less than
* or equal to the maximum.
*/
public boolean maxValue(final Number value, final Number max) {
if (isAllowFractions()) {
return value.doubleValue() <= max.doubleValue();
}
return value.longValue() <= max.longValue();
}
/**
* <p>Parse the value using the specified pattern.</p>
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against, or the
* default for the <code>Locale</code> if <code>null</code>.
* @param locale The locale to use for the date format, system default if null.
* @return The parsed value if valid or <code>null</code> if invalid.
*/
protected Object parse(String value, final String pattern, final Locale locale) {
value = value == null ? null : value.trim();
if (value == null || value.isEmpty()) {
return null;
}
final Format formatter = getFormat(pattern, locale);
return parse(value, formatter);
}
/**
* <p>Process the parsed value, performing any further validation
* and type conversion required.</p>
*
* @param value The parsed object created.
* @param formatter The Format used to parse the value with.
* @return The parsed value converted to the appropriate type
* if valid or <code>null</code> if invalid.
*/
@Override
protected abstract Object processParsedValue(Object value, Format formatter);
/**
* <p>Returns a <code>NumberFormat</code> for the specified <i>pattern</i>
* and/or <code>Locale</code>.</p>
*
* @param pattern The pattern used to validate the value against or
* <code>null</code> to use the default for the <code>Locale</code>.
* @param locale The locale to use for the currency format, system default if null.
* @return The <code>NumberFormat</code> to created.
*/
@Override
protected Format getFormat(final String pattern, final Locale locale) {
NumberFormat formatter;
final boolean usePattern = pattern != null && !pattern.isEmpty();
if (!usePattern) {
formatter = (NumberFormat)getFormat(locale);
} else if (locale == null) {
formatter = new DecimalFormat(pattern);
} else {
final DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale);
formatter = new DecimalFormat(pattern, symbols);
}
if (!isAllowFractions()) {
formatter.setParseIntegerOnly(true);
}
return formatter;
}
/**
* <p>Returns the <i>multiplier</i> of the <code>NumberFormat</code>.</p>
*
* @param format The <code>NumberFormat</code> to determine the
* multiplier of.
* @return The multiplying factor for the format..
*/
protected int determineScale(final NumberFormat format) {
if (!isStrict()) {
return -1;
}
if (!isAllowFractions() || format.isParseIntegerOnly()) {
return 0;
}
final int minimumFraction = format.getMinimumFractionDigits();
final int maximumFraction = format.getMaximumFractionDigits();
if (minimumFraction != maximumFraction) {
return -1;
}
int scale = minimumFraction;
if (format instanceof DecimalFormat) {
final int multiplier = ((DecimalFormat)format).getMultiplier();
if (multiplier == 100) { // CHECKSTYLE IGNORE MagicNumber
scale += 2; // CHECKSTYLE IGNORE MagicNumber
} else if (multiplier == 1000) { // CHECKSTYLE IGNORE MagicNumber
scale += 3; // CHECKSTYLE IGNORE MagicNumber
}
} else if (formatType == PERCENT_FORMAT) {
scale += 2; // CHECKSTYLE IGNORE MagicNumber
}
return scale;
}
/**
* <p>Returns a <code>NumberFormat</code> for the specified Locale.</p>
*
* @param locale The locale a <code>NumberFormat</code> is required for,
* system default if null.
* @return The <code>NumberFormat</code> to created.
*/
protected Format getFormat(final Locale locale) {
NumberFormat formatter;
switch (formatType) {
case CURRENCY_FORMAT:
if (locale == null) {
formatter = NumberFormat.getCurrencyInstance();
} else {
formatter = NumberFormat.getCurrencyInstance(locale);
}
break;
case PERCENT_FORMAT:
if (locale == null) {
formatter = NumberFormat.getPercentInstance();
} else {
formatter = NumberFormat.getPercentInstance(locale);
}
break;
default:
if (locale == null) {
formatter = NumberFormat.getInstance();
} else {
formatter = NumberFormat.getInstance(locale);
}
if (!isAllowFractions()) {
formatter.setParseIntegerOnly(true);
}
break;
}
return formatter;
}
}
| 7,981 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/routines/CalendarValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.text.DateFormat;
import java.text.Format;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
/**
* <p><b>Calendar Validation</b> and Conversion routines (<code>java.util.Calendar</code>).</p>
*
* <p>This validator provides a number of methods for validating/converting
* a <code>String</code> date value to a <code>java.util.Calendar</code> using
* <code>java.text.DateFormat</code> to parse either:</p>
* <ul>
* <li>using the default format for the default <code>Locale</code></li>
* <li>using a specified pattern with the default <code>Locale</code></li>
* <li>using the default format for a specified <code>Locale</code></li>
* <li>using a specified pattern with a specified <code>Locale</code></li>
* </ul>
*
* <p>For each of the above mechanisms, conversion method (i.e the
* <code>validate</code> methods) implementations are provided which
* either use the default <code>TimeZone</code> or allow the
* <code>TimeZone</code> to be specified.</p>
*
* <p>Use one of the <code>isValid()</code> methods to just validate or
* one of the <code>validate()</code> methods to validate and receive a
* <i>converted</i> <code>Calendar</code> value.</p>
*
* <p>Implementations of the <code>validate()</code> method are provided
* to create <code>Calendar</code> objects for different <i>time zones</i>
* if the system default is not appropriate.</p>
*
* <p>Alternatively the CalendarValidator's <code>adjustToTimeZone()</code> method
* can be used to adjust the <code>TimeZone</code> of the <code>Calendar</code>
* object afterwards.</p>
*
* <p>Once a value has been successfully converted the following
* methods can be used to perform various date comparison checks:</p>
* <ul>
* <li><code>compareDates()</code> compares the day, month and
* year of two calendars, returning 0, -1 or +1 indicating
* whether the first date is equal, before or after the second.</li>
* <li><code>compareWeeks()</code> compares the week and
* year of two calendars, returning 0, -1 or +1 indicating
* whether the first week is equal, before or after the second.</li>
* <li><code>compareMonths()</code> compares the month and
* year of two calendars, returning 0, -1 or +1 indicating
* whether the first month is equal, before or after the second.</li>
* <li><code>compareQuarters()</code> compares the quarter and
* year of two calendars, returning 0, -1 or +1 indicating
* whether the first quarter is equal, before or after the second.</li>
* <li><code>compareYears()</code> compares the
* year of two calendars, returning 0, -1 or +1 indicating
* whether the first year is equal, before or after the second.</li>
* </ul>
*
* <p>So that the same mechanism used for parsing an <i>input</i> value
* for validation can be used to format <i>output</i>, corresponding
* <code>format()</code> methods are also provided. That is you can
* format either:</p>
* <ul>
* <li>using a specified pattern</li>
* <li>using the format for a specified <code>Locale</code></li>
* <li>using the format for the <i>default</i> <code>Locale</code></li>
* </ul>
*
* @since 1.3.0
*/
public class CalendarValidator extends AbstractCalendarValidator {
private static final long serialVersionUID = 9109652318762134167L;
private static final CalendarValidator VALIDATOR = new CalendarValidator();
/**
* Return a singleton instance of this validator.
* @return A singleton instance of the CalendarValidator.
*/
public static CalendarValidator getInstance() {
return VALIDATOR;
}
/**
* Constructs a <i>strict</i> instance with <i>short</i>
* date style.
*/
public CalendarValidator() {
this(true, DateFormat.SHORT);
}
/**
* Constructs an instance with the specified <i>strict</i>
* and <i>date style</i> parameters.
*
* @param strict {@code true} if strict
* <code>Format</code> parsing should be used.
* @param dateStyle the date style to use for Locale validation.
*/
public CalendarValidator(final boolean strict, final int dateStyle) {
super(strict, dateStyle, -1);
}
/**
* <p>Validate/convert a <code>Calendar</code> using the default
* <code>Locale</code> and <code>TimeZone</code>.
*
* @param value The value validation is being performed on.
* @return The parsed <code>Calendar</code> if valid or <code>null</code>
* if invalid.
*/
public Calendar validate(final String value) {
return (Calendar)parse(value, (String)null, (Locale)null, (TimeZone)null);
}
/**
* <p>Validate/convert a <code>Calendar</code> using the specified
* <code>TimeZone</code> and default <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @param timeZone The Time Zone used to parse the date, system default if null.
* @return The parsed <code>Calendar</code> if valid or <code>null</code>
* if invalid.
*/
public Calendar validate(final String value, final TimeZone timeZone) {
return (Calendar)parse(value, (String)null, (Locale)null, timeZone);
}
/**
* <p>Validate/convert a <code>Calendar</code> using the specified
* <i>pattern</i> and default <code>TimeZone</code>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against.
* @return The parsed <code>Calendar</code> if valid or <code>null</code> if invalid.
*/
public Calendar validate(final String value, final String pattern) {
return (Calendar)parse(value, pattern, (Locale)null, (TimeZone)null);
}
/**
* <p>Validate/convert a <code>Calendar</code> using the specified
* <i>pattern</i> and <code>TimeZone</code>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against.
* @param timeZone The Time Zone used to parse the date, system default if null.
* @return The parsed <code>Calendar</code> if valid or <code>null</code> if invalid.
*/
public Calendar validate(final String value, final String pattern, final TimeZone timeZone) {
return (Calendar)parse(value, pattern, (Locale)null, timeZone);
}
/**
* <p>Validate/convert a <code>Calendar</code> using the specified
* <code>Locale</code> and default <code>TimeZone</code>.
*
* @param value The value validation is being performed on.
* @param locale The locale to use for the date format, system default if null.
* @return The parsed <code>Calendar</code> if valid or <code>null</code> if invalid.
*/
public Calendar validate(final String value, final Locale locale) {
return (Calendar)parse(value, (String)null, locale, (TimeZone)null);
}
/**
* <p>Validate/convert a <code>Calendar</code> using the specified
* <code>Locale</code> and <code>TimeZone</code>.
*
* @param value The value validation is being performed on.
* @param locale The locale to use for the date format, system default if null.
* @param timeZone The Time Zone used to parse the date, system default if null.
* @return The parsed <code>Calendar</code> if valid or <code>null</code> if invalid.
*/
public Calendar validate(final String value, final Locale locale, final TimeZone timeZone) {
return (Calendar)parse(value, (String)null, locale, timeZone);
}
/**
* <p>Validate/convert a <code>Calendar</code> using the specified pattern
* and <code>Locale</code> and the default <code>TimeZone</code>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against, or the
* default for the <code>Locale</code> if <code>null</code>.
* @param locale The locale to use for the date format, system default if null.
* @return The parsed <code>Calendar</code> if valid or <code>null</code> if invalid.
*/
public Calendar validate(final String value, final String pattern, final Locale locale) {
return (Calendar)parse(value, pattern, locale, (TimeZone)null);
}
/**
* <p>Validate/convert a <code>Calendar</code> using the specified
* pattern, and <code>Locale</code> and <code>TimeZone</code>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against, or the
* default for the <code>Locale</code> if <code>null</code>.
* @param locale The locale to use for the date format, system default if null.
* @param timeZone The Time Zone used to parse the date, system default if null.
* @return The parsed <code>Calendar</code> if valid or <code>null</code> if invalid.
*/
public Calendar validate(final String value, final String pattern, final Locale locale, final TimeZone timeZone) {
return (Calendar)parse(value, pattern, locale, timeZone);
}
/**
* <p>Adjusts a Calendar's value to a different TimeZone.</p>
*
* @param value The value to adjust.
* @param timeZone The new time zone to use to adjust the Calendar to.
*/
public static void adjustToTimeZone(final Calendar value, final TimeZone timeZone) {
if (value.getTimeZone().hasSameRules(timeZone)) {
value.setTimeZone(timeZone);
} else {
final int year = value.get(Calendar.YEAR);
final int month = value.get(Calendar.MONTH);
final int date = value.get(Calendar.DATE);
final int hour = value.get(Calendar.HOUR_OF_DAY);
final int minute = value.get(Calendar.MINUTE);
value.setTimeZone(timeZone);
value.set(year, month, date, hour, minute);
}
}
/**
* <p>Compare Dates (day, month and year - not time).</p>
*
* @param value The <code>Calendar</code> value to check.
* @param compare The <code>Calendar</code> to compare the value to.
* @return Zero if the dates are equal, -1 if first
* date is less than the seconds and +1 if the first
* date is greater than.
*/
public int compareDates(final Calendar value, final Calendar compare) {
return compare(value, compare, Calendar.DATE);
}
/**
* <p>Compare Weeks (week and year).</p>
*
* @param value The <code>Calendar</code> value to check.
* @param compare The <code>Calendar</code> to compare the value to.
* @return Zero if the weeks are equal, -1 if first
* parameter's week is less than the seconds and +1 if the first
* parameter's week is greater than.
*/
public int compareWeeks(final Calendar value, final Calendar compare) {
return compare(value, compare, Calendar.WEEK_OF_YEAR);
}
/**
* <p>Compare Months (month and year).</p>
*
* @param value The <code>Calendar</code> value to check.
* @param compare The <code>Calendar</code> to compare the value to.
* @return Zero if the months are equal, -1 if first
* parameter's month is less than the seconds and +1 if the first
* parameter's month is greater than.
*/
public int compareMonths(final Calendar value, final Calendar compare) {
return compare(value, compare, Calendar.MONTH);
}
/**
* <p>Compare Quarters (quarter and year).</p>
*
* @param value The <code>Calendar</code> value to check.
* @param compare The <code>Calendar</code> to check the value against.
* @return Zero if the quarters are equal, -1 if first
* parameter's quarter is less than the seconds and +1 if the first
* parameter's quarter is greater than.
*/
public int compareQuarters(final Calendar value, final Calendar compare) {
return compareQuarters(value, compare, 1);
}
/**
* <p>Compare Quarters (quarter and year).</p>
*
* @param value The <code>Calendar</code> value to check.
* @param compare The <code>Calendar</code> to compare the value to.
* @param monthOfFirstQuarter The month that the first quarter starts.
* @return Zero if the quarters are equal, -1 if first
* parameter's quarter is less than the seconds and +1 if the first
* parameter's quarter is greater than.
*/
@Override
public int compareQuarters(final Calendar value, final Calendar compare, final int monthOfFirstQuarter) {
return super.compareQuarters(value, compare, monthOfFirstQuarter);
}
/**
* <p>Compare Years.</p>
*
* @param value The <code>Calendar</code> value to check.
* @param compare The <code>Calendar</code> to compare the value to.
* @return Zero if the years are equal, -1 if first
* parameter's year is less than the seconds and +1 if the first
* parameter's year is greater than.
*/
public int compareYears(final Calendar value, final Calendar compare) {
return compare(value, compare, Calendar.YEAR);
}
/**
* <p>Convert the parsed <code>Date</code> to a <code>Calendar</code>.</p>
*
* @param value The parsed <code>Date</code> object created.
* @param formatter The Format used to parse the value with.
* @return The parsed value converted to a <code>Calendar</code>.
*/
@Override
protected Object processParsedValue(final Object value, final Format formatter) {
return ((DateFormat)formatter).getCalendar();
}
}
| 7,982 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/routines/ByteValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.text.Format;
import java.util.Locale;
/**
* <p><b>Byte Validation</b> and Conversion routines (<code>java.lang.Byte</code>).</p>
*
* <p>This validator provides a number of methods for
* validating/converting a <code>String</code> value to
* a <code>Byte</code> using <code>java.text.NumberFormat</code>
* to parse either:</p>
* <ul>
* <li>using the default format for the default <code>Locale</code></li>
* <li>using a specified pattern with the default <code>Locale</code></li>
* <li>using the default format for a specified <code>Locale</code></li>
* <li>using a specified pattern with a specified <code>Locale</code></li>
* </ul>
*
* <p>Use one of the <code>isValid()</code> methods to just validate or
* one of the <code>validate()</code> methods to validate and receive a
* <i>converted</i> <code>Byte</code> value.</p>
*
* <p>Once a value has been successfully converted the following
* methods can be used to perform minimum, maximum and range checks:</p>
* <ul>
* <li><code>minValue()</code> checks whether the value is greater
* than or equal to a specified minimum.</li>
* <li><code>maxValue()</code> checks whether the value is less
* than or equal to a specified maximum.</li>
* <li><code>isInRange()</code> checks whether the value is within
* a specified range of values.</li>
* </ul>
*
* <p>So that the same mechanism used for parsing an <i>input</i> value
* for validation can be used to format <i>output</i>, corresponding
* <code>format()</code> methods are also provided. That is you can
* format either:</p>
* <ul>
* <li>using the default format for the default <code>Locale</code></li>
* <li>using a specified pattern with the default <code>Locale</code></li>
* <li>using the default format for a specified <code>Locale</code></li>
* <li>using a specified pattern with a specified <code>Locale</code></li>
* </ul>
*
* @since 1.3.0
*/
public class ByteValidator extends AbstractNumberValidator {
private static final long serialVersionUID = 7001640945881854649L;
private static final ByteValidator VALIDATOR = new ByteValidator();
/**
* Return a singleton instance of this validator.
* @return A singleton instance of the ByteValidator.
*/
public static ByteValidator getInstance() {
return VALIDATOR;
}
/**
* Constructs a <i>strict</i> instance.
*/
public ByteValidator() {
this(true, STANDARD_FORMAT);
}
/**
* <p>Construct an instance with the specified strict setting
* and format type.</p>
*
* <p>The <code>formatType</code> specified what type of
* <code>NumberFormat</code> is created - valid types
* are:</p>
* <ul>
* <li>AbstractNumberValidator.STANDARD_FORMAT -to create
* <i>standard</i> number formats (the default).</li>
* <li>AbstractNumberValidator.CURRENCY_FORMAT -to create
* <i>currency</i> number formats.</li>
* <li>AbstractNumberValidator.PERCENT_FORMAT -to create
* <i>percent</i> number formats (the default).</li>
* </ul>
*
* @param strict {@code true} if strict
* <code>Format</code> parsing should be used.
* @param formatType The <code>NumberFormat</code> type to
* create for validation, default is STANDARD_FORMAT.
*/
public ByteValidator(final boolean strict, final int formatType) {
super(strict, formatType, false);
}
/**
* <p>Validate/convert a <code>Byte</code> using the default
* <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @return The parsed <code>Byte</code> if valid or <code>null</code>
* if invalid.
*/
public Byte validate(final String value) {
return (Byte)parse(value, (String)null, (Locale)null);
}
/**
* <p>Validate/convert a <code>Byte</code> using the
* specified <i>pattern</i>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against.
* @return The parsed <code>Byte</code> if valid or <code>null</code> if invalid.
*/
public Byte validate(final String value, final String pattern) {
return (Byte)parse(value, pattern, (Locale)null);
}
/**
* <p>Validate/convert a <code>Byte</code> using the
* specified <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @param locale The locale to use for the number format, system default if null.
* @return The parsed <code>Byte</code> if valid or <code>null</code> if invalid.
*/
public Byte validate(final String value, final Locale locale) {
return (Byte)parse(value, (String)null, locale);
}
/**
* <p>Validate/convert a <code>Byte</code> using the
* specified pattern and/ or <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against, or the
* default for the <code>Locale</code> if <code>null</code>.
* @param locale The locale to use for the date format, system default if null.
* @return The parsed <code>Byte</code> if valid or <code>null</code> if invalid.
*/
public Byte validate(final String value, final String pattern, final Locale locale) {
return (Byte)parse(value, pattern, locale);
}
/**
* Check if the value is within a specified range.
*
* @param value The <code>Number</code> value to check.
* @param min The minimum value of the range.
* @param max The maximum value of the range.
* @return {@code true} if the value is within the
* specified range.
*/
public boolean isInRange(final byte value, final byte min, final byte max) {
return value >= min && value <= max;
}
/**
* Check if the value is within a specified range.
*
* @param value The <code>Number</code> value to check.
* @param min The minimum value of the range.
* @param max The maximum value of the range.
* @return {@code true} if the value is within the
* specified range.
*/
public boolean isInRange(final Byte value, final byte min, final byte max) {
return isInRange(value.byteValue(), min, max);
}
/**
* Check if the value is greater than or equal to a minimum.
*
* @param value The value validation is being performed on.
* @param min The minimum value.
* @return {@code true} if the value is greater than
* or equal to the minimum.
*/
public boolean minValue(final byte value, final byte min) {
return value >= min;
}
/**
* Check if the value is greater than or equal to a minimum.
*
* @param value The value validation is being performed on.
* @param min The minimum value.
* @return {@code true} if the value is greater than
* or equal to the minimum.
*/
public boolean minValue(final Byte value, final byte min) {
return minValue(value.byteValue(), min);
}
/**
* Check if the value is less than or equal to a maximum.
*
* @param value The value validation is being performed on.
* @param max The maximum value.
* @return {@code true} if the value is less than
* or equal to the maximum.
*/
public boolean maxValue(final byte value, final byte max) {
return value <= max;
}
/**
* Check if the value is less than or equal to a maximum.
*
* @param value The value validation is being performed on.
* @param max The maximum value.
* @return {@code true} if the value is less than
* or equal to the maximum.
*/
public boolean maxValue(final Byte value, final byte max) {
return maxValue(value.byteValue(), max);
}
/**
* <p>Perform further validation and convert the <code>Number</code> to
* a <code>Byte</code>.</p>
*
* @param value The parsed <code>Number</code> object created.
* @param formatter The Format used to parse the value with.
* @return The parsed <code>Number</code> converted to a
* <code>Byte</code> if valid or <code>null</code> if invalid.
*/
@Override
protected Object processParsedValue(final Object value, final Format formatter) {
// Parsed value will be Long if it fits in a long and is not fractional
if (value instanceof Long) {
final long longValue = ((Long)value).longValue();
if (longValue >= Byte.MIN_VALUE &&
longValue <= Byte.MAX_VALUE) {
return Byte.valueOf((byte)longValue);
}
}
return null;
}
}
| 7,983 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/routines/ISSNValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.io.Serializable;
import org.apache.commons.validator.routines.checkdigit.CheckDigitException;
import org.apache.commons.validator.routines.checkdigit.EAN13CheckDigit;
import org.apache.commons.validator.routines.checkdigit.ISSNCheckDigit;
/**
* International Standard Serial Number (ISSN)
* is an eight-digit serial number used to
* uniquely identify a serial publication.
* <pre>
* The format is:
*
* ISSN dddd-dddC
* where:
* d = decimal digit (0-9)
* C = checksum (0-9 or X)
*
* The checksum is formed by adding the first 7 digits multiplied by
* the position in the entire number (counting from the right).
*
* For example, abcd-efg would be 8a + 7b + 6c + 5d + 4e +3f +2g.
* The check digit is modulus 11, where the value 10 is represented by 'X'
* For example:
* ISSN 0317-8471
* ISSN 1050-124X
*
* This class strips off the 'ISSN ' prefix if it is present before passing
* the remainder to the checksum routine.
*
* </pre>
* <p>
* Note: the {@link #isValid(String)} and {@link #validate(String)} methods strip off any leading
* or trailing spaces before doing the validation.
* To ensure that only a valid code (without 'ISSN ' prefix) is passed to a method,
* use the following code:
* <pre>
* Object valid = validator.validate(input);
* if (valid != null) {
* some_method(valid.toString());
* }
* </pre>
* @since 1.5.0
*/
public class ISSNValidator implements Serializable {
private static final long serialVersionUID = 4319515687976420405L;
private static final String ISSN_REGEX = "(?:ISSN )?(\\d{4})-(\\d{3}[0-9X])$"; // We don't include the '-' in the code, so it is 8 chars
private static final int ISSN_LEN = 8;
private static final String ISSN_PREFIX = "977";
private static final String EAN_ISSN_REGEX = "^(977)(?:(\\d{10}))$";
private static final int EAN_ISSN_LEN = 13;
private static final CodeValidator VALIDATOR = new CodeValidator(ISSN_REGEX, ISSN_LEN, ISSNCheckDigit.ISSN_CHECK_DIGIT);
private static final CodeValidator EAN_VALIDATOR = new CodeValidator(EAN_ISSN_REGEX, EAN_ISSN_LEN, EAN13CheckDigit.EAN13_CHECK_DIGIT);
/** ISSN Code Validator */
private static final ISSNValidator ISSN_VALIDATOR = new ISSNValidator();
/**
* Return a singleton instance of the ISSN validator
*
* @return A singleton instance of the ISSN validator.
*/
public static ISSNValidator getInstance() {
return ISSN_VALIDATOR;
}
/**
* Check the code is a valid EAN code.
* <p>
* If valid, this method returns the EAN code
*
* @param code The code to validate.
* @return A valid EAN code if valid, otherwise <code>null</code>.
* @since 1.7
*/
public Object validateEan(final String code) {
return EAN_VALIDATOR.validate(code);
}
/**
* Check the code is a valid ISSN code after any transformation
* by the validate routine.
* @param code The code to validate.
* @return {@code true} if a valid ISSN
* code, otherwise {@code false}.
*/
public boolean isValid(final String code) {
return VALIDATOR.isValid(code);
}
/**
* Check the code is valid ISSN code.
* <p>
* If valid, this method returns the ISSN code with
* the 'ISSN ' prefix removed (if it was present)
*
* @param code The code to validate.
* @return A valid ISSN code if valid, otherwise <code>null</code>.
*/
public Object validate(final String code) {
return VALIDATOR.validate(code);
}
/**
* Convert an ISSN code to an EAN-13 code.
* <p>
* This method requires a valid ISSN code.
* It may contain a leading 'ISSN ' prefix,
* as the input is passed through the {@link #validate(String)}
* method.
*
* @param issn The ISSN code to convert
* @param suffix the two digit suffix, e.g. "00"
* @return A converted EAN-13 code or <code>null</code>
* if the input ISSN code is not valid
*/
public String convertToEAN13(final String issn, final String suffix) {
if (suffix == null || !suffix.matches("\\d\\d")) {
throw new IllegalArgumentException("Suffix must be two digits: '" + suffix + "'");
}
final Object result = validate(issn);
if (result == null) {
return null;
}
// Calculate the new EAN-13 code
final String input = result.toString();
String ean13 = ISSN_PREFIX + input.substring(0, input.length() -1) + suffix;
try {
final String checkDigit = EAN13CheckDigit.EAN13_CHECK_DIGIT.calculate(ean13);
ean13 += checkDigit;
return ean13;
} catch (final CheckDigitException e) { // Should not happen
throw new IllegalArgumentException("Check digit error for '" + ean13 + "' - " + e.getMessage());
}
}
/**
* Extract an ISSN code from an ISSN-EAN-13 code.
* <p>
* This method requires a valid ISSN-EAN-13 code with NO formatting
* characters.
* That is a 13 digit EAN-13 code with the '977' prefix
*
* @param ean13 The ISSN code to convert
* @return A valid ISSN code or <code>null</code>
* if the input ISSN EAN-13 code is not valid
* @since 1.7
*/
public String extractFromEAN13(final String ean13) {
String input = ean13.trim();
if (input.length() != EAN_ISSN_LEN ) {
throw new IllegalArgumentException("Invalid length " + input.length() + " for '" + input + "'");
}
if (!input.startsWith(ISSN_PREFIX)) {
throw new IllegalArgumentException("Prefix must be " + ISSN_PREFIX + " to contain an ISSN: '" + ean13 + "'");
}
final Object result = validateEan(input);
if (result == null) {
return null;
}
// Calculate the ISSN code
input = result.toString();
try {
//CHECKSTYLE:OFF: MagicNumber
final String issnBase = input.substring(3,10); // TODO: how to derive these
//CHECKSTYLE:ON: MagicNumber
final String checkDigit = ISSNCheckDigit.ISSN_CHECK_DIGIT.calculate(issnBase);
final String issn = issnBase + checkDigit;
return issn;
} catch (final CheckDigitException e) { // Should not happen
throw new IllegalArgumentException("Check digit error for '" + ean13 + "' - " + e.getMessage());
}
}
}
| 7,984 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/routines/IntegerValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.text.Format;
import java.util.Locale;
/**
* <p><b>Integer Validation</b> and Conversion routines (<code>java.lang.Integer</code>).</p>
*
* <p>This validator provides a number of methods for
* validating/converting a <code>String</code> value to
* a <code>Integer</code> using <code>java.text.NumberFormat</code>
* to parse either:</p>
* <ul>
* <li>using the default format for the default <code>Locale</code></li>
* <li>using a specified pattern with the default <code>Locale</code></li>
* <li>using the default format for a specified <code>Locale</code></li>
* <li>using a specified pattern with a specified <code>Locale</code></li>
* </ul>
*
* <p>Use one of the <code>isValid()</code> methods to just validate or
* one of the <code>validate()</code> methods to validate and receive a
* <i>converted</i> <code>Integer</code> value.</p>
*
* <p>Once a value has been successfully converted the following
* methods can be used to perform minimum, maximum and range checks:</p>
* <ul>
* <li><code>minValue()</code> checks whether the value is greater
* than or equal to a specified minimum.</li>
* <li><code>maxValue()</code> checks whether the value is less
* than or equal to a specified maximum.</li>
* <li><code>isInRange()</code> checks whether the value is within
* a specified range of values.</li>
* </ul>
*
* <p>So that the same mechanism used for parsing an <i>input</i> value
* for validation can be used to format <i>output</i>, corresponding
* <code>format()</code> methods are also provided. That is you can
* format either:</p>
* <ul>
* <li>using the default format for the default <code>Locale</code></li>
* <li>using a specified pattern with the default <code>Locale</code></li>
* <li>using the default format for a specified <code>Locale</code></li>
* <li>using a specified pattern with a specified <code>Locale</code></li>
* </ul>
*
* @since 1.3.0
*/
public class IntegerValidator extends AbstractNumberValidator {
private static final long serialVersionUID = 422081746310306596L;
private static final IntegerValidator VALIDATOR = new IntegerValidator();
/**
* Return a singleton instance of this validator.
* @return A singleton instance of the IntegerValidator.
*/
public static IntegerValidator getInstance() {
return VALIDATOR;
}
/**
* Constructs a <i>strict</i> instance.
*/
public IntegerValidator() {
this(true, STANDARD_FORMAT);
}
/**
* <p>Construct an instance with the specified strict setting
* and format type.</p>
*
* <p>The <code>formatType</code> specified what type of
* <code>NumberFormat</code> is created - valid types
* are:</p>
* <ul>
* <li>AbstractNumberValidator.STANDARD_FORMAT -to create
* <i>standard</i> number formats (the default).</li>
* <li>AbstractNumberValidator.CURRENCY_FORMAT -to create
* <i>currency</i> number formats.</li>
* <li>AbstractNumberValidator.PERCENT_FORMAT -to create
* <i>percent</i> number formats (the default).</li>
* </ul>
*
* @param strict {@code true} if strict
* <code>Format</code> parsing should be used.
* @param formatType The <code>NumberFormat</code> type to
* create for validation, default is STANDARD_FORMAT.
*/
public IntegerValidator(final boolean strict, final int formatType) {
super(strict, formatType, false);
}
/**
* <p>Validate/convert an <code>Integer</code> using the default
* <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @return The parsed <code>Integer</code> if valid or <code>null</code>
* if invalid.
*/
public Integer validate(final String value) {
return (Integer)parse(value, (String)null, (Locale)null);
}
/**
* <p>Validate/convert an <code>Integer</code> using the
* specified <i>pattern</i>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against.
* @return The parsed <code>Integer</code> if valid or <code>null</code> if invalid.
*/
public Integer validate(final String value, final String pattern) {
return (Integer)parse(value, pattern, (Locale)null);
}
/**
* <p>Validate/convert an <code>Integer</code> using the
* specified <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @param locale The locale to use for the number format, system default if null.
* @return The parsed <code>Integer</code> if valid or <code>null</code> if invalid.
*/
public Integer validate(final String value, final Locale locale) {
return (Integer)parse(value, (String)null, locale);
}
/**
* <p>Validate/convert a <code>Integer</code> using the
* specified pattern and/ or <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against, or the
* default for the <code>Locale</code> if <code>null</code>.
* @param locale The locale to use for the date format, system default if null.
* @return The parsed <code>Integer</code> if valid or <code>null</code> if invalid.
*/
public Integer validate(final String value, final String pattern, final Locale locale) {
return (Integer)parse(value, pattern, locale);
}
/**
* Check if the value is within a specified range.
*
* @param value The <code>Number</code> value to check.
* @param min The minimum value of the range.
* @param max The maximum value of the range.
* @return {@code true} if the value is within the
* specified range.
*/
public boolean isInRange(final int value, final int min, final int max) {
return value >= min && value <= max;
}
/**
* Check if the value is within a specified range.
*
* @param value The <code>Number</code> value to check.
* @param min The minimum value of the range.
* @param max The maximum value of the range.
* @return {@code true} if the value is within the
* specified range.
*/
public boolean isInRange(final Integer value, final int min, final int max) {
return isInRange(value.intValue(), min, max);
}
/**
* Check if the value is greater than or equal to a minimum.
*
* @param value The value validation is being performed on.
* @param min The minimum value.
* @return {@code true} if the value is greater than
* or equal to the minimum.
*/
public boolean minValue(final int value, final int min) {
return value >= min;
}
/**
* Check if the value is greater than or equal to a minimum.
*
* @param value The value validation is being performed on.
* @param min The minimum value.
* @return {@code true} if the value is greater than
* or equal to the minimum.
*/
public boolean minValue(final Integer value, final int min) {
return minValue(value.intValue(), min);
}
/**
* Check if the value is less than or equal to a maximum.
*
* @param value The value validation is being performed on.
* @param max The maximum value.
* @return {@code true} if the value is less than
* or equal to the maximum.
*/
public boolean maxValue(final int value, final int max) {
return value <= max;
}
/**
* Check if the value is less than or equal to a maximum.
*
* @param value The value validation is being performed on.
* @param max The maximum value.
* @return {@code true} if the value is less than
* or equal to the maximum.
*/
public boolean maxValue(final Integer value, final int max) {
return maxValue(value.intValue(), max);
}
/**
* <p>Perform further validation and convert the <code>Number</code> to
* an <code>Integer</code>.</p>
*
* @param value The parsed <code>Number</code> object created.
* @param formatter The Format used to parse the value with.
* @return The parsed <code>Number</code> converted to an
* <code>Integer</code> if valid or <code>null</code> if invalid.
*/
@Override
protected Object processParsedValue(final Object value, final Format formatter) {
// Parsed value will be Long if it fits in a long and is not fractional
if (value instanceof Long) {
final long longValue = ((Long)value).longValue();
if (longValue >= Integer.MIN_VALUE &&
longValue <= Integer.MAX_VALUE) {
return Integer.valueOf((int)longValue);
}
}
return null;
}
}
| 7,985 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/routines/DateValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.text.DateFormat;
import java.text.Format;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* <p><b>Date Validation</b> and Conversion routines (<code>java.util.Date</code>).</p>
*
* <p>This validator provides a number of methods for validating/converting
* a <code>String</code> date value to a <code>java.util.Date</code> using
* <code>java.text.DateFormat</code> to parse either:</p>
* <ul>
* <li>using the default format for the default <code>Locale</code></li>
* <li>using a specified pattern with the default <code>Locale</code></li>
* <li>using the default format for a specified <code>Locale</code></li>
* <li>using a specified pattern with a specified <code>Locale</code></li>
* </ul>
*
* <p>For each of the above mechanisms, conversion method (i.e the
* <code>validate</code> methods) implementations are provided which
* either use the default <code>TimeZone</code> or allow the
* <code>TimeZone</code> to be specified.</p>
*
* <p>Use one of the <code>isValid()</code> methods to just validate or
* one of the <code>validate()</code> methods to validate and receive a
* <i>converted</i> <code>Date</code> value.</p>
*
* <p>Implementations of the <code>validate()</code> method are provided
* to create <code>Date</code> objects for different <i>time zones</i>
* if the system default is not appropriate.</p>
*
* <p>Once a value has been successfully converted the following
* methods can be used to perform various date comparison checks:</p>
* <ul>
* <li><code>compareDates()</code> compares the day, month and
* year of two dates, returning 0, -1 or +1 indicating
* whether the first date is equal, before or after the second.</li>
* <li><code>compareWeeks()</code> compares the week and
* year of two dates, returning 0, -1 or +1 indicating
* whether the first week is equal, before or after the second.</li>
* <li><code>compareMonths()</code> compares the month and
* year of two dates, returning 0, -1 or +1 indicating
* whether the first month is equal, before or after the second.</li>
* <li><code>compareQuarters()</code> compares the quarter and
* year of two dates, returning 0, -1 or +1 indicating
* whether the first quarter is equal, before or after the second.</li>
* <li><code>compareYears()</code> compares the
* year of two dates, returning 0, -1 or +1 indicating
* whether the first year is equal, before or after the second.</li>
* </ul>
*
* <p>So that the same mechanism used for parsing an <i>input</i> value
* for validation can be used to format <i>output</i>, corresponding
* <code>format()</code> methods are also provided. That is you can
* format either:</p>
* <ul>
* <li>using a specified pattern</li>
* <li>using the format for a specified <code>Locale</code></li>
* <li>using the format for the <i>default</i> <code>Locale</code></li>
* </ul>
*
* @since 1.3.0
*/
public class DateValidator extends AbstractCalendarValidator {
private static final long serialVersionUID = -3966328400469953190L;
private static final DateValidator VALIDATOR = new DateValidator();
/**
* Return a singleton instance of this validator.
* @return A singleton instance of the DateValidator.
*/
public static DateValidator getInstance() {
return VALIDATOR;
}
/**
* Constructs a <i>strict</i> instance with <i>short</i>
* date style.
*/
public DateValidator() {
this(true, DateFormat.SHORT);
}
/**
* Constructs an instance with the specified <i>strict</i>
* and <i>date style</i> parameters.
*
* @param strict {@code true} if strict
* <code>Format</code> parsing should be used.
* @param dateStyle the date style to use for Locale validation.
*/
public DateValidator(final boolean strict, final int dateStyle) {
super(strict, dateStyle, -1);
}
/**
* <p>Validate/convert a <code>Date</code> using the default
* <code>Locale</code> and <code>TimeZone</code>.
*
* @param value The value validation is being performed on.
* @return The parsed <code>Date</code> if valid or <code>null</code>
* if invalid.
*/
public Date validate(final String value) {
return (Date)parse(value, (String)null, (Locale)null, (TimeZone)null);
}
/**
* <p>Validate/convert a <code>Date</code> using the specified
* <code>TimeZone</code> and default <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @param timeZone The Time Zone used to parse the date, system default if null.
* @return The parsed <code>Date</code> if valid or <code>null</code> if invalid.
*/
public Date validate(final String value, final TimeZone timeZone) {
return (Date)parse(value, (String)null, (Locale)null, timeZone);
}
/**
* <p>Validate/convert a <code>Date</code> using the specified
* <i>pattern</i> and default <code>TimeZone</code>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against, or the
* default for the <code>Locale</code> if <code>null</code>.
* @return The parsed <code>Date</code> if valid or <code>null</code> if invalid.
*/
public Date validate(final String value, final String pattern) {
return (Date)parse(value, pattern, (Locale)null, (TimeZone)null);
}
/**
* <p>Validate/convert a <code>Date</code> using the specified
* <i>pattern</i> and <code>TimeZone</code>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against, or the
* default for the <code>Locale</code> if <code>null</code>.
* @param timeZone The Time Zone used to parse the date, system default if null.
* @return The parsed <code>Date</code> if valid or <code>null</code> if invalid.
*/
public Date validate(final String value, final String pattern, final TimeZone timeZone) {
return (Date)parse(value, pattern, (Locale)null, timeZone);
}
/**
* <p>Validate/convert a <code>Date</code> using the specified
* <code>Locale</code> and default <code>TimeZone</code>.
*
* @param value The value validation is being performed on.
* @param locale The locale to use for the date format, system default if null.
* @return The parsed <code>Date</code> if valid or <code>null</code> if invalid.
*/
public Date validate(final String value, final Locale locale) {
return (Date)parse(value, (String)null, locale, (TimeZone)null);
}
/**
* <p>Validate/convert a <code>Date</code> using the specified
* <code>Locale</code> and <code>TimeZone</code>.
*
* @param value The value validation is being performed on.
* @param locale The locale to use for the date format, system default if null.
* @param timeZone The Time Zone used to parse the date, system default if null.
* @return The parsed <code>Date</code> if valid or <code>null</code> if invalid.
*/
public Date validate(final String value, final Locale locale, final TimeZone timeZone) {
return (Date)parse(value, (String)null, locale, timeZone);
}
/**
* <p>Validate/convert a <code>Date</code> using the specified pattern
* and <code>Locale</code> and the default <code>TimeZone</code>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against, or the
* default for the <code>Locale</code> if <code>null</code>.
* @param locale The locale to use for the date format, system default if null.
* @return The parsed <code>Date</code> if valid or <code>null</code> if invalid.
*/
public Date validate(final String value, final String pattern, final Locale locale) {
return (Date)parse(value, pattern, locale, (TimeZone)null);
}
/**
* <p>Validate/convert a <code>Date</code> using the specified
* pattern, and <code>Locale</code> and <code>TimeZone</code>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against, or the
* default for the <code>Locale</code> if <code>null</code>.
* @param locale The locale to use for the date format, system default if null.
* @param timeZone The Time Zone used to parse the date, system default if null.
* @return The parsed <code>Date</code> if valid or <code>null</code> if invalid.
*/
public Date validate(final String value, final String pattern, final Locale locale, final TimeZone timeZone) {
return (Date)parse(value, pattern, locale, timeZone);
}
/**
* <p>Compare Dates (day, month and year - not time).</p>
*
* @param value The <code>Calendar</code> value to check.
* @param compare The <code>Calendar</code> to compare the value to.
* @param timeZone The Time Zone used to compare the dates, system default if null.
* @return Zero if the dates are equal, -1 if first
* date is less than the seconds and +1 if the first
* date is greater than.
*/
public int compareDates(final Date value, final Date compare, final TimeZone timeZone) {
final Calendar calendarValue = getCalendar(value, timeZone);
final Calendar calendarCompare = getCalendar(compare, timeZone);
return compare(calendarValue, calendarCompare, Calendar.DATE);
}
/**
* <p>Compare Weeks (week and year).</p>
*
* @param value The <code>Date</code> value to check.
* @param compare The <code>Date</code> to compare the value to.
* @param timeZone The Time Zone used to compare the dates, system default if null.
* @return Zero if the weeks are equal, -1 if first
* parameter's week is less than the seconds and +1 if the first
* parameter's week is greater than.
*/
public int compareWeeks(final Date value, final Date compare, final TimeZone timeZone) {
final Calendar calendarValue = getCalendar(value, timeZone);
final Calendar calendarCompare = getCalendar(compare, timeZone);
return compare(calendarValue, calendarCompare, Calendar.WEEK_OF_YEAR);
}
/**
* <p>Compare Months (month and year).</p>
*
* @param value The <code>Date</code> value to check.
* @param compare The <code>Date</code> to compare the value to.
* @param timeZone The Time Zone used to compare the dates, system default if null.
* @return Zero if the months are equal, -1 if first
* parameter's month is less than the seconds and +1 if the first
* parameter's month is greater than.
*/
public int compareMonths(final Date value, final Date compare, final TimeZone timeZone) {
final Calendar calendarValue = getCalendar(value, timeZone);
final Calendar calendarCompare = getCalendar(compare, timeZone);
return compare(calendarValue, calendarCompare, Calendar.MONTH);
}
/**
* <p>Compare Quarters (quarter and year).</p>
*
* @param value The <code>Date</code> value to check.
* @param compare The <code>Date</code> to compare the value to.
* @param timeZone The Time Zone used to compare the dates, system default if null.
* @return Zero if the months are equal, -1 if first
* parameter's quarter is less than the seconds and +1 if the first
* parameter's quarter is greater than.
*/
public int compareQuarters(final Date value, final Date compare, final TimeZone timeZone) {
return compareQuarters(value, compare, timeZone, 1);
}
/**
* <p>Compare Quarters (quarter and year).</p>
*
* @param value The <code>Date</code> value to check.
* @param compare The <code>Date</code> to compare the value to.
* @param timeZone The Time Zone used to compare the dates, system default if null.
* @param monthOfFirstQuarter The month that the first quarter starts.
* @return Zero if the quarters are equal, -1 if first
* parameter's quarter is less than the seconds and +1 if the first
* parameter's quarter is greater than.
*/
public int compareQuarters(final Date value, final Date compare, final TimeZone timeZone, final int monthOfFirstQuarter) {
final Calendar calendarValue = getCalendar(value, timeZone);
final Calendar calendarCompare = getCalendar(compare, timeZone);
return super.compareQuarters(calendarValue, calendarCompare, monthOfFirstQuarter);
}
/**
* <p>Compare Years.</p>
*
* @param value The <code>Date</code> value to check.
* @param compare The <code>Date</code> to compare the value to.
* @param timeZone The Time Zone used to compare the dates, system default if null.
* @return Zero if the years are equal, -1 if first
* parameter's year is less than the seconds and +1 if the first
* parameter's year is greater than.
*/
public int compareYears(final Date value, final Date compare, final TimeZone timeZone) {
final Calendar calendarValue = getCalendar(value, timeZone);
final Calendar calendarCompare = getCalendar(compare, timeZone);
return compare(calendarValue, calendarCompare, Calendar.YEAR);
}
/**
* <p>Returns the parsed <code>Date</code> unchanged.</p>
*
* @param value The parsed <code>Date</code> object created.
* @param formatter The Format used to parse the value with.
* @return The parsed value converted to a <code>Calendar</code>.
*/
@Override
protected Object processParsedValue(final Object value, final Format formatter) {
return value;
}
/**
* <p>Convert a <code>Date</code> to a <code>Calendar</code>.</p>
*
* @param value The date value to be converted.
* @return The converted <code>Calendar</code>.
*/
private Calendar getCalendar(final Date value, final TimeZone timeZone) {
Calendar calendar;
if (timeZone != null) {
calendar = Calendar.getInstance(timeZone);
} else {
calendar = Calendar.getInstance();
}
calendar.setTime(value);
return calendar;
}
}
| 7,986 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/routines/CurrencyValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.text.DecimalFormat;
import java.text.Format;
/**
* <p><b>Currency Validation</b> and Conversion routines (<code>java.math.BigDecimal</code>).</p>
*
* <p>This is one implementation of a currency validator that has the following features:</p>
* <ul>
* <li>It is <i>lenient</i> about the presence of the <i>currency symbol</i></li>
* <li>It converts the currency to a <code>java.math.BigDecimal</code></li>
* </ul>
*
* <p>However any of the <i>number</i> validators can be used for <i>currency</i> validation.
* For example, if you wanted a <i>currency</i> validator that converts to a
* <code>java.lang.Integer</code> then you can simply instantiate an
* <code>IntegerValidator</code> with the appropriate <i>format type</i>:</p>
*
* <p><code>... = new IntegerValidator(false, IntegerValidator.CURRENCY_FORMAT);</code></p>
*
* <p>Pick the appropriate validator, depending on the type (e.g Float, Double, Integer, Long etc)
* you want the currency converted to. One thing to note - only the CurrencyValidator
* implements <i>lenient</i> behavior regarding the currency symbol.</p>
*
* @since 1.3.0
*/
public class CurrencyValidator extends BigDecimalValidator {
private static final long serialVersionUID = -4201640771171486514L;
private static final CurrencyValidator VALIDATOR = new CurrencyValidator();
/** DecimalFormat's currency symbol */
private static final char CURRENCY_SYMBOL = '\u00A4';
/**
* Return a singleton instance of this validator.
* @return A singleton instance of the CurrencyValidator.
*/
public static BigDecimalValidator getInstance() {
return VALIDATOR;
}
/**
* Constructs a <i>strict</i> instance.
*/
public CurrencyValidator() {
this(true, true);
}
/**
* Constructs an instance with the specified strict setting.
*
* @param strict {@code true} if strict
* <code>Format</code> parsing should be used.
* @param allowFractions {@code true} if fractions are
* allowed or {@code false} if integers only.
*/
public CurrencyValidator(final boolean strict, final boolean allowFractions) {
super(strict, CURRENCY_FORMAT, allowFractions);
}
/**
* <p>Parse the value with the specified <code>Format</code>.</p>
*
* <p>This implementation is lenient whether the currency symbol
* is present or not. The default <code>NumberFormat</code>
* behavior is for the parsing to "fail" if the currency
* symbol is missing. This method re-parses with a format
* without the currency symbol if it fails initially.</p>
*
* @param value The value to be parsed.
* @param formatter The Format to parse the value with.
* @return The parsed value if valid or <code>null</code> if invalid.
*/
@Override
protected Object parse(final String value, final Format formatter) {
// Initial parse of the value
Object parsedValue = super.parse(value, formatter);
if (parsedValue != null || !(formatter instanceof DecimalFormat)) {
return parsedValue;
}
// Re-parse using a pattern without the currency symbol
final DecimalFormat decimalFormat = (DecimalFormat)formatter;
final String pattern = decimalFormat.toPattern();
if (pattern.indexOf(CURRENCY_SYMBOL) >= 0) {
final StringBuilder buffer = new StringBuilder(pattern.length());
for (int i = 0; i < pattern.length(); i++) {
if (pattern.charAt(i) != CURRENCY_SYMBOL) {
buffer.append(pattern.charAt(i));
}
}
decimalFormat.applyPattern(buffer.toString());
parsedValue = super.parse(value, decimalFormat);
}
return parsedValue;
}
}
| 7,987 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/routines/DoubleValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.text.Format;
import java.util.Locale;
/**
* <p><b>Double Validation</b> and Conversion routines (<code>java.lang.Double</code>).</p>
*
* <p>This validator provides a number of methods for
* validating/converting a <code>String</code> value to
* a <code>Double</code> using <code>java.text.NumberFormat</code>
* to parse either:</p>
* <ul>
* <li>using the default format for the default <code>Locale</code></li>
* <li>using a specified pattern with the default <code>Locale</code></li>
* <li>using the default format for a specified <code>Locale</code></li>
* <li>using a specified pattern with a specified <code>Locale</code></li>
* </ul>
*
* <p>Use one of the <code>isValid()</code> methods to just validate or
* one of the <code>validate()</code> methods to validate and receive a
* <i>converted</i> <code>Double</code> value.</p>
*
* <p>Once a value has been successfully converted the following
* methods can be used to perform minimum, maximum and range checks:</p>
* <ul>
* <li><code>minValue()</code> checks whether the value is greater
* than or equal to a specified minimum.</li>
* <li><code>maxValue()</code> checks whether the value is less
* than or equal to a specified maximum.</li>
* <li><code>isInRange()</code> checks whether the value is within
* a specified range of values.</li>
* </ul>
*
* <p>So that the same mechanism used for parsing an <i>input</i> value
* for validation can be used to format <i>output</i>, corresponding
* <code>format()</code> methods are also provided. That is you can
* format either:</p>
* <ul>
* <li>using the default format for the default <code>Locale</code></li>
* <li>using a specified pattern with the default <code>Locale</code></li>
* <li>using the default format for a specified <code>Locale</code></li>
* <li>using a specified pattern with a specified <code>Locale</code></li>
* </ul>
*
* @since 1.3.0
*/
public class DoubleValidator extends AbstractNumberValidator {
private static final long serialVersionUID = 5867946581318211330L;
private static final DoubleValidator VALIDATOR = new DoubleValidator();
/**
* Return a singleton instance of this validator.
* @return A singleton instance of the DoubleValidator.
*/
public static DoubleValidator getInstance() {
return VALIDATOR;
}
/**
* Constructs a <i>strict</i> instance.
*/
public DoubleValidator() {
this(true, STANDARD_FORMAT);
}
/**
* <p>Construct an instance with the specified strict setting
* and format type.</p>
*
* <p>The <code>formatType</code> specified what type of
* <code>NumberFormat</code> is created - valid types
* are:</p>
* <ul>
* <li>AbstractNumberValidator.STANDARD_FORMAT -to create
* <i>standard</i> number formats (the default).</li>
* <li>AbstractNumberValidator.CURRENCY_FORMAT -to create
* <i>currency</i> number formats.</li>
* <li>AbstractNumberValidator.PERCENT_FORMAT -to create
* <i>percent</i> number formats (the default).</li>
* </ul>
*
* @param strict {@code true} if strict
* <code>Format</code> parsing should be used.
* @param formatType The <code>NumberFormat</code> type to
* create for validation, default is STANDARD_FORMAT.
*/
public DoubleValidator(final boolean strict, final int formatType) {
super(strict, formatType, true);
}
/**
* <p>Validate/convert a <code>Double</code> using the default
* <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @return The parsed <code>Double</code> if valid or <code>null</code>
* if invalid.
*/
public Double validate(final String value) {
return (Double)parse(value, (String)null, (Locale)null);
}
/**
* <p>Validate/convert a <code>Double</code> using the
* specified <i>pattern</i>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against.
* @return The parsed <code>BigDecimal</code> if valid or <code>null</code> if invalid.
*/
public Double validate(final String value, final String pattern) {
return (Double)parse(value, pattern, (Locale)null);
}
/**
* <p>Validate/convert a <code>Double</code> using the
* specified <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @param locale The locale to use for the number format, system default if null.
* @return The parsed <code>Double</code> if valid or <code>null</code> if invalid.
*/
public Double validate(final String value, final Locale locale) {
return (Double)parse(value, (String)null, locale);
}
/**
* <p>Validate/convert a <code>Double</code> using the
* specified pattern and/ or <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against, or the
* default for the <code>Locale</code> if <code>null</code>.
* @param locale The locale to use for the date format, system default if null.
* @return The parsed <code>Double</code> if valid or <code>null</code> if invalid.
*/
public Double validate(final String value, final String pattern, final Locale locale) {
return (Double)parse(value, pattern, locale);
}
/**
* Check if the value is within a specified range.
*
* @param value The <code>Number</code> value to check.
* @param min The minimum value of the range.
* @param max The maximum value of the range.
* @return {@code true} if the value is within the
* specified range.
*/
public boolean isInRange(final double value, final double min, final double max) {
return value >= min && value <= max;
}
/**
* Check if the value is within a specified range.
*
* @param value The <code>Number</code> value to check.
* @param min The minimum value of the range.
* @param max The maximum value of the range.
* @return {@code true} if the value is within the
* specified range.
*/
public boolean isInRange(final Double value, final double min, final double max) {
return isInRange(value.doubleValue(), min, max);
}
/**
* Check if the value is greater than or equal to a minimum.
*
* @param value The value validation is being performed on.
* @param min The minimum value.
* @return {@code true} if the value is greater than
* or equal to the minimum.
*/
public boolean minValue(final double value, final double min) {
return value >= min;
}
/**
* Check if the value is greater than or equal to a minimum.
*
* @param value The value validation is being performed on.
* @param min The minimum value.
* @return {@code true} if the value is greater than
* or equal to the minimum.
*/
public boolean minValue(final Double value, final double min) {
return minValue(value.doubleValue(), min);
}
/**
* Check if the value is less than or equal to a maximum.
*
* @param value The value validation is being performed on.
* @param max The maximum value.
* @return {@code true} if the value is less than
* or equal to the maximum.
*/
public boolean maxValue(final double value, final double max) {
return value <= max;
}
/**
* Check if the value is less than or equal to a maximum.
*
* @param value The value validation is being performed on.
* @param max The maximum value.
* @return {@code true} if the value is less than
* or equal to the maximum.
*/
public boolean maxValue(final Double value, final double max) {
return maxValue(value.doubleValue(), max);
}
/**
* Convert the parsed value to a <code>Double</code>.
*
* @param value The parsed <code>Number</code> object created.
* @param formatter The Format used to parse the value with.
* @return The validated/converted <code>Double</code> value if valid
* or <code>null</code> if invalid.
*/
@Override
protected Object processParsedValue(final Object value, final Format formatter) {
if (value instanceof Double) {
return value;
}
return Double.valueOf(((Number)value).doubleValue());
}
}
| 7,988 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/routines/RegexValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.io.Serializable;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <b>Regular Expression</b> validation (using the JRE's regular expression support).
* <p>
* Constructs the validator either for a single regular expression or a set (array) of
* regular expressions. By default validation is <i>case sensitive</i> but constructors
* are provided to allow <i>case in-sensitive</i> validation. For example to create
* a validator which does <i>case in-sensitive</i> validation for a set of regular
* expressions:
* </p>
* <pre>
* <code>
* String[] regexs = new String[] {...};
* RegexValidator validator = new RegexValidator(regexs, false);
* </code>
* </pre>
*
* <ul>
* <li>Validate {@code true} or {@code false}:</li>
* <li>
* <ul>
* <li><code>boolean valid = validator.isValid(value);</code></li>
* </ul>
* </li>
* <li>Validate returning an aggregated String of the matched groups:</li>
* <li>
* <ul>
* <li><code>String result = validator.validate(value);</code></li>
* </ul>
* </li>
* <li>Validate returning the matched groups:</li>
* <li>
* <ul>
* <li><code>String[] result = validator.match(value);</code></li>
* </ul>
* </li>
* </ul>
*
* <b>Note that patterns are matched against the entire input.</b>
*
* <p>
* Cached instances pre-compile and re-use {@link Pattern}(s) - which according
* to the {@link Pattern} API are safe to use in a multi-threaded environment.
* </p>
*
* @since 1.4
*/
public class RegexValidator implements Serializable {
private static final long serialVersionUID = -8832409930574867162L;
private final Pattern[] patterns;
/**
* Constructs a <i>case sensitive</i> validator that matches any one
* in the list of regular expressions.
*
* @param regexs The set of regular expressions this validator will
* validate against
*/
RegexValidator(final List<String> regexs) {
this(regexs.toArray(new String[] {}), true);
}
/**
* Constructs a <i>case sensitive</i> validator for a single
* regular expression.
*
* @param regex The regular expression this validator will
* validate against
*/
public RegexValidator(final String regex) {
this(regex, true);
}
/**
* Constructs a validator for a single regular expression
* with the specified case sensitivity.
*
* @param regex The regular expression this validator will
* validate against
* @param caseSensitive when {@code true} matching is <i>case
* sensitive</i>, otherwise matching is <i>case in-sensitive</i>
*/
public RegexValidator(final String regex, final boolean caseSensitive) {
this(new String[] { regex }, caseSensitive);
}
/**
* Constructs a <i>case sensitive</i> validator that matches any one
* in the array of regular expressions.
*
* @param regexs The set of regular expressions this validator will
* validate against
*/
public RegexValidator(final String... regexs) {
this(regexs, true);
}
/**
* Constructs a validator that matches any one of the set of regular
* expressions with the specified case sensitivity.
*
* @param regexs The set of regular expressions this validator will
* validate against
* @param caseSensitive when {@code true} matching is <i>case
* sensitive</i>, otherwise matching is <i>case in-sensitive</i>
*/
public RegexValidator(final String[] regexs, final boolean caseSensitive) {
if (regexs == null || regexs.length == 0) {
throw new IllegalArgumentException("Regular expressions are missing");
}
patterns = new Pattern[regexs.length];
final int flags = caseSensitive ? 0 : Pattern.CASE_INSENSITIVE;
for (int i = 0; i < regexs.length; i++) {
if (regexs[i] == null || regexs[i].isEmpty()) {
throw new IllegalArgumentException("Regular expression[" + i + "] is missing");
}
patterns[i] = Pattern.compile(regexs[i], flags);
}
}
/**
* Gets a copy of the Patterns.
*
* @return a copy of the Patterns.
* @since 1.8
*/
public Pattern[] getPatterns() {
return patterns.clone();
}
/**
* Validates a value against the set of regular expressions.
*
* @param value The value to validate.
* @return {@code true} if the value is valid
* otherwise {@code false}.
*/
public boolean isValid(final String value) {
if (value == null) {
return false;
}
for (final Pattern pattern : patterns) {
if (pattern.matcher(value).matches()) {
return true;
}
}
return false;
}
/**
* Validates a value against the set of regular expressions
* returning the array of matched groups.
*
* @param value The value to validate.
* @return String array of the <i>groups</i> matched if
* valid or <code>null</code> if invalid
*/
public String[] match(final String value) {
if (value == null) {
return null;
}
for (final Pattern pattern : patterns) {
final Matcher matcher = pattern.matcher(value);
if (matcher.matches()) {
final int count = matcher.groupCount();
final String[] groups = new String[count];
for (int j = 0; j < count; j++) {
groups[j] = matcher.group(j + 1);
}
return groups;
}
}
return null;
}
/**
* Validates a value against the set of regular expressions
* returning a String value of the aggregated groups.
*
* @param value The value to validate.
* @return Aggregated String value comprised of the
* <i>groups</i> matched if valid or <code>null</code> if invalid
*/
public String validate(final String value) {
if (value == null) {
return null;
}
for (final Pattern pattern : patterns) {
final Matcher matcher = pattern.matcher(value);
if (matcher.matches()) {
final int count = matcher.groupCount();
if (count == 1) {
return matcher.group(1);
}
final StringBuilder buffer = new StringBuilder();
for (int j = 0; j < count; j++) {
final String component = matcher.group(j+1);
if (component != null) {
buffer.append(component);
}
}
return buffer.toString();
}
}
return null;
}
/**
* Provides a String representation of this validator.
* @return A String representation of this validator.
*/
@Override
public String toString() {
final StringBuilder buffer = new StringBuilder();
buffer.append("RegexValidator{");
for (int i = 0; i < patterns.length; i++) {
if (i > 0) {
buffer.append(",");
}
buffer.append(patterns[i].pattern());
}
buffer.append("}");
return buffer.toString();
}
}
| 7,989 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/routines/CodeValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.io.Serializable;
import org.apache.commons.validator.routines.checkdigit.CheckDigit;
/**
* Generic <b>Code Validation</b> providing format, minimum/maximum
* length and {@link CheckDigit} validations.
* <p>
* Performs the following validations on a code:
* <ul>
* <li>if the code is null, return null/false as appropriate</li>
* <li>trim the input. If the resulting code is empty, return null/false as appropriate</li>
* <li>Check the <i>format</i> of the code using a <i>regular expression.</i> (if specified)</li>
* <li>Check the <i>minimum</i> and <i>maximum</i> length (if specified) of the <i>parsed</i> code
* (i.e. parsed by the <i>regular expression</i>).</li>
* <li>Performs {@link CheckDigit} validation on the parsed code (if specified).</li>
* <li>The {@link #validate(String)} method returns the trimmed, parsed input (or null if validation failed)</li>
* </ul>
* <p>
* <b>Note</b>
* The {@link #isValid(String)} method will return true if the input passes validation.
* Since this includes trimming as well as potentially dropping parts of the input,
* it is possible for a String to pass validation
* but fail the checkdigit test if passed directly to it (the check digit routines generally don't trim input
* nor do they generally check the format/length).
* To be sure that you are passing valid input to a method use {@link #validate(String)} as follows:
* <pre>
* Object valid = validator.validate(input);
* if (valid != null) {
* some_method(valid.toString());
* }
* </pre>
* <p>
* Configure the validator with the appropriate regular expression, minimum/maximum length
* and {@link CheckDigit} validator and then call one of the two validation
* methods provided:</p>
* <ul>
* <li><code>boolean isValid(code)</code></li>
* <li><code>String validate(code)</code></li>
* </ul>
* <p>
* Codes often include <i>format</i> characters - such as hyphens - to make them
* more easily human readable. These can be removed prior to length and check digit
* validation by specifying them as a <i>non-capturing</i> group in the regular
* expression (i.e. use the <code>(?: )</code> notation).
* <br>
* Or just avoid using parentheses except for the parts you want to capture
*
* @since 1.4
*/
public final class CodeValidator implements Serializable {
private static final long serialVersionUID = 446960910870938233L;
private final RegexValidator regexValidator;
private final int minLength;
private final int maxLength;
private final CheckDigit checkdigit;
/**
* Constructs a code validator with a specified regular
* expression and {@link CheckDigit}.
* The RegexValidator validator is created to be case-sensitive
*
* @param regex The format regular expression
* @param checkdigit The check digit validation routine
*/
public CodeValidator(final String regex, final CheckDigit checkdigit) {
this(regex, -1, -1, checkdigit);
}
/**
* Constructs a code validator with a specified regular
* expression, length and {@link CheckDigit}.
* The RegexValidator validator is created to be case-sensitive
*
* @param regex The format regular expression.
* @param length The length of the code
* (sets the mimimum/maximum to the same)
* @param checkdigit The check digit validation routine
*/
public CodeValidator(final String regex, final int length, final CheckDigit checkdigit) {
this(regex, length, length, checkdigit);
}
/**
* Constructs a code validator with a specified regular
* expression, minimum/maximum length and {@link CheckDigit} validation.
* The RegexValidator validator is created to be case-sensitive
*
* @param regex The regular expression
* @param minLength The minimum length of the code
* @param maxLength The maximum length of the code
* @param checkdigit The check digit validation routine
*/
public CodeValidator(final String regex, final int minLength, final int maxLength,
final CheckDigit checkdigit) {
if (regex != null && !regex.isEmpty()) {
this.regexValidator = new RegexValidator(regex);
} else {
this.regexValidator = null;
}
this.minLength = minLength;
this.maxLength = maxLength;
this.checkdigit = checkdigit;
}
/**
* Constructs a code validator with a specified regular expression,
* validator and {@link CheckDigit} validation.
*
* @param regexValidator The format regular expression validator
* @param checkdigit The check digit validation routine.
*/
public CodeValidator(final RegexValidator regexValidator, final CheckDigit checkdigit) {
this(regexValidator, -1, -1, checkdigit);
}
/**
* Constructs a code validator with a specified regular expression,
* validator, length and {@link CheckDigit} validation.
*
* @param regexValidator The format regular expression validator
* @param length The length of the code
* (sets the mimimum/maximum to the same value)
* @param checkdigit The check digit validation routine
*/
public CodeValidator(final RegexValidator regexValidator, final int length, final CheckDigit checkdigit) {
this(regexValidator, length, length, checkdigit);
}
/**
* Constructs a code validator with a specified regular expression
* validator, minimum/maximum length and {@link CheckDigit} validation.
*
* @param regexValidator The format regular expression validator
* @param minLength The minimum length of the code
* @param maxLength The maximum length of the code
* @param checkdigit The check digit validation routine
*/
public CodeValidator(final RegexValidator regexValidator, final int minLength, final int maxLength,
final CheckDigit checkdigit) {
this.regexValidator = regexValidator;
this.minLength = minLength;
this.maxLength = maxLength;
this.checkdigit = checkdigit;
}
/**
* Return the check digit validation routine.
* <p>
* <b>N.B.</b> Optional, if not set no Check Digit
* validation will be performed on the code.
*
* @return The check digit validation routine
*/
public CheckDigit getCheckDigit() {
return checkdigit;
}
/**
* Return the minimum length of the code.
* <p>
* <b>N.B.</b> Optional, if less than zero the
* minimum length will not be checked.
*
* @return The minimum length of the code or
* <code>-1</code> if the code has no minimum length
*/
public int getMinLength() {
return minLength;
}
/**
* Return the maximum length of the code.
* <p>
* <b>N.B.</b> Optional, if less than zero the
* maximum length will not be checked.
*
* @return The maximum length of the code or
* <code>-1</code> if the code has no maximum length
*/
public int getMaxLength() {
return maxLength;
}
/**
* Return the <i>regular expression</i> validator.
* <p>
* <b>N.B.</b> Optional, if not set no regular
* expression validation will be performed on the code.
*
* @return The regular expression validator
*/
public RegexValidator getRegexValidator() {
return regexValidator;
}
/**
* Validate the code returning either {@code true}
* or {@code false}.
* <p>
* This calls {@link #validate(String)} and returns false
* if the return value is null, true otherwise.
* <p>
* Note that {@link #validate(String)} trims the input
* and if there is a {@link RegexValidator} it may also
* change the input as part of the validation.
*
* @param input The code to validate
* @return {@code true} if valid, otherwise
* {@code false}
*/
public boolean isValid(final String input) {
return validate(input) != null;
}
/**
* Validate the code returning either the valid code or
* <code>null</code> if invalid.
* <p>
* Note that this method trims the input
* and if there is a {@link RegexValidator} it may also
* change the input as part of the validation.
*
* @param input The code to validate
* @return The code if valid, otherwise <code>null</code>
* if invalid
*/
public Object validate(final String input) {
if (input == null) {
return null;
}
String code = input.trim();
if (code.isEmpty()) {
return null;
}
// validate/reformat using regular expression
if (regexValidator != null) {
code = regexValidator.validate(code);
if (code == null) {
return null;
}
}
// check the length (must be done after validate as that can change the code)
if (minLength >= 0 && code.length() < minLength ||
maxLength >= 0 && code.length() > maxLength) {
return null;
}
// validate the check digit
if (checkdigit != null && !checkdigit.isValid(code)) {
return null;
}
return code;
}
}
| 7,990 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/routines/BigIntegerValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.math.BigInteger;
import java.text.Format;
import java.util.Locale;
/**
* <p><b>BigInteger Validation</b> and Conversion routines (<code>java.math.BigInteger</code>).</p>
*
* <p>This validator provides a number of methods for
* validating/converting a <code>String</code> value to
* a <code>BigInteger</code> using <code>java.text.NumberFormat</code>
* to parse either:</p>
* <ul>
* <li>using the default format for the default <code>Locale</code></li>
* <li>using a specified pattern with the default <code>Locale</code></li>
* <li>using the default format for a specified <code>Locale</code></li>
* <li>using a specified pattern with a specified <code>Locale</code></li>
* </ul>
*
* <p>Use one of the <code>isValid()</code> methods to just validate or
* one of the <code>validate()</code> methods to validate and receive a
* <i>converted</i> <code>BigInteger</code> value.</p>
*
* <p>Once a value has been successfully converted the following
* methods can be used to perform minimum, maximum and range checks:</p>
* <ul>
* <li><code>minValue()</code> checks whether the value is greater
* than or equal to a specified minimum.</li>
* <li><code>maxValue()</code> checks whether the value is less
* than or equal to a specified maximum.</li>
* <li><code>isInRange()</code> checks whether the value is within
* a specified range of values.</li>
* </ul>
*
* <p>So that the same mechanism used for parsing an <i>input</i> value
* for validation can be used to format <i>output</i>, corresponding
* <code>format()</code> methods are also provided. That is you can
* format either:</p>
* <ul>
* <li>using the default format for the default <code>Locale</code></li>
* <li>using a specified pattern with the default <code>Locale</code></li>
* <li>using the default format for a specified <code>Locale</code></li>
* <li>using a specified pattern with a specified <code>Locale</code></li>
* </ul>
*
* @since 1.3.0
*/
public class BigIntegerValidator extends AbstractNumberValidator {
private static final long serialVersionUID = 6713144356347139988L;
private static final BigIntegerValidator VALIDATOR = new BigIntegerValidator();
/**
* Return a singleton instance of this validator.
* @return A singleton instance of the BigIntegerValidator.
*/
public static BigIntegerValidator getInstance() {
return VALIDATOR;
}
/**
* Constructs a <i>strict</i> instance.
*/
public BigIntegerValidator() {
this(true, STANDARD_FORMAT);
}
/**
* <p>Construct an instance with the specified strict setting
* and format type.</p>
*
* <p>The <code>formatType</code> specified what type of
* <code>NumberFormat</code> is created - valid types
* are:</p>
* <ul>
* <li>AbstractNumberValidator.STANDARD_FORMAT -to create
* <i>standard</i> number formats (the default).</li>
* <li>AbstractNumberValidator.CURRENCY_FORMAT -to create
* <i>currency</i> number formats.</li>
* <li>AbstractNumberValidator.PERCENT_FORMAT -to create
* <i>percent</i> number formats (the default).</li>
* </ul>
*
* @param strict {@code true} if strict
* <code>Format</code> parsing should be used.
* @param formatType The <code>NumberFormat</code> type to
* create for validation, default is STANDARD_FORMAT.
*/
public BigIntegerValidator(final boolean strict, final int formatType) {
super(strict, formatType, false);
}
/**
* <p>Validate/convert a <code>BigInteger</code> using the default
* <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @return The parsed <code>BigInteger</code> if valid or <code>null</code>
* if invalid.
*/
public BigInteger validate(final String value) {
return (BigInteger)parse(value, (String)null, (Locale)null);
}
/**
* <p>Validate/convert a <code>BigInteger</code> using the
* specified <i>pattern</i>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against.
* @return The parsed <code>BigInteger</code> if valid or <code>null</code> if invalid.
*/
public BigInteger validate(final String value, final String pattern) {
return (BigInteger)parse(value, pattern, (Locale)null);
}
/**
* <p>Validate/convert a <code>BigInteger</code> using the
* specified <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @param locale The locale to use for the number format, system default if null.
* @return The parsed <code>BigInteger</code> if valid or <code>null</code> if invalid.
*/
public BigInteger validate(final String value, final Locale locale) {
return (BigInteger)parse(value, (String)null, locale);
}
/**
* <p>Validate/convert a <code>BigInteger</code> using the
* specified pattern and/ or <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against, or the
* default for the <code>Locale</code> if <code>null</code>.
* @param locale The locale to use for the date format, system default if null.
* @return The parsed <code>BigInteger</code> if valid or <code>null</code> if invalid.
*/
public BigInteger validate(final String value, final String pattern, final Locale locale) {
return (BigInteger)parse(value, pattern, locale);
}
/**
* Check if the value is within a specified range.
*
* @param value The <code>Number</code> value to check.
* @param min The minimum value of the range.
* @param max The maximum value of the range.
* @return {@code true} if the value is within the
* specified range.
*/
public boolean isInRange(final BigInteger value, final long min, final long max) {
return value.longValue() >= min && value.longValue() <= max;
}
/**
* Check if the value is greater than or equal to a minimum.
*
* @param value The value validation is being performed on.
* @param min The minimum value.
* @return {@code true} if the value is greater than
* or equal to the minimum.
*/
public boolean minValue(final BigInteger value, final long min) {
return value.longValue() >= min;
}
/**
* Check if the value is less than or equal to a maximum.
*
* @param value The value validation is being performed on.
* @param max The maximum value.
* @return {@code true} if the value is less than
* or equal to the maximum.
*/
public boolean maxValue(final BigInteger value, final long max) {
return value.longValue() <= max;
}
/**
* Convert the parsed value to a <code>BigInteger</code>.
*
* @param value The parsed <code>Number</code> object created.
* @param formatter The Format used to parse the value with.
* @return The parsed <code>Number</code> converted to a
* <code>BigInteger</code>.
*/
@Override
protected Object processParsedValue(final Object value, final Format formatter) {
return BigInteger.valueOf(((Number)value).longValue());
}
}
| 7,991 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/routines/ISINValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Locale;
import org.apache.commons.validator.routines.checkdigit.ISINCheckDigit;
/**
* <b>ISIN</b> (International Securities Identifying Number) validation.
*
* <p>
* ISIN Numbers are 12 character alphanumeric codes used to identify Securities.
* </p>
*
* <p>
* ISINs consist of two alphabetic characters,
* which are the ISO 3166-1 alpha-2 code for the issuing country,
* nine alpha-numeric characters (the National Securities Identifying Number, or NSIN, which identifies the security),
* and one numerical check digit.
* They are 12 characters in length.
* </p>
*
* <p>
* See <a href="http://en.wikipedia.org/wiki/ISIN">Wikipedia - ISIN</a>
* for more details.
* </p>
*
* @since 1.7
*/
public class ISINValidator implements Serializable {
private static final long serialVersionUID = -5964391439144260936L;
private static final String ISIN_REGEX = "([A-Z]{2}[A-Z0-9]{9}[0-9])";
private static final CodeValidator VALIDATOR = new CodeValidator(ISIN_REGEX, 12, ISINCheckDigit.ISIN_CHECK_DIGIT);
/** ISIN Code Validator (no countryCode check) */
private static final ISINValidator ISIN_VALIDATOR_FALSE = new ISINValidator(false);
/** ISIN Code Validator (with countryCode check) */
private static final ISINValidator ISIN_VALIDATOR_TRUE = new ISINValidator(true);
private static final String [] CCODES = Locale.getISOCountries();
private static final String [] SPECIALS = {
"EZ", // http://www.anna-web.org/standards/isin-iso-6166/
"XS", // https://www.isin.org/isin/
};
static {
Arrays.sort(CCODES); // we cannot assume the codes are sorted
Arrays.sort(SPECIALS); // Just in case ...
}
private final boolean checkCountryCode;
/**
* Return a singleton instance of the ISIN validator
* @param checkCountryCode whether to check the country-code prefix or not
* @return A singleton instance of the appropriate ISIN validator.
*/
public static ISINValidator getInstance(final boolean checkCountryCode) {
return checkCountryCode ? ISIN_VALIDATOR_TRUE : ISIN_VALIDATOR_FALSE;
}
private ISINValidator(final boolean checkCountryCode) {
this.checkCountryCode = checkCountryCode;
}
/**
* Check the code is a valid ISIN code after any transformation
* by the validate routine.
* @param code The code to validate.
* @return {@code true} if a valid ISIN
* code, otherwise {@code false}.
*/
public boolean isValid(final String code) {
final boolean valid = VALIDATOR.isValid(code);
if (valid && checkCountryCode) {
return checkCode(code.substring(0,2));
}
return valid;
}
/**
* Check the code is valid ISIN code.
*
* @param code The code to validate.
* @return A valid ISIN code if valid, otherwise <code>null</code>.
*/
public Object validate(final String code) {
final Object validate = VALIDATOR.validate(code);
if (validate != null && checkCountryCode) {
return checkCode(code.substring(0,2)) ? validate : null;
}
return validate;
}
private boolean checkCode(final String code) {
return Arrays.binarySearch(CCODES, code) >= 0
||
Arrays.binarySearch(SPECIALS, code) >= 0
;
}
}
| 7,992 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/routines/EmailValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <p>Perform email validations.</p>
* <p>
* Based on a script by <a href="mailto:stamhankar@hotmail.com">Sandeep V. Tamhankar</a>
* http://javascript.internet.com
* </p>
* <p>
* This implementation is not guaranteed to catch all possible errors in an email address.
* </p>.
*
* @since 1.4
*/
public class EmailValidator implements Serializable {
private static final long serialVersionUID = 1705927040799295880L;
private static final String SPECIAL_CHARS = "\\p{Cntrl}\\(\\)<>@,;:'\\\\\\\"\\.\\[\\]";
private static final String VALID_CHARS = "(\\\\.)|[^\\s" + SPECIAL_CHARS + "]";
private static final String QUOTED_USER = "(\"(\\\\\"|[^\"])*\")";
private static final String WORD = "((" + VALID_CHARS + "|')+|" + QUOTED_USER + ")";
private static final String EMAIL_REGEX = "^(.+)@(\\S+)$";
private static final String IP_DOMAIN_REGEX = "^\\[(.*)\\]$";
private static final String USER_REGEX = "^" + WORD + "(\\." + WORD + ")*$";
private static final Pattern EMAIL_PATTERN = Pattern.compile(EMAIL_REGEX);
private static final Pattern IP_DOMAIN_PATTERN = Pattern.compile(IP_DOMAIN_REGEX);
private static final Pattern USER_PATTERN = Pattern.compile(USER_REGEX);
private static final int MAX_USERNAME_LEN = 64;
private final boolean allowTld;
/**
* Singleton instance of this class, which
* doesn't consider local addresses as valid.
*/
private static final EmailValidator EMAIL_VALIDATOR = new EmailValidator(false, false);
/**
* Singleton instance of this class, which
* doesn't consider local addresses as valid.
*/
private static final EmailValidator EMAIL_VALIDATOR_WITH_TLD = new EmailValidator(false, true);
/**
* Singleton instance of this class, which does
* consider local addresses valid.
*/
private static final EmailValidator EMAIL_VALIDATOR_WITH_LOCAL = new EmailValidator(true, false);
/**
* Singleton instance of this class, which does
* consider local addresses valid.
*/
private static final EmailValidator EMAIL_VALIDATOR_WITH_LOCAL_WITH_TLD = new EmailValidator(true, true);
private final DomainValidator domainValidator;
/**
* Returns the Singleton instance of this validator.
*
* @return singleton instance of this validator.
*/
public static EmailValidator getInstance() {
return EMAIL_VALIDATOR;
}
/**
* Returns the Singleton instance of this validator,
* with local validation as required.
*
* @param allowLocal Should local addresses be considered valid?
* @param allowTld Should TLDs be allowed?
* @return singleton instance of this validator
*/
public static EmailValidator getInstance(final boolean allowLocal, final boolean allowTld) {
if (allowLocal) {
if (allowTld) {
return EMAIL_VALIDATOR_WITH_LOCAL_WITH_TLD;
}
return EMAIL_VALIDATOR_WITH_LOCAL;
}
if (allowTld) {
return EMAIL_VALIDATOR_WITH_TLD;
}
return EMAIL_VALIDATOR;
}
/**
* Returns the Singleton instance of this validator,
* with local validation as required.
*
* @param allowLocal Should local addresses be considered valid?
* @return singleton instance of this validator
*/
public static EmailValidator getInstance(final boolean allowLocal) {
return getInstance(allowLocal, false);
}
/**
* constructor for creating instances with the specified domainValidator
*
* @param allowLocal Should local addresses be considered valid?
* @param allowTld Should TLDs be allowed?
* @param domainValidator allow override of the DomainValidator.
* The instance must have the same allowLocal setting.
* @since 1.7
*/
public EmailValidator(final boolean allowLocal, final boolean allowTld, final DomainValidator domainValidator) {
this.allowTld = allowTld;
if (domainValidator == null) {
throw new IllegalArgumentException("DomainValidator cannot be null");
}
if (domainValidator.isAllowLocal() != allowLocal) {
throw new IllegalArgumentException("DomainValidator must agree with allowLocal setting");
}
this.domainValidator = domainValidator;
}
/**
* Protected constructor for subclasses to use.
*
* @param allowLocal Should local addresses be considered valid?
* @param allowTld Should TLDs be allowed?
*/
protected EmailValidator(final boolean allowLocal, final boolean allowTld) {
this.allowTld = allowTld;
this.domainValidator = DomainValidator.getInstance(allowLocal);
}
/**
* Protected constructor for subclasses to use.
*
* @param allowLocal Should local addresses be considered valid?
*/
protected EmailValidator(final boolean allowLocal) {
this(allowLocal, false);
}
/**
* <p>Checks if a field has a valid e-mail address.</p>
*
* @param email The value validation is being performed on. A <code>null</code>
* value is considered invalid.
* @return true if the email address is valid.
*/
public boolean isValid(final String email) {
if (email == null) {
return false;
}
if (email.endsWith(".")) { // check this first - it's cheap!
return false;
}
// Check the whole email address structure
final Matcher emailMatcher = EMAIL_PATTERN.matcher(email);
if (!emailMatcher.matches()) {
return false;
}
if (!isValidUser(emailMatcher.group(1))) {
return false;
}
if (!isValidDomain(emailMatcher.group(2))) {
return false;
}
return true;
}
/**
* Returns true if the domain component of an email address is valid.
*
* @param domain being validated, may be in IDN format
* @return true if the email address's domain is valid.
*/
protected boolean isValidDomain(final String domain) {
// see if domain is an IP address in brackets
final Matcher ipDomainMatcher = IP_DOMAIN_PATTERN.matcher(domain);
if (ipDomainMatcher.matches()) {
final InetAddressValidator inetAddressValidator =
InetAddressValidator.getInstance();
return inetAddressValidator.isValid(ipDomainMatcher.group(1));
}
// Domain is symbolic name
if (allowTld) {
return domainValidator.isValid(domain) || !domain.startsWith(".") && domainValidator.isValidTld(domain);
}
return domainValidator.isValid(domain);
}
/**
* Returns true if the user component of an email address is valid.
*
* @param user being validated
* @return true if the user name is valid.
*/
protected boolean isValidUser(final String user) {
if (user == null || user.length() > MAX_USERNAME_LEN) {
return false;
}
return USER_PATTERN.matcher(user).matches();
}
}
| 7,993 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/routines/UrlValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <p><b>URL Validation</b> routines.</p>
* Behavior of validation is modified by passing in options:
* <ul>
* <li>ALLOW_2_SLASHES - [FALSE] Allows double '/' characters in the path
* component.</li>
* <li>NO_FRAGMENT- [FALSE] By default fragments are allowed, if this option is
* included then fragments are flagged as illegal.</li>
* <li>ALLOW_ALL_SCHEMES - [FALSE] By default only http, https, and ftp are
* considered valid schemes. Enabling this option will let any scheme pass validation.</li>
* </ul>
*
* <p>Originally based in on php script by Debbie Dyer, validation.php v1.2b, Date: 03/07/02,
* http://javascript.internet.com. However, this validation now bears little resemblance
* to the php original.</p>
* <pre>
* Example of usage:
* Construct a UrlValidator with valid schemes of "http", and "https".
*
* String[] schemes = {"http","https"}.
* UrlValidator urlValidator = new UrlValidator(schemes);
* if (urlValidator.isValid("ftp://foo.bar.com/")) {
* System.out.println("URL is valid");
* } else {
* System.out.println("URL is invalid");
* }
*
* prints "URL is invalid"
* If instead the default constructor is used.
*
* UrlValidator urlValidator = new UrlValidator();
* if (urlValidator.isValid("ftp://foo.bar.com/")) {
* System.out.println("URL is valid");
* } else {
* System.out.println("URL is invalid");
* }
*
* prints out "URL is valid"
* </pre>
*
* @see
* <a href="http://www.ietf.org/rfc/rfc2396.txt">
* Uniform Resource Identifiers (URI): Generic Syntax
* </a>
*
* @since 1.4
*/
public class UrlValidator implements Serializable {
private static final long serialVersionUID = 7557161713937335013L;
private static final int MAX_UNSIGNED_16_BIT_INT = 0xFFFF; // port max
/**
* Allows all validly formatted schemes to pass validation instead of
* supplying a set of valid schemes.
*/
public static final long ALLOW_ALL_SCHEMES = 1 << 0;
/**
* Allow two slashes in the path component of the URL.
*/
public static final long ALLOW_2_SLASHES = 1 << 1;
/**
* Enabling this options disallows any URL fragments.
*/
public static final long NO_FRAGMENTS = 1 << 2;
/**
* Allow local URLs, such as http://localhost/ or http://machine/ .
* This enables a broad-brush check, for complex local machine name
* validation requirements you should create your validator with
* a {@link RegexValidator} instead ({@link #UrlValidator(RegexValidator, long)})
*/
public static final long ALLOW_LOCAL_URLS = 1 << 3; // CHECKSTYLE IGNORE MagicNumber
/**
* Protocol scheme (e.g. http, ftp, https).
*/
private static final String SCHEME_REGEX = "^\\p{Alpha}[\\p{Alnum}\\+\\-\\.]*";
private static final Pattern SCHEME_PATTERN = Pattern.compile(SCHEME_REGEX);
// Drop numeric, and "+-." for now
// TODO does not allow for optional userinfo.
// Validation of character set is done by isValidAuthority
private static final String AUTHORITY_CHARS_REGEX = "\\p{Alnum}\\-\\."; // allows for IPV4 but not IPV6
// Allow for IPv4 mapped addresses: ::FFF:123.123.123.123
private static final String IPV6_REGEX = "::FFFF:(?:\\d{1,3}\\.){3}\\d{1,3}|[0-9a-fA-F:]+"; // do this as separate match because : could cause ambiguity with port prefix
// userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
// sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
// We assume that password has the same valid chars as user info
private static final String USERINFO_CHARS_REGEX = "[a-zA-Z0-9%-._~!$&'()*+,;=]";
// since neither ':' nor '@' are allowed chars, we don't need to use non-greedy matching
private static final String USERINFO_FIELD_REGEX =
USERINFO_CHARS_REGEX + "+" + // At least one character for the name
"(?::" + USERINFO_CHARS_REGEX + "*)?@"; // colon and password may be absent
private static final String AUTHORITY_REGEX =
"(?:\\[("+IPV6_REGEX+")\\]|(?:(?:"+USERINFO_FIELD_REGEX+")?([" + AUTHORITY_CHARS_REGEX + "]*)))(?::(\\d*))?(.*)?";
// 1 e.g. user:pass@ 2 3 4
private static final Pattern AUTHORITY_PATTERN = Pattern.compile(AUTHORITY_REGEX);
private static final int PARSE_AUTHORITY_IPV6 = 1;
private static final int PARSE_AUTHORITY_HOST_IP = 2; // excludes userinfo, if present
private static final int PARSE_AUTHORITY_PORT = 3; // excludes leading colon
/**
* Should always be empty. The code currently allows spaces.
*/
private static final int PARSE_AUTHORITY_EXTRA = 4;
private static final String PATH_REGEX = "^(/[-\\w:@&?=+,.!/~*'%$_;\\(\\)]*)?$";
private static final Pattern PATH_PATTERN = Pattern.compile(PATH_REGEX);
private static final String QUERY_REGEX = "^(\\S*)$";
private static final Pattern QUERY_PATTERN = Pattern.compile(QUERY_REGEX);
/**
* Holds the set of current validation options.
*/
private final long options;
/**
* The set of schemes that are allowed to be in a URL.
*/
private final Set<String> allowedSchemes; // Must be lower-case
/**
* Regular expressions used to manually validate authorities if IANA
* domain name validation isn't desired.
*/
private final RegexValidator authorityValidator;
/**
* If no schemes are provided, default to this set.
*/
private static final String[] DEFAULT_SCHEMES = {"http", "https", "ftp"}; // Must be lower-case
/**
* Singleton instance of this class with default schemes and options.
*/
private static final UrlValidator DEFAULT_URL_VALIDATOR = new UrlValidator();
/**
* Returns the singleton instance of this class with default schemes and options.
* @return singleton instance with default schemes and options
*/
public static UrlValidator getInstance() {
return DEFAULT_URL_VALIDATOR;
}
private final DomainValidator domainValidator;
/**
* Create a UrlValidator with default properties.
*/
public UrlValidator() {
this(null);
}
/**
* Behavior of validation is modified by passing in several strings options:
* @param schemes Pass in one or more URL schemes to consider valid, passing in
* a null will default to "http,https,ftp" being valid.
* If a non-null schemes is specified then all valid schemes must
* be specified. Setting the ALLOW_ALL_SCHEMES option will
* ignore the contents of schemes.
*/
public UrlValidator(final String[] schemes) {
this(schemes, 0L);
}
/**
* Initialize a UrlValidator with the given validation options.
* @param options The options should be set using the public constants declared in
* this class. To set multiple options you simply add them together. For example,
* ALLOW_2_SLASHES + NO_FRAGMENTS enables both of those options.
*/
public UrlValidator(final long options) {
this(null, null, options);
}
/**
* Behavior of validation is modified by passing in options:
* @param schemes The set of valid schemes. Ignored if the ALLOW_ALL_SCHEMES option is set.
* @param options The options should be set using the public constants declared in
* this class. To set multiple options you simply add them together. For example,
* ALLOW_2_SLASHES + NO_FRAGMENTS enables both of those options.
*/
public UrlValidator(final String[] schemes, final long options) {
this(schemes, null, options);
}
/**
* Initialize a UrlValidator with the given validation options.
* @param authorityValidator Regular expression validator used to validate the authority part
* This allows the user to override the standard set of domains.
* @param options Validation options. Set using the public constants of this class.
* To set multiple options, simply add them together:
* <p><code>ALLOW_2_SLASHES + NO_FRAGMENTS</code></p>
* enables both of those options.
*/
public UrlValidator(final RegexValidator authorityValidator, final long options) {
this(null, authorityValidator, options);
}
/**
* Customizable constructor. Validation behavior is modified by passing in options.
* @param schemes the set of valid schemes. Ignored if the ALLOW_ALL_SCHEMES option is set.
* @param authorityValidator Regular expression validator used to validate the authority part
* @param options Validation options. Set using the public constants of this class.
* To set multiple options, simply add them together:
* <p><code>ALLOW_2_SLASHES + NO_FRAGMENTS</code></p>
* enables both of those options.
*/
public UrlValidator(final String[] schemes, final RegexValidator authorityValidator, final long options) {
this(schemes, authorityValidator, options, DomainValidator.getInstance(isOn(ALLOW_LOCAL_URLS, options)));
}
/**
* Customizable constructor. Validation behavior is modified by passing in options.
* @param schemes the set of valid schemes. Ignored if the ALLOW_ALL_SCHEMES option is set.
* @param authorityValidator Regular expression validator used to validate the authority part
* @param options Validation options. Set using the public constants of this class.
* To set multiple options, simply add them together:
* <p><code>ALLOW_2_SLASHES + NO_FRAGMENTS</code></p>
* enables both of those options.
* @param domainValidator the DomainValidator to use; must agree with ALLOW_LOCAL_URLS setting
* @since 1.7
*/
public UrlValidator(String[] schemes, final RegexValidator authorityValidator, final long options, final DomainValidator domainValidator) {
this.options = options;
if (domainValidator == null) {
throw new IllegalArgumentException("DomainValidator must not be null");
}
if (domainValidator.isAllowLocal() != (options & ALLOW_LOCAL_URLS) > 0){
throw new IllegalArgumentException("DomainValidator disagrees with ALLOW_LOCAL_URLS setting");
}
this.domainValidator = domainValidator;
if (isOn(ALLOW_ALL_SCHEMES)) {
allowedSchemes = Collections.emptySet();
} else {
if (schemes == null) {
schemes = DEFAULT_SCHEMES;
}
allowedSchemes = new HashSet<>(schemes.length);
for (final String scheme : schemes) {
allowedSchemes.add(scheme.toLowerCase(Locale.ENGLISH));
}
}
this.authorityValidator = authorityValidator;
}
/**
* <p>Checks if a field has a valid URL address.</p>
*
* Note that the method calls #isValidAuthority()
* which checks that the domain is valid.
*
* @param value The value validation is being performed on. A <code>null</code>
* value is considered invalid.
* @return true if the URL is valid.
*/
public boolean isValid(final String value) {
if (value == null) {
return false;
}
URI uri; // ensure value is a valid URI
try {
uri = new URI(value);
} catch (final URISyntaxException e) {
return false;
}
// OK, perform additional validation
final String scheme = uri.getScheme();
if (!isValidScheme(scheme)) {
return false;
}
final String authority = uri.getRawAuthority();
if ("file".equals(scheme) && (authority == null || authority.isEmpty())) {// Special case - file: allows an empty authority
return true; // this is a local file - nothing more to do here
}
if ("file".equals(scheme) && authority != null && authority.contains(":")) {
return false;
}
// Validate the authority
if (!isValidAuthority(authority)) {
return false;
}
if (!isValidPath(uri.getRawPath())) {
return false;
}
if (!isValidQuery(uri.getRawQuery())) {
return false;
}
if (!isValidFragment(uri.getRawFragment())) {
return false;
}
return true;
}
/**
* Validate scheme. If schemes[] was initialized to a non null,
* then only those schemes are allowed.
* Otherwise the default schemes are "http", "https", "ftp".
* Matching is case-blind.
* @param scheme The scheme to validate. A <code>null</code> value is considered
* invalid.
* @return true if valid.
*/
protected boolean isValidScheme(final String scheme) {
if (scheme == null) {
return false;
}
if (!SCHEME_PATTERN.matcher(scheme).matches()) {
return false;
}
if (isOff(ALLOW_ALL_SCHEMES) && !allowedSchemes.contains(scheme.toLowerCase(Locale.ENGLISH))) {
return false;
}
return true;
}
/**
* Returns true if the authority is properly formatted. An authority is the combination
* of hostname and port. A <code>null</code> authority value is considered invalid.
* Note: this implementation validates the domain unless a RegexValidator was provided.
* If a RegexValidator was supplied and it matches, then the authority is regarded
* as valid with no further checks, otherwise the method checks against the
* AUTHORITY_PATTERN and the DomainValidator (ALLOW_LOCAL_URLS)
* @param authority Authority value to validate, alllows IDN
* @return true if authority (hostname and port) is valid.
*/
protected boolean isValidAuthority(final String authority) {
if (authority == null) {
return false;
}
// check manual authority validation if specified
if (authorityValidator != null && authorityValidator.isValid(authority)) {
return true;
}
// convert to ASCII if possible
final String authorityASCII = DomainValidator.unicodeToASCII(authority);
final Matcher authorityMatcher = AUTHORITY_PATTERN.matcher(authorityASCII);
if (!authorityMatcher.matches()) {
return false;
}
// We have to process IPV6 separately because that is parsed in a different group
final String ipv6 = authorityMatcher.group(PARSE_AUTHORITY_IPV6);
if (ipv6 != null) {
final InetAddressValidator inetAddressValidator = InetAddressValidator.getInstance();
if (!inetAddressValidator.isValidInet6Address(ipv6)) {
return false;
}
} else {
final String hostLocation = authorityMatcher.group(PARSE_AUTHORITY_HOST_IP);
// check if authority is hostname or IP address:
// try a hostname first since that's much more likely
if (!this.domainValidator.isValid(hostLocation)) {
// try an IPv4 address
final InetAddressValidator inetAddressValidator = InetAddressValidator.getInstance();
if (!inetAddressValidator.isValidInet4Address(hostLocation)) {
// isn't IPv4, so the URL is invalid
return false;
}
}
final String port = authorityMatcher.group(PARSE_AUTHORITY_PORT);
if (port != null && !port.isEmpty()) {
try {
final int iPort = Integer.parseInt(port);
if (iPort < 0 || iPort > MAX_UNSIGNED_16_BIT_INT) {
return false;
}
} catch (final NumberFormatException nfe) {
return false; // this can happen for big numbers
}
}
}
final String extra = authorityMatcher.group(PARSE_AUTHORITY_EXTRA);
if (extra != null && !extra.trim().isEmpty()){
return false;
}
return true;
}
/**
* Returns true if the path is valid. A <code>null</code> value is considered invalid.
* @param path Path value to validate.
* @return true if path is valid.
*/
protected boolean isValidPath(final String path) {
if (path == null) {
return false;
}
if (!PATH_PATTERN.matcher(path).matches()) {
return false;
}
try {
// Don't omit host otherwise leading path may be taken as host if it starts with //
final URI uri = new URI(null,"localhost",path,null);
final String norm = uri.normalize().getPath();
if (norm.startsWith("/../") // Trying to go via the parent dir
|| norm.equals("/..")) { // Trying to go to the parent dir
return false;
}
} catch (final URISyntaxException e) {
return false;
}
final int slash2Count = countToken("//", path);
if (isOff(ALLOW_2_SLASHES) && slash2Count > 0) {
return false;
}
return true;
}
/**
* Returns true if the query is null or it's a properly formatted query string.
* @param query Query value to validate.
* @return true if query is valid.
*/
protected boolean isValidQuery(final String query) {
if (query == null) {
return true;
}
return QUERY_PATTERN.matcher(query).matches();
}
/**
* Returns true if the given fragment is null or fragments are allowed.
* @param fragment Fragment value to validate.
* @return true if fragment is valid.
*/
protected boolean isValidFragment(final String fragment) {
if (fragment == null) {
return true;
}
return isOff(NO_FRAGMENTS);
}
/**
* Returns the number of times the token appears in the target.
* @param token Token value to be counted.
* @param target Target value to count tokens in.
* @return the number of tokens.
*/
protected int countToken(final String token, final String target) {
int tokenIndex = 0;
int count = 0;
while (tokenIndex != -1) {
tokenIndex = target.indexOf(token, tokenIndex);
if (tokenIndex > -1) {
tokenIndex++;
count++;
}
}
return count;
}
/**
* Tests whether the given flag is on. If the flag is not a power of 2
* (ie. 3) this tests whether the combination of flags is on.
*
* @param flag Flag value to check.
*
* @return whether the specified flag value is on.
*/
private boolean isOn(final long flag) {
return (options & flag) > 0;
}
/**
* Tests whether the given flag is on. If the flag is not a power of 2
* (e.g. 3) this tests whether the combination of flags is on.
*
* @param flag Flag value to check.
* @param options what to check
*
* @return whether the specified flag value is on.
*/
private static boolean isOn(final long flag, final long options) {
return (options & flag) > 0;
}
/**
* Tests whether the given flag is off. If the flag is not a power of 2
* (ie. 3) this tests whether the combination of flags is off.
*
* @param flag Flag value to check.
*
* @return whether the specified flag value is off.
*/
private boolean isOff(final long flag) {
return (options & flag) == 0;
}
}
| 7,994 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/routines/FloatValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.text.Format;
import java.util.Locale;
/**
* <p><b>Float Validation</b> and Conversion routines (<code>java.lang.Float</code>).</p>
*
* <p>This validator provides a number of methods for
* validating/converting a <code>String</code> value to
* a <code>Float</code> using <code>java.text.NumberFormat</code>
* to parse either:</p>
* <ul>
* <li>using the default format for the default <code>Locale</code></li>
* <li>using a specified pattern with the default <code>Locale</code></li>
* <li>using the default format for a specified <code>Locale</code></li>
* <li>using a specified pattern with a specified <code>Locale</code></li>
* </ul>
*
* <p>Use one of the <code>isValid()</code> methods to just validate or
* one of the <code>validate()</code> methods to validate and receive a
* <i>converted</i> <code>Float</code> value.</p>
*
* <p>Once a value has been successfully converted the following
* methods can be used to perform minimum, maximum and range checks:</p>
* <ul>
* <li><code>minValue()</code> checks whether the value is greater
* than or equal to a specified minimum.</li>
* <li><code>maxValue()</code> checks whether the value is less
* than or equal to a specified maximum.</li>
* <li><code>isInRange()</code> checks whether the value is within
* a specified range of values.</li>
* </ul>
*
* <p>So that the same mechanism used for parsing an <i>input</i> value
* for validation can be used to format <i>output</i>, corresponding
* <code>format()</code> methods are also provided. That is you can
* format either:</p>
* <ul>
* <li>using the default format for the default <code>Locale</code></li>
* <li>using a specified pattern with the default <code>Locale</code></li>
* <li>using the default format for a specified <code>Locale</code></li>
* <li>using a specified pattern with a specified <code>Locale</code></li>
* </ul>
*
* @since 1.3.0
*/
public class FloatValidator extends AbstractNumberValidator {
private static final long serialVersionUID = -4513245432806414267L;
private static final FloatValidator VALIDATOR = new FloatValidator();
/**
* Return a singleton instance of this validator.
* @return A singleton instance of the FloatValidator.
*/
public static FloatValidator getInstance() {
return VALIDATOR;
}
/**
* Constructs a <i>strict</i> instance.
*/
public FloatValidator() {
this(true, STANDARD_FORMAT);
}
/**
* <p>Construct an instance with the specified strict setting
* and format type.</p>
*
* <p>The <code>formatType</code> specified what type of
* <code>NumberFormat</code> is created - valid types
* are:</p>
* <ul>
* <li>AbstractNumberValidator.STANDARD_FORMAT -to create
* <i>standard</i> number formats (the default).</li>
* <li>AbstractNumberValidator.CURRENCY_FORMAT -to create
* <i>currency</i> number formats.</li>
* <li>AbstractNumberValidator.PERCENT_FORMAT -to create
* <i>percent</i> number formats (the default).</li>
* </ul>
*
* @param strict {@code true} if strict
* <code>Format</code> parsing should be used.
* @param formatType The <code>NumberFormat</code> type to
* create for validation, default is STANDARD_FORMAT.
*/
public FloatValidator(final boolean strict, final int formatType) {
super(strict, formatType, true);
}
/**
* <p>Validate/convert a <code>Float</code> using the default
* <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @return The parsed <code>Float</code> if valid or <code>null</code>
* if invalid.
*/
public Float validate(final String value) {
return (Float)parse(value, (String)null, (Locale)null);
}
/**
* <p>Validate/convert a <code>Float</code> using the
* specified <i>pattern</i>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against.
* @return The parsed <code>Float</code> if valid or <code>null</code> if invalid.
*/
public Float validate(final String value, final String pattern) {
return (Float)parse(value, pattern, (Locale)null);
}
/**
* <p>Validate/convert a <code>Float</code> using the
* specified <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @param locale The locale to use for the number format, system default if null.
* @return The parsed <code>Float</code> if valid or <code>null</code> if invalid.
*/
public Float validate(final String value, final Locale locale) {
return (Float)parse(value, (String)null, locale);
}
/**
* <p>Validate/convert a <code>Float</code> using the
* specified pattern and/ or <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against, or the
* default for the <code>Locale</code> if <code>null</code>.
* @param locale The locale to use for the date format, system default if null.
* @return The parsed <code>Float</code> if valid or <code>null</code> if invalid.
*/
public Float validate(final String value, final String pattern, final Locale locale) {
return (Float)parse(value, pattern, locale);
}
/**
* Check if the value is within a specified range.
*
* @param value The <code>Number</code> value to check.
* @param min The minimum value of the range.
* @param max The maximum value of the range.
* @return {@code true} if the value is within the
* specified range.
*/
public boolean isInRange(final float value, final float min, final float max) {
return value >= min && value <= max;
}
/**
* Check if the value is within a specified range.
*
* @param value The <code>Number</code> value to check.
* @param min The minimum value of the range.
* @param max The maximum value of the range.
* @return {@code true} if the value is within the
* specified range.
*/
public boolean isInRange(final Float value, final float min, final float max) {
return isInRange(value.floatValue(), min, max);
}
/**
* Check if the value is greater than or equal to a minimum.
*
* @param value The value validation is being performed on.
* @param min The minimum value.
* @return {@code true} if the value is greater than
* or equal to the minimum.
*/
public boolean minValue(final float value, final float min) {
return value >= min;
}
/**
* Check if the value is greater than or equal to a minimum.
*
* @param value The value validation is being performed on.
* @param min The minimum value.
* @return {@code true} if the value is greater than
* or equal to the minimum.
*/
public boolean minValue(final Float value, final float min) {
return minValue(value.floatValue(), min);
}
/**
* Check if the value is less than or equal to a maximum.
*
* @param value The value validation is being performed on.
* @param max The maximum value.
* @return {@code true} if the value is less than
* or equal to the maximum.
*/
public boolean maxValue(final float value, final float max) {
return value <= max;
}
/**
* Check if the value is less than or equal to a maximum.
*
* @param value The value validation is being performed on.
* @param max The maximum value.
* @return {@code true} if the value is less than
* or equal to the maximum.
*/
public boolean maxValue(final Float value, final float max) {
return maxValue(value.floatValue(), max);
}
/**
* <p>Perform further validation and convert the <code>Number</code> to
* a <code>Float</code>.</p>
*
* @param value The parsed <code>Number</code> object created.
* @param formatter The Format used to parse the value with.
* @return The parsed <code>Number</code> converted to a
* <code>Float</code> if valid or <code>null</code> if invalid.
*/
@Override
protected Object processParsedValue(final Object value, final Format formatter) {
final double doubleValue = ((Number)value).doubleValue();
if (doubleValue > 0) {
if (doubleValue < Float.MIN_VALUE) {
return null;
}
if (doubleValue > Float.MAX_VALUE) {
return null;
}
} else if (doubleValue < 0){
final double posDouble = doubleValue * -1;
if (posDouble < Float.MIN_VALUE) {
return null;
}
if (posDouble > Float.MAX_VALUE) {
return null;
}
}
return Float.valueOf((float)doubleValue);
}
}
| 7,995 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/routines/BigDecimalValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.math.BigDecimal;
import java.text.Format;
import java.text.NumberFormat;
import java.util.Locale;
/**
* <p><b>BigDecimal Validation</b> and Conversion routines (<code>java.math.BigDecimal</code>).</p>
*
* <p>This validator provides a number of methods for
* validating/converting a <code>String</code> value to
* a <code>BigDecimal</code> using <code>java.text.NumberFormat</code>
* to parse either:</p>
* <ul>
* <li>using the default format for the default <code>Locale</code></li>
* <li>using a specified pattern with the default <code>Locale</code></li>
* <li>using the default format for a specified <code>Locale</code></li>
* <li>using a specified pattern with a specified <code>Locale</code></li>
* </ul>
*
* <p>Use one of the <code>isValid()</code> methods to just validate or
* one of the <code>validate()</code> methods to validate and receive a
* <i>converted</i> <code>BigDecimal</code> value.</p>
*
* <p>Fraction/decimal values are automatically trimmed to the appropriate length.</p>
*
* <p>Once a value has been successfully converted the following
* methods can be used to perform minimum, maximum and range checks:</p>
* <ul>
* <li><code>minValue()</code> checks whether the value is greater
* than or equal to a specified minimum.</li>
* <li><code>maxValue()</code> checks whether the value is less
* than or equal to a specified maximum.</li>
* <li><code>isInRange()</code> checks whether the value is within
* a specified range of values.</li>
* </ul>
*
* <p>So that the same mechanism used for parsing an <i>input</i> value
* for validation can be used to format <i>output</i>, corresponding
* <code>format()</code> methods are also provided. That is you can
* format either:</p>
* <ul>
* <li>using the default format for the default <code>Locale</code></li>
* <li>using a specified pattern with the default <code>Locale</code></li>
* <li>using the default format for a specified <code>Locale</code></li>
* <li>using a specified pattern with a specified <code>Locale</code></li>
* </ul>
*
* @since 1.3.0
*/
public class BigDecimalValidator extends AbstractNumberValidator {
private static final long serialVersionUID = -670320911490506772L;
private static final BigDecimalValidator VALIDATOR = new BigDecimalValidator();
/**
* Return a singleton instance of this validator.
* @return A singleton instance of the BigDecimalValidator.
*/
public static BigDecimalValidator getInstance() {
return VALIDATOR;
}
/**
* Constructs a <i>strict</i> instance.
*/
public BigDecimalValidator() {
this(true);
}
/**
* <p>Construct an instance with the specified strict setting.</p>
*
* @param strict {@code true} if strict
* <code>Format</code> parsing should be used.
*/
public BigDecimalValidator(final boolean strict) {
this(strict, STANDARD_FORMAT, true);
}
/**
* <p>Construct an instance with the specified strict setting
* and format type.</p>
*
* <p>The <code>formatType</code> specified what type of
* <code>NumberFormat</code> is created - valid types
* are:</p>
* <ul>
* <li>AbstractNumberValidator.STANDARD_FORMAT -to create
* <i>standard</i> number formats (the default).</li>
* <li>AbstractNumberValidator.CURRENCY_FORMAT -to create
* <i>currency</i> number formats.</li>
* <li>AbstractNumberValidator.PERCENT_FORMAT -to create
* <i>percent</i> number formats (the default).</li>
* </ul>
*
* @param strict {@code true} if strict
* <code>Format</code> parsing should be used.
* @param formatType The <code>NumberFormat</code> type to
* create for validation, default is STANDARD_FORMAT.
* @param allowFractions {@code true} if fractions are
* allowed or {@code false} if integers only.
*/
protected BigDecimalValidator(final boolean strict, final int formatType,
final boolean allowFractions) {
super(strict, formatType, allowFractions);
}
/**
* <p>Validate/convert a <code>BigDecimal</code> using the default
* <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @return The parsed <code>BigDecimal</code> if valid or <code>null</code>
* if invalid.
*/
public BigDecimal validate(final String value) {
return (BigDecimal)parse(value, (String)null, (Locale)null);
}
/**
* <p>Validate/convert a <code>BigDecimal</code> using the
* specified <i>pattern</i>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against, or the
* default for the <code>Locale</code> if <code>null</code>.
* @return The parsed <code>BigDecimal</code> if valid or <code>null</code> if invalid.
*/
public BigDecimal validate(final String value, final String pattern) {
return (BigDecimal)parse(value, pattern, (Locale)null);
}
/**
* <p>Validate/convert a <code>BigDecimal</code> using the
* specified <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @param locale The locale to use for the number format, system default if null.
* @return The parsed <code>BigDecimal</code> if valid or <code>null</code> if invalid.
*/
public BigDecimal validate(final String value, final Locale locale) {
return (BigDecimal)parse(value, (String)null, locale);
}
/**
* <p>Validate/convert a <code>BigDecimal</code> using the
* specified pattern and/ or <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against, or the
* default for the <code>Locale</code> if <code>null</code>.
* @param locale The locale to use for the date format, system default if null.
* @return The parsed <code>BigDecimal</code> if valid or <code>null</code> if invalid.
*/
public BigDecimal validate(final String value, final String pattern, final Locale locale) {
return (BigDecimal)parse(value, pattern, locale);
}
/**
* Check if the value is within a specified range.
*
* @param value The <code>Number</code> value to check.
* @param min The minimum value of the range.
* @param max The maximum value of the range.
* @return {@code true} if the value is within the
* specified range.
*/
public boolean isInRange(final BigDecimal value, final double min, final double max) {
return value.doubleValue() >= min && value.doubleValue() <= max;
}
/**
* Check if the value is greater than or equal to a minimum.
*
* @param value The value validation is being performed on.
* @param min The minimum value.
* @return {@code true} if the value is greater than
* or equal to the minimum.
*/
public boolean minValue(final BigDecimal value, final double min) {
return value.doubleValue() >= min;
}
/**
* Check if the value is less than or equal to a maximum.
*
* @param value The value validation is being performed on.
* @param max The maximum value.
* @return {@code true} if the value is less than
* or equal to the maximum.
*/
public boolean maxValue(final BigDecimal value, final double max) {
return value.doubleValue() <= max;
}
/**
* Convert the parsed value to a <code>BigDecimal</code>.
*
* @param value The parsed <code>Number</code> object created.
* @param formatter The Format used to parse the value with.
* @return The parsed <code>Number</code> converted to a
* <code>BigDecimal</code>.
*/
@Override
protected Object processParsedValue(final Object value, final Format formatter) {
BigDecimal decimal;
if (value instanceof Long) {
decimal = BigDecimal.valueOf(((Long)value).longValue());
} else {
decimal = new BigDecimal(value.toString());
}
final int scale = determineScale((NumberFormat)formatter);
if (scale >= 0) {
decimal = decimal.setScale(scale, BigDecimal.ROUND_DOWN);
}
return decimal;
}
}
| 7,996 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/routines/TimeValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.text.DateFormat;
import java.text.Format;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
/**
* <p><b>Time Validation</b> and Conversion routines (<code>java.util.Calendar</code>).</p>
*
* <p>This validator provides a number of methods for validating/converting
* a <code>String</code> time value to a <code>java.util.Calendar</code> using
* <code>java.text.DateFormat</code> to parse either:</p>
* <ul>
* <li>using the default format for the default <code>Locale</code></li>
* <li>using a specified pattern with the default <code>Locale</code></li>
* <li>using the default format for a specified <code>Locale</code></li>
* <li>using a specified pattern with a specified <code>Locale</code></li>
* </ul>
*
* <p>For each of the above mechanisms, conversion method (i.e the
* <code>validate</code> methods) implementations are provided which
* either use the default <code>TimeZone</code> or allow the
* <code>TimeZone</code> to be specified.</p>
*
* <p>Use one of the <code>isValid()</code> methods to just validate or
* one of the <code>validate()</code> methods to validate and receive a
* <i>converted</i> <code>Calendar</code> value for the time.</p>
*
* <p>Implementations of the <code>validate()</code> method are provided
* to create <code>Calendar</code> objects for different <i>time zones</i>
* if the system default is not appropriate.</p>
*
* <p>Alternatively the CalendarValidator's <code>adjustToTimeZone()</code> method
* can be used to adjust the <code>TimeZone</code> of the <code>Calendar</code>
* object afterwards.</p>
*
* <p>Once a value has been successfully converted the following
* methods can be used to perform various time comparison checks:</p>
* <ul>
* <li><code>compareTime()</code> compares the hours, minutes, seconds
* and milliseconds of two calendars, returning 0, -1 or +1 indicating
* whether the first time is equal, before or after the second.</li>
* <li><code>compareSeconds()</code> compares the hours, minutes and
* seconds of two times, returning 0, -1 or +1 indicating
* whether the first is equal to, before or after the second.</li>
* <li><code>compareMinutes()</code> compares the hours and minutes
* two times, returning 0, -1 or +1 indicating
* whether the first is equal to, before or after the second.</li>
* <li><code>compareHours()</code> compares the hours
* of two times, returning 0, -1 or +1 indicating
* whether the first is equal to, before or after the second.</li>
* </ul>
*
* <p>So that the same mechanism used for parsing an <i>input</i> value
* for validation can be used to format <i>output</i>, corresponding
* <code>format()</code> methods are also provided. That is you can
* format either:</p>
* <ul>
* <li>using a specified pattern</li>
* <li>using the format for a specified <code>Locale</code></li>
* <li>using the format for the <i>default</i> <code>Locale</code></li>
* </ul>
*
* @since 1.3.0
*/
public class TimeValidator extends AbstractCalendarValidator {
private static final long serialVersionUID = 3494007492269691581L;
private static final TimeValidator VALIDATOR = new TimeValidator();
/**
* Return a singleton instance of this validator.
* @return A singleton instance of the TimeValidator.
*/
public static TimeValidator getInstance() {
return VALIDATOR;
}
/**
* Constructs a <i>strict</i> instance with <i>short</i>
* time style.
*/
public TimeValidator() {
this(true, DateFormat.SHORT);
}
/**
* Constructs an instance with the specified <i>strict</i>
* and <i>time style</i> parameters.
*
* @param strict {@code true} if strict
* <code>Format</code> parsing should be used.
* @param timeStyle the time style to use for Locale validation.
*/
public TimeValidator(final boolean strict, final int timeStyle) {
super(strict, -1, timeStyle);
}
/**
* <p>Validate/convert a time using the default <code>Locale</code>
* and <code>TimeZone</code>.
*
* @param value The value validation is being performed on.
* @return The parsed <code>Calendar</code> if valid or <code>null</code>
* if invalid.
*/
public Calendar validate(final String value) {
return (Calendar)parse(value, (String)null, (Locale)null, (TimeZone)null);
}
/**
* <p>Validate/convert a time using the specified <code>TimeZone</code>
* and default <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @param timeZone The Time Zone used to parse the time, system default if null.
* @return The parsed <code>Calendar</code> if valid or <code>null</code> if invalid.
*/
public Calendar validate(final String value, final TimeZone timeZone) {
return (Calendar)parse(value, (String)null, (Locale)null, timeZone);
}
/**
* <p>Validate/convert a time using the specified <i>pattern</i> and
* default <code>TimeZone</code>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against.
* @return The parsed <code>Calendar</code> if valid or <code>null</code> if invalid.
*/
public Calendar validate(final String value, final String pattern) {
return (Calendar)parse(value, pattern, (Locale)null, (TimeZone)null);
}
/**
* <p>Validate/convert a time using the specified <i>pattern</i>
* and <code>TimeZone</code>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against.
* @param timeZone The Time Zone used to parse the time, system default if null.
* @return The parsed <code>Calendar</code> if valid or <code>null</code> if invalid.
*/
public Calendar validate(final String value, final String pattern, final TimeZone timeZone) {
return (Calendar)parse(value, pattern, (Locale)null, timeZone);
}
/**
* <p>Validate/convert a time using the specified <code>Locale</code>
* default <code>TimeZone</code>.
*
* @param value The value validation is being performed on.
* @param locale The locale to use for the time format, system default if null.
* @return The parsed <code>Calendar</code> if valid or <code>null</code> if invalid.
*/
public Calendar validate(final String value, final Locale locale) {
return (Calendar)parse(value, (String)null, locale, (TimeZone)null);
}
/**
* <p>Validate/convert a time using the specified <code>Locale</code>
* and <code>TimeZone</code>.
*
* @param value The value validation is being performed on.
* @param locale The locale to use for the time format, system default if null.
* @param timeZone The Time Zone used to parse the time, system default if null.
* @return The parsed <code>Calendar</code> if valid or <code>null</code> if invalid.
*/
public Calendar validate(final String value, final Locale locale, final TimeZone timeZone) {
return (Calendar)parse(value, (String)null, locale, timeZone);
}
/**
* <p>Validate/convert a time using the specified pattern and <code>Locale</code>
* and the default <code>TimeZone</code>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against, or the
* default for the <code>Locale</code> if <code>null</code>.
* @param locale The locale to use for the date format, system default if null.
* @return The parsed <code>Calendar</code> if valid or <code>null</code> if invalid.
*/
public Calendar validate(final String value, final String pattern, final Locale locale) {
return (Calendar)parse(value, pattern, locale, (TimeZone)null);
}
/**
* <p>Validate/convert a time using the specified pattern, <code>Locale</code>
* and <code>TimeZone</code>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against, or the
* default for the <code>Locale</code> if <code>null</code>.
* @param locale The locale to use for the date format, system default if null.
* @param timeZone The Time Zone used to parse the date, system default if null.
* @return The parsed <code>Calendar</code> if valid or <code>null</code> if invalid.
*/
public Calendar validate(final String value, final String pattern, final Locale locale, final TimeZone timeZone) {
return (Calendar)parse(value, pattern, locale, timeZone);
}
/**
* <p>Compare Times (hour, minute, second and millisecond - not date).</p>
*
* @param value The <code>Calendar</code> value to check.
* @param compare The <code>Calendar</code> to compare the value to.
* @return Zero if the hours are equal, -1 if first
* time is less than the seconds and +1 if the first
* time is greater than.
*/
public int compareTime(final Calendar value, final Calendar compare) {
return compareTime(value, compare, Calendar.MILLISECOND);
}
/**
* <p>Compare Seconds (hours, minutes and seconds).</p>
*
* @param value The <code>Calendar</code> value to check.
* @param compare The <code>Calendar</code> to compare the value to.
* @return Zero if the hours are equal, -1 if first
* parameter's seconds are less than the seconds and +1 if the first
* parameter's seconds are greater than.
*/
public int compareSeconds(final Calendar value, final Calendar compare) {
return compareTime(value, compare, Calendar.SECOND);
}
/**
* <p>Compare Minutes (hours and minutes).</p>
*
* @param value The <code>Calendar</code> value to check.
* @param compare The <code>Calendar</code> to compare the value to.
* @return Zero if the hours are equal, -1 if first
* parameter's minutes are less than the seconds and +1 if the first
* parameter's minutes are greater than.
*/
public int compareMinutes(final Calendar value, final Calendar compare) {
return compareTime(value, compare, Calendar.MINUTE);
}
/**
* <p>Compare Hours.</p>
*
* @param value The <code>Calendar</code> value to check.
* @param compare The <code>Calendar</code> to compare the value to.
* @return Zero if the hours are equal, -1 if first
* parameter's hour is less than the seconds and +1 if the first
* parameter's hour is greater than.
*/
public int compareHours(final Calendar value, final Calendar compare) {
return compareTime(value, compare, Calendar.HOUR_OF_DAY);
}
/**
* <p>Convert the parsed <code>Date</code> to a <code>Calendar</code>.</p>
*
* @param value The parsed <code>Date</code> object created.
* @param formatter The Format used to parse the value with.
* @return The parsed value converted to a <code>Calendar</code>.
*/
@Override
protected Object processParsedValue(final Object value, final Format formatter) {
return ((DateFormat)formatter).getCalendar();
}
}
| 7,997 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/routines/AbstractCalendarValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
/**
* <p>Abstract class for Date/Time/Calendar validation.</p>
*
* <p>This is a <i>base</i> class for building Date / Time
* Validators using format parsing.</p>
*
* @since 1.3.0
*/
public abstract class AbstractCalendarValidator extends AbstractFormatValidator {
private static final long serialVersionUID = -1410008585975827379L;
private final int dateStyle;
private final int timeStyle;
/**
* Constructs an instance with the specified <i>strict</i>,
* <i>time</i> and <i>date</i> style parameters.
*
* @param strict {@code true} if strict
* <code>Format</code> parsing should be used.
* @param dateStyle the date style to use for Locale validation.
* @param timeStyle the time style to use for Locale validation.
*/
public AbstractCalendarValidator(final boolean strict, final int dateStyle, final int timeStyle) {
super(strict);
this.dateStyle = dateStyle;
this.timeStyle = timeStyle;
}
/**
* <p>Validate using the specified <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to format the value.
* @param locale The locale to use for the Format, defaults to the default
* @return {@code true} if the value is valid.
*/
@Override
public boolean isValid(final String value, final String pattern, final Locale locale) {
final Object parsedValue = parse(value, pattern, locale, (TimeZone)null);
return parsedValue == null ? false : true;
}
/**
* <p>Format an object into a <code>String</code> using
* the default Locale.</p>
*
* @param value The value validation is being performed on.
* @param timeZone The Time Zone used to format the date,
* system default if null (unless value is a <code>Calendar</code>.
* @return The value formatted as a <code>String</code>.
*/
public String format(final Object value, final TimeZone timeZone) {
return format(value, (String)null, (Locale)null, timeZone);
}
/**
* <p>Format an object into a <code>String</code> using
* the specified pattern.</p>
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to format the value.
* @param timeZone The Time Zone used to format the date,
* system default if null (unless value is a <code>Calendar</code>.
* @return The value formatted as a <code>String</code>.
*/
public String format(final Object value, final String pattern, final TimeZone timeZone) {
return format(value, pattern, (Locale)null, timeZone);
}
/**
* <p>Format an object into a <code>String</code> using
* the specified Locale.</p>
*
* @param value The value validation is being performed on.
* @param locale The locale to use for the Format.
* @param timeZone The Time Zone used to format the date,
* system default if null (unless value is a <code>Calendar</code>.
* @return The value formatted as a <code>String</code>.
*/
public String format(final Object value, final Locale locale, final TimeZone timeZone) {
return format(value, (String)null, locale, timeZone);
}
/**
* <p>Format an object using the specified pattern and/or
* <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to format the value.
* @param locale The locale to use for the Format.
* @return The value formatted as a <code>String</code>.
*/
@Override
public String format(final Object value, final String pattern, final Locale locale) {
return format(value, pattern, locale, (TimeZone)null);
}
/**
* <p>Format an object using the specified pattern and/or
* <code>Locale</code>.
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to format the value.
* @param locale The locale to use for the Format.
* @param timeZone The Time Zone used to format the date,
* system default if null (unless value is a <code>Calendar</code>.
* @return The value formatted as a <code>String</code>.
*/
public String format(final Object value, final String pattern, final Locale locale, final TimeZone timeZone) {
final DateFormat formatter = (DateFormat)getFormat(pattern, locale);
if (timeZone != null) {
formatter.setTimeZone(timeZone);
} else if (value instanceof Calendar) {
formatter.setTimeZone(((Calendar)value).getTimeZone());
}
return format(value, formatter);
}
/**
* <p>Format a value with the specified <code>DateFormat</code>.</p>
*
* @param value The value to be formatted.
* @param formatter The Format to use.
* @return The formatted value.
*/
@Override
protected String format(Object value, final Format formatter) {
if (value == null) {
return null;
}
if (value instanceof Calendar) {
value = ((Calendar)value).getTime();
}
return formatter.format(value);
}
/**
* <p>Checks if the value is valid against a specified pattern.</p>
*
* @param value The value validation is being performed on.
* @param pattern The pattern used to validate the value against, or the
* default for the <code>Locale</code> if <code>null</code>.
* @param locale The locale to use for the date format, system default if null.
* @param timeZone The Time Zone used to parse the date, system default if null.
* @return The parsed value if valid or <code>null</code> if invalid.
*/
protected Object parse(String value, final String pattern, final Locale locale, final TimeZone timeZone) {
value = value == null ? null : value.trim();
if (value == null || value.isEmpty()) {
return null;
}
final DateFormat formatter = (DateFormat)getFormat(pattern, locale);
if (timeZone != null) {
formatter.setTimeZone(timeZone);
}
return parse(value, formatter);
}
/**
* <p>Process the parsed value, performing any further validation
* and type conversion required.</p>
*
* @param value The parsed object created.
* @param formatter The Format used to parse the value with.
* @return The parsed value converted to the appropriate type
* if valid or <code>null</code> if invalid.
*/
@Override
protected abstract Object processParsedValue(Object value, Format formatter);
/**
* <p>Returns a <code>DateFormat</code> for the specified <i>pattern</i>
* and/or <code>Locale</code>.</p>
*
* @param pattern The pattern used to validate the value against or
* <code>null</code> to use the default for the <code>Locale</code>.
* @param locale The locale to use for the currency format, system default if null.
* @return The <code>DateFormat</code> to created.
*/
@Override
protected Format getFormat(final String pattern, final Locale locale) {
DateFormat formatter;
final boolean usePattern = pattern != null && !pattern.isEmpty();
if (!usePattern) {
formatter = (DateFormat)getFormat(locale);
} else if (locale == null) {
formatter = new SimpleDateFormat(pattern);
} else {
final DateFormatSymbols symbols = new DateFormatSymbols(locale);
formatter = new SimpleDateFormat(pattern, symbols);
}
formatter.setLenient(false);
return formatter;
}
/**
* <p>Returns a <code>DateFormat</code> for the specified Locale.</p>
*
* @param locale The locale a <code>DateFormat</code> is required for,
* system default if null.
* @return The <code>DateFormat</code> to created.
*/
protected Format getFormat(final Locale locale) {
DateFormat formatter;
if (dateStyle >= 0 && timeStyle >= 0) {
if (locale == null) {
formatter = DateFormat.getDateTimeInstance(dateStyle, timeStyle);
} else {
formatter = DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale);
}
} else if (timeStyle >= 0) {
if (locale == null) {
formatter = DateFormat.getTimeInstance(timeStyle);
} else {
formatter = DateFormat.getTimeInstance(timeStyle, locale);
}
} else {
final int useDateStyle = dateStyle >= 0 ? dateStyle : DateFormat.SHORT;
if (locale == null) {
formatter = DateFormat.getDateInstance(useDateStyle);
} else {
formatter = DateFormat.getDateInstance(useDateStyle, locale);
}
}
formatter.setLenient(false);
return formatter;
}
/**
* <p>Compares a calendar value to another, indicating whether it is
* equal, less then or more than at a specified level.</p>
*
* @param value The Calendar value.
* @param compare The <code>Calendar</code> to check the value against.
* @param field The field <i>level</i> to compare to - e.g. specifying
* <code>Calendar.MONTH</code> will compare the year and month
* portions of the calendar.
* @return Zero if the first value is equal to the second, -1
* if it is less than the second or +1 if it is greater than the second.
*/
protected int compare(final Calendar value, final Calendar compare, final int field) {
int result;
// Compare Year
result = calculateCompareResult(value, compare, Calendar.YEAR);
if (result != 0 || field == Calendar.YEAR) {
return result;
}
// Compare Week of Year
if (field == Calendar.WEEK_OF_YEAR) {
return calculateCompareResult(value, compare, Calendar.WEEK_OF_YEAR);
}
// Compare Day of the Year
if (field == Calendar.DAY_OF_YEAR) {
return calculateCompareResult(value, compare, Calendar.DAY_OF_YEAR);
}
// Compare Month
result = calculateCompareResult(value, compare, Calendar.MONTH);
if (result != 0 || field == Calendar.MONTH) {
return result;
}
// Compare Week of Month
if (field == Calendar.WEEK_OF_MONTH) {
return calculateCompareResult(value, compare, Calendar.WEEK_OF_MONTH);
}
// Compare Date
result = calculateCompareResult(value, compare, Calendar.DATE);
if (result != 0 || field == Calendar.DATE ||
field == Calendar.DAY_OF_WEEK ||
field == Calendar.DAY_OF_WEEK_IN_MONTH) {
return result;
}
// Compare Time fields
return compareTime(value, compare, field);
}
/**
* <p>Compares a calendar time value to another, indicating whether it is
* equal, less then or more than at a specified level.</p>
*
* @param value The Calendar value.
* @param compare The <code>Calendar</code> to check the value against.
* @param field The field <i>level</i> to compare to - e.g. specifying
* <code>Calendar.MINUTE</code> will compare the hours and minutes
* portions of the calendar.
* @return Zero if the first value is equal to the second, -1
* if it is less than the second or +1 if it is greater than the second.
*/
protected int compareTime(final Calendar value, final Calendar compare, final int field) {
int result;
// Compare Hour
result = calculateCompareResult(value, compare, Calendar.HOUR_OF_DAY);
if (result != 0 || field == Calendar.HOUR || field == Calendar.HOUR_OF_DAY) {
return result;
}
// Compare Minute
result = calculateCompareResult(value, compare, Calendar.MINUTE);
if (result != 0 || field == Calendar.MINUTE) {
return result;
}
// Compare Second
result = calculateCompareResult(value, compare, Calendar.SECOND);
if (result != 0 || field == Calendar.SECOND) {
return result;
}
// Compare Milliseconds
if (field == Calendar.MILLISECOND) {
return calculateCompareResult(value, compare, Calendar.MILLISECOND);
}
throw new IllegalArgumentException("Invalid field: " + field);
}
/**
* <p>Compares a calendar's quarter value to another, indicating whether it is
* equal, less then or more than the specified quarter.</p>
*
* @param value The Calendar value.
* @param compare The <code>Calendar</code> to check the value against.
* @param monthOfFirstQuarter The month that the first quarter starts.
* @return Zero if the first quarter is equal to the second, -1
* if it is less than the second or +1 if it is greater than the second.
*/
protected int compareQuarters(final Calendar value, final Calendar compare, final int monthOfFirstQuarter) {
final int valueQuarter = calculateQuarter(value, monthOfFirstQuarter);
final int compareQuarter = calculateQuarter(compare, monthOfFirstQuarter);
if (valueQuarter < compareQuarter) {
return -1;
}
if (valueQuarter > compareQuarter) {
return 1;
}
return 0;
}
/**
* <p>Calculate the quarter for the specified Calendar.</p>
*
* @param calendar The Calendar value.
* @param monthOfFirstQuarter The month that the first quarter starts.
* @return The calculated quarter.
*/
private int calculateQuarter(final Calendar calendar, final int monthOfFirstQuarter) {
// Add Year
int year = calendar.get(Calendar.YEAR);
final int month = calendar.get(Calendar.MONTH) + 1;
final int relativeMonth = month >= monthOfFirstQuarter
? month - monthOfFirstQuarter
: month + 12 - monthOfFirstQuarter; // CHECKSTYLE IGNORE MagicNumber
final int quarter = relativeMonth / 3 + 1; // CHECKSTYLE IGNORE MagicNumber
// adjust the year if the quarter doesn't start in January
if (month < monthOfFirstQuarter) {
--year;
}
return year * 10 + quarter; // CHECKSTYLE IGNORE MagicNumber
}
/**
* <p>Compares the field from two calendars indicating whether the field for the
* first calendar is equal to, less than or greater than the field from the
* second calendar.
*
* @param value The Calendar value.
* @param compare The <code>Calendar</code> to check the value against.
* @param field The field to compare for the calendars.
* @return Zero if the first calendar's field is equal to the seconds, -1
* if it is less than the seconds or +1 if it is greater than the seconds.
*/
private int calculateCompareResult(final Calendar value, final Calendar compare, final int field) {
final int difference = value.get(field) - compare.get(field);
if (difference < 0) {
return -1;
}
if (difference > 0) {
return 1;
}
return 0;
}
}
| 7,998 |
0 | Create_ds/commons-validator/src/main/java/org/apache/commons/validator | Create_ds/commons-validator/src/main/java/org/apache/commons/validator/routines/ISBNValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.io.Serializable;
import org.apache.commons.validator.routines.checkdigit.CheckDigitException;
import org.apache.commons.validator.routines.checkdigit.EAN13CheckDigit;
import org.apache.commons.validator.routines.checkdigit.ISBN10CheckDigit;
/**
* <b>ISBN-10</b> and <b>ISBN-13</b> Code Validation.
* <p>
* This validator validates the code is either a valid ISBN-10
* (using a {@link CodeValidator} with the {@link ISBN10CheckDigit})
* or a valid ISBN-13 code (using a {@link CodeValidator} with the
* the {@link EAN13CheckDigit} routine).
* <p>
* The <code>validate()</code> methods return the ISBN code with formatting
* characters removed if valid or <code>null</code> if invalid.
* <p>
* This validator also provides the facility to convert ISBN-10 codes to
* ISBN-13 if the <code>convert</code> property is {@code true}.
* <p>
* From 1st January 2007 the book industry will start to use a new 13 digit
* ISBN number (rather than this 10 digit ISBN number). ISBN-13 codes are
* <a href="http://en.wikipedia.org/wiki/European_Article_Number">EAN</a>
* codes, for more information see:</p>
*
* <ul>
* <li><a href="http://en.wikipedia.org/wiki/ISBN">Wikipedia - International
* Standard Book Number (ISBN)</a>.</li>
* <li>EAN - see
* <a href="http://en.wikipedia.org/wiki/European_Article_Number">Wikipedia -
* European Article Number</a>.</li>
* <li><a href="http://www.isbn.org/standards/home/isbn/transition.asp">ISBN-13
* Transition details</a>.</li>
* </ul>
*
* <p>ISBN-13s are either prefixed with 978 or 979. 978 prefixes are only assigned
* to the ISBN agency. 979 prefixes may be assigned to ISBNs or ISMNs
* (<a href="https://www.ismn-international.org/">International
* Standard Music Numbers</a>).
* <ul>
* <li>979-0 are assigned to the ISMN agency</li>
* <li>979-10, 979-11, 979-12 are assigned to the ISBN agency</li>
* </ul>
* All other 979 prefixed EAN-13 numbers have not yet been assigned to an agency. The
* validator validates all 13 digit codes with 978 or 979 prefixes.
*
* @since 1.4
*/
public class ISBNValidator implements Serializable {
private static final int ISBN_10_LEN = 10;
private static final long serialVersionUID = 4319515687976420405L;
private static final String SEP = "(?:\\-|\\s)";
private static final String GROUP = "(\\d{1,5})";
private static final String PUBLISHER = "(\\d{1,7})";
private static final String TITLE = "(\\d{1,6})";
/**
* ISBN-10 consists of 4 groups of numbers separated by either dashes (-)
* or spaces. The first group is 1-5 characters, second 1-7, third 1-6,
* and fourth is 1 digit or an X.
*/
static final String ISBN10_REGEX =
"^(?:(\\d{9}[0-9X])|(?:" + GROUP + SEP + PUBLISHER + SEP + TITLE + SEP + "([0-9X])))$";
/**
* ISBN-13 consists of 5 groups of numbers separated by either dashes (-)
* or spaces. The first group is 978 or 979, the second group is
* 1-5 characters, third 1-7, fourth 1-6, and fifth is 1 digit.
*/
static final String ISBN13_REGEX =
"^(978|979)(?:(\\d{10})|(?:" + SEP + GROUP + SEP + PUBLISHER + SEP + TITLE + SEP + "([0-9])))$";
/** ISBN Code Validator (which converts ISBN-10 codes to ISBN-13 */
private static final ISBNValidator ISBN_VALIDATOR = new ISBNValidator();
/** ISBN Code Validator (which converts ISBN-10 codes to ISBN-13 */
private static final ISBNValidator ISBN_VALIDATOR_NO_CONVERT = new ISBNValidator(false);
/** ISBN-10 Code Validator */
private final CodeValidator isbn10Validator = new CodeValidator(ISBN10_REGEX, 10, ISBN10CheckDigit.ISBN10_CHECK_DIGIT);
/** ISBN-13 Code Validator */
private final CodeValidator isbn13Validator = new CodeValidator(ISBN13_REGEX, 13, EAN13CheckDigit.EAN13_CHECK_DIGIT);
private final boolean convert;
/**
* Return a singleton instance of the ISBN validator which
* converts ISBN-10 codes to ISBN-13.
*
* @return A singleton instance of the ISBN validator.
*/
public static ISBNValidator getInstance() {
return ISBN_VALIDATOR;
}
/**
* Return a singleton instance of the ISBN validator specifying
* whether ISBN-10 codes should be converted to ISBN-13.
*
* @param convert {@code true} if valid ISBN-10 codes
* should be converted to ISBN-13 codes or {@code false}
* if valid ISBN-10 codes should be returned unchanged.
* @return A singleton instance of the ISBN validator.
*/
public static ISBNValidator getInstance(final boolean convert) {
return convert ? ISBN_VALIDATOR : ISBN_VALIDATOR_NO_CONVERT;
}
/**
* Constructs an ISBN validator which converts ISBN-10 codes
* to ISBN-13.
*/
public ISBNValidator() {
this(true);
}
/**
* Constructs an ISBN validator indicating whether
* ISBN-10 codes should be converted to ISBN-13.
*
* @param convert {@code true} if valid ISBN-10 codes
* should be converted to ISBN-13 codes or {@code false}
* if valid ISBN-10 codes should be returned unchanged.
*/
public ISBNValidator(final boolean convert) {
this.convert = convert;
}
/**
* Check the code is either a valid ISBN-10 or ISBN-13 code.
*
* @param code The code to validate.
* @return {@code true} if a valid ISBN-10 or
* ISBN-13 code, otherwise {@code false}.
*/
public boolean isValid(final String code) {
return isValidISBN13(code) || isValidISBN10(code);
}
/**
* Check the code is a valid ISBN-10 code.
*
* @param code The code to validate.
* @return {@code true} if a valid ISBN-10
* code, otherwise {@code false}.
*/
public boolean isValidISBN10(final String code) {
return isbn10Validator.isValid(code);
}
/**
* Check the code is a valid ISBN-13 code.
*
* @param code The code to validate.
* @return {@code true} if a valid ISBN-13
* code, otherwise {@code false}.
*/
public boolean isValidISBN13(final String code) {
return isbn13Validator.isValid(code);
}
/**
* Check the code is either a valid ISBN-10 or ISBN-13 code.
* <p>
* If valid, this method returns the ISBN code with
* formatting characters removed (i.e. space or hyphen).
* <p>
* Converts an ISBN-10 codes to ISBN-13 if
* <code>convertToISBN13</code> is {@code true}.
*
* @param code The code to validate.
* @return A valid ISBN code if valid, otherwise <code>null</code>.
*/
public String validate(final String code) {
String result = validateISBN13(code);
if (result == null) {
result = validateISBN10(code);
if (result != null && convert) {
result = convertToISBN13(result);
}
}
return result;
}
/**
* Check the code is a valid ISBN-10 code.
* <p>
* If valid, this method returns the ISBN-10 code with
* formatting characters removed (i.e. space or hyphen).
*
* @param code The code to validate.
* @return A valid ISBN-10 code if valid,
* otherwise <code>null</code>.
*/
public String validateISBN10(final String code) {
final Object result = isbn10Validator.validate(code);
return result == null ? null : result.toString();
}
/**
* Check the code is a valid ISBN-13 code.
* <p>
* If valid, this method returns the ISBN-13 code with
* formatting characters removed (i.e. space or hyphen).
*
* @param code The code to validate.
* @return A valid ISBN-13 code if valid,
* otherwise <code>null</code>.
*/
public String validateISBN13(final String code) {
final Object result = isbn13Validator.validate(code);
return result == null ? null : result.toString();
}
/**
* Convert an ISBN-10 code to an ISBN-13 code.
* <p>
* This method requires a valid ISBN-10 with NO formatting
* characters.
*
* @param isbn10 The ISBN-10 code to convert
* @return A converted ISBN-13 code or <code>null</code>
* if the ISBN-10 code is not valid
*/
public String convertToISBN13(final String isbn10) {
if (isbn10 == null) {
return null;
}
final String input = isbn10.trim();
if (input.length() != ISBN_10_LEN) {
throw new IllegalArgumentException("Invalid length " + input.length() + " for '" + input + "'");
}
// Calculate the new ISBN-13 code (drop the original checkdigit)
String isbn13 = "978" + input.substring(0, ISBN_10_LEN - 1);
try {
final String checkDigit = isbn13Validator.getCheckDigit().calculate(isbn13);
isbn13 += checkDigit;
return isbn13;
} catch (final CheckDigitException e) {
throw new IllegalArgumentException("Check digit error for '" + input + "' - " + e.getMessage());
}
}
}
| 7,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.