Moved tests over from testsuite to core
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* Copyright 2002-2006 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.core;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* @author Rob Harrop
|
||||
* @since 2.0
|
||||
*/
|
||||
public class AttributeAccessorSupportTests extends TestCase {
|
||||
|
||||
private static final String NAME = "foo";
|
||||
|
||||
private static final String VALUE = "bar";
|
||||
|
||||
private AttributeAccessor attributeAccessor;
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
this.attributeAccessor = new AttributeAccessorSupport() {
|
||||
};
|
||||
}
|
||||
|
||||
public void testSetAndGet() throws Exception {
|
||||
this.attributeAccessor.setAttribute(NAME, VALUE);
|
||||
assertEquals(VALUE, this.attributeAccessor.getAttribute(NAME));
|
||||
}
|
||||
|
||||
public void testSetAndHas() throws Exception {
|
||||
assertFalse(this.attributeAccessor.hasAttribute(NAME));
|
||||
this.attributeAccessor.setAttribute(NAME, VALUE);
|
||||
assertTrue(this.attributeAccessor.hasAttribute(NAME));
|
||||
}
|
||||
|
||||
public void testRemove() throws Exception {
|
||||
assertFalse(this.attributeAccessor.hasAttribute(NAME));
|
||||
this.attributeAccessor.setAttribute(NAME, VALUE);
|
||||
assertEquals(VALUE, this.attributeAccessor.removeAttribute(NAME));
|
||||
assertFalse(this.attributeAccessor.hasAttribute(NAME));
|
||||
}
|
||||
|
||||
public void testAttributeNames() throws Exception {
|
||||
this.attributeAccessor.setAttribute(NAME, VALUE);
|
||||
this.attributeAccessor.setAttribute("abc", "123");
|
||||
String[] attributeNames = this.attributeAccessor.attributeNames();
|
||||
Arrays.sort(attributeNames);
|
||||
assertTrue(Arrays.binarySearch(attributeNames, NAME) > -1);
|
||||
assertTrue(Arrays.binarySearch(attributeNames, "abc") > -1);
|
||||
}
|
||||
protected void tearDown() throws Exception {
|
||||
this.attributeAccessor.removeAttribute(NAME);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* Copyright 2002-2007 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.core;
|
||||
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* @author Darren Davison
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class CollectionFactoryTests extends TestCase {
|
||||
|
||||
public void testLinkedSet() {
|
||||
Set set = CollectionFactory.createLinkedSetIfPossible(16);
|
||||
assertTrue(set instanceof LinkedHashSet);
|
||||
}
|
||||
|
||||
public void testLinkedMap() {
|
||||
Map map = CollectionFactory.createLinkedMapIfPossible(16);
|
||||
assertTrue(map instanceof LinkedHashMap);
|
||||
}
|
||||
|
||||
public void testIdentityMap() {
|
||||
Map map = CollectionFactory.createIdentityMapIfPossible(16);
|
||||
assertTrue(map instanceof IdentityHashMap);
|
||||
}
|
||||
|
||||
public void testConcurrentMap() {
|
||||
Map map = CollectionFactory.createConcurrentMapIfPossible(16);
|
||||
assertTrue(map.getClass().getName().endsWith("ConcurrentHashMap"));
|
||||
}
|
||||
|
||||
public void testConcurrentMapWithExplicitInterface() {
|
||||
ConcurrentMap map = CollectionFactory.createConcurrentMap(16);
|
||||
assertTrue(map.getClass().getSuperclass().getName().endsWith("ConcurrentHashMap"));
|
||||
map.putIfAbsent("key", "value1");
|
||||
map.putIfAbsent("key", "value2");
|
||||
assertEquals("value1", map.get("key"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
/*
|
||||
* Copyright 2002-2007 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.core;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
* @author Rick Evans
|
||||
* @since 28.04.2003
|
||||
*/
|
||||
public class ConstantsTests extends TestCase {
|
||||
|
||||
public void testConstants() {
|
||||
Constants c = new Constants(A.class);
|
||||
assertEquals(A.class.getName(), c.getClassName());
|
||||
assertEquals(9, c.getSize());
|
||||
|
||||
assertEquals(c.asNumber("DOG").intValue(), A.DOG);
|
||||
assertEquals(c.asNumber("dog").intValue(), A.DOG);
|
||||
assertEquals(c.asNumber("cat").intValue(), A.CAT);
|
||||
|
||||
try {
|
||||
c.asNumber("bogus");
|
||||
fail("Can't get bogus field");
|
||||
}
|
||||
catch (ConstantException expected) {
|
||||
}
|
||||
|
||||
assertTrue(c.asString("S1").equals(A.S1));
|
||||
try {
|
||||
c.asNumber("S1");
|
||||
fail("Wrong type");
|
||||
}
|
||||
catch (ConstantException expected) {
|
||||
}
|
||||
}
|
||||
|
||||
public void testGetNames() {
|
||||
Constants c = new Constants(A.class);
|
||||
|
||||
Set names = c.getNames("");
|
||||
assertEquals(c.getSize(), names.size());
|
||||
assertTrue(names.contains("DOG"));
|
||||
assertTrue(names.contains("CAT"));
|
||||
assertTrue(names.contains("S1"));
|
||||
|
||||
names = c.getNames("D");
|
||||
assertEquals(1, names.size());
|
||||
assertTrue(names.contains("DOG"));
|
||||
|
||||
names = c.getNames("d");
|
||||
assertEquals(1, names.size());
|
||||
assertTrue(names.contains("DOG"));
|
||||
}
|
||||
|
||||
public void testGetValues() {
|
||||
Constants c = new Constants(A.class);
|
||||
|
||||
Set values = c.getValues("");
|
||||
assertEquals(7, values.size());
|
||||
assertTrue(values.contains(new Integer(0)));
|
||||
assertTrue(values.contains(new Integer(66)));
|
||||
assertTrue(values.contains(""));
|
||||
|
||||
values = c.getValues("D");
|
||||
assertEquals(1, values.size());
|
||||
assertTrue(values.contains(new Integer(0)));
|
||||
|
||||
values = c.getValues("prefix");
|
||||
assertEquals(2, values.size());
|
||||
assertTrue(values.contains(new Integer(1)));
|
||||
assertTrue(values.contains(new Integer(2)));
|
||||
|
||||
values = c.getValuesForProperty("myProperty");
|
||||
assertEquals(2, values.size());
|
||||
assertTrue(values.contains(new Integer(1)));
|
||||
assertTrue(values.contains(new Integer(2)));
|
||||
}
|
||||
|
||||
public void testGetValuesInTurkey() {
|
||||
Locale oldLocale = Locale.getDefault();
|
||||
Locale.setDefault(new Locale("tr", ""));
|
||||
try {
|
||||
Constants c = new Constants(A.class);
|
||||
|
||||
Set values = c.getValues("");
|
||||
assertEquals(7, values.size());
|
||||
assertTrue(values.contains(new Integer(0)));
|
||||
assertTrue(values.contains(new Integer(66)));
|
||||
assertTrue(values.contains(""));
|
||||
|
||||
values = c.getValues("D");
|
||||
assertEquals(1, values.size());
|
||||
assertTrue(values.contains(new Integer(0)));
|
||||
|
||||
values = c.getValues("prefix");
|
||||
assertEquals(2, values.size());
|
||||
assertTrue(values.contains(new Integer(1)));
|
||||
assertTrue(values.contains(new Integer(2)));
|
||||
|
||||
values = c.getValuesForProperty("myProperty");
|
||||
assertEquals(2, values.size());
|
||||
assertTrue(values.contains(new Integer(1)));
|
||||
assertTrue(values.contains(new Integer(2)));
|
||||
}
|
||||
finally {
|
||||
Locale.setDefault(oldLocale);
|
||||
}
|
||||
}
|
||||
|
||||
public void testSuffixAccess() {
|
||||
Constants c = new Constants(A.class);
|
||||
|
||||
Set names = c.getNamesForSuffix("_PROPERTY");
|
||||
assertEquals(2, names.size());
|
||||
assertTrue(names.contains("NO_PROPERTY"));
|
||||
assertTrue(names.contains("YES_PROPERTY"));
|
||||
|
||||
Set values = c.getValuesForSuffix("_PROPERTY");
|
||||
assertEquals(2, values.size());
|
||||
assertTrue(values.contains(new Integer(3)));
|
||||
assertTrue(values.contains(new Integer(4)));
|
||||
}
|
||||
|
||||
public void testToCode() {
|
||||
Constants c = new Constants(A.class);
|
||||
|
||||
assertEquals(c.toCode(new Integer(0), ""), "DOG");
|
||||
assertEquals(c.toCode(new Integer(0), "D"), "DOG");
|
||||
assertEquals(c.toCode(new Integer(0), "DO"), "DOG");
|
||||
assertEquals(c.toCode(new Integer(0), "DoG"), "DOG");
|
||||
assertEquals(c.toCode(new Integer(66), ""), "CAT");
|
||||
assertEquals(c.toCode(new Integer(66), "C"), "CAT");
|
||||
assertEquals(c.toCode(new Integer(66), "ca"), "CAT");
|
||||
assertEquals(c.toCode(new Integer(66), "cAt"), "CAT");
|
||||
assertEquals(c.toCode("", ""), "S1");
|
||||
assertEquals(c.toCode("", "s"), "S1");
|
||||
assertEquals(c.toCode("", "s1"), "S1");
|
||||
try {
|
||||
c.toCode("bogus", "bogus");
|
||||
fail("Should have thrown ConstantException");
|
||||
}
|
||||
catch (ConstantException expected) {
|
||||
}
|
||||
|
||||
assertEquals(c.toCodeForProperty(new Integer(1), "myProperty"), "MY_PROPERTY_NO");
|
||||
assertEquals(c.toCodeForProperty(new Integer(2), "myProperty"), "MY_PROPERTY_YES");
|
||||
try {
|
||||
c.toCodeForProperty("bogus", "bogus");
|
||||
fail("Should have thrown ConstantException");
|
||||
}
|
||||
catch (ConstantException expected) {
|
||||
}
|
||||
|
||||
assertEquals(c.toCodeForSuffix(new Integer(0), ""), "DOG");
|
||||
assertEquals(c.toCodeForSuffix(new Integer(0), "G"), "DOG");
|
||||
assertEquals(c.toCodeForSuffix(new Integer(0), "OG"), "DOG");
|
||||
assertEquals(c.toCodeForSuffix(new Integer(0), "DoG"), "DOG");
|
||||
assertEquals(c.toCodeForSuffix(new Integer(66), ""), "CAT");
|
||||
assertEquals(c.toCodeForSuffix(new Integer(66), "T"), "CAT");
|
||||
assertEquals(c.toCodeForSuffix(new Integer(66), "at"), "CAT");
|
||||
assertEquals(c.toCodeForSuffix(new Integer(66), "cAt"), "CAT");
|
||||
assertEquals(c.toCodeForSuffix("", ""), "S1");
|
||||
assertEquals(c.toCodeForSuffix("", "1"), "S1");
|
||||
assertEquals(c.toCodeForSuffix("", "s1"), "S1");
|
||||
try {
|
||||
c.toCodeForSuffix("bogus", "bogus");
|
||||
fail("Should have thrown ConstantException");
|
||||
}
|
||||
catch (ConstantException expected) {
|
||||
}
|
||||
}
|
||||
|
||||
public void testGetValuesWithNullPrefix() throws Exception {
|
||||
Constants c = new Constants(A.class);
|
||||
Set values = c.getValues(null);
|
||||
assertEquals("Must have returned *all* public static final values", 7, values.size());
|
||||
}
|
||||
|
||||
public void testGetValuesWithEmptyStringPrefix() throws Exception {
|
||||
Constants c = new Constants(A.class);
|
||||
Set values = c.getValues("");
|
||||
assertEquals("Must have returned *all* public static final values", 7, values.size());
|
||||
}
|
||||
|
||||
public void testGetValuesWithWhitespacedStringPrefix() throws Exception {
|
||||
Constants c = new Constants(A.class);
|
||||
Set values = c.getValues(" ");
|
||||
assertEquals("Must have returned *all* public static final values", 7, values.size());
|
||||
}
|
||||
|
||||
public void testWithClassThatExposesNoConstants() throws Exception {
|
||||
Constants c = new Constants(NoConstants.class);
|
||||
assertEquals(0, c.getSize());
|
||||
final Set values = c.getValues("");
|
||||
assertNotNull(values);
|
||||
assertEquals(0, values.size());
|
||||
}
|
||||
|
||||
public void testCtorWithNullClass() throws Exception {
|
||||
try {
|
||||
new Constants(null);
|
||||
fail("Must have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {}
|
||||
}
|
||||
|
||||
|
||||
private static final class NoConstants {
|
||||
}
|
||||
|
||||
|
||||
private static final class A {
|
||||
|
||||
public static final int DOG = 0;
|
||||
public static final int CAT = 66;
|
||||
public static final String S1 = "";
|
||||
|
||||
public static final int PREFIX_NO = 1;
|
||||
public static final int PREFIX_YES = 2;
|
||||
|
||||
public static final int MY_PROPERTY_NO = 1;
|
||||
public static final int MY_PROPERTY_YES = 2;
|
||||
|
||||
public static final int NO_PROPERTY = 3;
|
||||
public static final int YES_PROPERTY = 4;
|
||||
|
||||
/** ignore these */
|
||||
protected static final int P = -1;
|
||||
protected boolean f;
|
||||
static final Object o = new Object();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* Copyright 2002-2005 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.core;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import junit.framework.Assert;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class NestedExceptionTests extends TestCase {
|
||||
|
||||
public void testNestedRuntimeExceptionWithNoRootCause() {
|
||||
String mesg = "mesg of mine";
|
||||
// Making a class abstract doesn't _really_ prevent instantiation :-)
|
||||
NestedRuntimeException nex = new NestedRuntimeException(mesg) {};
|
||||
assertNull(nex.getCause());
|
||||
assertEquals(nex.getMessage(), mesg);
|
||||
|
||||
// Check printStackTrace
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
PrintWriter pw = new PrintWriter(baos);
|
||||
nex.printStackTrace(pw);
|
||||
pw.flush();
|
||||
String stackTrace = new String(baos.toByteArray());
|
||||
assertFalse(stackTrace.indexOf(mesg) == -1);
|
||||
}
|
||||
|
||||
public void testNestedRuntimeExceptionWithRootCause() {
|
||||
String myMessage = "mesg for this exception";
|
||||
String rootCauseMesg = "this is the obscure message of the root cause";
|
||||
ServletException rootCause = new ServletException(rootCauseMesg);
|
||||
// Making a class abstract doesn't _really_ prevent instantiation :-)
|
||||
NestedRuntimeException nex = new NestedRuntimeException(myMessage, rootCause) {};
|
||||
Assert.assertEquals(nex.getCause(), rootCause);
|
||||
assertTrue(nex.getMessage().indexOf(myMessage) != -1);
|
||||
assertTrue(nex.getMessage().indexOf(rootCauseMesg) != -1);
|
||||
|
||||
// check PrintStackTrace
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
PrintWriter pw = new PrintWriter(baos);
|
||||
nex.printStackTrace(pw);
|
||||
pw.flush();
|
||||
String stackTrace = new String(baos.toByteArray());
|
||||
assertFalse(stackTrace.indexOf(rootCause.getClass().getName()) == -1);
|
||||
assertFalse(stackTrace.indexOf(rootCauseMesg) == -1);
|
||||
}
|
||||
|
||||
public void testNestedCheckedExceptionWithNoRootCause() {
|
||||
String mesg = "mesg of mine";
|
||||
// Making a class abstract doesn't _really_ prevent instantiation :-)
|
||||
NestedCheckedException nex = new NestedCheckedException(mesg) {};
|
||||
assertNull(nex.getCause());
|
||||
assertEquals(nex.getMessage(), mesg);
|
||||
|
||||
// Check printStackTrace
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
PrintWriter pw = new PrintWriter(baos);
|
||||
nex.printStackTrace(pw);
|
||||
pw.flush();
|
||||
String stackTrace = new String(baos.toByteArray());
|
||||
assertFalse(stackTrace.indexOf(mesg) == -1);
|
||||
}
|
||||
|
||||
public void testNestedCheckedExceptionWithRootCause() {
|
||||
String myMessage = "mesg for this exception";
|
||||
String rootCauseMesg = "this is the obscure message of the root cause";
|
||||
ServletException rootCause = new ServletException(rootCauseMesg);
|
||||
// Making a class abstract doesn't _really_ prevent instantiation :-)
|
||||
NestedCheckedException nex = new NestedCheckedException(myMessage, rootCause) {};
|
||||
Assert.assertEquals(nex.getCause(), rootCause);
|
||||
assertTrue(nex.getMessage().indexOf(myMessage) != -1);
|
||||
assertTrue(nex.getMessage().indexOf(rootCauseMesg) != -1);
|
||||
|
||||
// check PrintStackTrace
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
PrintWriter pw = new PrintWriter(baos);
|
||||
nex.printStackTrace(pw);
|
||||
pw.flush();
|
||||
String stackTrace = new String(baos.toByteArray());
|
||||
assertFalse(stackTrace.indexOf(rootCause.getClass().getName()) == -1);
|
||||
assertFalse(stackTrace.indexOf(rootCauseMesg) == -1);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* Copyright 2002-2006 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.core;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import java.util.Comparator;
|
||||
|
||||
/**
|
||||
* Unit tests for the {@link OrderComparator} class.
|
||||
*
|
||||
* @author Rick Evans
|
||||
*/
|
||||
public final class OrderComparatorTests extends TestCase {
|
||||
|
||||
private Comparator comparator;
|
||||
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
this.comparator = new OrderComparator();
|
||||
}
|
||||
|
||||
|
||||
public void testCompareOrderedInstancesBefore() throws Exception {
|
||||
assertEquals(-1, this.comparator.compare(
|
||||
new StubOrdered(100), new StubOrdered(2000)));
|
||||
}
|
||||
|
||||
public void testCompareOrderedInstancesSame() throws Exception {
|
||||
assertEquals(0, this.comparator.compare(
|
||||
new StubOrdered(100), new StubOrdered(100)));
|
||||
}
|
||||
|
||||
public void testCompareOrderedInstancesAfter() throws Exception {
|
||||
assertEquals(1, this.comparator.compare(
|
||||
new StubOrdered(982300), new StubOrdered(100)));
|
||||
}
|
||||
|
||||
public void testCompareTwoNonOrderedInstancesEndsUpAsSame() throws Exception {
|
||||
assertEquals(0, this.comparator.compare(new Object(), new Object()));
|
||||
}
|
||||
|
||||
|
||||
private static final class StubOrdered implements Ordered {
|
||||
|
||||
private final int order;
|
||||
|
||||
|
||||
public StubOrdered(int order) {
|
||||
this.order = order;
|
||||
}
|
||||
|
||||
public int getOrder() {
|
||||
return this.order;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
/*
|
||||
* Copyright 2002-2007 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.core.enums;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* @author Keith Donald
|
||||
* @author Juergen Hoeller
|
||||
* @author Sam Brannen
|
||||
*/
|
||||
public class LabeledEnumTests extends TestCase {
|
||||
|
||||
private byte[] serializeObject(final Object obj) throws IOException {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ObjectOutputStream oos = new ObjectOutputStream(baos);
|
||||
oos.writeObject(obj);
|
||||
oos.close();
|
||||
return baos.toByteArray();
|
||||
}
|
||||
|
||||
private Object deserializeObject(final byte[] serializedBytes) throws IOException, ClassNotFoundException {
|
||||
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(serializedBytes));
|
||||
Object obj = ois.readObject();
|
||||
ois.close();
|
||||
return obj;
|
||||
}
|
||||
|
||||
private Object serializeAndDeserializeObject(Object obj) throws IOException, ClassNotFoundException {
|
||||
return deserializeObject(serializeObject(obj));
|
||||
}
|
||||
|
||||
public void testCodeFound() {
|
||||
Dog golden = (Dog) StaticLabeledEnumResolver.instance().getLabeledEnumByCode(Dog.class, new Short((short) 11));
|
||||
Dog borderCollie = (Dog) StaticLabeledEnumResolver.instance().getLabeledEnumByCode(Dog.class,
|
||||
new Short((short) 13));
|
||||
assertSame(golden, Dog.GOLDEN_RETRIEVER);
|
||||
assertSame(borderCollie, Dog.BORDER_COLLIE);
|
||||
}
|
||||
|
||||
public void testCodeFoundForAbstractEnums() {
|
||||
ValuedEnum one = (ValuedEnum) StaticLabeledEnumResolver.instance().getLabeledEnumByCode(ValuedEnum.class,
|
||||
new Short((short) 1));
|
||||
ValuedEnum two = (ValuedEnum) StaticLabeledEnumResolver.instance().getLabeledEnumByCode(ValuedEnum.class,
|
||||
new Short((short) 2));
|
||||
assertSame(one, ValuedEnum.ONE);
|
||||
assertSame(two, ValuedEnum.TWO);
|
||||
}
|
||||
|
||||
public void testDeserializationOfInnerClassEnums() throws Exception {
|
||||
assertSame(serializeAndDeserializeObject(Other.THING1), Other.THING1);
|
||||
}
|
||||
|
||||
public void testDeserializationOfStandAloneEnums() throws Exception {
|
||||
assertSame(serializeAndDeserializeObject(StandAloneStaticLabeledEnum.ENUM1),
|
||||
StandAloneStaticLabeledEnum.ENUM1);
|
||||
}
|
||||
|
||||
public void testLabelFound() {
|
||||
Dog golden = (Dog) StaticLabeledEnumResolver.instance().getLabeledEnumByLabel(Dog.class, "Golden Retriever");
|
||||
Dog borderCollie = (Dog) StaticLabeledEnumResolver.instance().getLabeledEnumByLabel(Dog.class, "Border Collie");
|
||||
assertSame(golden, Dog.GOLDEN_RETRIEVER);
|
||||
assertSame(borderCollie, Dog.BORDER_COLLIE);
|
||||
}
|
||||
|
||||
public void testLabelFoundForStandAloneEnum() {
|
||||
StandAloneStaticLabeledEnum enum1 = (StandAloneStaticLabeledEnum)
|
||||
StaticLabeledEnumResolver.instance().getLabeledEnumByLabel(StandAloneStaticLabeledEnum.class, "Enum1");
|
||||
StandAloneStaticLabeledEnum enum2 = (StandAloneStaticLabeledEnum)
|
||||
StaticLabeledEnumResolver.instance().getLabeledEnumByLabel(StandAloneStaticLabeledEnum.class, "Enum2");
|
||||
assertSame(enum1, StandAloneStaticLabeledEnum.ENUM1);
|
||||
assertSame(enum2, StandAloneStaticLabeledEnum.ENUM2);
|
||||
}
|
||||
|
||||
public void testLabelFoundForAbstractEnums() {
|
||||
ValuedEnum one = (ValuedEnum)
|
||||
StaticLabeledEnumResolver.instance().getLabeledEnumByLabel(ValuedEnum.class, "one");
|
||||
ValuedEnum two = (ValuedEnum)
|
||||
StaticLabeledEnumResolver.instance().getLabeledEnumByLabel(ValuedEnum.class, "two");
|
||||
assertSame(one, ValuedEnum.ONE);
|
||||
assertSame(two, ValuedEnum.TWO);
|
||||
}
|
||||
|
||||
public void testDoesNotMatchWrongClass() {
|
||||
try {
|
||||
LabeledEnum none = StaticLabeledEnumResolver.instance().getLabeledEnumByCode(Dog.class,
|
||||
new Short((short) 1));
|
||||
fail("Should have failed");
|
||||
}
|
||||
catch (IllegalArgumentException e) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
public void testEquals() {
|
||||
assertEquals("Code equality means equals", Dog.GOLDEN_RETRIEVER, new Dog(11, "Golden Retriever"));
|
||||
assertFalse("Code inequality means notEquals", Dog.GOLDEN_RETRIEVER.equals(new Dog(12, "Golden Retriever")));
|
||||
}
|
||||
|
||||
|
||||
private static class Other extends StaticLabeledEnum {
|
||||
|
||||
public static final Other THING1 = new Other(1, "Thing1");
|
||||
public static final Other THING2 = new Other(2, "Thing2");
|
||||
|
||||
|
||||
private Other(int code, String name) {
|
||||
super(code, name);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class Dog extends StaticLabeledEnum {
|
||||
|
||||
public static final Dog GOLDEN_RETRIEVER = new Dog(11, null) {
|
||||
|
||||
public String getLabel() {
|
||||
return "Golden Retriever";
|
||||
}
|
||||
|
||||
// Overriding getType() is no longer necessary as of Spring 2.5;
|
||||
// however, this is left here to provide valid testing for
|
||||
// backwards compatibility.
|
||||
public Class getType() {
|
||||
return Dog.class;
|
||||
}
|
||||
};
|
||||
|
||||
public static final Dog BORDER_COLLIE = new Dog(13, "Border Collie");
|
||||
public static final Dog WHIPPET = new Dog(14, "Whippet");
|
||||
|
||||
// Ignore this
|
||||
public static final Other THING1 = Other.THING1;
|
||||
|
||||
|
||||
private Dog(int code, String name) {
|
||||
super(code, name);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static abstract class ValuedEnum extends StaticLabeledEnum {
|
||||
|
||||
public static final ValuedEnum ONE = new ValuedEnum(1, "one") {
|
||||
public int getValue() {
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
|
||||
public static final ValuedEnum TWO = new ValuedEnum(2, "two") {
|
||||
public int getValue() {
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
|
||||
private ValuedEnum(int code, String name) {
|
||||
super(code, name);
|
||||
}
|
||||
|
||||
public abstract int getValue();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/*
|
||||
* Copyright 2002-2007 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.core.enums;
|
||||
|
||||
/**
|
||||
* Stand-alone static enum for use in {@link LabeledEnumTests}.
|
||||
*
|
||||
* @author Sam Brannen
|
||||
* @since 2.5
|
||||
*/
|
||||
public class StandAloneStaticLabeledEnum extends StaticLabeledEnum {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public static final StandAloneStaticLabeledEnum ENUM1 = new StandAloneStaticLabeledEnum(1, "Enum1");
|
||||
public static final StandAloneStaticLabeledEnum ENUM2 = new StandAloneStaticLabeledEnum(2, "Enum2");
|
||||
|
||||
|
||||
private StandAloneStaticLabeledEnum(int code, String name) {
|
||||
super(code, name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
/*
|
||||
* Copyright 2002-2005 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.core.style;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.core.CollectionFactory;
|
||||
import org.springframework.util.ObjectUtils;
|
||||
|
||||
/**
|
||||
* @author Keith Donald
|
||||
*/
|
||||
public class ToStringCreatorTests extends TestCase {
|
||||
|
||||
private SomeObject s1, s2, s3;
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
s1 = new SomeObject() {
|
||||
public String toString() {
|
||||
return "A";
|
||||
}
|
||||
};
|
||||
s2 = new SomeObject() {
|
||||
public String toString() {
|
||||
return "B";
|
||||
}
|
||||
};
|
||||
s3 = new SomeObject() {
|
||||
public String toString() {
|
||||
return "C";
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public void testDefaultStyleMap() {
|
||||
final Map map = getMap();
|
||||
Object stringy = new Object() {
|
||||
public String toString() {
|
||||
return new ToStringCreator(this).append("familyFavoriteSport", map).toString();
|
||||
}
|
||||
};
|
||||
assertEquals("[ToStringCreatorTests.4@" + ObjectUtils.getIdentityHexString(stringy)
|
||||
+ " familyFavoriteSport = map['Keri' -> 'Softball', 'Scot' -> 'Fishing', 'Keith' -> 'Flag Football']]",
|
||||
stringy.toString());
|
||||
}
|
||||
|
||||
private Map getMap() {
|
||||
Map map = CollectionFactory.createLinkedMapIfPossible(3);
|
||||
map.put("Keri", "Softball");
|
||||
map.put("Scot", "Fishing");
|
||||
map.put("Keith", "Flag Football");
|
||||
return map;
|
||||
}
|
||||
|
||||
public void testDefaultStyleArray() {
|
||||
SomeObject[] array = new SomeObject[] { s1, s2, s3 };
|
||||
String str = new ToStringCreator(array).toString();
|
||||
assertEquals("[@" + ObjectUtils.getIdentityHexString(array)
|
||||
+ " array<ToStringCreatorTests.SomeObject>[A, B, C]]", str);
|
||||
}
|
||||
|
||||
public void testPrimitiveArrays() {
|
||||
int[] integers = new int[] { 0, 1, 2, 3, 4 };
|
||||
String str = new ToStringCreator(integers).toString();
|
||||
assertEquals("[@" + ObjectUtils.getIdentityHexString(integers) + " array<Integer>[0, 1, 2, 3, 4]]", str);
|
||||
}
|
||||
|
||||
public void testList() {
|
||||
List list = new ArrayList();
|
||||
list.add(s1);
|
||||
list.add(s2);
|
||||
list.add(s3);
|
||||
String str = new ToStringCreator(this).append("myLetters", list).toString();
|
||||
assertEquals("[ToStringCreatorTests@" + ObjectUtils.getIdentityHexString(this) + " myLetters = list[A, B, C]]",
|
||||
str);
|
||||
}
|
||||
|
||||
public void testSet() {
|
||||
Set set = CollectionFactory.createLinkedSetIfPossible(3);
|
||||
set.add(s1);
|
||||
set.add(s2);
|
||||
set.add(s3);
|
||||
String str = new ToStringCreator(this).append("myLetters", set).toString();
|
||||
assertEquals("[ToStringCreatorTests@" + ObjectUtils.getIdentityHexString(this) + " myLetters = set[A, B, C]]",
|
||||
str);
|
||||
}
|
||||
|
||||
public void testClass() {
|
||||
String str = new ToStringCreator(this).append("myClass", this.getClass()).toString();
|
||||
assertEquals("[ToStringCreatorTests@" + ObjectUtils.getIdentityHexString(this)
|
||||
+ " myClass = ToStringCreatorTests]", str);
|
||||
}
|
||||
|
||||
public void testMethod() throws Exception {
|
||||
String str = new ToStringCreator(this).append("myMethod", this.getClass().getMethod("testMethod", null))
|
||||
.toString();
|
||||
assertEquals("[ToStringCreatorTests@" + ObjectUtils.getIdentityHexString(this)
|
||||
+ " myMethod = testMethod@ToStringCreatorTests]", str);
|
||||
}
|
||||
|
||||
|
||||
public static class SomeObject {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
/*
|
||||
* Copyright 2002-2007 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.core.task;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.util.ClassUtils;
|
||||
import org.springframework.util.ConcurrencyThrottleSupport;
|
||||
|
||||
/**
|
||||
* @author Rick Evans
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public final class SimpleAsyncTaskExecutorTests extends TestCase {
|
||||
|
||||
public void testCannotExecuteWhenConcurrencyIsSwitchedOff() throws Exception {
|
||||
SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor();
|
||||
executor.setConcurrencyLimit(ConcurrencyThrottleSupport.NO_CONCURRENCY);
|
||||
assertFalse(executor.isThrottleActive());
|
||||
try {
|
||||
executor.execute(new NoOpRunnable());
|
||||
}
|
||||
catch (IllegalStateException expected) {
|
||||
}
|
||||
}
|
||||
|
||||
public void testThrottleIsNotActiveByDefault() throws Exception {
|
||||
SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor();
|
||||
assertFalse("Concurrency throttle must not default to being active (on)", executor.isThrottleActive());
|
||||
}
|
||||
|
||||
public void testThreadNameGetsSetCorrectly() throws Exception {
|
||||
final String customPrefix = "chankPop#";
|
||||
final Object monitor = new Object();
|
||||
SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor(customPrefix);
|
||||
ThreadNameHarvester task = new ThreadNameHarvester(monitor);
|
||||
executeAndWait(executor, task, monitor);
|
||||
assertTrue(task.getThreadName().startsWith(customPrefix));
|
||||
}
|
||||
|
||||
public void testThreadNameRevertsToDefaultIfSetToNull() throws Exception {
|
||||
final Object monitor = new Object();
|
||||
SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor(null);
|
||||
ThreadNameHarvester task = new ThreadNameHarvester(monitor);
|
||||
executeAndWait(executor, task, monitor);
|
||||
assertTrue(task.getThreadName().startsWith(ClassUtils.getShortName(SimpleAsyncTaskExecutor.class) + "-"));
|
||||
}
|
||||
|
||||
public void testThrowsExceptionWhenSuppliedWithNullRunnable() throws Exception {
|
||||
try {
|
||||
new SimpleAsyncTaskExecutor().execute(null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
}
|
||||
|
||||
private void executeAndWait(SimpleAsyncTaskExecutor executor, Runnable task, Object monitor) {
|
||||
synchronized (monitor) {
|
||||
executor.execute(task);
|
||||
try {
|
||||
monitor.wait();
|
||||
}
|
||||
catch (InterruptedException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static final class NoOpRunnable implements Runnable {
|
||||
|
||||
public void run() {
|
||||
// no-op
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static abstract class AbstractNotifyingRunnable implements Runnable {
|
||||
|
||||
private final Object monitor;
|
||||
|
||||
protected AbstractNotifyingRunnable(Object monitor) {
|
||||
this.monitor = monitor;
|
||||
}
|
||||
|
||||
public final void run() {
|
||||
synchronized (this.monitor) {
|
||||
try {
|
||||
doRun();
|
||||
}
|
||||
finally {
|
||||
this.monitor.notifyAll();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract void doRun();
|
||||
}
|
||||
|
||||
|
||||
private static final class ThreadNameHarvester extends AbstractNotifyingRunnable {
|
||||
|
||||
private String threadName;
|
||||
|
||||
protected ThreadNameHarvester(Object monitor) {
|
||||
super(monitor);
|
||||
}
|
||||
|
||||
public String getThreadName() {
|
||||
return this.threadName;
|
||||
}
|
||||
|
||||
protected void doRun() {
|
||||
this.threadName = Thread.currentThread().getName();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* Copyright 2002-2005 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.util;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* @author Keith Donald
|
||||
*/
|
||||
public class CachingMapDecoratorTests extends TestCase {
|
||||
|
||||
public void testValidCache() {
|
||||
MyCachingMap cache = new MyCachingMap();
|
||||
Object value;
|
||||
|
||||
value = cache.get("value key");
|
||||
assertTrue(cache.createCalled());
|
||||
assertEquals(value, "expensive value to cache");
|
||||
|
||||
cache.get("value key 2");
|
||||
assertTrue(cache.createCalled());
|
||||
|
||||
value = cache.get("value key");
|
||||
assertEquals(cache.createCalled(), false);
|
||||
assertEquals(value, "expensive value to cache");
|
||||
|
||||
cache.get("value key 2");
|
||||
assertEquals(cache.createCalled(), false);
|
||||
assertEquals(value, "expensive value to cache");
|
||||
}
|
||||
|
||||
|
||||
private static class MyCachingMap extends CachingMapDecorator {
|
||||
|
||||
private boolean createCalled;
|
||||
|
||||
protected Object create(Object key) {
|
||||
createCalled = true;
|
||||
return "expensive value to cache";
|
||||
}
|
||||
|
||||
public boolean createCalled() {
|
||||
boolean c = createCalled;
|
||||
this.createCalled = false;
|
||||
return c;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
/*
|
||||
* Copyright 2002-2007 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Hashtable;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* @author Rob Harrop
|
||||
* @author Juergen Hoeller
|
||||
* @author Rick Evans
|
||||
*/
|
||||
public class CollectionUtilsTests extends TestCase {
|
||||
|
||||
public void testIsEmpty() {
|
||||
assertTrue(CollectionUtils.isEmpty((Set) null));
|
||||
assertTrue(CollectionUtils.isEmpty((Map) null));
|
||||
assertTrue(CollectionUtils.isEmpty(new HashMap()));
|
||||
assertTrue(CollectionUtils.isEmpty(new HashSet()));
|
||||
|
||||
List list = new LinkedList();
|
||||
list.add(new Object());
|
||||
assertFalse(CollectionUtils.isEmpty(list));
|
||||
|
||||
Map map = new HashMap();
|
||||
map.put("foo", "bar");
|
||||
assertFalse(CollectionUtils.isEmpty(map));
|
||||
}
|
||||
|
||||
public void testMergeArrayIntoCollection() {
|
||||
Object[] arr = new Object[] {"value1", "value2"};
|
||||
List list = new LinkedList();
|
||||
list.add("value3");
|
||||
|
||||
CollectionUtils.mergeArrayIntoCollection(arr, list);
|
||||
assertEquals("value3", list.get(0));
|
||||
assertEquals("value1", list.get(1));
|
||||
assertEquals("value2", list.get(2));
|
||||
}
|
||||
|
||||
public void testMergePrimitiveArrayIntoCollection() {
|
||||
int[] arr = new int[] {1, 2};
|
||||
List list = new LinkedList();
|
||||
list.add(new Integer(3));
|
||||
|
||||
CollectionUtils.mergeArrayIntoCollection(arr, list);
|
||||
assertEquals(new Integer(3), list.get(0));
|
||||
assertEquals(new Integer(1), list.get(1));
|
||||
assertEquals(new Integer(2), list.get(2));
|
||||
}
|
||||
|
||||
public void testMergePropertiesIntoMap() {
|
||||
Properties defaults = new Properties();
|
||||
defaults.setProperty("prop1", "value1");
|
||||
Properties props = new Properties(defaults);
|
||||
props.setProperty("prop2", "value2");
|
||||
|
||||
Map map = new HashMap();
|
||||
map.put("prop3", "value3");
|
||||
|
||||
CollectionUtils.mergePropertiesIntoMap(props, map);
|
||||
assertEquals("value1", map.get("prop1"));
|
||||
assertEquals("value2", map.get("prop2"));
|
||||
assertEquals("value3", map.get("prop3"));
|
||||
}
|
||||
|
||||
public void testContains() {
|
||||
assertFalse(CollectionUtils.contains((Iterator) null, "myElement"));
|
||||
assertFalse(CollectionUtils.contains((Enumeration) null, "myElement"));
|
||||
assertFalse(CollectionUtils.contains(new LinkedList().iterator(), "myElement"));
|
||||
assertFalse(CollectionUtils.contains(new Hashtable().keys(), "myElement"));
|
||||
|
||||
List list = new LinkedList();
|
||||
list.add("myElement");
|
||||
assertTrue(CollectionUtils.contains(list.iterator(), "myElement"));
|
||||
|
||||
Hashtable ht = new Hashtable();
|
||||
ht.put("myElement", "myValue");
|
||||
assertTrue(CollectionUtils.contains(ht.keys(), "myElement"));
|
||||
}
|
||||
|
||||
public void testContainsAny() throws Exception {
|
||||
List source = new ArrayList();
|
||||
source.add("abc");
|
||||
source.add("def");
|
||||
source.add("ghi");
|
||||
|
||||
List candidates = new ArrayList();
|
||||
candidates.add("xyz");
|
||||
candidates.add("def");
|
||||
candidates.add("abc");
|
||||
|
||||
assertTrue(CollectionUtils.containsAny(source, candidates));
|
||||
candidates.remove("def");
|
||||
assertTrue(CollectionUtils.containsAny(source, candidates));
|
||||
candidates.remove("abc");
|
||||
assertFalse(CollectionUtils.containsAny(source, candidates));
|
||||
}
|
||||
|
||||
public void testContainsInstanceWithNullCollection() throws Exception {
|
||||
assertFalse("Must return false if supplied Collection argument is null",
|
||||
CollectionUtils.containsInstance(null, this));
|
||||
}
|
||||
|
||||
public void testContainsInstanceWithInstancesThatAreEqualButDistinct() throws Exception {
|
||||
List list = new ArrayList();
|
||||
list.add(new Instance("fiona"));
|
||||
assertFalse("Must return false if instance is not in the supplied Collection argument",
|
||||
CollectionUtils.containsInstance(list, new Instance("fiona")));
|
||||
}
|
||||
|
||||
public void testContainsInstanceWithSameInstance() throws Exception {
|
||||
List list = new ArrayList();
|
||||
list.add(new Instance("apple"));
|
||||
Instance instance = new Instance("fiona");
|
||||
list.add(instance);
|
||||
assertTrue("Must return true if instance is in the supplied Collection argument",
|
||||
CollectionUtils.containsInstance(list, instance));
|
||||
}
|
||||
|
||||
public void testContainsInstanceWithNullInstance() throws Exception {
|
||||
List list = new ArrayList();
|
||||
list.add(new Instance("apple"));
|
||||
list.add(new Instance("fiona"));
|
||||
assertFalse("Must return false if null instance is supplied",
|
||||
CollectionUtils.containsInstance(list, null));
|
||||
}
|
||||
|
||||
public void testFindFirstMatch() throws Exception {
|
||||
List source = new ArrayList();
|
||||
source.add("abc");
|
||||
source.add("def");
|
||||
source.add("ghi");
|
||||
|
||||
List candidates = new ArrayList();
|
||||
candidates.add("xyz");
|
||||
candidates.add("def");
|
||||
candidates.add("abc");
|
||||
|
||||
assertEquals("def", CollectionUtils.findFirstMatch(source, candidates));
|
||||
}
|
||||
|
||||
public void testHasUniqueObject() {
|
||||
List list = new LinkedList();
|
||||
list.add("myElement");
|
||||
list.add("myOtherElement");
|
||||
assertFalse(CollectionUtils.hasUniqueObject(list));
|
||||
|
||||
list = new LinkedList();
|
||||
list.add("myElement");
|
||||
assertTrue(CollectionUtils.hasUniqueObject(list));
|
||||
|
||||
list = new LinkedList();
|
||||
list.add("myElement");
|
||||
list.add(null);
|
||||
assertFalse(CollectionUtils.hasUniqueObject(list));
|
||||
|
||||
list = new LinkedList();
|
||||
list.add(null);
|
||||
list.add("myElement");
|
||||
assertFalse(CollectionUtils.hasUniqueObject(list));
|
||||
|
||||
list = new LinkedList();
|
||||
list.add(null);
|
||||
list.add(null);
|
||||
assertTrue(CollectionUtils.hasUniqueObject(list));
|
||||
|
||||
list = new LinkedList();
|
||||
list.add(null);
|
||||
assertTrue(CollectionUtils.hasUniqueObject(list));
|
||||
|
||||
list = new LinkedList();
|
||||
assertFalse(CollectionUtils.hasUniqueObject(list));
|
||||
}
|
||||
|
||||
|
||||
private static final class Instance {
|
||||
|
||||
private final String name;
|
||||
|
||||
public Instance(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public boolean equals(Object rhs) {
|
||||
if (this == rhs) {
|
||||
return true;
|
||||
}
|
||||
if (rhs == null || this.getClass() != rhs.getClass()) {
|
||||
return false;
|
||||
}
|
||||
Instance instance = (Instance) rhs;
|
||||
return this.name.equals(instance.name);
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return this.name.hashCode();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Copyright 2002-2006 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.util;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.io.StringWriter;
|
||||
import java.util.Arrays;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* Unit tests for the FileCopyUtils class.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @since 12.03.2005
|
||||
*/
|
||||
public class FileCopyUtilsTests extends TestCase {
|
||||
|
||||
public void testCopyFromInputStream() throws IOException {
|
||||
byte[] content = "content".getBytes();
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(content);
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream(content.length);
|
||||
int count = FileCopyUtils.copy(in, out);
|
||||
assertEquals(content.length, count);
|
||||
assertTrue(Arrays.equals(content, out.toByteArray()));
|
||||
}
|
||||
|
||||
public void testCopyFromByteArray() throws IOException {
|
||||
byte[] content = "content".getBytes();
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream(content.length);
|
||||
FileCopyUtils.copy(content, out);
|
||||
assertTrue(Arrays.equals(content, out.toByteArray()));
|
||||
}
|
||||
|
||||
public void testCopyToByteArray() throws IOException {
|
||||
byte[] content = "content".getBytes();
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(content);
|
||||
byte[] result = FileCopyUtils.copyToByteArray(in);
|
||||
assertTrue(Arrays.equals(content, result));
|
||||
}
|
||||
|
||||
public void testCopyFromReader() throws IOException {
|
||||
String content = "content";
|
||||
StringReader in = new StringReader(content);
|
||||
StringWriter out = new StringWriter();
|
||||
int count = FileCopyUtils.copy(in, out);
|
||||
assertEquals(content.length(), count);
|
||||
assertEquals(content, out.toString());
|
||||
}
|
||||
|
||||
public void testCopyFromString() throws IOException {
|
||||
String content = "content";
|
||||
StringWriter out = new StringWriter();
|
||||
FileCopyUtils.copy(content, out);
|
||||
assertEquals(content, out.toString());
|
||||
}
|
||||
|
||||
public void testCopyToString() throws IOException {
|
||||
String content = "content";
|
||||
StringReader in = new StringReader(content);
|
||||
String result = FileCopyUtils.copyToString(in);
|
||||
assertEquals(content, result);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* Copyright 2002-2008 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.util;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* @author Rob Harrop
|
||||
*/
|
||||
public class FileSystemUtilsTests extends TestCase {
|
||||
|
||||
public void testDeleteRecursively() throws Exception {
|
||||
File root = new File("./tmp/root");
|
||||
File child = new File(root, "child");
|
||||
File grandchild = new File(child, "grandchild");
|
||||
|
||||
grandchild.mkdirs();
|
||||
|
||||
File bar = new File(child, "bar.txt");
|
||||
bar.createNewFile();
|
||||
|
||||
assertTrue(root.exists());
|
||||
assertTrue(child.exists());
|
||||
assertTrue(grandchild.exists());
|
||||
assertTrue(bar.exists());
|
||||
|
||||
FileSystemUtils.deleteRecursively(root);
|
||||
|
||||
assertFalse(root.exists());
|
||||
assertFalse(child.exists());
|
||||
assertFalse(grandchild.exists());
|
||||
assertFalse(bar.exists());
|
||||
}
|
||||
|
||||
public void testCopyRecursively() throws Exception {
|
||||
File src = new File("./tmp/src");
|
||||
File child = new File(src, "child");
|
||||
File grandchild = new File(child, "grandchild");
|
||||
|
||||
grandchild.mkdirs();
|
||||
|
||||
File bar = new File(child, "bar.txt");
|
||||
bar.createNewFile();
|
||||
|
||||
assertTrue(src.exists());
|
||||
assertTrue(child.exists());
|
||||
assertTrue(grandchild.exists());
|
||||
assertTrue(bar.exists());
|
||||
|
||||
File dest = new File("./dest");
|
||||
FileSystemUtils.copyRecursively(src, dest);
|
||||
|
||||
assertTrue(dest.exists());
|
||||
assertTrue(new File(dest, child.getName()).exists());
|
||||
|
||||
FileSystemUtils.deleteRecursively(src);
|
||||
assertTrue(!src.exists());
|
||||
}
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
File tmp = new File("./tmp");
|
||||
if (tmp.exists()) {
|
||||
FileSystemUtils.deleteRecursively(tmp);
|
||||
}
|
||||
File dest = new File("./dest");
|
||||
if (dest.exists()) {
|
||||
FileSystemUtils.deleteRecursively(dest);
|
||||
}
|
||||
super.tearDown();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
* Copyright 2002-2005 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.util;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.net.URL;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
/**
|
||||
* @author Alef Arendsen
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class Log4jConfigurerTests extends TestCase {
|
||||
|
||||
public void testInitLoggingWithClasspath() throws FileNotFoundException {
|
||||
doTestInitLogging("classpath:org/springframework/util/testlog4j.properties", false);
|
||||
}
|
||||
|
||||
public void testInitLoggingWithRelativeFilePath() throws FileNotFoundException {
|
||||
doTestInitLogging("src/test/resources/org/springframework/util/testlog4j.properties", false);
|
||||
}
|
||||
|
||||
public void testInitLoggingWithAbsoluteFilePath() throws FileNotFoundException {
|
||||
URL url = getClass().getResource("testlog4j.properties");
|
||||
doTestInitLogging(url.toString(), false);
|
||||
}
|
||||
|
||||
public void testInitLoggingWithClasspathAndRefreshInterval() throws FileNotFoundException {
|
||||
doTestInitLogging("classpath:org/springframework/util/testlog4j.properties", true);
|
||||
}
|
||||
|
||||
public void testInitLoggingWithRelativeFilePathAndRefreshInterval() throws FileNotFoundException {
|
||||
doTestInitLogging("src/test/resources/org/springframework/util/testlog4j.properties", true);
|
||||
}
|
||||
|
||||
/* only works on Windows
|
||||
public void testInitLoggingWithAbsoluteFilePathAndRefreshInterval() throws FileNotFoundException {
|
||||
URL url = getClass().getResource("testlog4j.properties");
|
||||
doTestInitLogging(url.getFile(), true);
|
||||
}
|
||||
*/
|
||||
|
||||
public void testInitLoggingWithFileUrlAndRefreshInterval() throws FileNotFoundException {
|
||||
URL url = getClass().getResource("testlog4j.properties");
|
||||
doTestInitLogging(url.toString(), true);
|
||||
}
|
||||
|
||||
private void doTestInitLogging(String location, boolean refreshInterval) throws FileNotFoundException {
|
||||
if (refreshInterval) {
|
||||
Log4jConfigurer.initLogging(location, 10);
|
||||
}
|
||||
else {
|
||||
Log4jConfigurer.initLogging(location);
|
||||
}
|
||||
|
||||
Log log = LogFactory.getLog(this.getClass());
|
||||
log.debug("debug");
|
||||
log.info("info");
|
||||
log.warn("warn");
|
||||
log.error("error");
|
||||
log.fatal("fatal");
|
||||
|
||||
assertTrue(MockLog4jAppender.loggingStrings.contains("debug"));
|
||||
assertTrue(MockLog4jAppender.loggingStrings.contains("info"));
|
||||
assertTrue(MockLog4jAppender.loggingStrings.contains("warn"));
|
||||
assertTrue(MockLog4jAppender.loggingStrings.contains("error"));
|
||||
assertTrue(MockLog4jAppender.loggingStrings.contains("fatal"));
|
||||
|
||||
Log4jConfigurer.shutdownLogging();
|
||||
assertTrue(MockLog4jAppender.closeCalled);
|
||||
}
|
||||
|
||||
public void testInitLoggingWithRefreshIntervalAndFileNotFound() throws FileNotFoundException {
|
||||
try {
|
||||
Log4jConfigurer.initLogging("test/org/springframework/util/bla.properties", 10);
|
||||
fail("Exception should have been thrown, file does not exist!");
|
||||
}
|
||||
catch (FileNotFoundException ex) {
|
||||
// OK
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
/*
|
||||
* Copyright 2002-2008 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* @author Colin Sampaleanu
|
||||
* @author Juergen Hoeller
|
||||
* @since 21.11.2003
|
||||
*/
|
||||
public class MethodInvokerTests extends TestCase {
|
||||
|
||||
public void testPlainMethodInvoker() throws Exception {
|
||||
// sanity check: singleton, non-static should work
|
||||
TestClass1 tc1 = new TestClass1();
|
||||
MethodInvoker mi = new MethodInvoker();
|
||||
mi.setTargetObject(tc1);
|
||||
mi.setTargetMethod("method1");
|
||||
mi.prepare();
|
||||
Integer i = (Integer) mi.invoke();
|
||||
assertEquals(1, i.intValue());
|
||||
|
||||
// sanity check: check that argument count matching works
|
||||
mi = new MethodInvoker();
|
||||
mi.setTargetClass(TestClass1.class);
|
||||
mi.setTargetMethod("supertypes");
|
||||
mi.setArguments(new Object[] {new ArrayList(), new ArrayList(), "hello"});
|
||||
mi.prepare();
|
||||
assertEquals("hello", mi.invoke());
|
||||
|
||||
mi = new MethodInvoker();
|
||||
mi.setTargetClass(TestClass1.class);
|
||||
mi.setTargetMethod("supertypes2");
|
||||
mi.setArguments(new Object[] {new ArrayList(), new ArrayList(), "hello", "bogus"});
|
||||
mi.prepare();
|
||||
assertEquals("hello", mi.invoke());
|
||||
|
||||
// Sanity check: check that argument conversion doesn't work with plain MethodInvoker
|
||||
mi = new MethodInvoker();
|
||||
mi.setTargetClass(TestClass1.class);
|
||||
mi.setTargetMethod("supertypes2");
|
||||
mi.setArguments(new Object[] {new ArrayList(), new ArrayList(), "hello", Boolean.TRUE});
|
||||
try {
|
||||
mi.prepare();
|
||||
fail("Shouldn't have matched without argument conversion");
|
||||
}
|
||||
catch (NoSuchMethodException ex) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
public void testStringWithMethodInvoker() throws Exception {
|
||||
try {
|
||||
MethodInvoker methodInvoker = new MethodInvoker();
|
||||
methodInvoker.setTargetObject(new Greeter());
|
||||
methodInvoker.setTargetMethod("greet");
|
||||
methodInvoker.setArguments(new Object[] {new String("no match")});
|
||||
methodInvoker.prepare();
|
||||
fail("Should have thrown a NoSuchMethodException");
|
||||
}
|
||||
catch (NoSuchMethodException e) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
public void testPurchaserWithMethodInvoker() throws Exception {
|
||||
MethodInvoker methodInvoker = new MethodInvoker();
|
||||
methodInvoker.setTargetObject(new Greeter());
|
||||
methodInvoker.setTargetMethod("greet");
|
||||
methodInvoker.setArguments(new Object[] {new Purchaser()});
|
||||
methodInvoker.prepare();
|
||||
String greeting = (String) methodInvoker.invoke();
|
||||
assertEquals("purchaser: hello", greeting);
|
||||
}
|
||||
|
||||
public void testShopperWithMethodInvoker() throws Exception {
|
||||
MethodInvoker methodInvoker = new MethodInvoker();
|
||||
methodInvoker.setTargetObject(new Greeter());
|
||||
methodInvoker.setTargetMethod("greet");
|
||||
methodInvoker.setArguments(new Object[] {new Shopper()});
|
||||
methodInvoker.prepare();
|
||||
String greeting = (String) methodInvoker.invoke();
|
||||
assertEquals("purchaser: may I help you?", greeting);
|
||||
}
|
||||
|
||||
public void testSalesmanWithMethodInvoker() throws Exception {
|
||||
MethodInvoker methodInvoker = new MethodInvoker();
|
||||
methodInvoker.setTargetObject(new Greeter());
|
||||
methodInvoker.setTargetMethod("greet");
|
||||
methodInvoker.setArguments(new Object[] {new Salesman()});
|
||||
methodInvoker.prepare();
|
||||
String greeting = (String) methodInvoker.invoke();
|
||||
assertEquals("greetable: how are sales?", greeting);
|
||||
}
|
||||
|
||||
public void testCustomerWithMethodInvoker() throws Exception {
|
||||
MethodInvoker methodInvoker = new MethodInvoker();
|
||||
methodInvoker.setTargetObject(new Greeter());
|
||||
methodInvoker.setTargetMethod("greet");
|
||||
methodInvoker.setArguments(new Object[] {new Customer()});
|
||||
methodInvoker.prepare();
|
||||
String greeting = (String) methodInvoker.invoke();
|
||||
assertEquals("customer: good day", greeting);
|
||||
}
|
||||
|
||||
public void testRegularWithMethodInvoker() throws Exception {
|
||||
MethodInvoker methodInvoker = new MethodInvoker();
|
||||
methodInvoker.setTargetObject(new Greeter());
|
||||
methodInvoker.setTargetMethod("greet");
|
||||
methodInvoker.setArguments(new Object[] {new Regular("Kotter")});
|
||||
methodInvoker.prepare();
|
||||
String greeting = (String) methodInvoker.invoke();
|
||||
assertEquals("regular: welcome back Kotter", greeting);
|
||||
}
|
||||
|
||||
public void testVIPWithMethodInvoker() throws Exception {
|
||||
MethodInvoker methodInvoker = new MethodInvoker();
|
||||
methodInvoker.setTargetObject(new Greeter());
|
||||
methodInvoker.setTargetMethod("greet");
|
||||
methodInvoker.setArguments(new Object[] {new VIP("Fonzie")});
|
||||
methodInvoker.prepare();
|
||||
String greeting = (String) methodInvoker.invoke();
|
||||
assertEquals("regular: whassup dude?", greeting);
|
||||
}
|
||||
|
||||
|
||||
public static class TestClass1 {
|
||||
|
||||
public static int _staticField1;
|
||||
|
||||
public int _field1 = 0;
|
||||
|
||||
public int method1() {
|
||||
return ++_field1;
|
||||
}
|
||||
|
||||
public static int staticMethod1() {
|
||||
return ++TestClass1._staticField1;
|
||||
}
|
||||
|
||||
public static void voidRetvalMethod() {
|
||||
}
|
||||
|
||||
public static void nullArgument(Object arg) {
|
||||
}
|
||||
|
||||
public static void intArgument(int arg) {
|
||||
}
|
||||
|
||||
public static void intArguments(int[] arg) {
|
||||
}
|
||||
|
||||
public static String supertypes(Collection c, Integer i) {
|
||||
return i.toString();
|
||||
}
|
||||
|
||||
public static String supertypes(Collection c, List l, String s) {
|
||||
return s;
|
||||
}
|
||||
|
||||
public static String supertypes2(Collection c, List l, Integer i) {
|
||||
return i.toString();
|
||||
}
|
||||
|
||||
public static String supertypes2(Collection c, List l, String s, Integer i) {
|
||||
return s;
|
||||
}
|
||||
|
||||
public static String supertypes2(Collection c, List l, String s, String s2) {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class Greeter {
|
||||
|
||||
// should handle Salesman (only interface)
|
||||
public String greet(Greetable greetable) {
|
||||
return "greetable: " + greetable.getGreeting();
|
||||
}
|
||||
|
||||
// should handle Shopper (beats Greetable since it is a class)
|
||||
protected String greet(Purchaser purchaser) {
|
||||
return "purchaser: " + purchaser.getGreeting();
|
||||
}
|
||||
|
||||
// should handle Customer (exact match)
|
||||
String greet(Customer customer) {
|
||||
return "customer: " + customer.getGreeting();
|
||||
}
|
||||
|
||||
// should handle Regular (exact) and VIP (closest match)
|
||||
private String greet(Regular regular) {
|
||||
return "regular: " + regular.getGreeting();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static interface Greetable {
|
||||
|
||||
String getGreeting();
|
||||
}
|
||||
|
||||
|
||||
private static interface Person extends Greetable {
|
||||
}
|
||||
|
||||
|
||||
private static class Purchaser implements Greetable {
|
||||
|
||||
public String getGreeting() {
|
||||
return "hello";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class Shopper extends Purchaser implements Person {
|
||||
|
||||
public String getGreeting() {
|
||||
return "may I help you?";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class Salesman implements Person {
|
||||
|
||||
public String getGreeting() {
|
||||
return "how are sales?";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class Customer extends Shopper {
|
||||
|
||||
public String getGreeting() {
|
||||
return "good day";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class Regular extends Customer {
|
||||
|
||||
private String name;
|
||||
|
||||
public Regular(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getGreeting() {
|
||||
return "welcome back " + name ;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class VIP extends Regular {
|
||||
|
||||
public VIP(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
public String getGreeting() {
|
||||
return "whassup dude?";
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* Copyright 2002-2005 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.log4j.AppenderSkeleton;
|
||||
import org.apache.log4j.spi.LoggingEvent;
|
||||
|
||||
/**
|
||||
* @author Alef Arendsen
|
||||
*/
|
||||
public class MockLog4jAppender extends AppenderSkeleton {
|
||||
|
||||
public static final List loggingStrings = new ArrayList();
|
||||
|
||||
public static boolean closeCalled = false;
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see org.apache.log4j.AppenderSkeleton#append(org.apache.log4j.spi.LoggingEvent)
|
||||
*/
|
||||
protected void append(LoggingEvent evt) {
|
||||
//System.out.println("Adding " + evt.getMessage());
|
||||
loggingStrings.add(evt.getMessage());
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see org.apache.log4j.Appender#close()
|
||||
*/
|
||||
public void close() {
|
||||
closeCalled = true;
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see org.apache.log4j.Appender#requiresLayout()
|
||||
*/
|
||||
public boolean requiresLayout() {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
/*
|
||||
* Copyright 2002-2008 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.util;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.text.NumberFormat;
|
||||
import java.util.Locale;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.core.JdkVersion;
|
||||
|
||||
/**
|
||||
* @author Rob Harrop
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class NumberUtilsTests extends TestCase {
|
||||
|
||||
public void testParseNumber() {
|
||||
String aByte = "" + Byte.MAX_VALUE;
|
||||
String aShort = "" + Short.MAX_VALUE;
|
||||
String anInteger = "" + Integer.MAX_VALUE;
|
||||
String aLong = "" + Long.MAX_VALUE;
|
||||
String aFloat = "" + Float.MAX_VALUE;
|
||||
String aDouble = "" + Double.MAX_VALUE;
|
||||
|
||||
assertEquals("Byte did not parse", new Byte(Byte.MAX_VALUE), NumberUtils.parseNumber(aByte, Byte.class));
|
||||
assertEquals("Short did not parse", new Short(Short.MAX_VALUE), NumberUtils.parseNumber(aShort, Short.class));
|
||||
assertEquals("Integer did not parse", new Integer(Integer.MAX_VALUE), NumberUtils.parseNumber(anInteger, Integer.class));
|
||||
assertEquals("Long did not parse", new Long(Long.MAX_VALUE), NumberUtils.parseNumber(aLong, Long.class));
|
||||
assertEquals("Float did not parse", new Float(Float.MAX_VALUE), NumberUtils.parseNumber(aFloat, Float.class));
|
||||
assertEquals("Double did not parse", new Double(Double.MAX_VALUE), NumberUtils.parseNumber(aDouble, Double.class));
|
||||
}
|
||||
|
||||
public void testParseNumberUsingNumberFormat() {
|
||||
NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
|
||||
String aByte = "" + Byte.MAX_VALUE;
|
||||
String aShort = "" + Short.MAX_VALUE;
|
||||
String anInteger = "" + Integer.MAX_VALUE;
|
||||
String aLong = "" + Long.MAX_VALUE;
|
||||
String aFloat = "" + Float.MAX_VALUE;
|
||||
String aDouble = "" + Double.MAX_VALUE;
|
||||
|
||||
assertEquals("Byte did not parse", new Byte(Byte.MAX_VALUE), NumberUtils.parseNumber(aByte, Byte.class, nf));
|
||||
assertEquals("Short did not parse", new Short(Short.MAX_VALUE), NumberUtils.parseNumber(aShort, Short.class, nf));
|
||||
assertEquals("Integer did not parse", new Integer(Integer.MAX_VALUE), NumberUtils.parseNumber(anInteger, Integer.class, nf));
|
||||
assertEquals("Long did not parse", new Long(Long.MAX_VALUE), NumberUtils.parseNumber(aLong, Long.class, nf));
|
||||
assertEquals("Float did not parse", new Float(Float.MAX_VALUE), NumberUtils.parseNumber(aFloat, Float.class, nf));
|
||||
assertEquals("Double did not parse", new Double(Double.MAX_VALUE), NumberUtils.parseNumber(aDouble, Double.class, nf));
|
||||
}
|
||||
|
||||
public void testParseWithTrim() {
|
||||
String aByte = " " + Byte.MAX_VALUE + " ";
|
||||
String aShort = " " + Short.MAX_VALUE + " ";
|
||||
String anInteger = " " + Integer.MAX_VALUE + " ";
|
||||
String aLong = " " + Long.MAX_VALUE + " ";
|
||||
String aFloat = " " + Float.MAX_VALUE + " ";
|
||||
String aDouble = " " + Double.MAX_VALUE + " ";
|
||||
|
||||
assertEquals("Byte did not parse", new Byte(Byte.MAX_VALUE), NumberUtils.parseNumber(aByte, Byte.class));
|
||||
assertEquals("Short did not parse", new Short(Short.MAX_VALUE), NumberUtils.parseNumber(aShort, Short.class));
|
||||
assertEquals("Integer did not parse", new Integer(Integer.MAX_VALUE), NumberUtils.parseNumber(anInteger, Integer.class));
|
||||
assertEquals("Long did not parse", new Long(Long.MAX_VALUE), NumberUtils.parseNumber(aLong, Long.class));
|
||||
assertEquals("Float did not parse", new Float(Float.MAX_VALUE), NumberUtils.parseNumber(aFloat, Float.class));
|
||||
assertEquals("Double did not parse", new Double(Double.MAX_VALUE), NumberUtils.parseNumber(aDouble, Double.class));
|
||||
}
|
||||
|
||||
public void testParseWithTrimUsingNumberFormat() {
|
||||
NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
|
||||
String aByte = " " + Byte.MAX_VALUE + " ";
|
||||
String aShort = " " + Short.MAX_VALUE + " ";
|
||||
String anInteger = " " + Integer.MAX_VALUE + " ";
|
||||
String aLong = " " + Long.MAX_VALUE + " ";
|
||||
String aFloat = " " + Float.MAX_VALUE + " ";
|
||||
String aDouble = " " + Double.MAX_VALUE + " ";
|
||||
|
||||
assertEquals("Byte did not parse", new Byte(Byte.MAX_VALUE), NumberUtils.parseNumber(aByte, Byte.class, nf));
|
||||
assertEquals("Short did not parse", new Short(Short.MAX_VALUE), NumberUtils.parseNumber(aShort, Short.class, nf));
|
||||
assertEquals("Integer did not parse", new Integer(Integer.MAX_VALUE), NumberUtils.parseNumber(anInteger, Integer.class, nf));
|
||||
assertEquals("Long did not parse", new Long(Long.MAX_VALUE), NumberUtils.parseNumber(aLong, Long.class, nf));
|
||||
assertEquals("Float did not parse", new Float(Float.MAX_VALUE), NumberUtils.parseNumber(aFloat, Float.class, nf));
|
||||
assertEquals("Double did not parse", new Double(Double.MAX_VALUE), NumberUtils.parseNumber(aDouble, Double.class, nf));
|
||||
}
|
||||
|
||||
public void testParseAsHex() {
|
||||
String aByte = "0x" + Integer.toHexString(new Byte(Byte.MAX_VALUE).intValue());
|
||||
String aShort = "0x" + Integer.toHexString(new Short(Short.MAX_VALUE).intValue());
|
||||
String anInteger = "0x" + Integer.toHexString(Integer.MAX_VALUE);
|
||||
String aLong = "0x" + Long.toHexString(Long.MAX_VALUE);
|
||||
String aReallyBigInt = "FEBD4E677898DFEBFFEE44";
|
||||
|
||||
assertByteEquals(aByte);
|
||||
assertShortEquals(aShort);
|
||||
assertIntegerEquals(anInteger);
|
||||
assertLongEquals(aLong);
|
||||
assertEquals("BigInteger did not parse",
|
||||
new BigInteger(aReallyBigInt, 16), NumberUtils.parseNumber("0x" + aReallyBigInt, BigInteger.class));
|
||||
}
|
||||
|
||||
public void testParseNegativeHex() {
|
||||
String aByte = "-0x80";
|
||||
String aShort = "-0x8000";
|
||||
String anInteger = "-0x80000000";
|
||||
String aLong = "-0x8000000000000000";
|
||||
String aReallyBigInt = "FEBD4E677898DFEBFFEE44";
|
||||
|
||||
assertNegativeByteEquals(aByte);
|
||||
assertNegativeShortEquals(aShort);
|
||||
assertNegativeIntegerEquals(anInteger);
|
||||
assertNegativeLongEquals(aLong);
|
||||
assertEquals("BigInteger did not parse",
|
||||
new BigInteger(aReallyBigInt, 16).negate(), NumberUtils.parseNumber("-0x" + aReallyBigInt, BigInteger.class));
|
||||
}
|
||||
|
||||
public void testDoubleToBigInteger() {
|
||||
Double decimal = new Double(3.14d);
|
||||
assertEquals(new BigInteger("3"), NumberUtils.convertNumberToTargetClass(decimal, BigInteger.class));
|
||||
}
|
||||
|
||||
public void testBigDecimalToBigInteger() {
|
||||
String number = "987459837583750387355346";
|
||||
BigDecimal decimal = new BigDecimal(number);
|
||||
assertEquals(new BigInteger(number), NumberUtils.convertNumberToTargetClass(decimal, BigInteger.class));
|
||||
}
|
||||
|
||||
public void testNonExactBigDecimalToBigInteger() {
|
||||
BigDecimal decimal = new BigDecimal("987459837583750387355346.14");
|
||||
assertEquals(new BigInteger("987459837583750387355346"), NumberUtils.convertNumberToTargetClass(decimal, BigInteger.class));
|
||||
}
|
||||
|
||||
public void testParseBigDecimalNumber1() {
|
||||
String bigDecimalAsString = "0.10";
|
||||
Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class);
|
||||
assertEquals(new BigDecimal(bigDecimalAsString), bigDecimal);
|
||||
}
|
||||
|
||||
public void testParseBigDecimalNumber2() {
|
||||
String bigDecimalAsString = "0.001";
|
||||
Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class);
|
||||
assertEquals(new BigDecimal(bigDecimalAsString), bigDecimal);
|
||||
}
|
||||
|
||||
public void testParseBigDecimalNumber3() {
|
||||
String bigDecimalAsString = "3.14159265358979323846";
|
||||
Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class);
|
||||
assertEquals(new BigDecimal(bigDecimalAsString), bigDecimal);
|
||||
}
|
||||
|
||||
public void testParseLocalizedBigDecimalNumber1() {
|
||||
if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_15) {
|
||||
return;
|
||||
}
|
||||
String bigDecimalAsString = "0.10";
|
||||
NumberFormat numberFormat = NumberFormat.getInstance(Locale.ENGLISH);
|
||||
Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class, numberFormat);
|
||||
assertEquals(new BigDecimal(bigDecimalAsString), bigDecimal);
|
||||
}
|
||||
|
||||
public void testParseLocalizedBigDecimalNumber2() {
|
||||
if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_15) {
|
||||
return;
|
||||
}
|
||||
String bigDecimalAsString = "0.001";
|
||||
NumberFormat numberFormat = NumberFormat.getInstance(Locale.ENGLISH);
|
||||
Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class, numberFormat);
|
||||
assertEquals(new BigDecimal(bigDecimalAsString), bigDecimal);
|
||||
}
|
||||
|
||||
public void testParseLocalizedBigDecimalNumber3() {
|
||||
if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_15) {
|
||||
return;
|
||||
}
|
||||
String bigDecimalAsString = "3.14159265358979323846";
|
||||
NumberFormat numberFormat = NumberFormat.getInstance(Locale.ENGLISH);
|
||||
Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class, numberFormat);
|
||||
assertEquals(new BigDecimal(bigDecimalAsString), bigDecimal);
|
||||
}
|
||||
|
||||
public void testParseOverflow() {
|
||||
String aLong = "" + Long.MAX_VALUE;
|
||||
String aDouble = "" + Double.MAX_VALUE;
|
||||
|
||||
try {
|
||||
NumberUtils.parseNumber(aLong, Byte.class);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
|
||||
try {
|
||||
NumberUtils.parseNumber(aLong, Short.class);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
|
||||
try {
|
||||
NumberUtils.parseNumber(aLong, Integer.class);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
|
||||
assertEquals(new Long(Long.MAX_VALUE), NumberUtils.parseNumber(aLong, Long.class));
|
||||
|
||||
assertEquals(new Double(Double.MAX_VALUE), NumberUtils.parseNumber(aDouble, Double.class));
|
||||
}
|
||||
|
||||
public void testParseNegativeOverflow() {
|
||||
String aLong = "" + Long.MIN_VALUE;
|
||||
String aDouble = "" + Double.MIN_VALUE;
|
||||
|
||||
try {
|
||||
NumberUtils.parseNumber(aLong, Byte.class);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
|
||||
try {
|
||||
NumberUtils.parseNumber(aLong, Short.class);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
|
||||
try {
|
||||
NumberUtils.parseNumber(aLong, Integer.class);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
|
||||
assertEquals(new Long(Long.MIN_VALUE), NumberUtils.parseNumber(aLong, Long.class));
|
||||
|
||||
assertEquals(new Double(Double.MIN_VALUE), NumberUtils.parseNumber(aDouble, Double.class));
|
||||
}
|
||||
|
||||
public void testParseOverflowUsingNumberFormat() {
|
||||
NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
|
||||
String aLong = "" + Long.MAX_VALUE;
|
||||
String aDouble = "" + Double.MAX_VALUE;
|
||||
|
||||
try {
|
||||
NumberUtils.parseNumber(aLong, Byte.class, nf);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
|
||||
try {
|
||||
NumberUtils.parseNumber(aLong, Short.class, nf);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
|
||||
try {
|
||||
NumberUtils.parseNumber(aLong, Integer.class, nf);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
|
||||
assertEquals(new Long(Long.MAX_VALUE), NumberUtils.parseNumber(aLong, Long.class, nf));
|
||||
|
||||
assertEquals(new Double(Double.MAX_VALUE), NumberUtils.parseNumber(aDouble, Double.class, nf));
|
||||
}
|
||||
|
||||
public void testParseNegativeOverflowUsingNumberFormat() {
|
||||
NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
|
||||
String aLong = "" + Long.MIN_VALUE;
|
||||
String aDouble = "" + Double.MIN_VALUE;
|
||||
|
||||
try {
|
||||
NumberUtils.parseNumber(aLong, Byte.class, nf);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
|
||||
try {
|
||||
NumberUtils.parseNumber(aLong, Short.class, nf);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
|
||||
try {
|
||||
NumberUtils.parseNumber(aLong, Integer.class, nf);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
|
||||
assertEquals(new Long(Long.MIN_VALUE), NumberUtils.parseNumber(aLong, Long.class, nf));
|
||||
|
||||
assertEquals(new Double(Double.MIN_VALUE), NumberUtils.parseNumber(aDouble, Double.class, nf));
|
||||
}
|
||||
|
||||
private void assertLongEquals(String aLong) {
|
||||
assertEquals("Long did not parse", Long.MAX_VALUE, NumberUtils.parseNumber(aLong, Long.class).longValue());
|
||||
}
|
||||
|
||||
private void assertIntegerEquals(String anInteger) {
|
||||
assertEquals("Integer did not parse", Integer.MAX_VALUE, NumberUtils.parseNumber(anInteger, Integer.class).intValue());
|
||||
}
|
||||
|
||||
private void assertShortEquals(String aShort) {
|
||||
assertEquals("Short did not parse", Short.MAX_VALUE, NumberUtils.parseNumber(aShort, Short.class).shortValue());
|
||||
}
|
||||
|
||||
private void assertByteEquals(String aByte) {
|
||||
assertEquals("Byte did not parse", Byte.MAX_VALUE, NumberUtils.parseNumber(aByte, Byte.class).byteValue());
|
||||
}
|
||||
|
||||
private void assertNegativeLongEquals(String aLong) {
|
||||
assertEquals("Long did not parse", Long.MIN_VALUE, NumberUtils.parseNumber(aLong, Long.class).longValue());
|
||||
}
|
||||
|
||||
private void assertNegativeIntegerEquals(String anInteger) {
|
||||
assertEquals("Integer did not parse", Integer.MIN_VALUE, NumberUtils.parseNumber(anInteger, Integer.class).intValue());
|
||||
}
|
||||
|
||||
private void assertNegativeShortEquals(String aShort) {
|
||||
assertEquals("Short did not parse", Short.MIN_VALUE, NumberUtils.parseNumber(aShort, Short.class).shortValue());
|
||||
}
|
||||
|
||||
private void assertNegativeByteEquals(String aByte) {
|
||||
assertEquals("Byte did not parse", Byte.MIN_VALUE, NumberUtils.parseNumber(aByte, Byte.class).byteValue());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,627 @@
|
||||
/*
|
||||
* Copyright 2002-2006 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.util;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.core.task.TaskRejectedException;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
* @author Rick Evans
|
||||
*/
|
||||
public final class ObjectUtilsTests extends TestCase {
|
||||
|
||||
public void testIsCheckedException() {
|
||||
assertTrue(ObjectUtils.isCheckedException(new Exception()));
|
||||
assertTrue(ObjectUtils.isCheckedException(new ServletException()));
|
||||
|
||||
assertFalse(ObjectUtils.isCheckedException(new RuntimeException()));
|
||||
assertFalse(ObjectUtils.isCheckedException(new TaskRejectedException("")));
|
||||
|
||||
// Any Throwable other than RuntimeException and Error
|
||||
// has to be considered checked according to the JLS.
|
||||
assertTrue(ObjectUtils.isCheckedException(new Throwable()));
|
||||
}
|
||||
|
||||
public void testIsCompatibleWithThrowsClause() {
|
||||
Class[] empty = new Class[0];
|
||||
Class[] exception = new Class[] {Exception.class};
|
||||
Class[] servletAndIO = new Class[] {ServletException.class, IOException.class};
|
||||
Class[] throwable = new Class[] {Throwable.class};
|
||||
|
||||
assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException(), null));
|
||||
assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException(), empty));
|
||||
assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException(), exception));
|
||||
assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException(), servletAndIO));
|
||||
assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException(), throwable));
|
||||
|
||||
assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new Exception(), null));
|
||||
assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new Exception(), empty));
|
||||
assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new Exception(), exception));
|
||||
assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new Exception(), servletAndIO));
|
||||
assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new Exception(), throwable));
|
||||
|
||||
assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new ServletException(), null));
|
||||
assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new ServletException(), empty));
|
||||
assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new ServletException(), exception));
|
||||
assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new ServletException(), servletAndIO));
|
||||
assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new ServletException(), throwable));
|
||||
|
||||
assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new Throwable(), null));
|
||||
assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new Throwable(), empty));
|
||||
assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new Throwable(), exception));
|
||||
assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new Throwable(), servletAndIO));
|
||||
assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new Throwable(), throwable));
|
||||
}
|
||||
|
||||
public void testToObjectArray() {
|
||||
int[] a = new int[] {1, 2, 3, 4, 5};
|
||||
Integer[] wrapper = (Integer[]) ObjectUtils.toObjectArray(a);
|
||||
assertTrue(wrapper.length == 5);
|
||||
for (int i = 0; i < wrapper.length; i++) {
|
||||
assertEquals(a[i], wrapper[i].intValue());
|
||||
}
|
||||
}
|
||||
|
||||
public void testToObjectArrayWithNull() {
|
||||
Object[] objects = ObjectUtils.toObjectArray(null);
|
||||
assertNotNull(objects);
|
||||
assertEquals(0, objects.length);
|
||||
}
|
||||
|
||||
public void testToObjectArrayWithEmptyPrimitiveArray() {
|
||||
Object[] objects = ObjectUtils.toObjectArray(new byte[] {});
|
||||
assertNotNull(objects);
|
||||
assertEquals(0, objects.length);
|
||||
}
|
||||
|
||||
public void testToObjectArrayWithNonArrayType() {
|
||||
try {
|
||||
ObjectUtils.toObjectArray("Not an []");
|
||||
fail("Must have thrown an IllegalArgumentException by this point.");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
}
|
||||
|
||||
public void testToObjectArrayWithNonPrimitiveArray() {
|
||||
String[] source = new String[] {"Bingo"};
|
||||
assertEquals(source, ObjectUtils.toObjectArray(source));
|
||||
}
|
||||
|
||||
public void testAddObjectToArraySunnyDay() {
|
||||
String[] array = new String[] {"foo", "bar"};
|
||||
String newElement = "baz";
|
||||
Object[] newArray = ObjectUtils.addObjectToArray(array, newElement);
|
||||
assertEquals(3, newArray.length);
|
||||
assertEquals(newElement, newArray[2]);
|
||||
}
|
||||
|
||||
public void testAddObjectToArrayWhenEmpty() {
|
||||
String[] array = new String[0];
|
||||
String newElement = "foo";
|
||||
Object[] newArray = ObjectUtils.addObjectToArray(array, newElement);
|
||||
assertEquals(1, newArray.length);
|
||||
assertEquals(newElement, newArray[0]);
|
||||
}
|
||||
|
||||
public void testAddObjectToSingleNonNullElementArray() {
|
||||
String existingElement = "foo";
|
||||
String[] array = new String[] {existingElement};
|
||||
String newElement = "bar";
|
||||
Object[] newArray = ObjectUtils.addObjectToArray(array, newElement);
|
||||
assertEquals(2, newArray.length);
|
||||
assertEquals(existingElement, newArray[0]);
|
||||
assertEquals(newElement, newArray[1]);
|
||||
}
|
||||
|
||||
public void testAddObjectToSingleNullElementArray() {
|
||||
String[] array = new String[] {null};
|
||||
String newElement = "bar";
|
||||
Object[] newArray = ObjectUtils.addObjectToArray(array, newElement);
|
||||
assertEquals(2, newArray.length);
|
||||
assertEquals(null, newArray[0]);
|
||||
assertEquals(newElement, newArray[1]);
|
||||
}
|
||||
|
||||
public void testAddObjectToNullArray() throws Exception {
|
||||
String newElement = "foo";
|
||||
Object[] newArray = ObjectUtils.addObjectToArray(null, newElement);
|
||||
assertEquals(1, newArray.length);
|
||||
assertEquals(newElement, newArray[0]);
|
||||
}
|
||||
|
||||
public void testAddNullObjectToNullArray() throws Exception {
|
||||
Object[] newArray = ObjectUtils.addObjectToArray(null, null);
|
||||
assertEquals(1, newArray.length);
|
||||
assertEquals(null, newArray[0]);
|
||||
}
|
||||
|
||||
public void testNullSafeEqualsWithArrays() throws Exception {
|
||||
assertTrue(ObjectUtils.nullSafeEquals(new String[] {"a", "b", "c"}, new String[] {"a", "b", "c"}));
|
||||
assertTrue(ObjectUtils.nullSafeEquals(new int[] {1, 2, 3}, new int[] {1, 2, 3}));
|
||||
}
|
||||
|
||||
public void testHashCodeWithBooleanFalse() {
|
||||
int expected = Boolean.FALSE.hashCode();
|
||||
assertEquals(expected, ObjectUtils.hashCode(false));
|
||||
}
|
||||
|
||||
public void testHashCodeWithBooleanTrue() {
|
||||
int expected = Boolean.TRUE.hashCode();
|
||||
assertEquals(expected, ObjectUtils.hashCode(true));
|
||||
}
|
||||
|
||||
public void testHashCodeWithDouble() {
|
||||
double dbl = 9830.43;
|
||||
int expected = (new Double(dbl)).hashCode();
|
||||
assertEquals(expected, ObjectUtils.hashCode(dbl));
|
||||
}
|
||||
|
||||
public void testHashCodeWithFloat() {
|
||||
float flt = 34.8f;
|
||||
int expected = (new Float(flt)).hashCode();
|
||||
assertEquals(expected, ObjectUtils.hashCode(flt));
|
||||
}
|
||||
|
||||
public void testHashCodeWithLong() {
|
||||
long lng = 883l;
|
||||
int expected = (new Long(lng)).hashCode();
|
||||
assertEquals(expected, ObjectUtils.hashCode(lng));
|
||||
}
|
||||
|
||||
public void testIdentityToString() {
|
||||
Object obj = new Object();
|
||||
String expected = obj.getClass().getName() + "@" + ObjectUtils.getIdentityHexString(obj);
|
||||
String actual = ObjectUtils.identityToString(obj);
|
||||
assertEquals(expected.toString(), actual);
|
||||
}
|
||||
|
||||
public void testIdentityToStringWithNullObject() {
|
||||
assertEquals("", ObjectUtils.identityToString(null));
|
||||
}
|
||||
|
||||
public void testIsArrayOfPrimitivesWithBooleanArray() {
|
||||
assertTrue(ClassUtils.isPrimitiveArray(boolean[].class));
|
||||
}
|
||||
|
||||
public void testIsArrayOfPrimitivesWithObjectArray() {
|
||||
assertFalse(ClassUtils.isPrimitiveArray(Object[].class));
|
||||
}
|
||||
|
||||
public void testIsArrayOfPrimitivesWithNonArray() {
|
||||
assertFalse(ClassUtils.isPrimitiveArray(String.class));
|
||||
}
|
||||
|
||||
public void testIsPrimitiveOrWrapperWithBooleanPrimitiveClass() {
|
||||
assertTrue(ClassUtils.isPrimitiveOrWrapper(boolean.class));
|
||||
}
|
||||
|
||||
public void testIsPrimitiveOrWrapperWithBooleanWrapperClass() {
|
||||
assertTrue(ClassUtils.isPrimitiveOrWrapper(Boolean.class));
|
||||
}
|
||||
|
||||
public void testIsPrimitiveOrWrapperWithBytePrimitiveClass() {
|
||||
assertTrue(ClassUtils.isPrimitiveOrWrapper(byte.class));
|
||||
}
|
||||
|
||||
public void testIsPrimitiveOrWrapperWithByteWrapperClass() {
|
||||
assertTrue(ClassUtils.isPrimitiveOrWrapper(Byte.class));
|
||||
}
|
||||
|
||||
public void testIsPrimitiveOrWrapperWithCharacterClass() {
|
||||
assertTrue(ClassUtils.isPrimitiveOrWrapper(Character.class));
|
||||
}
|
||||
|
||||
public void testIsPrimitiveOrWrapperWithCharClass() {
|
||||
assertTrue(ClassUtils.isPrimitiveOrWrapper(char.class));
|
||||
}
|
||||
|
||||
public void testIsPrimitiveOrWrapperWithDoublePrimitiveClass() {
|
||||
assertTrue(ClassUtils.isPrimitiveOrWrapper(double.class));
|
||||
}
|
||||
|
||||
public void testIsPrimitiveOrWrapperWithDoubleWrapperClass() {
|
||||
assertTrue(ClassUtils.isPrimitiveOrWrapper(Double.class));
|
||||
}
|
||||
|
||||
public void testIsPrimitiveOrWrapperWithFloatPrimitiveClass() {
|
||||
assertTrue(ClassUtils.isPrimitiveOrWrapper(float.class));
|
||||
}
|
||||
|
||||
public void testIsPrimitiveOrWrapperWithFloatWrapperClass() {
|
||||
assertTrue(ClassUtils.isPrimitiveOrWrapper(Float.class));
|
||||
}
|
||||
|
||||
public void testIsPrimitiveOrWrapperWithIntClass() {
|
||||
assertTrue(ClassUtils.isPrimitiveOrWrapper(int.class));
|
||||
}
|
||||
|
||||
public void testIsPrimitiveOrWrapperWithIntegerClass() {
|
||||
assertTrue(ClassUtils.isPrimitiveOrWrapper(Integer.class));
|
||||
}
|
||||
|
||||
public void testIsPrimitiveOrWrapperWithLongPrimitiveClass() {
|
||||
assertTrue(ClassUtils.isPrimitiveOrWrapper(long.class));
|
||||
}
|
||||
|
||||
public void testIsPrimitiveOrWrapperWithLongWrapperClass() {
|
||||
assertTrue(ClassUtils.isPrimitiveOrWrapper(Long.class));
|
||||
}
|
||||
|
||||
public void testIsPrimitiveOrWrapperWithNonPrimitiveOrWrapperClass() {
|
||||
assertFalse(ClassUtils.isPrimitiveOrWrapper(Object.class));
|
||||
}
|
||||
|
||||
public void testIsPrimitiveOrWrapperWithShortPrimitiveClass() {
|
||||
assertTrue(ClassUtils.isPrimitiveOrWrapper(short.class));
|
||||
}
|
||||
|
||||
public void testIsPrimitiveOrWrapperWithShortWrapperClass() {
|
||||
assertTrue(ClassUtils.isPrimitiveOrWrapper(Short.class));
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithBooleanArray() {
|
||||
int expected = 31 * 7 + Boolean.TRUE.hashCode();
|
||||
expected = 31 * expected + Boolean.FALSE.hashCode();
|
||||
|
||||
boolean[] array = {true, false};
|
||||
int actual = ObjectUtils.nullSafeHashCode(array);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithBooleanArrayEqualToNull() {
|
||||
assertEquals(0, ObjectUtils.nullSafeHashCode((boolean[]) null));
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithByteArray() {
|
||||
int expected = 31 * 7 + 8;
|
||||
expected = 31 * expected + 10;
|
||||
|
||||
byte[] array = {8, 10};
|
||||
int actual = ObjectUtils.nullSafeHashCode(array);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithByteArrayEqualToNull() {
|
||||
assertEquals(0, ObjectUtils.nullSafeHashCode((byte[]) null));
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithCharArray() {
|
||||
int expected = 31 * 7 + 'a';
|
||||
expected = 31 * expected + 'E';
|
||||
|
||||
char[] array = {'a', 'E'};
|
||||
int actual = ObjectUtils.nullSafeHashCode(array);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithCharArrayEqualToNull() {
|
||||
assertEquals(0, ObjectUtils.nullSafeHashCode((char[]) null));
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithDoubleArray() {
|
||||
long bits = Double.doubleToLongBits(8449.65);
|
||||
int expected = 31 * 7 + (int) (bits ^ (bits >>> 32));
|
||||
bits = Double.doubleToLongBits(9944.923);
|
||||
expected = 31 * expected + (int) (bits ^ (bits >>> 32));
|
||||
|
||||
double[] array = {8449.65, 9944.923};
|
||||
int actual = ObjectUtils.nullSafeHashCode(array);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithDoubleArrayEqualToNull() {
|
||||
assertEquals(0, ObjectUtils.nullSafeHashCode((double[]) null));
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithFloatArray() {
|
||||
int expected = 31 * 7 + Float.floatToIntBits(9.6f);
|
||||
expected = 31 * expected + Float.floatToIntBits(7.4f);
|
||||
|
||||
float[] array = {9.6f, 7.4f};
|
||||
int actual = ObjectUtils.nullSafeHashCode(array);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithFloatArrayEqualToNull() {
|
||||
assertEquals(0, ObjectUtils.nullSafeHashCode((float[]) null));
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithIntArray() {
|
||||
int expected = 31 * 7 + 884;
|
||||
expected = 31 * expected + 340;
|
||||
|
||||
int[] array = {884, 340};
|
||||
int actual = ObjectUtils.nullSafeHashCode(array);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithIntArrayEqualToNull() {
|
||||
assertEquals(0, ObjectUtils.nullSafeHashCode((int[]) null));
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithLongArray() {
|
||||
long lng = 7993l;
|
||||
int expected = 31 * 7 + (int) (lng ^ (lng >>> 32));
|
||||
lng = 84320l;
|
||||
expected = 31 * expected + (int) (lng ^ (lng >>> 32));
|
||||
|
||||
long[] array = {7993l, 84320l};
|
||||
int actual = ObjectUtils.nullSafeHashCode(array);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithLongArrayEqualToNull() {
|
||||
assertEquals(0, ObjectUtils.nullSafeHashCode((long[]) null));
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithObject() {
|
||||
String str = "Luke";
|
||||
assertEquals(str.hashCode(), ObjectUtils.nullSafeHashCode(str));
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithObjectArray() {
|
||||
int expected = 31 * 7 + "Leia".hashCode();
|
||||
expected = 31 * expected + "Han".hashCode();
|
||||
|
||||
Object[] array = {"Leia", "Han"};
|
||||
int actual = ObjectUtils.nullSafeHashCode(array);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithObjectArrayEqualToNull() {
|
||||
assertEquals(0, ObjectUtils.nullSafeHashCode((Object[]) null));
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithObjectBeingBooleanArray() {
|
||||
Object array = new boolean[] {true, false};
|
||||
int expected = ObjectUtils.nullSafeHashCode((boolean[]) array);
|
||||
assertEqualHashCodes(expected, array);
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithObjectBeingByteArray() {
|
||||
Object array = new byte[] {6, 39};
|
||||
int expected = ObjectUtils.nullSafeHashCode((byte[]) array);
|
||||
assertEqualHashCodes(expected, array);
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithObjectBeingCharArray() {
|
||||
Object array = new char[] {'l', 'M'};
|
||||
int expected = ObjectUtils.nullSafeHashCode((char[]) array);
|
||||
assertEqualHashCodes(expected, array);
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithObjectBeingDoubleArray() {
|
||||
Object array = new double[] {68930.993, 9022.009};
|
||||
int expected = ObjectUtils.nullSafeHashCode((double[]) array);
|
||||
assertEqualHashCodes(expected, array);
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithObjectBeingFloatArray() {
|
||||
Object array = new float[] {9.9f, 9.54f};
|
||||
int expected = ObjectUtils.nullSafeHashCode((float[]) array);
|
||||
assertEqualHashCodes(expected, array);
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithObjectBeingIntArray() {
|
||||
Object array = new int[] {89, 32};
|
||||
int expected = ObjectUtils.nullSafeHashCode((int[]) array);
|
||||
assertEqualHashCodes(expected, array);
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithObjectBeingLongArray() {
|
||||
Object array = new long[] {4389, 320};
|
||||
int expected = ObjectUtils.nullSafeHashCode((long[]) array);
|
||||
assertEqualHashCodes(expected, array);
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithObjectBeingObjectArray() {
|
||||
Object array = new Object[] {"Luke", "Anakin"};
|
||||
int expected = ObjectUtils.nullSafeHashCode((Object[]) array);
|
||||
assertEqualHashCodes(expected, array);
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithObjectBeingShortArray() {
|
||||
Object array = new short[] {5, 3};
|
||||
int expected = ObjectUtils.nullSafeHashCode((short[]) array);
|
||||
assertEqualHashCodes(expected, array);
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithObjectEqualToNull() {
|
||||
assertEquals(0, ObjectUtils.nullSafeHashCode((Object) null));
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithShortArray() {
|
||||
int expected = 31 * 7 + 70;
|
||||
expected = 31 * expected + 8;
|
||||
|
||||
short[] array = {70, 8};
|
||||
int actual = ObjectUtils.nullSafeHashCode(array);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
public void testNullSafeHashCodeWithShortArrayEqualToNull() {
|
||||
assertEquals(0, ObjectUtils.nullSafeHashCode((short[]) null));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithBooleanArray() {
|
||||
boolean[] array = {true, false};
|
||||
assertEquals("{true, false}", ObjectUtils.nullSafeToString(array));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithBooleanArrayBeingEmpty() {
|
||||
boolean[] array = {};
|
||||
assertEquals("{}", ObjectUtils.nullSafeToString(array));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithBooleanArrayEqualToNull() {
|
||||
assertEquals("null", ObjectUtils.nullSafeToString((boolean[]) null));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithByteArray() {
|
||||
byte[] array = {5, 8};
|
||||
assertEquals("{5, 8}", ObjectUtils.nullSafeToString(array));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithByteArrayBeingEmpty() {
|
||||
byte[] array = {};
|
||||
assertEquals("{}", ObjectUtils.nullSafeToString(array));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithByteArrayEqualToNull() {
|
||||
assertEquals("null", ObjectUtils.nullSafeToString((byte[]) null));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithCharArray() {
|
||||
char[] array = {'A', 'B'};
|
||||
assertEquals("{'A', 'B'}", ObjectUtils.nullSafeToString(array));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithCharArrayBeingEmpty() {
|
||||
char[] array = {};
|
||||
assertEquals("{}", ObjectUtils.nullSafeToString(array));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithCharArrayEqualToNull() {
|
||||
assertEquals("null", ObjectUtils.nullSafeToString((char[]) null));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithDoubleArray() {
|
||||
double[] array = {8594.93, 8594023.95};
|
||||
assertEquals("{8594.93, 8594023.95}", ObjectUtils.nullSafeToString(array));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithDoubleArrayBeingEmpty() {
|
||||
double[] array = {};
|
||||
assertEquals("{}", ObjectUtils.nullSafeToString(array));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithDoubleArrayEqualToNull() {
|
||||
assertEquals("null", ObjectUtils.nullSafeToString((double[]) null));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithFloatArray() {
|
||||
float[] array = {8.6f, 43.8f};
|
||||
assertEquals("{8.6, 43.8}", ObjectUtils.nullSafeToString(array));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithFloatArrayBeingEmpty() {
|
||||
float[] array = {};
|
||||
assertEquals("{}", ObjectUtils.nullSafeToString(array));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithFloatArrayEqualToNull() {
|
||||
assertEquals("null", ObjectUtils.nullSafeToString((float[]) null));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithIntArray() {
|
||||
int[] array = {9, 64};
|
||||
assertEquals("{9, 64}", ObjectUtils.nullSafeToString(array));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithIntArrayBeingEmpty() {
|
||||
int[] array = {};
|
||||
assertEquals("{}", ObjectUtils.nullSafeToString(array));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithIntArrayEqualToNull() {
|
||||
assertEquals("null", ObjectUtils.nullSafeToString((int[]) null));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithLongArray() {
|
||||
long[] array = {434l, 23423l};
|
||||
assertEquals("{434, 23423}", ObjectUtils.nullSafeToString(array));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithLongArrayBeingEmpty() {
|
||||
long[] array = {};
|
||||
assertEquals("{}", ObjectUtils.nullSafeToString(array));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithLongArrayEqualToNull() {
|
||||
assertEquals("null", ObjectUtils.nullSafeToString((long[]) null));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithPlainOldString() {
|
||||
assertEquals("I shoh love tha taste of mangoes", ObjectUtils.nullSafeToString("I shoh love tha taste of mangoes"));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithObjectArray() {
|
||||
Object[] array = {"Han", new Long(43)};
|
||||
assertEquals("{Han, 43}", ObjectUtils.nullSafeToString(array));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithObjectArrayBeingEmpty() {
|
||||
Object[] array = {};
|
||||
assertEquals("{}", ObjectUtils.nullSafeToString(array));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithObjectArrayEqualToNull() {
|
||||
assertEquals("null", ObjectUtils.nullSafeToString((Object[]) null));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithShortArray() {
|
||||
short[] array = {7, 9};
|
||||
assertEquals("{7, 9}", ObjectUtils.nullSafeToString(array));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithShortArrayBeingEmpty() {
|
||||
short[] array = {};
|
||||
assertEquals("{}", ObjectUtils.nullSafeToString(array));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithShortArrayEqualToNull() {
|
||||
assertEquals("null", ObjectUtils.nullSafeToString((short[]) null));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithStringArray() {
|
||||
String[] array = {"Luke", "Anakin"};
|
||||
assertEquals("{Luke, Anakin}", ObjectUtils.nullSafeToString(array));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithStringArrayBeingEmpty() {
|
||||
String[] array = {};
|
||||
assertEquals("{}", ObjectUtils.nullSafeToString(array));
|
||||
}
|
||||
|
||||
public void testNullSafeToStringWithStringArrayEqualToNull() {
|
||||
assertEquals("null", ObjectUtils.nullSafeToString((String[]) null));
|
||||
}
|
||||
|
||||
private void assertEqualHashCodes(int expected, Object array) {
|
||||
int actual = ObjectUtils.nullSafeHashCode(array);
|
||||
assertEquals(expected, actual);
|
||||
assertTrue(array.hashCode() != actual);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
/*
|
||||
* Copyright 2002-2007 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.util;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* @author Alef Arendsen
|
||||
* @author Seth Ladd
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class PathMatcherTests extends TestCase {
|
||||
|
||||
public void testAntPathMatcher() {
|
||||
PathMatcher pathMatcher = new AntPathMatcher();
|
||||
|
||||
// test exact matching
|
||||
assertTrue(pathMatcher.match("test", "test"));
|
||||
assertTrue(pathMatcher.match("/test", "/test"));
|
||||
assertFalse(pathMatcher.match("/test.jpg", "test.jpg"));
|
||||
assertFalse(pathMatcher.match("test", "/test"));
|
||||
assertFalse(pathMatcher.match("/test", "test"));
|
||||
|
||||
// test matching with ?'s
|
||||
assertTrue(pathMatcher.match("t?st", "test"));
|
||||
assertTrue(pathMatcher.match("??st", "test"));
|
||||
assertTrue(pathMatcher.match("tes?", "test"));
|
||||
assertTrue(pathMatcher.match("te??", "test"));
|
||||
assertTrue(pathMatcher.match("?es?", "test"));
|
||||
assertFalse(pathMatcher.match("tes?", "tes"));
|
||||
assertFalse(pathMatcher.match("tes?", "testt"));
|
||||
assertFalse(pathMatcher.match("tes?", "tsst"));
|
||||
|
||||
// test matchin with *'s
|
||||
assertTrue(pathMatcher.match("*", "test"));
|
||||
assertTrue(pathMatcher.match("test*", "test"));
|
||||
assertTrue(pathMatcher.match("test*", "testTest"));
|
||||
assertTrue(pathMatcher.match("test/*", "test/Test"));
|
||||
assertTrue(pathMatcher.match("test/*", "test/t"));
|
||||
assertTrue(pathMatcher.match("test/*", "test/"));
|
||||
assertTrue(pathMatcher.match("*test*", "AnothertestTest"));
|
||||
assertTrue(pathMatcher.match("*test", "Anothertest"));
|
||||
assertTrue(pathMatcher.match("*.*", "test."));
|
||||
assertTrue(pathMatcher.match("*.*", "test.test"));
|
||||
assertTrue(pathMatcher.match("*.*", "test.test.test"));
|
||||
assertTrue(pathMatcher.match("test*aaa", "testblaaaa"));
|
||||
assertFalse(pathMatcher.match("test*", "tst"));
|
||||
assertFalse(pathMatcher.match("test*", "tsttest"));
|
||||
assertFalse(pathMatcher.match("test*", "test/"));
|
||||
assertFalse(pathMatcher.match("test*", "test/t"));
|
||||
assertFalse(pathMatcher.match("test/*", "test"));
|
||||
assertFalse(pathMatcher.match("*test*", "tsttst"));
|
||||
assertFalse(pathMatcher.match("*test", "tsttst"));
|
||||
assertFalse(pathMatcher.match("*.*", "tsttst"));
|
||||
assertFalse(pathMatcher.match("test*aaa", "test"));
|
||||
assertFalse(pathMatcher.match("test*aaa", "testblaaab"));
|
||||
|
||||
// test matching with ?'s and /'s
|
||||
assertTrue(pathMatcher.match("/?", "/a"));
|
||||
assertTrue(pathMatcher.match("/?/a", "/a/a"));
|
||||
assertTrue(pathMatcher.match("/a/?", "/a/b"));
|
||||
assertTrue(pathMatcher.match("/??/a", "/aa/a"));
|
||||
assertTrue(pathMatcher.match("/a/??", "/a/bb"));
|
||||
assertTrue(pathMatcher.match("/?", "/a"));
|
||||
|
||||
// test matching with **'s
|
||||
assertTrue(pathMatcher.match("/**", "/testing/testing"));
|
||||
assertTrue(pathMatcher.match("/*/**", "/testing/testing"));
|
||||
assertTrue(pathMatcher.match("/**/*", "/testing/testing"));
|
||||
assertTrue(pathMatcher.match("/bla/**/bla", "/bla/testing/testing/bla"));
|
||||
assertTrue(pathMatcher.match("/bla/**/bla", "/bla/testing/testing/bla/bla"));
|
||||
assertTrue(pathMatcher.match("/**/test", "/bla/bla/test"));
|
||||
assertTrue(pathMatcher.match("/bla/**/**/bla", "/bla/bla/bla/bla/bla/bla"));
|
||||
assertTrue(pathMatcher.match("/bla*bla/test", "/blaXXXbla/test"));
|
||||
assertTrue(pathMatcher.match("/*bla/test", "/XXXbla/test"));
|
||||
assertFalse(pathMatcher.match("/bla*bla/test", "/blaXXXbl/test"));
|
||||
assertFalse(pathMatcher.match("/*bla/test", "XXXblab/test"));
|
||||
assertFalse(pathMatcher.match("/*bla/test", "XXXbl/test"));
|
||||
|
||||
assertFalse(pathMatcher.match("/????", "/bala/bla"));
|
||||
assertFalse(pathMatcher.match("/**/*bla", "/bla/bla/bla/bbb"));
|
||||
|
||||
assertTrue(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing/"));
|
||||
assertTrue(pathMatcher.match("/*bla*/**/bla/*", "/XXXblaXXXX/testing/testing/bla/testing"));
|
||||
assertTrue(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing"));
|
||||
assertTrue(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing.jpg"));
|
||||
|
||||
assertTrue(pathMatcher.match("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing/"));
|
||||
assertTrue(pathMatcher.match("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing"));
|
||||
assertTrue(pathMatcher.match("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing"));
|
||||
assertFalse(pathMatcher.match("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing/testing"));
|
||||
|
||||
assertFalse(pathMatcher.match("/x/x/**/bla", "/x/x/x/"));
|
||||
|
||||
assertTrue(pathMatcher.match("", ""));
|
||||
}
|
||||
|
||||
public void testAntPathMatcherWithMatchStart() {
|
||||
PathMatcher pathMatcher = new AntPathMatcher();
|
||||
|
||||
// test exact matching
|
||||
assertTrue(pathMatcher.matchStart("test", "test"));
|
||||
assertTrue(pathMatcher.matchStart("/test", "/test"));
|
||||
assertFalse(pathMatcher.matchStart("/test.jpg", "test.jpg"));
|
||||
assertFalse(pathMatcher.matchStart("test", "/test"));
|
||||
assertFalse(pathMatcher.matchStart("/test", "test"));
|
||||
|
||||
// test matching with ?'s
|
||||
assertTrue(pathMatcher.matchStart("t?st", "test"));
|
||||
assertTrue(pathMatcher.matchStart("??st", "test"));
|
||||
assertTrue(pathMatcher.matchStart("tes?", "test"));
|
||||
assertTrue(pathMatcher.matchStart("te??", "test"));
|
||||
assertTrue(pathMatcher.matchStart("?es?", "test"));
|
||||
assertFalse(pathMatcher.matchStart("tes?", "tes"));
|
||||
assertFalse(pathMatcher.matchStart("tes?", "testt"));
|
||||
assertFalse(pathMatcher.matchStart("tes?", "tsst"));
|
||||
|
||||
// test matchin with *'s
|
||||
assertTrue(pathMatcher.matchStart("*", "test"));
|
||||
assertTrue(pathMatcher.matchStart("test*", "test"));
|
||||
assertTrue(pathMatcher.matchStart("test*", "testTest"));
|
||||
assertTrue(pathMatcher.matchStart("test/*", "test/Test"));
|
||||
assertTrue(pathMatcher.matchStart("test/*", "test/t"));
|
||||
assertTrue(pathMatcher.matchStart("test/*", "test/"));
|
||||
assertTrue(pathMatcher.matchStart("*test*", "AnothertestTest"));
|
||||
assertTrue(pathMatcher.matchStart("*test", "Anothertest"));
|
||||
assertTrue(pathMatcher.matchStart("*.*", "test."));
|
||||
assertTrue(pathMatcher.matchStart("*.*", "test.test"));
|
||||
assertTrue(pathMatcher.matchStart("*.*", "test.test.test"));
|
||||
assertTrue(pathMatcher.matchStart("test*aaa", "testblaaaa"));
|
||||
assertFalse(pathMatcher.matchStart("test*", "tst"));
|
||||
assertFalse(pathMatcher.matchStart("test*", "test/"));
|
||||
assertFalse(pathMatcher.matchStart("test*", "tsttest"));
|
||||
assertFalse(pathMatcher.matchStart("test*", "test/"));
|
||||
assertFalse(pathMatcher.matchStart("test*", "test/t"));
|
||||
assertTrue(pathMatcher.matchStart("test/*", "test"));
|
||||
assertTrue(pathMatcher.matchStart("test/t*.txt", "test"));
|
||||
assertFalse(pathMatcher.matchStart("*test*", "tsttst"));
|
||||
assertFalse(pathMatcher.matchStart("*test", "tsttst"));
|
||||
assertFalse(pathMatcher.matchStart("*.*", "tsttst"));
|
||||
assertFalse(pathMatcher.matchStart("test*aaa", "test"));
|
||||
assertFalse(pathMatcher.matchStart("test*aaa", "testblaaab"));
|
||||
|
||||
// test matching with ?'s and /'s
|
||||
assertTrue(pathMatcher.matchStart("/?", "/a"));
|
||||
assertTrue(pathMatcher.matchStart("/?/a", "/a/a"));
|
||||
assertTrue(pathMatcher.matchStart("/a/?", "/a/b"));
|
||||
assertTrue(pathMatcher.matchStart("/??/a", "/aa/a"));
|
||||
assertTrue(pathMatcher.matchStart("/a/??", "/a/bb"));
|
||||
assertTrue(pathMatcher.matchStart("/?", "/a"));
|
||||
|
||||
// test matching with **'s
|
||||
assertTrue(pathMatcher.matchStart("/**", "/testing/testing"));
|
||||
assertTrue(pathMatcher.matchStart("/*/**", "/testing/testing"));
|
||||
assertTrue(pathMatcher.matchStart("/**/*", "/testing/testing"));
|
||||
assertTrue(pathMatcher.matchStart("test*/**", "test/"));
|
||||
assertTrue(pathMatcher.matchStart("test*/**", "test/t"));
|
||||
assertTrue(pathMatcher.matchStart("/bla/**/bla", "/bla/testing/testing/bla"));
|
||||
assertTrue(pathMatcher.matchStart("/bla/**/bla", "/bla/testing/testing/bla/bla"));
|
||||
assertTrue(pathMatcher.matchStart("/**/test", "/bla/bla/test"));
|
||||
assertTrue(pathMatcher.matchStart("/bla/**/**/bla", "/bla/bla/bla/bla/bla/bla"));
|
||||
assertTrue(pathMatcher.matchStart("/bla*bla/test", "/blaXXXbla/test"));
|
||||
assertTrue(pathMatcher.matchStart("/*bla/test", "/XXXbla/test"));
|
||||
assertFalse(pathMatcher.matchStart("/bla*bla/test", "/blaXXXbl/test"));
|
||||
assertFalse(pathMatcher.matchStart("/*bla/test", "XXXblab/test"));
|
||||
assertFalse(pathMatcher.matchStart("/*bla/test", "XXXbl/test"));
|
||||
|
||||
assertFalse(pathMatcher.matchStart("/????", "/bala/bla"));
|
||||
assertTrue(pathMatcher.matchStart("/**/*bla", "/bla/bla/bla/bbb"));
|
||||
|
||||
assertTrue(pathMatcher.matchStart("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing/"));
|
||||
assertTrue(pathMatcher.matchStart("/*bla*/**/bla/*", "/XXXblaXXXX/testing/testing/bla/testing"));
|
||||
assertTrue(pathMatcher.matchStart("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing"));
|
||||
assertTrue(pathMatcher.matchStart("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing.jpg"));
|
||||
|
||||
assertTrue(pathMatcher.matchStart("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing/"));
|
||||
assertTrue(pathMatcher.matchStart("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing"));
|
||||
assertTrue(pathMatcher.matchStart("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing"));
|
||||
assertTrue(pathMatcher.matchStart("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing/testing"));
|
||||
|
||||
assertTrue(pathMatcher.matchStart("/x/x/**/bla", "/x/x/x/"));
|
||||
|
||||
assertTrue(pathMatcher.matchStart("", ""));
|
||||
}
|
||||
|
||||
public void testAntPathMatcherWithUniqueDeliminator() {
|
||||
AntPathMatcher pathMatcher = new AntPathMatcher();
|
||||
pathMatcher.setPathSeparator(".");
|
||||
|
||||
// test exact matching
|
||||
assertTrue(pathMatcher.match("test", "test"));
|
||||
assertTrue(pathMatcher.match(".test", ".test"));
|
||||
assertFalse(pathMatcher.match(".test/jpg", "test/jpg"));
|
||||
assertFalse(pathMatcher.match("test", ".test"));
|
||||
assertFalse(pathMatcher.match(".test", "test"));
|
||||
|
||||
// test matching with ?'s
|
||||
assertTrue(pathMatcher.match("t?st", "test"));
|
||||
assertTrue(pathMatcher.match("??st", "test"));
|
||||
assertTrue(pathMatcher.match("tes?", "test"));
|
||||
assertTrue(pathMatcher.match("te??", "test"));
|
||||
assertTrue(pathMatcher.match("?es?", "test"));
|
||||
assertFalse(pathMatcher.match("tes?", "tes"));
|
||||
assertFalse(pathMatcher.match("tes?", "testt"));
|
||||
assertFalse(pathMatcher.match("tes?", "tsst"));
|
||||
|
||||
// test matchin with *'s
|
||||
assertTrue(pathMatcher.match("*", "test"));
|
||||
assertTrue(pathMatcher.match("test*", "test"));
|
||||
assertTrue(pathMatcher.match("test*", "testTest"));
|
||||
assertTrue(pathMatcher.match("*test*", "AnothertestTest"));
|
||||
assertTrue(pathMatcher.match("*test", "Anothertest"));
|
||||
assertTrue(pathMatcher.match("*/*", "test/"));
|
||||
assertTrue(pathMatcher.match("*/*", "test/test"));
|
||||
assertTrue(pathMatcher.match("*/*", "test/test/test"));
|
||||
assertTrue(pathMatcher.match("test*aaa", "testblaaaa"));
|
||||
assertFalse(pathMatcher.match("test*", "tst"));
|
||||
assertFalse(pathMatcher.match("test*", "tsttest"));
|
||||
assertFalse(pathMatcher.match("*test*", "tsttst"));
|
||||
assertFalse(pathMatcher.match("*test", "tsttst"));
|
||||
assertFalse(pathMatcher.match("*/*", "tsttst"));
|
||||
assertFalse(pathMatcher.match("test*aaa", "test"));
|
||||
assertFalse(pathMatcher.match("test*aaa", "testblaaab"));
|
||||
|
||||
// test matching with ?'s and .'s
|
||||
assertTrue(pathMatcher.match(".?", ".a"));
|
||||
assertTrue(pathMatcher.match(".?.a", ".a.a"));
|
||||
assertTrue(pathMatcher.match(".a.?", ".a.b"));
|
||||
assertTrue(pathMatcher.match(".??.a", ".aa.a"));
|
||||
assertTrue(pathMatcher.match(".a.??", ".a.bb"));
|
||||
assertTrue(pathMatcher.match(".?", ".a"));
|
||||
|
||||
// test matching with **'s
|
||||
assertTrue(pathMatcher.match(".**", ".testing.testing"));
|
||||
assertTrue(pathMatcher.match(".*.**", ".testing.testing"));
|
||||
assertTrue(pathMatcher.match(".**.*", ".testing.testing"));
|
||||
assertTrue(pathMatcher.match(".bla.**.bla", ".bla.testing.testing.bla"));
|
||||
assertTrue(pathMatcher.match(".bla.**.bla", ".bla.testing.testing.bla.bla"));
|
||||
assertTrue(pathMatcher.match(".**.test", ".bla.bla.test"));
|
||||
assertTrue(pathMatcher.match(".bla.**.**.bla", ".bla.bla.bla.bla.bla.bla"));
|
||||
assertTrue(pathMatcher.match(".bla*bla.test", ".blaXXXbla.test"));
|
||||
assertTrue(pathMatcher.match(".*bla.test", ".XXXbla.test"));
|
||||
assertFalse(pathMatcher.match(".bla*bla.test", ".blaXXXbl.test"));
|
||||
assertFalse(pathMatcher.match(".*bla.test", "XXXblab.test"));
|
||||
assertFalse(pathMatcher.match(".*bla.test", "XXXbl.test"));
|
||||
}
|
||||
|
||||
public void testAntPathMatcherExtractPathWithinPattern() throws Exception {
|
||||
PathMatcher pathMatcher = new AntPathMatcher();
|
||||
|
||||
assertEquals("", pathMatcher.extractPathWithinPattern("/docs/commit.html", "/docs/commit.html"));
|
||||
|
||||
assertEquals("cvs/commit", pathMatcher.extractPathWithinPattern("/docs/*", "/docs/cvs/commit"));
|
||||
assertEquals("commit.html", pathMatcher.extractPathWithinPattern("/docs/cvs/*.html", "/docs/cvs/commit.html"));
|
||||
assertEquals("cvs/commit", pathMatcher.extractPathWithinPattern("/docs/**", "/docs/cvs/commit"));
|
||||
assertEquals("cvs/commit.html", pathMatcher.extractPathWithinPattern("/docs/**/*.html", "/docs/cvs/commit.html"));
|
||||
assertEquals("commit.html", pathMatcher.extractPathWithinPattern("/docs/**/*.html", "/docs/commit.html"));
|
||||
assertEquals("commit.html", pathMatcher.extractPathWithinPattern("/*.html", "/commit.html"));
|
||||
assertEquals("docs/commit.html", pathMatcher.extractPathWithinPattern("/*.html", "/docs/commit.html"));
|
||||
assertEquals("/commit.html", pathMatcher.extractPathWithinPattern("*.html", "/commit.html"));
|
||||
assertEquals("/docs/commit.html", pathMatcher.extractPathWithinPattern("*.html", "/docs/commit.html"));
|
||||
assertEquals("/docs/commit.html", pathMatcher.extractPathWithinPattern("**/*.*", "/docs/commit.html"));
|
||||
assertEquals("/docs/commit.html", pathMatcher.extractPathWithinPattern("*", "/docs/commit.html"));
|
||||
|
||||
assertEquals("docs/cvs/commit", pathMatcher.extractPathWithinPattern("/d?cs/*", "/docs/cvs/commit"));
|
||||
assertEquals("cvs/commit.html", pathMatcher.extractPathWithinPattern("/docs/c?s/*.html", "/docs/cvs/commit.html"));
|
||||
assertEquals("docs/cvs/commit", pathMatcher.extractPathWithinPattern("/d?cs/**", "/docs/cvs/commit"));
|
||||
assertEquals("docs/cvs/commit.html", pathMatcher.extractPathWithinPattern("/d?cs/**/*.html", "/docs/cvs/commit.html"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
* Copyright 2002-2007 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.util;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @author Johan Gorter
|
||||
*/
|
||||
public class PatternMatchUtilsTests extends TestCase {
|
||||
|
||||
public void testTrivial() {
|
||||
assertEquals(false, PatternMatchUtils.simpleMatch((String) null, ""));
|
||||
assertEquals(false, PatternMatchUtils.simpleMatch("1", null));
|
||||
doTest("*", "123", true);
|
||||
doTest("123", "123", true);
|
||||
}
|
||||
|
||||
public void testStartsWith() {
|
||||
doTest("get*", "getMe", true);
|
||||
doTest("get*", "setMe", false);
|
||||
}
|
||||
|
||||
public void testEndsWith() {
|
||||
doTest("*Test", "getMeTest", true);
|
||||
doTest("*Test", "setMe", false);
|
||||
}
|
||||
|
||||
public void testBetween() {
|
||||
doTest("*stuff*", "getMeTest", false);
|
||||
doTest("*stuff*", "getstuffTest", true);
|
||||
doTest("*stuff*", "stuffTest", true);
|
||||
doTest("*stuff*", "getstuff", true);
|
||||
doTest("*stuff*", "stuff", true);
|
||||
}
|
||||
|
||||
public void testStartsEnds() {
|
||||
doTest("on*Event", "onMyEvent", true);
|
||||
doTest("on*Event", "onEvent", true);
|
||||
doTest("3*3", "3", false);
|
||||
doTest("3*3", "33", true);
|
||||
}
|
||||
|
||||
public void testStartsEndsBetween() {
|
||||
doTest("12*45*78", "12345678", true);
|
||||
doTest("12*45*78", "123456789", false);
|
||||
doTest("12*45*78", "012345678", false);
|
||||
doTest("12*45*78", "124578", true);
|
||||
doTest("12*45*78", "1245457878", true);
|
||||
doTest("3*3*3", "33", false);
|
||||
doTest("3*3*3", "333", true);
|
||||
}
|
||||
|
||||
public void testRidiculous() {
|
||||
doTest("*1*2*3*", "0011002001010030020201030", true);
|
||||
doTest("1*2*3*4", "10300204", false);
|
||||
doTest("1*2*3*3", "10300203", false);
|
||||
doTest("*1*2*3*", "123", true);
|
||||
doTest("*1*2*3*", "132", false);
|
||||
}
|
||||
|
||||
private void doTest(String pattern, String str, boolean shouldMatch) {
|
||||
assertEquals(shouldMatch, PatternMatchUtils.simpleMatch(pattern, str));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
/*
|
||||
* Copyright 2002-2005 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.util;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.io.StringWriter;
|
||||
import java.util.Properties;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 11.01.2005
|
||||
*/
|
||||
public class PropertiesPersisterTests extends TestCase {
|
||||
|
||||
public void testPropertiesPersister() throws IOException {
|
||||
String propString = "code1=message1\ncode2:message2";
|
||||
Properties props = loadProperties(propString, false);
|
||||
String propCopy = storeProperties(props, null, false);
|
||||
loadProperties(propCopy, false);
|
||||
}
|
||||
|
||||
public void testPropertiesPersisterWithWhitespace() throws IOException {
|
||||
String propString = " code1\t= \tmessage1\n code2 \t :\t mess\\\n \t age2";
|
||||
Properties props = loadProperties(propString, false);
|
||||
String propCopy = storeProperties(props, null, false);
|
||||
loadProperties(propCopy, false);
|
||||
}
|
||||
|
||||
public void testPropertiesPersisterWithHeader() throws IOException {
|
||||
String propString = "code1=message1\ncode2:message2";
|
||||
Properties props = loadProperties(propString, false);
|
||||
String propCopy = storeProperties(props, "myHeader", false);
|
||||
loadProperties(propCopy, false);
|
||||
}
|
||||
|
||||
public void testPropertiesPersisterWithEmptyValue() throws IOException {
|
||||
String propString = "code1=message1\ncode2:message2\ncode3=";
|
||||
Properties props = loadProperties(propString, false);
|
||||
String propCopy = storeProperties(props, null, false);
|
||||
loadProperties(propCopy, false);
|
||||
}
|
||||
|
||||
public void testPropertiesPersisterWithReader() throws IOException {
|
||||
String propString = "code1=message1\ncode2:message2";
|
||||
Properties props = loadProperties(propString, true);
|
||||
String propCopy = storeProperties(props, null, true);
|
||||
loadProperties(propCopy, false);
|
||||
}
|
||||
|
||||
public void testPropertiesPersisterWithReaderAndWhitespace() throws IOException {
|
||||
String propString = " code1\t= \tmessage1\n code2 \t :\t mess\\\n \t age2";
|
||||
Properties props = loadProperties(propString, true);
|
||||
String propCopy = storeProperties(props, null, true);
|
||||
loadProperties(propCopy, false);
|
||||
}
|
||||
|
||||
public void testPropertiesPersisterWithReaderAndHeader() throws IOException {
|
||||
String propString = "code1\t=\tmessage1\n code2 \t : \t message2";
|
||||
Properties props = loadProperties(propString, true);
|
||||
String propCopy = storeProperties(props, "myHeader", true);
|
||||
loadProperties(propCopy, false);
|
||||
}
|
||||
|
||||
public void testPropertiesPersisterWithReaderAndEmptyValue() throws IOException {
|
||||
String propString = "code1=message1\ncode2:message2\ncode3=";
|
||||
Properties props = loadProperties(propString, true);
|
||||
String propCopy = storeProperties(props, null, true);
|
||||
loadProperties(propCopy, false);
|
||||
}
|
||||
|
||||
private Properties loadProperties(String propString, boolean useReader) throws IOException {
|
||||
DefaultPropertiesPersister persister = new DefaultPropertiesPersister();
|
||||
Properties props = new Properties();
|
||||
if (useReader) {
|
||||
persister.load(props, new StringReader(propString));
|
||||
}
|
||||
else {
|
||||
persister.load(props, new ByteArrayInputStream(propString.getBytes()));
|
||||
}
|
||||
assertEquals("message1", props.getProperty("code1"));
|
||||
assertEquals("message2", props.getProperty("code2"));
|
||||
return props;
|
||||
}
|
||||
|
||||
private String storeProperties(Properties props, String header, boolean useWriter) throws IOException {
|
||||
DefaultPropertiesPersister persister = new DefaultPropertiesPersister();
|
||||
String propCopy = null;
|
||||
if (useWriter) {
|
||||
StringWriter propWriter = new StringWriter();
|
||||
persister.store(props, propWriter, header);
|
||||
propCopy = propWriter.toString();
|
||||
}
|
||||
else {
|
||||
ByteArrayOutputStream propOut = new ByteArrayOutputStream();
|
||||
persister.store(props, propOut, header);
|
||||
propCopy = new String(propOut.toByteArray());
|
||||
}
|
||||
if (header != null) {
|
||||
assertTrue(propCopy.indexOf(header) != -1);
|
||||
}
|
||||
assertTrue(propCopy.indexOf("\ncode1=message1") != -1);
|
||||
assertTrue(propCopy.indexOf("\ncode2=message2") != -1);
|
||||
return propCopy;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
* Copyright 2002-2006 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.net.URLStreamHandler;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class ResourceUtilsTests extends TestCase {
|
||||
|
||||
public void testIsJarURL() throws Exception {
|
||||
assertTrue(ResourceUtils.isJarURL(new URL("jar:file:myjar.jar!/mypath")));
|
||||
assertTrue(ResourceUtils.isJarURL(new URL(null, "zip:file:myjar.jar!/mypath", new DummyURLStreamHandler())));
|
||||
assertTrue(ResourceUtils.isJarURL(new URL(null, "wsjar:file:myjar.jar!/mypath", new DummyURLStreamHandler())));
|
||||
assertFalse(ResourceUtils.isJarURL(new URL("file:myjar.jar")));
|
||||
assertFalse(ResourceUtils.isJarURL(new URL("http:myserver/myjar.jar")));
|
||||
}
|
||||
|
||||
public void testExtractJarFileURL() throws Exception {
|
||||
assertEquals(new URL("file:myjar.jar"),
|
||||
ResourceUtils.extractJarFileURL(new URL("jar:file:myjar.jar!/mypath")));
|
||||
assertEquals(new URL("file:/myjar.jar"),
|
||||
ResourceUtils.extractJarFileURL(new URL(null, "jar:myjar.jar!/mypath", new DummyURLStreamHandler())));
|
||||
assertEquals(new URL("file:myjar.jar"),
|
||||
ResourceUtils.extractJarFileURL(new URL(null, "zip:file:myjar.jar!/mypath", new DummyURLStreamHandler())));
|
||||
assertEquals(new URL("file:myjar.jar"),
|
||||
ResourceUtils.extractJarFileURL(new URL(null, "wsjar:file:myjar.jar!/mypath", new DummyURLStreamHandler())));
|
||||
assertEquals(new URL("file:myjar.jar"),
|
||||
ResourceUtils.extractJarFileURL(new URL("jar:file:myjar.jar!/")));
|
||||
assertEquals(new URL("file:myjar.jar"),
|
||||
ResourceUtils.extractJarFileURL(new URL(null, "zip:file:myjar.jar!/", new DummyURLStreamHandler())));
|
||||
assertEquals(new URL("file:myjar.jar"),
|
||||
ResourceUtils.extractJarFileURL(new URL(null, "wsjar:file:myjar.jar!/", new DummyURLStreamHandler())));
|
||||
assertEquals(new URL("file:myjar.jar"),
|
||||
ResourceUtils.extractJarFileURL(new URL("file:myjar.jar")));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Dummy URLStreamHandler that's just specified to suppress the standard
|
||||
* <code>java.net.URL</code> URLStreamHandler lookup, to be able to
|
||||
* use the standard URL class for parsing "rmi:..." URLs.
|
||||
*/
|
||||
private static class DummyURLStreamHandler extends URLStreamHandler {
|
||||
|
||||
protected URLConnection openConnection(URL url) throws IOException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
|
||||
/*
|
||||
* Copyright 2002-2005 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.util;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
*/
|
||||
public class StopWatchTests extends TestCase {
|
||||
|
||||
/**
|
||||
* Are timings off in JUnit?
|
||||
*/
|
||||
public void testValidUsage() throws Exception {
|
||||
StopWatch sw = new StopWatch();
|
||||
long int1 = 166L;
|
||||
long int2 = 45L;
|
||||
String name1 = "Task 1";
|
||||
String name2 = "Task 2";
|
||||
|
||||
long fudgeFactor = 5L;
|
||||
assertFalse(sw.isRunning());
|
||||
sw.start(name1);
|
||||
Thread.sleep(int1);
|
||||
assertTrue(sw.isRunning());
|
||||
sw.stop();
|
||||
|
||||
// TODO are timings off in JUnit? Why do these assertions sometimes fail
|
||||
// under both Ant and Eclipse?
|
||||
|
||||
//assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() >= int1);
|
||||
//assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() <= int1 + fudgeFactor);
|
||||
sw.start(name2);
|
||||
Thread.sleep(int2);
|
||||
sw.stop();
|
||||
//assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() >= int1 + int2);
|
||||
//assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() <= int1 + int2 + fudgeFactor);
|
||||
|
||||
assertTrue(sw.getTaskCount() == 2);
|
||||
String pp = sw.prettyPrint();
|
||||
assertTrue(pp.indexOf(name1) != -1);
|
||||
assertTrue(pp.indexOf(name2) != -1);
|
||||
|
||||
StopWatch.TaskInfo[] tasks = sw.getTaskInfo();
|
||||
assertTrue(tasks.length == 2);
|
||||
assertTrue(tasks[0].getTaskName().equals(name1));
|
||||
assertTrue(tasks[1].getTaskName().equals(name2));
|
||||
sw.toString();
|
||||
}
|
||||
|
||||
public void testValidUsageNotKeepingTaskList() throws Exception {
|
||||
StopWatch sw = new StopWatch();
|
||||
sw.setKeepTaskList(false);
|
||||
long int1 = 166L;
|
||||
long int2 = 45L;
|
||||
String name1 = "Task 1";
|
||||
String name2 = "Task 2";
|
||||
|
||||
long fudgeFactor = 5L;
|
||||
assertFalse(sw.isRunning());
|
||||
sw.start(name1);
|
||||
Thread.sleep(int1);
|
||||
assertTrue(sw.isRunning());
|
||||
sw.stop();
|
||||
|
||||
// TODO are timings off in JUnit? Why do these assertions sometimes fail
|
||||
// under both Ant and Eclipse?
|
||||
|
||||
//assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() >= int1);
|
||||
//assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() <= int1 + fudgeFactor);
|
||||
sw.start(name2);
|
||||
Thread.sleep(int2);
|
||||
sw.stop();
|
||||
//assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() >= int1 + int2);
|
||||
//assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() <= int1 + int2 + fudgeFactor);
|
||||
|
||||
assertTrue(sw.getTaskCount() == 2);
|
||||
String pp = sw.prettyPrint();
|
||||
assertTrue(pp.indexOf("kept") != -1);
|
||||
sw.toString();
|
||||
|
||||
try {
|
||||
sw.getTaskInfo();
|
||||
fail();
|
||||
}
|
||||
catch (UnsupportedOperationException ex) {
|
||||
// Ok
|
||||
}
|
||||
}
|
||||
|
||||
public void testFailureToStartBeforeGettingTimings() {
|
||||
StopWatch sw = new StopWatch();
|
||||
try {
|
||||
sw.getLastTaskTimeMillis();
|
||||
fail("Can't get last interval if no tests run");
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
// Ok
|
||||
}
|
||||
}
|
||||
|
||||
public void testFailureToStartBeforeStop() {
|
||||
StopWatch sw = new StopWatch();
|
||||
try {
|
||||
sw.stop();
|
||||
fail("Can't stop without starting");
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
// Ok
|
||||
}
|
||||
}
|
||||
|
||||
public void testRejectsStartTwice() {
|
||||
StopWatch sw = new StopWatch();
|
||||
try {
|
||||
sw.start("");
|
||||
sw.stop();
|
||||
sw.start("");
|
||||
assertTrue(sw.isRunning());
|
||||
sw.start("");
|
||||
fail("Can't start twice");
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
// Ok
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,614 @@
|
||||
/*
|
||||
* Copyright 2002-2008 the original author or authors.
|
||||
*
|
||||
* Licensed 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.springframework.util;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
import java.util.Properties;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
* @author Rick Evans
|
||||
*/
|
||||
public class StringUtilsTests extends TestCase {
|
||||
|
||||
public void testHasTextBlank() throws Exception {
|
||||
String blank = " ";
|
||||
assertEquals(false, StringUtils.hasText(blank));
|
||||
}
|
||||
|
||||
public void testHasTextNullEmpty() throws Exception {
|
||||
assertEquals(false, StringUtils.hasText(null));
|
||||
assertEquals(false, StringUtils.hasText(""));
|
||||
}
|
||||
|
||||
public void testHasTextValid() throws Exception {
|
||||
assertEquals(true, StringUtils.hasText("t"));
|
||||
}
|
||||
|
||||
public void testContainsWhitespace() throws Exception {
|
||||
assertFalse(StringUtils.containsWhitespace(null));
|
||||
assertFalse(StringUtils.containsWhitespace(""));
|
||||
assertFalse(StringUtils.containsWhitespace("a"));
|
||||
assertFalse(StringUtils.containsWhitespace("abc"));
|
||||
assertTrue(StringUtils.containsWhitespace(" "));
|
||||
assertTrue(StringUtils.containsWhitespace(" a"));
|
||||
assertTrue(StringUtils.containsWhitespace("abc "));
|
||||
assertTrue(StringUtils.containsWhitespace("a b"));
|
||||
assertTrue(StringUtils.containsWhitespace("a b"));
|
||||
}
|
||||
|
||||
public void testTrimWhitespace() throws Exception {
|
||||
assertEquals(null, StringUtils.trimWhitespace(null));
|
||||
assertEquals("", StringUtils.trimWhitespace(""));
|
||||
assertEquals("", StringUtils.trimWhitespace(" "));
|
||||
assertEquals("", StringUtils.trimWhitespace("\t"));
|
||||
assertEquals("a", StringUtils.trimWhitespace(" a"));
|
||||
assertEquals("a", StringUtils.trimWhitespace("a "));
|
||||
assertEquals("a", StringUtils.trimWhitespace(" a "));
|
||||
assertEquals("a b", StringUtils.trimWhitespace(" a b "));
|
||||
assertEquals("a b c", StringUtils.trimWhitespace(" a b c "));
|
||||
}
|
||||
|
||||
public void testTrimAllWhitespace() throws Exception {
|
||||
assertEquals("", StringUtils.trimAllWhitespace(""));
|
||||
assertEquals("", StringUtils.trimAllWhitespace(" "));
|
||||
assertEquals("", StringUtils.trimAllWhitespace("\t"));
|
||||
assertEquals("a", StringUtils.trimAllWhitespace(" a"));
|
||||
assertEquals("a", StringUtils.trimAllWhitespace("a "));
|
||||
assertEquals("a", StringUtils.trimAllWhitespace(" a "));
|
||||
assertEquals("ab", StringUtils.trimAllWhitespace(" a b "));
|
||||
assertEquals("abc", StringUtils.trimAllWhitespace(" a b c "));
|
||||
}
|
||||
|
||||
public void testTrimLeadingWhitespace() throws Exception {
|
||||
assertEquals(null, StringUtils.trimLeadingWhitespace(null));
|
||||
assertEquals("", StringUtils.trimLeadingWhitespace(""));
|
||||
assertEquals("", StringUtils.trimLeadingWhitespace(" "));
|
||||
assertEquals("", StringUtils.trimLeadingWhitespace("\t"));
|
||||
assertEquals("a", StringUtils.trimLeadingWhitespace(" a"));
|
||||
assertEquals("a ", StringUtils.trimLeadingWhitespace("a "));
|
||||
assertEquals("a ", StringUtils.trimLeadingWhitespace(" a "));
|
||||
assertEquals("a b ", StringUtils.trimLeadingWhitespace(" a b "));
|
||||
assertEquals("a b c ", StringUtils.trimLeadingWhitespace(" a b c "));
|
||||
}
|
||||
|
||||
public void testTrimTrailingWhitespace() throws Exception {
|
||||
assertEquals(null, StringUtils.trimTrailingWhitespace(null));
|
||||
assertEquals("", StringUtils.trimTrailingWhitespace(""));
|
||||
assertEquals("", StringUtils.trimTrailingWhitespace(" "));
|
||||
assertEquals("", StringUtils.trimTrailingWhitespace("\t"));
|
||||
assertEquals("a", StringUtils.trimTrailingWhitespace("a "));
|
||||
assertEquals(" a", StringUtils.trimTrailingWhitespace(" a"));
|
||||
assertEquals(" a", StringUtils.trimTrailingWhitespace(" a "));
|
||||
assertEquals(" a b", StringUtils.trimTrailingWhitespace(" a b "));
|
||||
assertEquals(" a b c", StringUtils.trimTrailingWhitespace(" a b c "));
|
||||
}
|
||||
|
||||
public void testTrimLeadingCharacter() throws Exception {
|
||||
assertEquals(null, StringUtils.trimLeadingCharacter(null, ' '));
|
||||
assertEquals("", StringUtils.trimLeadingCharacter("", ' '));
|
||||
assertEquals("", StringUtils.trimLeadingCharacter(" ", ' '));
|
||||
assertEquals("\t", StringUtils.trimLeadingCharacter("\t", ' '));
|
||||
assertEquals("a", StringUtils.trimLeadingCharacter(" a", ' '));
|
||||
assertEquals("a ", StringUtils.trimLeadingCharacter("a ", ' '));
|
||||
assertEquals("a ", StringUtils.trimLeadingCharacter(" a ", ' '));
|
||||
assertEquals("a b ", StringUtils.trimLeadingCharacter(" a b ", ' '));
|
||||
assertEquals("a b c ", StringUtils.trimLeadingCharacter(" a b c ", ' '));
|
||||
}
|
||||
|
||||
public void testTrimTrailingCharacter() throws Exception {
|
||||
assertEquals(null, StringUtils.trimTrailingCharacter(null, ' '));
|
||||
assertEquals("", StringUtils.trimTrailingCharacter("", ' '));
|
||||
assertEquals("", StringUtils.trimTrailingCharacter(" ", ' '));
|
||||
assertEquals("\t", StringUtils.trimTrailingCharacter("\t", ' '));
|
||||
assertEquals("a", StringUtils.trimTrailingCharacter("a ", ' '));
|
||||
assertEquals(" a", StringUtils.trimTrailingCharacter(" a", ' '));
|
||||
assertEquals(" a", StringUtils.trimTrailingCharacter(" a ", ' '));
|
||||
assertEquals(" a b", StringUtils.trimTrailingCharacter(" a b ", ' '));
|
||||
assertEquals(" a b c", StringUtils.trimTrailingCharacter(" a b c ", ' '));
|
||||
}
|
||||
|
||||
public void testCountOccurrencesOf() {
|
||||
assertTrue("nullx2 = 0",
|
||||
StringUtils.countOccurrencesOf(null, null) == 0);
|
||||
assertTrue("null string = 0",
|
||||
StringUtils.countOccurrencesOf("s", null) == 0);
|
||||
assertTrue("null substring = 0",
|
||||
StringUtils.countOccurrencesOf(null, "s") == 0);
|
||||
String s = "erowoiueoiur";
|
||||
assertTrue("not found = 0",
|
||||
StringUtils.countOccurrencesOf(s, "WERWER") == 0);
|
||||
assertTrue("not found char = 0",
|
||||
StringUtils.countOccurrencesOf(s, "x") == 0);
|
||||
assertTrue("not found ws = 0",
|
||||
StringUtils.countOccurrencesOf(s, " ") == 0);
|
||||
assertTrue("not found empty string = 0",
|
||||
StringUtils.countOccurrencesOf(s, "") == 0);
|
||||
assertTrue("found char=2", StringUtils.countOccurrencesOf(s, "e") == 2);
|
||||
assertTrue("found substring=2",
|
||||
StringUtils.countOccurrencesOf(s, "oi") == 2);
|
||||
assertTrue("found substring=2",
|
||||
StringUtils.countOccurrencesOf(s, "oiu") == 2);
|
||||
assertTrue("found substring=3",
|
||||
StringUtils.countOccurrencesOf(s, "oiur") == 1);
|
||||
assertTrue("test last", StringUtils.countOccurrencesOf(s, "r") == 2);
|
||||
}
|
||||
|
||||
public void testReplace() throws Exception {
|
||||
String inString = "a6AazAaa77abaa";
|
||||
String oldPattern = "aa";
|
||||
String newPattern = "foo";
|
||||
|
||||
// Simple replace
|
||||
String s = StringUtils.replace(inString, oldPattern, newPattern);
|
||||
assertTrue("Replace 1 worked", s.equals("a6AazAfoo77abfoo"));
|
||||
|
||||
// Non match: no change
|
||||
s = StringUtils.replace(inString, "qwoeiruqopwieurpoqwieur", newPattern);
|
||||
assertTrue("Replace non matched is equal", s.equals(inString));
|
||||
|
||||
// Null new pattern: should ignore
|
||||
s = StringUtils.replace(inString, oldPattern, null);
|
||||
assertTrue("Replace non matched is equal", s.equals(inString));
|
||||
|
||||
// Null old pattern: should ignore
|
||||
s = StringUtils.replace(inString, null, newPattern);
|
||||
assertTrue("Replace non matched is equal", s.equals(inString));
|
||||
}
|
||||
|
||||
public void testDelete() throws Exception {
|
||||
String inString = "The quick brown fox jumped over the lazy dog";
|
||||
|
||||
String noThe = StringUtils.delete(inString, "the");
|
||||
assertTrue("Result has no the [" + noThe + "]",
|
||||
noThe.equals("The quick brown fox jumped over lazy dog"));
|
||||
|
||||
String nohe = StringUtils.delete(inString, "he");
|
||||
assertTrue("Result has no he [" + nohe + "]",
|
||||
nohe.equals("T quick brown fox jumped over t lazy dog"));
|
||||
|
||||
String nosp = StringUtils.delete(inString, " ");
|
||||
assertTrue("Result has no spaces",
|
||||
nosp.equals("Thequickbrownfoxjumpedoverthelazydog"));
|
||||
|
||||
String killEnd = StringUtils.delete(inString, "dog");
|
||||
assertTrue("Result has no dog",
|
||||
killEnd.equals("The quick brown fox jumped over the lazy "));
|
||||
|
||||
String mismatch = StringUtils.delete(inString, "dxxcxcxog");
|
||||
assertTrue("Result is unchanged", mismatch.equals(inString));
|
||||
|
||||
String nochange = StringUtils.delete(inString, "");
|
||||
assertTrue("Result is unchanged", nochange.equals(inString));
|
||||
}
|
||||
|
||||
public void testDeleteAny() throws Exception {
|
||||
String inString = "Able was I ere I saw Elba";
|
||||
|
||||
String res = StringUtils.deleteAny(inString, "I");
|
||||
assertTrue("Result has no Is [" + res + "]", res.equals("Able was ere saw Elba"));
|
||||
|
||||
res = StringUtils.deleteAny(inString, "AeEba!");
|
||||
assertTrue("Result has no Is [" + res + "]", res.equals("l ws I r I sw l"));
|
||||
|
||||
String mismatch = StringUtils.deleteAny(inString, "#@$#$^");
|
||||
assertTrue("Result is unchanged", mismatch.equals(inString));
|
||||
|
||||
String whitespace = "This is\n\n\n \t a messagy string with whitespace\n";
|
||||
assertTrue("Has CR", whitespace.indexOf("\n") != -1);
|
||||
assertTrue("Has tab", whitespace.indexOf("\t") != -1);
|
||||
assertTrue("Has sp", whitespace.indexOf(" ") != -1);
|
||||
String cleaned = StringUtils.deleteAny(whitespace, "\n\t ");
|
||||
assertTrue("Has no CR", cleaned.indexOf("\n") == -1);
|
||||
assertTrue("Has no tab", cleaned.indexOf("\t") == -1);
|
||||
assertTrue("Has no sp", cleaned.indexOf(" ") == -1);
|
||||
assertTrue("Still has chars", cleaned.length() > 10);
|
||||
}
|
||||
|
||||
|
||||
public void testQuote() {
|
||||
assertEquals("'myString'", StringUtils.quote("myString"));
|
||||
assertEquals("''", StringUtils.quote(""));
|
||||
assertNull(StringUtils.quote(null));
|
||||
}
|
||||
|
||||
public void testQuoteIfString() {
|
||||
assertEquals("'myString'", StringUtils.quoteIfString("myString"));
|
||||
assertEquals("''", StringUtils.quoteIfString(""));
|
||||
assertEquals(new Integer(5), StringUtils.quoteIfString(new Integer(5)));
|
||||
assertNull(StringUtils.quoteIfString(null));
|
||||
}
|
||||
|
||||
public void testUnqualify() {
|
||||
String qualified = "i.am.not.unqualified";
|
||||
assertEquals("unqualified", StringUtils.unqualify(qualified));
|
||||
}
|
||||
|
||||
public void testCapitalize() {
|
||||
String capitalized = "i am not capitalized";
|
||||
assertEquals("I am not capitalized", StringUtils.capitalize(capitalized));
|
||||
}
|
||||
|
||||
public void testUncapitalize() {
|
||||
String capitalized = "I am capitalized";
|
||||
assertEquals("i am capitalized", StringUtils.uncapitalize(capitalized));
|
||||
}
|
||||
|
||||
public void testGetFilename() {
|
||||
assertEquals(null, StringUtils.getFilename(null));
|
||||
assertEquals("", StringUtils.getFilename(""));
|
||||
assertEquals("myfile", StringUtils.getFilename("myfile"));
|
||||
assertEquals("myfile", StringUtils.getFilename("mypath/myfile"));
|
||||
assertEquals("myfile.", StringUtils.getFilename("myfile."));
|
||||
assertEquals("myfile.", StringUtils.getFilename("mypath/myfile."));
|
||||
assertEquals("myfile.txt", StringUtils.getFilename("myfile.txt"));
|
||||
assertEquals("myfile.txt", StringUtils.getFilename("mypath/myfile.txt"));
|
||||
}
|
||||
|
||||
public void testGetFilenameExtension() {
|
||||
assertEquals(null, StringUtils.getFilenameExtension(null));
|
||||
assertEquals(null, StringUtils.getFilenameExtension(""));
|
||||
assertEquals(null, StringUtils.getFilenameExtension("myfile"));
|
||||
assertEquals(null, StringUtils.getFilenameExtension("myPath/myfile"));
|
||||
assertEquals("", StringUtils.getFilenameExtension("myfile."));
|
||||
assertEquals("", StringUtils.getFilenameExtension("myPath/myfile."));
|
||||
assertEquals("txt", StringUtils.getFilenameExtension("myfile.txt"));
|
||||
assertEquals("txt", StringUtils.getFilenameExtension("mypath/myfile.txt"));
|
||||
}
|
||||
|
||||
public void testStripFilenameExtension() {
|
||||
assertEquals(null, StringUtils.stripFilenameExtension(null));
|
||||
assertEquals("", StringUtils.stripFilenameExtension(""));
|
||||
assertEquals("myfile", StringUtils.stripFilenameExtension("myfile"));
|
||||
assertEquals("mypath/myfile", StringUtils.stripFilenameExtension("mypath/myfile"));
|
||||
assertEquals("myfile", StringUtils.stripFilenameExtension("myfile."));
|
||||
assertEquals("mypath/myfile", StringUtils.stripFilenameExtension("mypath/myfile."));
|
||||
assertEquals("myfile", StringUtils.stripFilenameExtension("myfile.txt"));
|
||||
assertEquals("mypath/myfile", StringUtils.stripFilenameExtension("mypath/myfile.txt"));
|
||||
}
|
||||
|
||||
public void testCleanPath() {
|
||||
assertEquals("mypath/myfile", StringUtils.cleanPath("mypath/myfile"));
|
||||
assertEquals("mypath/myfile", StringUtils.cleanPath("mypath\\myfile"));
|
||||
assertEquals("mypath/myfile", StringUtils.cleanPath("mypath/../mypath/myfile"));
|
||||
assertEquals("mypath/myfile", StringUtils.cleanPath("mypath/myfile/../../mypath/myfile"));
|
||||
assertEquals("../mypath/myfile", StringUtils.cleanPath("../mypath/myfile"));
|
||||
assertEquals("../mypath/myfile", StringUtils.cleanPath("../mypath/../mypath/myfile"));
|
||||
assertEquals("../mypath/myfile", StringUtils.cleanPath("mypath/../../mypath/myfile"));
|
||||
assertEquals("/../mypath/myfile", StringUtils.cleanPath("/../mypath/myfile"));
|
||||
}
|
||||
|
||||
public void testPathEquals() {
|
||||
assertTrue("Must be true for the same strings",
|
||||
StringUtils.pathEquals("/dummy1/dummy2/dummy3",
|
||||
"/dummy1/dummy2/dummy3"));
|
||||
assertTrue("Must be true for the same win strings",
|
||||
StringUtils.pathEquals("C:\\dummy1\\dummy2\\dummy3",
|
||||
"C:\\dummy1\\dummy2\\dummy3"));
|
||||
assertTrue("Must be true for one top path on 1",
|
||||
StringUtils.pathEquals("/dummy1/bin/../dummy2/dummy3",
|
||||
"/dummy1/dummy2/dummy3"));
|
||||
assertTrue("Must be true for one win top path on 2",
|
||||
StringUtils.pathEquals("C:\\dummy1\\dummy2\\dummy3",
|
||||
"C:\\dummy1\\bin\\..\\dummy2\\dummy3"));
|
||||
assertTrue("Must be true for two top paths on 1",
|
||||
StringUtils.pathEquals("/dummy1/bin/../dummy2/bin/../dummy3",
|
||||
"/dummy1/dummy2/dummy3"));
|
||||
assertTrue("Must be true for two win top paths on 2",
|
||||
StringUtils.pathEquals("C:\\dummy1\\dummy2\\dummy3",
|
||||
"C:\\dummy1\\bin\\..\\dummy2\\bin\\..\\dummy3"));
|
||||
assertTrue("Must be true for double top paths on 1",
|
||||
StringUtils.pathEquals("/dummy1/bin/tmp/../../dummy2/dummy3",
|
||||
"/dummy1/dummy2/dummy3"));
|
||||
assertTrue("Must be true for double top paths on 2 with similarity",
|
||||
StringUtils.pathEquals("/dummy1/dummy2/dummy3",
|
||||
"/dummy1/dum/dum/../../dummy2/dummy3"));
|
||||
assertTrue("Must be true for current paths",
|
||||
StringUtils.pathEquals("./dummy1/dummy2/dummy3",
|
||||
"dummy1/dum/./dum/../../dummy2/dummy3"));
|
||||
assertFalse("Must be false for relative/absolute paths",
|
||||
StringUtils.pathEquals("./dummy1/dummy2/dummy3",
|
||||
"/dummy1/dum/./dum/../../dummy2/dummy3"));
|
||||
assertFalse("Must be false for different strings",
|
||||
StringUtils.pathEquals("/dummy1/dummy2/dummy3",
|
||||
"/dummy1/dummy4/dummy3"));
|
||||
assertFalse("Must be false for one false path on 1",
|
||||
StringUtils.pathEquals("/dummy1/bin/tmp/../dummy2/dummy3",
|
||||
"/dummy1/dummy2/dummy3"));
|
||||
assertFalse("Must be false for one false win top path on 2",
|
||||
StringUtils.pathEquals("C:\\dummy1\\dummy2\\dummy3",
|
||||
"C:\\dummy1\\bin\\tmp\\..\\dummy2\\dummy3"));
|
||||
assertFalse("Must be false for top path on 1 + difference",
|
||||
StringUtils.pathEquals("/dummy1/bin/../dummy2/dummy3",
|
||||
"/dummy1/dummy2/dummy4"));
|
||||
}
|
||||
|
||||
public void testConcatenateStringArrays() {
|
||||
String[] input1 = new String[] {"myString2"};
|
||||
String[] input2 = new String[] {"myString1", "myString2"};
|
||||
String[] result = StringUtils.concatenateStringArrays(input1, input2);
|
||||
assertEquals(3, result.length);
|
||||
assertEquals("myString2", result[0]);
|
||||
assertEquals("myString1", result[1]);
|
||||
assertEquals("myString2", result[2]);
|
||||
|
||||
assertEquals(input1, StringUtils.concatenateStringArrays(input1, null));
|
||||
assertEquals(input2, StringUtils.concatenateStringArrays(null, input2));
|
||||
assertNull(StringUtils.concatenateStringArrays(null, null));
|
||||
}
|
||||
|
||||
public void testMergeStringArrays() {
|
||||
String[] input1 = new String[] {"myString2"};
|
||||
String[] input2 = new String[] {"myString1", "myString2"};
|
||||
String[] result = StringUtils.mergeStringArrays(input1, input2);
|
||||
assertEquals(2, result.length);
|
||||
assertEquals("myString2", result[0]);
|
||||
assertEquals("myString1", result[1]);
|
||||
|
||||
assertEquals(input1, StringUtils.mergeStringArrays(input1, null));
|
||||
assertEquals(input2, StringUtils.mergeStringArrays(null, input2));
|
||||
assertNull(StringUtils.mergeStringArrays(null, null));
|
||||
}
|
||||
|
||||
public void testSortStringArray() {
|
||||
String[] input = new String[] {"myString2"};
|
||||
input = StringUtils.addStringToArray(input, "myString1");
|
||||
assertEquals("myString2", input[0]);
|
||||
assertEquals("myString1", input[1]);
|
||||
|
||||
StringUtils.sortStringArray(input);
|
||||
assertEquals("myString1", input[0]);
|
||||
assertEquals("myString2", input[1]);
|
||||
}
|
||||
|
||||
public void testRemoveDuplicateStrings() {
|
||||
String[] input = new String[] {"myString2", "myString1", "myString2"};
|
||||
input = StringUtils.removeDuplicateStrings(input);
|
||||
assertEquals("myString1", input[0]);
|
||||
assertEquals("myString2", input[1]);
|
||||
}
|
||||
|
||||
public void testSplitArrayElementsIntoProperties() {
|
||||
String[] input = new String[] {"key1=value1 ", "key2 =\"value2\""};
|
||||
Properties result = StringUtils.splitArrayElementsIntoProperties(input, "=");
|
||||
assertEquals("value1", result.getProperty("key1"));
|
||||
assertEquals("\"value2\"", result.getProperty("key2"));
|
||||
}
|
||||
|
||||
public void testSplitArrayElementsIntoPropertiesAndDeletedChars() {
|
||||
String[] input = new String[] {"key1=value1 ", "key2 =\"value2\""};
|
||||
Properties result = StringUtils.splitArrayElementsIntoProperties(input, "=", "\"");
|
||||
assertEquals("value1", result.getProperty("key1"));
|
||||
assertEquals("value2", result.getProperty("key2"));
|
||||
}
|
||||
|
||||
public void testTokenizeToStringArray() {
|
||||
String[] sa = StringUtils.tokenizeToStringArray("a,b , ,c", ",");
|
||||
assertEquals(3, sa.length);
|
||||
assertTrue("components are correct",
|
||||
sa[0].equals("a") && sa[1].equals("b") && sa[2].equals("c"));
|
||||
}
|
||||
|
||||
public void testTokenizeToStringArrayWithNotIgnoreEmptyTokens() {
|
||||
String[] sa = StringUtils.tokenizeToStringArray("a,b , ,c", ",", true, false);
|
||||
assertEquals(4, sa.length);
|
||||
assertTrue("components are correct",
|
||||
sa[0].equals("a") && sa[1].equals("b") && sa[2].equals("") && sa[3].equals("c"));
|
||||
}
|
||||
|
||||
public void testTokenizeToStringArrayWithNotTrimTokens() {
|
||||
String[] sa = StringUtils.tokenizeToStringArray("a,b ,c", ",", false, true);
|
||||
assertEquals(3, sa.length);
|
||||
assertTrue("components are correct",
|
||||
sa[0].equals("a") && sa[1].equals("b ") && sa[2].equals("c"));
|
||||
}
|
||||
|
||||
public void testCommaDelimitedListToStringArrayWithNullProducesEmptyArray() {
|
||||
String[] sa = StringUtils.commaDelimitedListToStringArray(null);
|
||||
assertTrue("String array isn't null with null input", sa != null);
|
||||
assertTrue("String array length == 0 with null input", sa.length == 0);
|
||||
}
|
||||
|
||||
public void testCommaDelimitedListToStringArrayWithEmptyStringProducesEmptyArray() {
|
||||
String[] sa = StringUtils.commaDelimitedListToStringArray("");
|
||||
assertTrue("String array isn't null with null input", sa != null);
|
||||
assertTrue("String array length == 0 with null input", sa.length == 0);
|
||||
}
|
||||
|
||||
private void testStringArrayReverseTransformationMatches(String[] sa) {
|
||||
String[] reverse =
|
||||
StringUtils.commaDelimitedListToStringArray(StringUtils.arrayToCommaDelimitedString(sa));
|
||||
assertEquals("Reverse transformation is equal",
|
||||
Arrays.asList(sa),
|
||||
Arrays.asList(reverse));
|
||||
}
|
||||
|
||||
public void testDelimitedListToStringArrayWithComma() {
|
||||
String[] sa = StringUtils.delimitedListToStringArray("a,b", ",");
|
||||
assertEquals(2, sa.length);
|
||||
assertEquals("a", sa[0]);
|
||||
assertEquals("b", sa[1]);
|
||||
}
|
||||
|
||||
public void testDelimitedListToStringArrayWithSemicolon() {
|
||||
String[] sa = StringUtils.delimitedListToStringArray("a;b", ";");
|
||||
assertEquals(2, sa.length);
|
||||
assertEquals("a", sa[0]);
|
||||
assertEquals("b", sa[1]);
|
||||
}
|
||||
|
||||
public void testDelimitedListToStringArrayWithEmptyString() {
|
||||
String[] sa = StringUtils.delimitedListToStringArray("a,b", "");
|
||||
assertEquals(3, sa.length);
|
||||
assertEquals("a", sa[0]);
|
||||
assertEquals(",", sa[1]);
|
||||
assertEquals("b", sa[2]);
|
||||
}
|
||||
|
||||
public void testDelimitedListToStringArrayWithNullDelimiter() {
|
||||
String[] sa = StringUtils.delimitedListToStringArray("a,b", null);
|
||||
assertEquals(1, sa.length);
|
||||
assertEquals("a,b", sa[0]);
|
||||
}
|
||||
|
||||
public void testCommaDelimitedListToStringArrayMatchWords() {
|
||||
// Could read these from files
|
||||
String[] sa = new String[] {"foo", "bar", "big"};
|
||||
doTestCommaDelimitedListToStringArrayLegalMatch(sa);
|
||||
testStringArrayReverseTransformationMatches(sa);
|
||||
|
||||
sa = new String[] {"a", "b", "c"};
|
||||
doTestCommaDelimitedListToStringArrayLegalMatch(sa);
|
||||
testStringArrayReverseTransformationMatches(sa);
|
||||
|
||||
// Test same words
|
||||
sa = new String[] {"AA", "AA", "AA", "AA", "AA"};
|
||||
doTestCommaDelimitedListToStringArrayLegalMatch(sa);
|
||||
testStringArrayReverseTransformationMatches(sa);
|
||||
}
|
||||
|
||||
public void testCommaDelimitedListToStringArraySingleString() {
|
||||
// Could read these from files
|
||||
String s = "woeirqupoiewuropqiewuorpqiwueopriquwopeiurqopwieur";
|
||||
String[] sa = StringUtils.commaDelimitedListToStringArray(s);
|
||||
assertTrue("Found one String with no delimiters", sa.length == 1);
|
||||
assertTrue("Single array entry matches input String with no delimiters",
|
||||
sa[0].equals(s));
|
||||
}
|
||||
|
||||
public void testCommaDelimitedListToStringArrayWithOtherPunctuation() {
|
||||
// Could read these from files
|
||||
String[] sa = new String[] {"xcvwert4456346&*.", "///", ".!", ".", ";"};
|
||||
doTestCommaDelimitedListToStringArrayLegalMatch(sa);
|
||||
}
|
||||
|
||||
/**
|
||||
* We expect to see the empty Strings in the output.
|
||||
*/
|
||||
public void testCommaDelimitedListToStringArrayEmptyStrings() {
|
||||
// Could read these from files
|
||||
String[] sa = StringUtils.commaDelimitedListToStringArray("a,,b");
|
||||
assertEquals("a,,b produces array length 3", 3, sa.length);
|
||||
assertTrue("components are correct",
|
||||
sa[0].equals("a") && sa[1].equals("") && sa[2].equals("b"));
|
||||
|
||||
sa = new String[] {"", "", "a", ""};
|
||||
doTestCommaDelimitedListToStringArrayLegalMatch(sa);
|
||||
}
|
||||
|
||||
private void doTestCommaDelimitedListToStringArrayLegalMatch(String[] components) {
|
||||
StringBuffer sbuf = new StringBuffer();
|
||||
for (int i = 0; i < components.length; i++) {
|
||||
if (i != 0) {
|
||||
sbuf.append(",");
|
||||
}
|
||||
sbuf.append(components[i]);
|
||||
}
|
||||
String[] sa = StringUtils.commaDelimitedListToStringArray(sbuf.toString());
|
||||
assertTrue("String array isn't null with legal match", sa != null);
|
||||
assertEquals("String array length is correct with legal match", components.length, sa.length);
|
||||
assertTrue("Output equals input", Arrays.equals(sa, components));
|
||||
}
|
||||
|
||||
public void testEndsWithIgnoreCase() {
|
||||
String suffix = "fOo";
|
||||
assertTrue(StringUtils.endsWithIgnoreCase("foo", suffix));
|
||||
assertTrue(StringUtils.endsWithIgnoreCase("Foo", suffix));
|
||||
assertTrue(StringUtils.endsWithIgnoreCase("barfoo", suffix));
|
||||
assertTrue(StringUtils.endsWithIgnoreCase("barbarfoo", suffix));
|
||||
assertTrue(StringUtils.endsWithIgnoreCase("barFoo", suffix));
|
||||
assertTrue(StringUtils.endsWithIgnoreCase("barBarFoo", suffix));
|
||||
assertTrue(StringUtils.endsWithIgnoreCase("barfoO", suffix));
|
||||
assertTrue(StringUtils.endsWithIgnoreCase("barFOO", suffix));
|
||||
assertTrue(StringUtils.endsWithIgnoreCase("barfOo", suffix));
|
||||
assertFalse(StringUtils.endsWithIgnoreCase(null, suffix));
|
||||
assertFalse(StringUtils.endsWithIgnoreCase("barfOo", null));
|
||||
assertFalse(StringUtils.endsWithIgnoreCase("b", suffix));
|
||||
}
|
||||
|
||||
public void testParseLocaleStringSunnyDay() throws Exception {
|
||||
Locale expectedLocale = Locale.UK;
|
||||
Locale locale = StringUtils.parseLocaleString(expectedLocale.toString());
|
||||
assertNotNull("When given a bona-fide Locale string, must not return null.", locale);
|
||||
assertEquals(expectedLocale, locale);
|
||||
}
|
||||
|
||||
public void testParseLocaleStringWithMalformedLocaleString() throws Exception {
|
||||
Locale locale = StringUtils.parseLocaleString("_banjo_on_my_knee");
|
||||
assertNotNull("When given a malformed Locale string, must not return null.", locale);
|
||||
}
|
||||
|
||||
public void testParseLocaleStringWithEmptyLocaleStringYieldsNullLocale() throws Exception {
|
||||
Locale locale = StringUtils.parseLocaleString("");
|
||||
assertNull("When given an empty Locale string, must return null.", locale);
|
||||
}
|
||||
|
||||
/**
|
||||
* <a href="http://opensource.atlassian.com/projects/spring/browse/SPR-3671">See SPR-3671</a>.
|
||||
*/
|
||||
public void testParseLocaleWithMultiValuedVariant() throws Exception {
|
||||
final String variant = "proper_northern";
|
||||
final String localeString = "en_GB_" + variant;
|
||||
Locale locale = StringUtils.parseLocaleString(localeString);
|
||||
assertEquals("Multi-valued variant portion of the Locale not extracted correctly.", variant, locale.getVariant());
|
||||
}
|
||||
|
||||
/**
|
||||
* <a href="http://opensource.atlassian.com/projects/spring/browse/SPR-3671">See SPR-3671</a>.
|
||||
*/
|
||||
public void testParseLocaleWithMultiValuedVariantUsingSpacesAsSeparators() throws Exception {
|
||||
final String variant = "proper northern";
|
||||
final String localeString = "en GB " + variant;
|
||||
Locale locale = StringUtils.parseLocaleString(localeString);
|
||||
assertEquals("Multi-valued variant portion of the Locale not extracted correctly.", variant, locale.getVariant());
|
||||
}
|
||||
|
||||
/**
|
||||
* <a href="http://opensource.atlassian.com/projects/spring/browse/SPR-3671">See SPR-3671</a>.
|
||||
*/
|
||||
public void testParseLocaleWithMultiValuedVariantUsingMixtureOfUnderscoresAndSpacesAsSeparators() throws Exception {
|
||||
final String variant = "proper northern";
|
||||
final String localeString = "en_GB_" + variant;
|
||||
Locale locale = StringUtils.parseLocaleString(localeString);
|
||||
assertEquals("Multi-valued variant portion of the Locale not extracted correctly.", variant, locale.getVariant());
|
||||
}
|
||||
|
||||
/**
|
||||
* <a href="http://opensource.atlassian.com/projects/spring/browse/SPR-3671">See SPR-3671</a>.
|
||||
*/
|
||||
public void testParseLocaleWithMultiValuedVariantUsingSpacesAsSeparatorsWithLotsOfLeadingWhitespace() throws Exception {
|
||||
final String variant = "proper northern";
|
||||
final String localeString = "en GB " + variant; // lots of whitespace
|
||||
Locale locale = StringUtils.parseLocaleString(localeString);
|
||||
assertEquals("Multi-valued variant portion of the Locale not extracted correctly.", variant, locale.getVariant());
|
||||
}
|
||||
|
||||
/**
|
||||
* <a href="http://opensource.atlassian.com/projects/spring/browse/SPR-3671">See SPR-3671</a>.
|
||||
*/
|
||||
public void testParseLocaleWithMultiValuedVariantUsingUnderscoresAsSeparatorsWithLotsOfLeadingWhitespace() throws Exception {
|
||||
final String variant = "proper_northern";
|
||||
final String localeString = "en_GB_____" + variant; // lots of underscores
|
||||
Locale locale = StringUtils.parseLocaleString(localeString);
|
||||
assertEquals("Multi-valued variant portion of the Locale not extracted correctly.", variant, locale.getVariant());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
log4j.rootCategory=DEBUG, mock
|
||||
log4j.appender.mock=org.springframework.util.MockLog4jAppender
|
||||
Reference in New Issue
Block a user