Make sure placement of curly braces is consistent

This commit is contained in:
Benedikt Ritter 2017-06-06 22:14:47 +02:00
parent 3a818ed6a8
commit 309b34f057
No known key found for this signature in database
GPG Key ID: 9DAADC1C9FCC82D0
24 changed files with 1291 additions and 1134 deletions

View File

@ -49,5 +49,8 @@ limitations under the License.
<module name="ModifierOrder"/> <module name="ModifierOrder"/>
<module name="RedundantModifier"/> <module name="RedundantModifier"/>
<module name="UpperEll" /> <module name="UpperEll" />
<module name="LeftCurly"/>
<module name="NeedBraces"/>
<module name="RightCurly"/>
</module> </module>
</module> </module>

View File

@ -805,7 +805,9 @@ public class ObjectUtils {
* @return the boolean v, unchanged * @return the boolean v, unchanged
* @since 3.2 * @since 3.2
*/ */
public static boolean CONST(final boolean v) { return v; } public static boolean CONST(final boolean v) {
return v;
}
/** /**
* This method returns the provided value unchanged. * This method returns the provided value unchanged.
@ -824,7 +826,9 @@ public class ObjectUtils {
* @return the byte v, unchanged * @return the byte v, unchanged
* @since 3.2 * @since 3.2
*/ */
public static byte CONST(final byte v) { return v; } public static byte CONST(final byte v) {
return v;
}
/** /**
* This method returns the provided value unchanged. * This method returns the provided value unchanged.
@ -870,7 +874,9 @@ public class ObjectUtils {
* @return the char v, unchanged * @return the char v, unchanged
* @since 3.2 * @since 3.2
*/ */
public static char CONST(final char v) { return v; } public static char CONST(final char v) {
return v;
}
/** /**
* This method returns the provided value unchanged. * This method returns the provided value unchanged.
@ -889,7 +895,9 @@ public class ObjectUtils {
* @return the short v, unchanged * @return the short v, unchanged
* @since 3.2 * @since 3.2
*/ */
public static short CONST(final short v) { return v; } public static short CONST(final short v) {
return v;
}
/** /**
* This method returns the provided value unchanged. * This method returns the provided value unchanged.
@ -936,7 +944,9 @@ public class ObjectUtils {
* @return the int v, unchanged * @return the int v, unchanged
* @since 3.2 * @since 3.2
*/ */
public static int CONST(final int v) { return v; } public static int CONST(final int v) {
return v;
}
/** /**
* This method returns the provided value unchanged. * This method returns the provided value unchanged.
@ -955,7 +965,9 @@ public class ObjectUtils {
* @return the long v, unchanged * @return the long v, unchanged
* @since 3.2 * @since 3.2
*/ */
public static long CONST(final long v) { return v; } public static long CONST(final long v) {
return v;
}
/** /**
* This method returns the provided value unchanged. * This method returns the provided value unchanged.
@ -974,7 +986,9 @@ public class ObjectUtils {
* @return the float v, unchanged * @return the float v, unchanged
* @since 3.2 * @since 3.2
*/ */
public static float CONST(final float v) { return v; } public static float CONST(final float v) {
return v;
}
/** /**
* This method returns the provided value unchanged. * This method returns the provided value unchanged.
@ -993,7 +1007,9 @@ public class ObjectUtils {
* @return the double v, unchanged * @return the double v, unchanged
* @since 3.2 * @since 3.2
*/ */
public static double CONST(final double v) { return v; } public static double CONST(final double v) {
return v;
}
/** /**
* This method returns the provided value unchanged. * This method returns the provided value unchanged.
@ -1013,6 +1029,8 @@ public class ObjectUtils {
* @return the genericized Object v, unchanged (typically a String). * @return the genericized Object v, unchanged (typically a String).
* @since 3.2 * @since 3.2
*/ */
public static <T> T CONST(final T v) { return v; } public static <T> T CONST(final T v) {
return v;
}
} }

View File

@ -8188,9 +8188,8 @@ public class StringUtils {
return m <= threshold ? m : -1; return m <= threshold ? m : -1;
} else if (m == 0) { } else if (m == 0) {
return n <= threshold ? n : -1; return n <= threshold ? n : -1;
} } else if (Math.abs(n - m) > threshold) {
// no need to calculate the distance if the length difference is greater than the threshold // no need to calculate the distance if the length difference is greater than the threshold
else if (Math.abs(n - m) > threshold) {
return -1; return -1;
} }

View File

@ -627,13 +627,12 @@ public class EqualsBuilder implements Builder<Boolean> {
* @param rhs the right hand object * @param rhs the right hand object
*/ */
private void appendArray(final Object lhs, final Object rhs) { private void appendArray(final Object lhs, final Object rhs) {
if (lhs.getClass() != rhs.getClass()) { // First we compare different dimensions, for example: a boolean[][] to a boolean[]
// Here when we compare different dimensions, for example: a boolean[][] to a boolean[] // then we 'Switch' on type of array, to dispatch to the correct handler
this.setEquals(false);
}
// 'Switch' on type of array, to dispatch to the correct handler
// This handles multi dimensional arrays of the same depth // This handles multi dimensional arrays of the same depth
else if (lhs instanceof long[]) { if (lhs.getClass() != rhs.getClass()) {
this.setEquals(false);
} else if (lhs instanceof long[]) {
append((long[]) lhs, (long[]) rhs); append((long[]) lhs, (long[]) rhs);
} else if (lhs instanceof int[]) { } else if (lhs instanceof int[]) {
append((int[]) lhs, (int[]) rhs); append((int[]) lhs, (int[]) rhs);

View File

@ -169,12 +169,10 @@ abstract class MemberUtils {
if (noVarArgsPassed) { if (noVarArgsPassed) {
// When no varargs passed, the best match is the most generic matching type, not the most specific. // When no varargs passed, the best match is the most generic matching type, not the most specific.
totalCost += getObjectTransformationCost(destClass, Object.class) + varArgsCost; totalCost += getObjectTransformationCost(destClass, Object.class) + varArgsCost;
} } else if (explicitArrayForVarags) {
else if (explicitArrayForVarags) {
final Class<?> sourceClass = srcArgs[srcArgs.length-1].getComponentType(); final Class<?> sourceClass = srcArgs[srcArgs.length-1].getComponentType();
totalCost += getObjectTransformationCost(sourceClass, destClass) + varArgsCost; totalCost += getObjectTransformationCost(sourceClass, destClass) + varArgsCost;
} } else {
else {
// This is typical varargs case. // This is typical varargs case.
for (int i = destArgs.length-1; i < srcArgs.length; i++) { for (int i = destArgs.length-1; i < srcArgs.length; i++) {
final Class<?> srcClass = srcArgs[i]; final Class<?> srcClass = srcArgs[i];
@ -283,8 +281,13 @@ abstract class MemberUtils {
private final Class<?>[] parameterTypes; private final Class<?>[] parameterTypes;
private final boolean isVarArgs; private final boolean isVarArgs;
private static Executable of(final Method method) { return new Executable(method); } private static Executable of(final Method method) {
private static Executable of(final Constructor<?> constructor) { return new Executable(constructor); } return new Executable(method);
}
private static Executable of(final Constructor<?> constructor) {
return new Executable(constructor);
}
private Executable(final Method method) { private Executable(final Method method) {
parameterTypes = method.getParameterTypes(); parameterTypes = method.getParameterTypes();
@ -296,9 +299,13 @@ abstract class MemberUtils {
isVarArgs = constructor.isVarArgs(); isVarArgs = constructor.isVarArgs();
} }
public Class<?>[] getParameterTypes() { return parameterTypes; } public Class<?>[] getParameterTypes() {
return parameterTypes;
}
public boolean isVarArgs() { return isVarArgs; } public boolean isVarArgs() {
return isVarArgs;
}
} }
} }

View File

@ -34,7 +34,10 @@ public class EntityArrays {
* characters to their named HTML 3.x equivalents. * characters to their named HTML 3.x equivalents.
* @return the mapping table * @return the mapping table
*/ */
public static String[][] ISO8859_1_ESCAPE() { return ISO8859_1_ESCAPE.clone(); } public static String[][] ISO8859_1_ESCAPE() {
return ISO8859_1_ESCAPE.clone();
}
private static final String[][] ISO8859_1_ESCAPE = { private static final String[][] ISO8859_1_ESCAPE = {
{"\u00A0", "&nbsp;"}, // non-breaking space {"\u00A0", "&nbsp;"}, // non-breaking space
{"\u00A1", "&iexcl;"}, // inverted exclamation mark {"\u00A1", "&iexcl;"}, // inverted exclamation mark
@ -138,7 +141,10 @@ public class EntityArrays {
* Reverse of {@link #ISO8859_1_ESCAPE()} for unescaping purposes. * Reverse of {@link #ISO8859_1_ESCAPE()} for unescaping purposes.
* @return the mapping table * @return the mapping table
*/ */
public static String[][] ISO8859_1_UNESCAPE() { return ISO8859_1_UNESCAPE.clone(); } public static String[][] ISO8859_1_UNESCAPE() {
return ISO8859_1_UNESCAPE.clone();
}
private static final String[][] ISO8859_1_UNESCAPE = invert(ISO8859_1_ESCAPE); private static final String[][] ISO8859_1_UNESCAPE = invert(ISO8859_1_ESCAPE);
/** /**
@ -147,7 +153,10 @@ public class EntityArrays {
* HTML 4.0 character entities. * HTML 4.0 character entities.
* @return the mapping table * @return the mapping table
*/ */
public static String[][] HTML40_EXTENDED_ESCAPE() { return HTML40_EXTENDED_ESCAPE.clone(); } public static String[][] HTML40_EXTENDED_ESCAPE() {
return HTML40_EXTENDED_ESCAPE.clone();
}
private static final String[][] HTML40_EXTENDED_ESCAPE = { private static final String[][] HTML40_EXTENDED_ESCAPE = {
// <!-- Latin Extended-B --> // <!-- Latin Extended-B -->
{"\u0192", "&fnof;"}, // latin small f with hook = function= florin, U+0192 ISOtech --> {"\u0192", "&fnof;"}, // latin small f with hook = function= florin, U+0192 ISOtech -->
@ -349,7 +358,10 @@ public class EntityArrays {
* Reverse of {@link #HTML40_EXTENDED_ESCAPE()} for unescaping purposes. * Reverse of {@link #HTML40_EXTENDED_ESCAPE()} for unescaping purposes.
* @return the mapping table * @return the mapping table
*/ */
public static String[][] HTML40_EXTENDED_UNESCAPE() { return HTML40_EXTENDED_UNESCAPE.clone(); } public static String[][] HTML40_EXTENDED_UNESCAPE() {
return HTML40_EXTENDED_UNESCAPE.clone();
}
private static final String[][] HTML40_EXTENDED_UNESCAPE = invert(HTML40_EXTENDED_ESCAPE); private static final String[][] HTML40_EXTENDED_UNESCAPE = invert(HTML40_EXTENDED_ESCAPE);
/** /**
@ -358,7 +370,10 @@ public class EntityArrays {
* Namely: {@code " & < >} * Namely: {@code " & < >}
* @return the mapping table * @return the mapping table
*/ */
public static String[][] BASIC_ESCAPE() { return BASIC_ESCAPE.clone(); } public static String[][] BASIC_ESCAPE() {
return BASIC_ESCAPE.clone();
}
private static final String[][] BASIC_ESCAPE = { private static final String[][] BASIC_ESCAPE = {
{"\"", "&quot;"}, // " - double-quote {"\"", "&quot;"}, // " - double-quote
{"&", "&amp;"}, // & - ampersand {"&", "&amp;"}, // & - ampersand
@ -370,14 +385,20 @@ public class EntityArrays {
* Reverse of {@link #BASIC_ESCAPE()} for unescaping purposes. * Reverse of {@link #BASIC_ESCAPE()} for unescaping purposes.
* @return the mapping table * @return the mapping table
*/ */
public static String[][] BASIC_UNESCAPE() { return BASIC_UNESCAPE.clone(); } public static String[][] BASIC_UNESCAPE() {
return BASIC_UNESCAPE.clone();
}
private static final String[][] BASIC_UNESCAPE = invert(BASIC_ESCAPE); private static final String[][] BASIC_UNESCAPE = invert(BASIC_ESCAPE);
/** /**
* Mapping to escape the apostrophe character to its XML character entity. * Mapping to escape the apostrophe character to its XML character entity.
* @return the mapping table * @return the mapping table
*/ */
public static String[][] APOS_ESCAPE() { return APOS_ESCAPE.clone(); } public static String[][] APOS_ESCAPE() {
return APOS_ESCAPE.clone();
}
private static final String[][] APOS_ESCAPE = { private static final String[][] APOS_ESCAPE = {
{"'", "&apos;"}, // XML apostrophe {"'", "&apos;"}, // XML apostrophe
}; };
@ -386,7 +407,10 @@ public class EntityArrays {
* Reverse of {@link #APOS_ESCAPE()} for unescaping purposes. * Reverse of {@link #APOS_ESCAPE()} for unescaping purposes.
* @return the mapping table * @return the mapping table
*/ */
public static String[][] APOS_UNESCAPE() { return APOS_UNESCAPE.clone(); } public static String[][] APOS_UNESCAPE() {
return APOS_UNESCAPE.clone();
}
private static final String[][] APOS_UNESCAPE = invert(APOS_ESCAPE); private static final String[][] APOS_UNESCAPE = invert(APOS_ESCAPE);
/** /**
@ -395,7 +419,10 @@ public class EntityArrays {
* Namely: {@code \b \n \t \f \r} * Namely: {@code \b \n \t \f \r}
* @return the mapping table * @return the mapping table
*/ */
public static String[][] JAVA_CTRL_CHARS_ESCAPE() { return JAVA_CTRL_CHARS_ESCAPE.clone(); } public static String[][] JAVA_CTRL_CHARS_ESCAPE() {
return JAVA_CTRL_CHARS_ESCAPE.clone();
}
private static final String[][] JAVA_CTRL_CHARS_ESCAPE = { private static final String[][] JAVA_CTRL_CHARS_ESCAPE = {
{"\b", "\\b"}, {"\b", "\\b"},
{"\n", "\\n"}, {"\n", "\\n"},
@ -408,7 +435,10 @@ public class EntityArrays {
* Reverse of {@link #JAVA_CTRL_CHARS_ESCAPE()} for unescaping purposes. * Reverse of {@link #JAVA_CTRL_CHARS_ESCAPE()} for unescaping purposes.
* @return the mapping table * @return the mapping table
*/ */
public static String[][] JAVA_CTRL_CHARS_UNESCAPE() { return JAVA_CTRL_CHARS_UNESCAPE.clone(); } public static String[][] JAVA_CTRL_CHARS_UNESCAPE() {
return JAVA_CTRL_CHARS_UNESCAPE.clone();
}
private static final String[][] JAVA_CTRL_CHARS_UNESCAPE = invert(JAVA_CTRL_CHARS_ESCAPE); private static final String[][] JAVA_CTRL_CHARS_UNESCAPE = invert(JAVA_CTRL_CHARS_ESCAPE);
/** /**

View File

@ -100,8 +100,7 @@ public class NumericEntityUnescaper extends CharSequenceTranslator {
// Note that this supports character codes without a ; on the end // Note that this supports character codes without a ; on the end
while(end < seqEnd && ( input.charAt(end) >= '0' && input.charAt(end) <= '9' || while(end < seqEnd && ( input.charAt(end) >= '0' && input.charAt(end) <= '9' ||
input.charAt(end) >= 'a' && input.charAt(end) <= 'f' || input.charAt(end) >= 'a' && input.charAt(end) <= 'f' ||
input.charAt(end) >= 'A' && input.charAt(end) <= 'F' ) ) input.charAt(end) >= 'A' && input.charAt(end) <= 'F' ) ) {
{
end++; end++;
} }

View File

@ -380,8 +380,7 @@ public class DateUtils {
if (fdp.parse(str, pos, calendar) && pos.getIndex()==str.length()) { if (fdp.parse(str, pos, calendar) && pos.getIndex()==str.length()) {
return calendar.getTime(); return calendar.getTime();
} }
} } catch(final IllegalArgumentException ignore) {
catch(final IllegalArgumentException ignore) {
// leniency is preventing calendar from being set // leniency is preventing calendar from being set
} }
pos.setIndex(0); pos.setIndex(0);

View File

@ -138,11 +138,9 @@ public class FastDateParser implements DateParser, Serializable {
if(centuryStart!=null) { if(centuryStart!=null) {
definingCalendar.setTime(centuryStart); definingCalendar.setTime(centuryStart);
centuryStartYear= definingCalendar.get(Calendar.YEAR); centuryStartYear= definingCalendar.get(Calendar.YEAR);
} } else if(locale.equals(JAPANESE_IMPERIAL)) {
else if(locale.equals(JAPANESE_IMPERIAL)) {
centuryStartYear= 0; centuryStartYear= 0;
} } else {
else {
// from 80 years ago to 20 years from now // from 80 years ago to 20 years from now
definingCalendar.setTime(new Date()); definingCalendar.setTime(new Date());
centuryStartYear= definingCalendar.get(Calendar.YEAR)-80; centuryStartYear= definingCalendar.get(Calendar.YEAR)-80;

View File

@ -196,11 +196,9 @@ abstract class FormatCache<F extends Format> {
DateFormat formatter; DateFormat formatter;
if (dateStyle == null) { if (dateStyle == null) {
formatter = DateFormat.getTimeInstance(timeStyle.intValue(), locale); formatter = DateFormat.getTimeInstance(timeStyle.intValue(), locale);
} } else if (timeStyle == null) {
else if (timeStyle == null) {
formatter = DateFormat.getDateInstance(dateStyle.intValue(), locale); formatter = DateFormat.getDateInstance(dateStyle.intValue(), locale);
} } else {
else {
formatter = DateFormat.getDateTimeInstance(dateStyle.intValue(), timeStyle.intValue(), locale); formatter = DateFormat.getDateTimeInstance(dateStyle.intValue(), timeStyle.intValue(), locale);
} }
pattern = ((SimpleDateFormat)formatter).toPattern(); pattern = ((SimpleDateFormat)formatter).toPattern();

View File

@ -80,24 +80,60 @@ public class StopWatch {
private enum State { private enum State {
UNSTARTED { UNSTARTED {
@Override boolean isStarted() { return false; } @Override
@Override boolean isStopped() { return true; } boolean isStarted() {
@Override boolean isSuspended() { return false; } return false;
}
@Override
boolean isStopped() {
return true;
}
@Override
boolean isSuspended() {
return false;
}
}, },
RUNNING { RUNNING {
@Override boolean isStarted() { return true; } @Override
@Override boolean isStopped() { return false; } boolean isStarted() {
@Override boolean isSuspended() { return false; } return true;
}
@Override
boolean isStopped() {
return false;
}
@Override
boolean isSuspended() {
return false;
}
}, },
STOPPED { STOPPED {
@Override boolean isStarted() { return false; } @Override
@Override boolean isStopped() { return true; } boolean isStarted() {
@Override boolean isSuspended() { return false; } return false;
}
@Override
boolean isStopped() {
return true;
}
@Override
boolean isSuspended() {
return false;
}
}, },
SUSPENDED { SUSPENDED {
@Override boolean isStarted() { return true; } @Override
@Override boolean isStopped() { return false; } boolean isStarted() {
@Override boolean isSuspended() { return true; } return true;
}
@Override
boolean isStopped() {
return false;
}
@Override
boolean isSuspended() {
return true;
}
}; };
/** /**

File diff suppressed because it is too large Load Diff

View File

@ -1076,8 +1076,7 @@ public class ClassUtilsTest {
try { try {
ClassUtils.getClass( className ); ClassUtils.getClass( className );
fail( "ClassUtils.getClass() should fail with an exception of type " + exceptionType.getName() + " when given class name \"" + className + "\"." ); fail( "ClassUtils.getClass() should fail with an exception of type " + exceptionType.getName() + " when given class name \"" + className + "\"." );
} } catch( final Exception e ) {
catch( final Exception e ) {
assertTrue( exceptionType.isAssignableFrom( e.getClass() ) ); assertTrue( exceptionType.isAssignableFrom( e.getClass() ) );
} }
} }

View File

@ -179,8 +179,7 @@ public class SerializationUtilsTest {
}; };
try { try {
SerializationUtils.serialize(iMap, streamTest); SerializationUtils.serialize(iMap, streamTest);
} } catch(final SerializationException e) {
catch(final SerializationException e) {
assertEquals("java.io.IOException: " + SERIALIZE_IO_EXCEPTION_MESSAGE, e.getMessage()); assertEquals("java.io.IOException: " + SERIALIZE_IO_EXCEPTION_MESSAGE, e.getMessage());
} }
} }
@ -422,8 +421,7 @@ public class SerializationUtilsTest {
} }
class ClassNotFoundSerialization implements Serializable class ClassNotFoundSerialization implements Serializable {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;

View File

@ -40,7 +40,7 @@ import org.junit.Test;
/** /**
* Unit tests {@link org.apache.commons.lang3.Validate}. * Unit tests {@link org.apache.commons.lang3.Validate}.
*/ */
public class ValidateTest { public class ValidateTest {
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
@Test @Test
@ -141,7 +141,7 @@ public class ValidateTest {
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
@Test @Test
public void testNotEmptyArray1() { public void testNotEmptyArray1() {
Validate.notEmpty(new Object[] {null}); Validate.notEmpty(new Object[]{null});
try { try {
Validate.notEmpty((Object[]) null); Validate.notEmpty((Object[]) null);
fail("Expecting NullPointerException"); fail("Expecting NullPointerException");
@ -155,7 +155,7 @@ public class ValidateTest {
assertEquals("The validated array is empty", ex.getMessage()); assertEquals("The validated array is empty", ex.getMessage());
} }
final String[] array = new String[] {"hi"}; final String[] array = new String[]{"hi"};
final String[] test = Validate.notEmpty(array); final String[] test = Validate.notEmpty(array);
assertSame(array, test); assertSame(array, test);
} }
@ -163,7 +163,7 @@ public class ValidateTest {
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
@Test @Test
public void testNotEmptyArray2() { public void testNotEmptyArray2() {
Validate.notEmpty(new Object[] {null}, "MSG"); Validate.notEmpty(new Object[]{null}, "MSG");
try { try {
Validate.notEmpty((Object[]) null, "MSG"); Validate.notEmpty((Object[]) null, "MSG");
fail("Expecting NullPointerException"); fail("Expecting NullPointerException");
@ -177,7 +177,7 @@ public class ValidateTest {
assertEquals("MSG", ex.getMessage()); assertEquals("MSG", ex.getMessage());
} }
final String[] array = new String[] {"hi"}; final String[] array = new String[]{"hi"};
final String[] test = Validate.notEmpty(array, "Message"); final String[] test = Validate.notEmpty(array, "Message");
assertSame(array, test); assertSame(array, test);
} }
@ -541,7 +541,7 @@ public class ValidateTest {
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
@Test @Test
public void testNoNullElementsArray1() { public void testNoNullElementsArray1() {
String[] array = new String[] {"a", "b"}; String[] array = new String[]{"a", "b"};
Validate.noNullElements(array); Validate.noNullElements(array);
try { try {
Validate.noNullElements((Object[]) null); Validate.noNullElements((Object[]) null);
@ -557,7 +557,7 @@ public class ValidateTest {
assertEquals("The validated array contains null element at index: 1", ex.getMessage()); assertEquals("The validated array contains null element at index: 1", ex.getMessage());
} }
array = new String[] {"a", "b"}; array = new String[]{"a", "b"};
final String[] test = Validate.noNullElements(array); final String[] test = Validate.noNullElements(array);
assertSame(array, test); assertSame(array, test);
} }
@ -565,7 +565,7 @@ public class ValidateTest {
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
@Test @Test
public void testNoNullElementsArray2() { public void testNoNullElementsArray2() {
String[] array = new String[] {"a", "b"}; String[] array = new String[]{"a", "b"};
Validate.noNullElements(array, "MSG"); Validate.noNullElements(array, "MSG");
try { try {
Validate.noNullElements((Object[]) null, "MSG"); Validate.noNullElements((Object[]) null, "MSG");
@ -581,7 +581,7 @@ public class ValidateTest {
assertEquals("MSG", ex.getMessage()); assertEquals("MSG", ex.getMessage());
} }
array = new String[] {"a", "b"}; array = new String[]{"a", "b"};
final String[] test = Validate.noNullElements(array, "Message"); final String[] test = Validate.noNullElements(array, "Message");
assertSame(array, test); assertSame(array, test);
} }
@ -671,7 +671,7 @@ public class ValidateTest {
assertEquals("Broken: ", ex.getMessage()); assertEquals("Broken: ", ex.getMessage());
} }
final String[] strArray = new String[] {"Hi"}; final String[] strArray = new String[]{"Hi"};
final String[] test = Validate.noNullElements(strArray, "Message"); final String[] test = Validate.noNullElements(strArray, "Message");
assertSame(strArray, test); assertSame(strArray, test);
} }
@ -694,7 +694,7 @@ public class ValidateTest {
assertEquals("The validated array index is invalid: 2", ex.getMessage()); assertEquals("The validated array index is invalid: 2", ex.getMessage());
} }
final String[] strArray = new String[] {"Hi"}; final String[] strArray = new String[]{"Hi"};
final String[] test = Validate.noNullElements(strArray); final String[] test = Validate.noNullElements(strArray);
assertSame(strArray, test); assertSame(strArray, test);
} }
@ -800,33 +800,25 @@ public class ValidateTest {
} }
@Test @Test
public void testMatchesPattern() public void testMatchesPattern() {
{
final CharSequence str = "hi"; final CharSequence str = "hi";
Validate.matchesPattern(str, "[a-z]*"); Validate.matchesPattern(str, "[a-z]*");
try try {
{
Validate.matchesPattern(str, "[0-9]*"); Validate.matchesPattern(str, "[0-9]*");
fail("Expecting IllegalArgumentException"); fail("Expecting IllegalArgumentException");
} } catch (final IllegalArgumentException e) {
catch (final IllegalArgumentException e)
{
assertEquals("The string hi does not match the pattern [0-9]*", e.getMessage()); assertEquals("The string hi does not match the pattern [0-9]*", e.getMessage());
} }
} }
@Test @Test
public void testMatchesPattern_withMessage() public void testMatchesPattern_withMessage() {
{
final CharSequence str = "hi"; final CharSequence str = "hi";
Validate.matchesPattern(str, "[a-z]*", "Does not match"); Validate.matchesPattern(str, "[a-z]*", "Does not match");
try try {
{
Validate.matchesPattern(str, "[0-9]*", "Does not match"); Validate.matchesPattern(str, "[0-9]*", "Does not match");
fail("Expecting IllegalArgumentException"); fail("Expecting IllegalArgumentException");
} } catch (final IllegalArgumentException e) {
catch (final IllegalArgumentException e)
{
assertEquals("Does not match", e.getMessage()); assertEquals("Does not match", e.getMessage());
} }
} }
@ -913,8 +905,7 @@ public class ValidateTest {
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
@Test @Test
public void testInclusiveBetween() public void testInclusiveBetween() {
{
Validate.inclusiveBetween("a", "c", "b"); Validate.inclusiveBetween("a", "c", "b");
try { try {
Validate.inclusiveBetween("0", "5", "6"); Validate.inclusiveBetween("0", "5", "6");
@ -925,8 +916,7 @@ public class ValidateTest {
} }
@Test @Test
public void testInclusiveBetween_withMessage() public void testInclusiveBetween_withMessage() {
{
Validate.inclusiveBetween("a", "c", "b", "Error"); Validate.inclusiveBetween("a", "c", "b", "Error");
try { try {
Validate.inclusiveBetween("0", "5", "6", "Error"); Validate.inclusiveBetween("0", "5", "6", "Error");
@ -937,8 +927,7 @@ public class ValidateTest {
} }
@Test @Test
public void testInclusiveBetweenLong() public void testInclusiveBetweenLong() {
{
Validate.inclusiveBetween(0, 2, 1); Validate.inclusiveBetween(0, 2, 1);
Validate.inclusiveBetween(0, 2, 2); Validate.inclusiveBetween(0, 2, 2);
try { try {
@ -950,8 +939,7 @@ public class ValidateTest {
} }
@Test @Test
public void testInclusiveBetweenLong_withMessage() public void testInclusiveBetweenLong_withMessage() {
{
Validate.inclusiveBetween(0, 2, 1, "Error"); Validate.inclusiveBetween(0, 2, 1, "Error");
Validate.inclusiveBetween(0, 2, 2, "Error"); Validate.inclusiveBetween(0, 2, 2, "Error");
try { try {
@ -963,8 +951,7 @@ public class ValidateTest {
} }
@Test @Test
public void testInclusiveBetweenDouble() public void testInclusiveBetweenDouble() {
{
Validate.inclusiveBetween(0.1, 2.1, 1.1); Validate.inclusiveBetween(0.1, 2.1, 1.1);
Validate.inclusiveBetween(0.1, 2.1, 2.1); Validate.inclusiveBetween(0.1, 2.1, 2.1);
try { try {
@ -976,8 +963,7 @@ public class ValidateTest {
} }
@Test @Test
public void testInclusiveBetweenDouble_withMessage() public void testInclusiveBetweenDouble_withMessage() {
{
Validate.inclusiveBetween(0.1, 2.1, 1.1, "Error"); Validate.inclusiveBetween(0.1, 2.1, 1.1, "Error");
Validate.inclusiveBetween(0.1, 2.1, 2.1, "Error"); Validate.inclusiveBetween(0.1, 2.1, 2.1, "Error");
try { try {
@ -989,8 +975,7 @@ public class ValidateTest {
} }
@Test @Test
public void testExclusiveBetween() public void testExclusiveBetween() {
{
Validate.exclusiveBetween("a", "c", "b"); Validate.exclusiveBetween("a", "c", "b");
try { try {
Validate.exclusiveBetween("0", "5", "6"); Validate.exclusiveBetween("0", "5", "6");
@ -1007,8 +992,7 @@ public class ValidateTest {
} }
@Test @Test
public void testExclusiveBetween_withMessage() public void testExclusiveBetween_withMessage() {
{
Validate.exclusiveBetween("a", "c", "b", "Error"); Validate.exclusiveBetween("a", "c", "b", "Error");
try { try {
Validate.exclusiveBetween("0", "5", "6", "Error"); Validate.exclusiveBetween("0", "5", "6", "Error");
@ -1025,8 +1009,7 @@ public class ValidateTest {
} }
@Test @Test
public void testExclusiveBetweenLong() public void testExclusiveBetweenLong() {
{
Validate.exclusiveBetween(0, 2, 1); Validate.exclusiveBetween(0, 2, 1);
try { try {
Validate.exclusiveBetween(0, 5, 6); Validate.exclusiveBetween(0, 5, 6);
@ -1043,8 +1026,7 @@ public class ValidateTest {
} }
@Test @Test
public void testExclusiveBetweenLong_withMessage() public void testExclusiveBetweenLong_withMessage() {
{
Validate.exclusiveBetween(0, 2, 1, "Error"); Validate.exclusiveBetween(0, 2, 1, "Error");
try { try {
Validate.exclusiveBetween(0, 5, 6, "Error"); Validate.exclusiveBetween(0, 5, 6, "Error");
@ -1061,8 +1043,7 @@ public class ValidateTest {
} }
@Test @Test
public void testExclusiveBetweenDouble() public void testExclusiveBetweenDouble() {
{
Validate.exclusiveBetween(0.1, 2.1, 1.1); Validate.exclusiveBetween(0.1, 2.1, 1.1);
try { try {
Validate.exclusiveBetween(0.1, 5.1, 6.1); Validate.exclusiveBetween(0.1, 5.1, 6.1);
@ -1079,8 +1060,7 @@ public class ValidateTest {
} }
@Test @Test
public void testExclusiveBetweenDouble_withMessage() public void testExclusiveBetweenDouble_withMessage() {
{
Validate.exclusiveBetween(0.1, 2.1, 1.1, "Error"); Validate.exclusiveBetween(0.1, 2.1, 1.1, "Error");
try { try {
Validate.exclusiveBetween(0.1, 5.1, 6.1, "Error"); Validate.exclusiveBetween(0.1, 5.1, 6.1, "Error");
@ -1107,7 +1087,7 @@ public class ValidateTest {
try { try {
Validate.isInstanceOf(List.class, "hi"); Validate.isInstanceOf(List.class, "hi");
fail("Expecting IllegalArgumentException"); fail("Expecting IllegalArgumentException");
} catch(final IllegalArgumentException e) { } catch (final IllegalArgumentException e) {
assertEquals("Expected type: java.util.List, actual: java.lang.String", e.getMessage()); assertEquals("Expected type: java.util.List, actual: java.lang.String", e.getMessage());
} }
} }
@ -1119,7 +1099,7 @@ public class ValidateTest {
try { try {
Validate.isInstanceOf(List.class, "hi", "Error"); Validate.isInstanceOf(List.class, "hi", "Error");
fail("Expecting IllegalArgumentException"); fail("Expecting IllegalArgumentException");
} catch(final IllegalArgumentException e) { } catch (final IllegalArgumentException e) {
assertEquals("Error", e.getMessage()); assertEquals("Error", e.getMessage());
} }
} }
@ -1131,19 +1111,19 @@ public class ValidateTest {
try { try {
Validate.isInstanceOf(List.class, "hi", "Error %s=%s", "Name", "Value"); Validate.isInstanceOf(List.class, "hi", "Error %s=%s", "Name", "Value");
fail("Expecting IllegalArgumentException"); fail("Expecting IllegalArgumentException");
} catch(final IllegalArgumentException e) { } catch (final IllegalArgumentException e) {
assertEquals("Error Name=Value", e.getMessage()); assertEquals("Error Name=Value", e.getMessage());
} }
try { try {
Validate.isInstanceOf(List.class, "hi", "Error %s=%s", List.class, "Value"); Validate.isInstanceOf(List.class, "hi", "Error %s=%s", List.class, "Value");
fail("Expecting IllegalArgumentException"); fail("Expecting IllegalArgumentException");
} catch(final IllegalArgumentException e) { } catch (final IllegalArgumentException e) {
assertEquals("Error interface java.util.List=Value", e.getMessage()); assertEquals("Error interface java.util.List=Value", e.getMessage());
} }
try { try {
Validate.isInstanceOf(List.class, "hi", "Error %s=%s", List.class, null); Validate.isInstanceOf(List.class, "hi", "Error %s=%s", List.class, null);
fail("Expecting IllegalArgumentException"); fail("Expecting IllegalArgumentException");
} catch(final IllegalArgumentException e) { } catch (final IllegalArgumentException e) {
assertEquals("Error interface java.util.List=null", e.getMessage()); assertEquals("Error interface java.util.List=null", e.getMessage());
} }
} }
@ -1159,7 +1139,7 @@ public class ValidateTest {
try { try {
Validate.isAssignableFrom(List.class, String.class); Validate.isAssignableFrom(List.class, String.class);
fail("Expecting IllegalArgumentException"); fail("Expecting IllegalArgumentException");
} catch(final IllegalArgumentException e) { } catch (final IllegalArgumentException e) {
assertEquals("Cannot assign a java.lang.String to a java.util.List", e.getMessage()); assertEquals("Cannot assign a java.lang.String to a java.util.List", e.getMessage());
} }
} }
@ -1171,7 +1151,7 @@ public class ValidateTest {
try { try {
Validate.isAssignableFrom(List.class, String.class, "Error"); Validate.isAssignableFrom(List.class, String.class, "Error");
fail("Expecting IllegalArgumentException"); fail("Expecting IllegalArgumentException");
} catch(final IllegalArgumentException e) { } catch (final IllegalArgumentException e) {
assertEquals("Error", e.getMessage()); assertEquals("Error", e.getMessage());
} }
} }

View File

@ -34,15 +34,22 @@ public class EqualsBuilderTest {
static class TestObject { static class TestObject {
private int a; private int a;
TestObject() { TestObject() {
} }
TestObject(final int a) { TestObject(final int a) {
this.a = a; this.a = a;
} }
@Override @Override
public boolean equals(final Object o) { public boolean equals(final Object o) {
if (o == null) { return false; } if (o == null) {
if (o == this) { return true; } return false;
}
if (o == this) {
return true;
}
if (o.getClass() != getClass()) { if (o.getClass() != getClass()) {
return false; return false;
} }
@ -67,17 +74,24 @@ public class EqualsBuilderTest {
static class TestSubObject extends TestObject { static class TestSubObject extends TestObject {
private int b; private int b;
TestSubObject() { TestSubObject() {
super(0); super(0);
} }
TestSubObject(final int a, final int b) { TestSubObject(final int a, final int b) {
super(a); super(a);
this.b = b; this.b = b;
} }
@Override @Override
public boolean equals(final Object o) { public boolean equals(final Object o) {
if (o == null) { return false; } if (o == null) {
if (o == this) { return true; } return false;
}
if (o == this) {
return true;
}
if (o.getClass() != getClass()) { if (o.getClass() != getClass()) {
return false; return false;
} }
@ -88,7 +102,7 @@ public class EqualsBuilderTest {
@Override @Override
public int hashCode() { public int hashCode() {
return b *17 + super.hashCode(); return b * 17 + super.hashCode();
} }
public void setB(final int b) { public void setB(final int b) {
@ -109,6 +123,7 @@ public class EqualsBuilderTest {
static class TestTSubObject extends TestObject { static class TestTSubObject extends TestObject {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private transient int t; private transient int t;
TestTSubObject(final int a, final int t) { TestTSubObject(final int a, final int t) {
super(a); super(a);
this.t = t; this.t = t;
@ -118,6 +133,7 @@ public class EqualsBuilderTest {
static class TestTTSubObject extends TestTSubObject { static class TestTTSubObject extends TestTSubObject {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private transient int tt; private transient int tt;
TestTTSubObject(final int a, final int t, final int tt) { TestTTSubObject(final int a, final int t, final int tt) {
super(a, t); super(a, t);
this.tt = tt; this.tt = tt;
@ -127,6 +143,7 @@ public class EqualsBuilderTest {
static class TestTTLeafObject extends TestTTSubObject { static class TestTTLeafObject extends TestTTSubObject {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final int leafValue; private final int leafValue;
TestTTLeafObject(final int a, final int t, final int tt, final int leafValue) { TestTTLeafObject(final int a, final int t, final int tt, final int leafValue) {
super(a, t, tt); super(a, t, tt);
this.leafValue = leafValue; this.leafValue = leafValue;
@ -135,12 +152,15 @@ public class EqualsBuilderTest {
static class TestTSubObject2 extends TestObject { static class TestTSubObject2 extends TestObject {
private transient int t; private transient int t;
TestTSubObject2(final int a, final int t) { TestTSubObject2(final int a, final int t) {
super(a); super(a);
} }
public int getT() { public int getT() {
return t; return t;
} }
public void setT(final int t) { public void setT(final int t) {
this.t = t; this.t = t;
} }
@ -152,7 +172,7 @@ public class EqualsBuilderTest {
private int z; private int z;
TestRecursiveObject(final TestRecursiveInnerObject a, TestRecursiveObject(final TestRecursiveInnerObject a,
final TestRecursiveInnerObject b, final int z) { final TestRecursiveInnerObject b, final int z) {
this.a = a; this.a = a;
this.b = b; this.b = b;
} }
@ -173,6 +193,7 @@ public class EqualsBuilderTest {
static class TestRecursiveInnerObject { static class TestRecursiveInnerObject {
private final int n; private final int n;
TestRecursiveInnerObject(final int n) { TestRecursiveInnerObject(final int n) {
this.n = n; this.n = n;
} }
@ -185,6 +206,7 @@ public class EqualsBuilderTest {
static class TestRecursiveCycleObject { static class TestRecursiveCycleObject {
private TestRecursiveCycleObject cycle; private TestRecursiveCycleObject cycle;
private final int n; private final int n;
TestRecursiveCycleObject(final int n) { TestRecursiveCycleObject(final int n) {
this.n = n; this.n = n;
this.cycle = this; this.cycle = this;
@ -301,20 +323,21 @@ public class EqualsBuilderTest {
* <li>consistency</li> * <li>consistency</li>
* <li>non-null reference</li> * <li>non-null reference</li>
* </ul> * </ul>
* @param to a TestObject *
* @param toBis a TestObject, equal to to and toTer * @param to a TestObject
* @param toTer Left hand side, equal to to and toBis * @param toBis a TestObject, equal to to and toTer
* @param to2 a different TestObject * @param toTer Left hand side, equal to to and toBis
* @param oToChange a TestObject that will be changed * @param to2 a different TestObject
* @param oToChange a TestObject that will be changed
* @param testTransients whether to test transient instance variables * @param testTransients whether to test transient instance variables
*/ */
private void testReflectionEqualsEquivalenceRelationship( private void testReflectionEqualsEquivalenceRelationship(
final TestObject to, final TestObject to,
final TestObject toBis, final TestObject toBis,
final TestObject toTer, final TestObject toTer,
final TestObject to2, final TestObject to2,
final TestObject oToChange, final TestObject oToChange,
final boolean testTransients) { final boolean testTransients) {
// reflection test // reflection test
assertTrue(EqualsBuilder.reflectionEquals(to, to, testTransients)); assertTrue(EqualsBuilder.reflectionEquals(to, to, testTransients));
@ -325,9 +348,9 @@ public class EqualsBuilderTest {
// transitive test // transitive test
assertTrue( assertTrue(
EqualsBuilder.reflectionEquals(to, toBis, testTransients) EqualsBuilder.reflectionEquals(to, toBis, testTransients)
&& EqualsBuilder.reflectionEquals(toBis, toTer, testTransients) && EqualsBuilder.reflectionEquals(toBis, toTer, testTransients)
&& EqualsBuilder.reflectionEquals(to, toTer, testTransients)); && EqualsBuilder.reflectionEquals(to, toTer, testTransients));
// consistency test // consistency test
oToChange.setA(to.getA()); oToChange.setA(to.getA());
@ -1146,8 +1169,8 @@ public class EqualsBuilderTest {
*/ */
@Test @Test
public void testNpeForNullElement() { public void testNpeForNullElement() {
final Object[] x1 = new Object[] { Integer.valueOf(1), null, Integer.valueOf(3) }; final Object[] x1 = new Object[]{Integer.valueOf(1), null, Integer.valueOf(3)};
final Object[] x2 = new Object[] { Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3) }; final Object[] x2 = new Object[]{Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)};
// causes an NPE in 2.0 according to: // causes an NPE in 2.0 according to:
// http://issues.apache.org/bugzilla/show_bug.cgi?id=33067 // http://issues.apache.org/bugzilla/show_bug.cgi?id=33067
@ -1249,17 +1272,17 @@ public class EqualsBuilderTest {
final TestObject one = new TestObject(1); final TestObject one = new TestObject(1);
final TestObject two = new TestObject(2); final TestObject two = new TestObject(2);
final Object[] o1 = new Object[] { one }; final Object[] o1 = new Object[]{one};
final Object[] o2 = new Object[] { two }; final Object[] o2 = new Object[]{two};
final Object[] o3 = new Object[] { one }; final Object[] o3 = new Object[]{one};
assertFalse(EqualsBuilder.reflectionEquals(o1, o2)); assertFalse(EqualsBuilder.reflectionEquals(o1, o2));
assertTrue(EqualsBuilder.reflectionEquals(o1, o1)); assertTrue(EqualsBuilder.reflectionEquals(o1, o1));
assertTrue(EqualsBuilder.reflectionEquals(o1, o3)); assertTrue(EqualsBuilder.reflectionEquals(o1, o3));
final double[] d1 = { 0, 1 }; final double[] d1 = {0, 1};
final double[] d2 = { 2, 3 }; final double[] d2 = {2, 3};
final double[] d3 = { 0, 1 }; final double[] d3 = {0, 1};
assertFalse(EqualsBuilder.reflectionEquals(d1, d2)); assertFalse(EqualsBuilder.reflectionEquals(d1, d2));
assertTrue(EqualsBuilder.reflectionEquals(d1, d1)); assertTrue(EqualsBuilder.reflectionEquals(d1, d1));

View File

@ -41,8 +41,7 @@ import org.junit.Test;
/** /**
* @since 3.0 * @since 3.0
*/ */
public class EventUtilsTest public class EventUtilsTest {
{
@Test @Test
public void testConstructor() { public void testConstructor() {
@ -55,8 +54,7 @@ public class EventUtilsTest
} }
@Test @Test
public void testAddEventListener() public void testAddEventListener() {
{
final PropertyChangeSource src = new PropertyChangeSource(); final PropertyChangeSource src = new PropertyChangeSource();
final EventCountingInvociationHandler handler = new EventCountingInvociationHandler(); final EventCountingInvociationHandler handler = new EventCountingInvociationHandler();
final PropertyChangeListener listener = handler.createListener(PropertyChangeListener.class); final PropertyChangeListener listener = handler.createListener(PropertyChangeListener.class);
@ -68,64 +66,49 @@ public class EventUtilsTest
} }
@Test @Test
public void testAddEventListenerWithNoAddMethod() public void testAddEventListenerWithNoAddMethod() {
{
final PropertyChangeSource src = new PropertyChangeSource(); final PropertyChangeSource src = new PropertyChangeSource();
final EventCountingInvociationHandler handler = new EventCountingInvociationHandler(); final EventCountingInvociationHandler handler = new EventCountingInvociationHandler();
final ObjectChangeListener listener = handler.createListener(ObjectChangeListener.class); final ObjectChangeListener listener = handler.createListener(ObjectChangeListener.class);
try try {
{
EventUtils.addEventListener(src, ObjectChangeListener.class, listener); EventUtils.addEventListener(src, ObjectChangeListener.class, listener);
fail("Should not be allowed to add a listener to an object that doesn't support it."); fail("Should not be allowed to add a listener to an object that doesn't support it.");
} } catch (final IllegalArgumentException e) {
catch (final IllegalArgumentException e)
{
assertEquals("Class " + src.getClass().getName() + " does not have a public add" + ObjectChangeListener.class.getSimpleName() + " method which takes a parameter of type " + ObjectChangeListener.class.getName() + ".", e.getMessage()); assertEquals("Class " + src.getClass().getName() + " does not have a public add" + ObjectChangeListener.class.getSimpleName() + " method which takes a parameter of type " + ObjectChangeListener.class.getName() + ".", e.getMessage());
} }
} }
@Test @Test
public void testAddEventListenerThrowsException() public void testAddEventListenerThrowsException() {
{
final ExceptionEventSource src = new ExceptionEventSource(); final ExceptionEventSource src = new ExceptionEventSource();
try try {
{ EventUtils.addEventListener(src, PropertyChangeListener.class, new PropertyChangeListener() {
EventUtils.addEventListener(src, PropertyChangeListener.class, new PropertyChangeListener()
{
@Override @Override
public void propertyChange(final PropertyChangeEvent e) public void propertyChange(final PropertyChangeEvent e) {
{
// Do nothing! // Do nothing!
} }
}); });
fail("Add method should have thrown an exception, so method should fail."); fail("Add method should have thrown an exception, so method should fail.");
} } catch (final RuntimeException e) {
catch (final RuntimeException e)
{
} }
} }
@Test @Test
public void testAddEventListenerWithPrivateAddMethod() public void testAddEventListenerWithPrivateAddMethod() {
{
final PropertyChangeSource src = new PropertyChangeSource(); final PropertyChangeSource src = new PropertyChangeSource();
final EventCountingInvociationHandler handler = new EventCountingInvociationHandler(); final EventCountingInvociationHandler handler = new EventCountingInvociationHandler();
final VetoableChangeListener listener = handler.createListener(VetoableChangeListener.class); final VetoableChangeListener listener = handler.createListener(VetoableChangeListener.class);
try try {
{
EventUtils.addEventListener(src, VetoableChangeListener.class, listener); EventUtils.addEventListener(src, VetoableChangeListener.class, listener);
fail("Should not be allowed to add a listener to an object that doesn't support it."); fail("Should not be allowed to add a listener to an object that doesn't support it.");
} } catch (final IllegalArgumentException e) {
catch (final IllegalArgumentException e)
{
assertEquals("Class " + src.getClass().getName() + " does not have a public add" + VetoableChangeListener.class.getSimpleName() + " method which takes a parameter of type " + VetoableChangeListener.class.getName() + ".", e.getMessage()); assertEquals("Class " + src.getClass().getName() + " does not have a public add" + VetoableChangeListener.class.getSimpleName() + " method which takes a parameter of type " + VetoableChangeListener.class.getName() + ".", e.getMessage());
} }
} }
@Test @Test
public void testBindEventsToMethod() public void testBindEventsToMethod() {
{
final PropertyChangeSource src = new PropertyChangeSource(); final PropertyChangeSource src = new PropertyChangeSource();
final EventCounter counter = new EventCounter(); final EventCounter counter = new EventCounter();
EventUtils.bindEventsToMethod(counter, "eventOccurred", src, PropertyChangeListener.class); EventUtils.bindEventsToMethod(counter, "eventOccurred", src, PropertyChangeListener.class);
@ -136,8 +119,7 @@ public class EventUtilsTest
@Test @Test
public void testBindEventsToMethodWithEvent() public void testBindEventsToMethodWithEvent() {
{
final PropertyChangeSource src = new PropertyChangeSource(); final PropertyChangeSource src = new PropertyChangeSource();
final EventCounterWithEvent counter = new EventCounterWithEvent(); final EventCounterWithEvent counter = new EventCounterWithEvent();
EventUtils.bindEventsToMethod(counter, "eventOccurred", src, PropertyChangeListener.class); EventUtils.bindEventsToMethod(counter, "eventOccurred", src, PropertyChangeListener.class);
@ -148,8 +130,7 @@ public class EventUtilsTest
@Test @Test
public void testBindFilteredEventsToMethod() public void testBindFilteredEventsToMethod() {
{
final MultipleEventSource src = new MultipleEventSource(); final MultipleEventSource src = new MultipleEventSource();
final EventCounter counter = new EventCounter(); final EventCounter counter = new EventCounter();
EventUtils.bindEventsToMethod(counter, "eventOccurred", src, MultipleEventListener.class, "event1"); EventUtils.bindEventsToMethod(counter, "eventOccurred", src, MultipleEventListener.class, "event1");
@ -160,120 +141,97 @@ public class EventUtilsTest
assertEquals(1, counter.getCount()); assertEquals(1, counter.getCount());
} }
public interface MultipleEventListener public interface MultipleEventListener {
{
void event1(PropertyChangeEvent e); void event1(PropertyChangeEvent e);
void event2(PropertyChangeEvent e); void event2(PropertyChangeEvent e);
} }
public static class EventCounter public static class EventCounter {
{
private int count; private int count;
public void eventOccurred() public void eventOccurred() {
{
count++; count++;
} }
public int getCount() public int getCount() {
{
return count; return count;
} }
} }
public static class EventCounterWithEvent public static class EventCounterWithEvent {
{
private int count; private int count;
public void eventOccurred(final PropertyChangeEvent e) public void eventOccurred(final PropertyChangeEvent e) {
{
count++; count++;
} }
public int getCount() public int getCount() {
{
return count; return count;
} }
} }
private static class EventCountingInvociationHandler implements InvocationHandler private static class EventCountingInvociationHandler implements InvocationHandler {
{
private final Map<String, Integer> eventCounts = new TreeMap<>(); private final Map<String, Integer> eventCounts = new TreeMap<>();
public <L> L createListener(final Class<L> listenerType) public <L> L createListener(final Class<L> listenerType) {
{
return listenerType.cast(Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), return listenerType.cast(Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
new Class[]{listenerType}, new Class[]{listenerType},
this)); this));
} }
public int getEventCount(final String eventName) public int getEventCount(final String eventName) {
{
final Integer count = eventCounts.get(eventName); final Integer count = eventCounts.get(eventName);
return count == null ? 0 : count.intValue(); return count == null ? 0 : count.intValue();
} }
@Override @Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
{
final Integer count = eventCounts.get(method.getName()); final Integer count = eventCounts.get(method.getName());
if (count == null) if (count == null) {
{
eventCounts.put(method.getName(), Integer.valueOf(1)); eventCounts.put(method.getName(), Integer.valueOf(1));
} } else {
else
{
eventCounts.put(method.getName(), Integer.valueOf(count.intValue() + 1)); eventCounts.put(method.getName(), Integer.valueOf(count.intValue() + 1));
} }
return null; return null;
} }
} }
public static class MultipleEventSource public static class MultipleEventSource {
{
private final EventListenerSupport<MultipleEventListener> listeners = EventListenerSupport.create(MultipleEventListener.class); private final EventListenerSupport<MultipleEventListener> listeners = EventListenerSupport.create(MultipleEventListener.class);
public void addMultipleEventListener(final MultipleEventListener listener) public void addMultipleEventListener(final MultipleEventListener listener) {
{
listeners.addListener(listener); listeners.addListener(listener);
} }
} }
public static class ExceptionEventSource public static class ExceptionEventSource {
{ public void addPropertyChangeListener(final PropertyChangeListener listener) {
public void addPropertyChangeListener(final PropertyChangeListener listener)
{
throw new RuntimeException(); throw new RuntimeException();
} }
} }
public static class PropertyChangeSource public static class PropertyChangeSource {
{
private final EventListenerSupport<PropertyChangeListener> listeners = EventListenerSupport.create(PropertyChangeListener.class); private final EventListenerSupport<PropertyChangeListener> listeners = EventListenerSupport.create(PropertyChangeListener.class);
private String property; private String property;
public void setProperty(final String property) public void setProperty(final String property) {
{
final String oldValue = this.property; final String oldValue = this.property;
this.property = property; this.property = property;
listeners.fire().propertyChange(new PropertyChangeEvent(this, "property", oldValue, property)); listeners.fire().propertyChange(new PropertyChangeEvent(this, "property", oldValue, property));
} }
protected void addVetoableChangeListener(final VetoableChangeListener listener) protected void addVetoableChangeListener(final VetoableChangeListener listener) {
{
// Do nothing! // Do nothing!
} }
public void addPropertyChangeListener(final PropertyChangeListener listener) public void addPropertyChangeListener(final PropertyChangeListener listener) {
{
listeners.addListener(listener); listeners.addListener(listener);
} }
public void removePropertyChangeListener(final PropertyChangeListener listener) public void removePropertyChangeListener(final PropertyChangeListener listener) {
{
listeners.removeListener(listener); listeners.removeListener(listener);
} }
} }

View File

@ -40,6 +40,7 @@ import org.junit.Test;
/** /**
* Tests {@link org.apache.commons.lang3.exception.ExceptionUtils}. * Tests {@link org.apache.commons.lang3.exception.ExceptionUtils}.
*
* @since 1.0 * @since 1.0
*/ */
public class ExceptionUtilsTest { public class ExceptionUtilsTest {
@ -133,15 +134,15 @@ public class ExceptionUtilsTest {
// not known type, so match on supplied method names // not known type, so match on supplied method names
assertSame(nested, ExceptionUtils.getCause(withCause, null)); // default names assertSame(nested, ExceptionUtils.getCause(withCause, null)); // default names
assertSame(null, ExceptionUtils.getCause(withCause, new String[0])); assertSame(null, ExceptionUtils.getCause(withCause, new String[0]));
assertSame(null, ExceptionUtils.getCause(withCause, new String[] {null})); assertSame(null, ExceptionUtils.getCause(withCause, new String[]{null}));
assertSame(nested, ExceptionUtils.getCause(withCause, new String[] {"getCause"})); assertSame(nested, ExceptionUtils.getCause(withCause, new String[]{"getCause"}));
// not known type, so match on supplied method names // not known type, so match on supplied method names
assertSame(null, ExceptionUtils.getCause(withoutCause, null)); assertSame(null, ExceptionUtils.getCause(withoutCause, null));
assertSame(null, ExceptionUtils.getCause(withoutCause, new String[0])); assertSame(null, ExceptionUtils.getCause(withoutCause, new String[0]));
assertSame(null, ExceptionUtils.getCause(withoutCause, new String[] {null})); assertSame(null, ExceptionUtils.getCause(withoutCause, new String[]{null}));
assertSame(null, ExceptionUtils.getCause(withoutCause, new String[] {"getCause"})); assertSame(null, ExceptionUtils.getCause(withoutCause, new String[]{"getCause"}));
assertSame(null, ExceptionUtils.getCause(withoutCause, new String[] {"getTargetException"})); assertSame(null, ExceptionUtils.getCause(withoutCause, new String[]{"getTargetException"}));
} }
@Test @Test
@ -449,7 +450,7 @@ public class ExceptionUtilsTest {
assertFalse(match); assertFalse(match);
} }
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testRemoveCommonFrames_ListList() throws Exception { public void testRemoveCommonFrames_ListList() throws Exception {
ExceptionUtils.removeCommonFrames(null, null); ExceptionUtils.removeCommonFrames(null, null);
} }
@ -479,6 +480,7 @@ public class ExceptionUtilsTest {
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
* Provides a method with a well known chained/nested exception * Provides a method with a well known chained/nested exception
* name which matches the full signature (e.g. has a return value * name which matches the full signature (e.g. has a return value
@ -517,7 +519,7 @@ public class ExceptionUtilsTest {
private static class ExceptionWithoutCause extends Exception { private static class ExceptionWithoutCause extends Exception {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public void getTargetException() { public void getTargetException() {
} }
} }
@ -528,8 +530,13 @@ public class ExceptionUtilsTest {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@SuppressWarnings("unused") @SuppressWarnings("unused")
NestableException() { super(); } NestableException() {
NestableException(final Throwable t) { super(t); } super();
}
NestableException(final Throwable t) {
super(t);
}
} }
@Test @Test
@ -538,8 +545,7 @@ public class ExceptionUtilsTest {
try { try {
ExceptionUtils.rethrow(expected); ExceptionUtils.rethrow(expected);
Assert.fail("Exception not thrown"); Assert.fail("Exception not thrown");
} } catch (final Exception actual) {
catch(final Exception actual) {
Assert.assertSame(expected, actual); Assert.assertSame(expected, actual);
} }
} }
@ -549,8 +555,7 @@ public class ExceptionUtilsTest {
try { try {
throwsCheckedException(); throwsCheckedException();
Assert.fail("Exception not thrown"); Assert.fail("Exception not thrown");
} } catch (final Exception ioe) {
catch(final Exception ioe) {
assertTrue(ioe instanceof IOException); assertTrue(ioe instanceof IOException);
assertEquals(1, ExceptionUtils.getThrowableCount(ioe)); assertEquals(1, ExceptionUtils.getThrowableCount(ioe));
} }
@ -558,8 +563,7 @@ public class ExceptionUtilsTest {
try { try {
redeclareCheckedException(); redeclareCheckedException();
Assert.fail("Exception not thrown"); Assert.fail("Exception not thrown");
} } catch (final IOException ioe) {
catch(final IOException ioe) {
assertEquals(1, ExceptionUtils.getThrowableCount(ioe)); assertEquals(1, ExceptionUtils.getThrowableCount(ioe));
} }
} }
@ -585,8 +589,7 @@ public class ExceptionUtilsTest {
try { try {
ExceptionUtils.wrapAndThrow(new OutOfMemoryError()); ExceptionUtils.wrapAndThrow(new OutOfMemoryError());
Assert.fail("Error not thrown"); Assert.fail("Error not thrown");
} } catch (final Throwable t) {
catch(final Throwable t) {
Assert.assertTrue(ExceptionUtils.hasCause(t, Error.class)); Assert.assertTrue(ExceptionUtils.hasCause(t, Error.class));
} }
} }
@ -596,8 +599,7 @@ public class ExceptionUtilsTest {
try { try {
ExceptionUtils.wrapAndThrow(new IllegalArgumentException()); ExceptionUtils.wrapAndThrow(new IllegalArgumentException());
Assert.fail("RuntimeException not thrown"); Assert.fail("RuntimeException not thrown");
} } catch (final Throwable t) {
catch(final Throwable t) {
Assert.assertTrue(ExceptionUtils.hasCause(t, RuntimeException.class)); Assert.assertTrue(ExceptionUtils.hasCause(t, RuntimeException.class));
} }
} }
@ -607,8 +609,7 @@ public class ExceptionUtilsTest {
try { try {
ExceptionUtils.wrapAndThrow(new IOException()); ExceptionUtils.wrapAndThrow(new IOException());
Assert.fail("Checked Exception not thrown"); Assert.fail("Checked Exception not thrown");
} } catch (final Throwable t) {
catch(final Throwable t) {
Assert.assertTrue(ExceptionUtils.hasCause(t, IOException.class)); Assert.assertTrue(ExceptionUtils.hasCause(t, IOException.class));
} }
} }
@ -618,8 +619,7 @@ public class ExceptionUtilsTest {
try { try {
ExceptionUtils.wrapAndThrow(new TestThrowable()); ExceptionUtils.wrapAndThrow(new TestThrowable());
Assert.fail("Checked Exception not thrown"); Assert.fail("Checked Exception not thrown");
} } catch (final Throwable t) {
catch(final Throwable t) {
Assert.assertTrue(ExceptionUtils.hasCause(t, TestThrowable.class)); Assert.assertTrue(ExceptionUtils.hasCause(t, TestThrowable.class));
} }
} }

View File

@ -59,7 +59,8 @@ import org.junit.Test;
*/ */
public class MethodUtilsTest { public class MethodUtilsTest {
private interface PrivateInterface {} private interface PrivateInterface {
}
static class TestBeanWithInterfaces implements PrivateInterface { static class TestBeanWithInterfaces implements PrivateInterface {
public String foo() { public String foo() {
@ -197,54 +198,107 @@ public class MethodUtilsTest {
// This method is overloaded for the wrapper class for every primitive type, plus the common supertypes // This method is overloaded for the wrapper class for every primitive type, plus the common supertypes
// Number and Object. This is an acid test since it easily leads to ambiguous methods. // Number and Object. This is an acid test since it easily leads to ambiguous methods.
public static String varOverload(final Byte... args) { return "Byte..."; } public static String varOverload(final Byte... args) {
public static String varOverload(final Character... args) { return "Character..."; } return "Byte...";
public static String varOverload(final Short... args) { return "Short..."; } }
public static String varOverload(final Boolean... args) { return "Boolean..."; }
public static String varOverload(final Float... args) { return "Float..."; } public static String varOverload(final Character... args) {
public static String varOverload(final Double... args) { return "Double..."; } return "Character...";
public static String varOverload(final Integer... args) { return "Integer..."; } }
public static String varOverload(final Long... args) { return "Long..."; }
public static String varOverload(final Number... args) { return "Number..."; } public static String varOverload(final Short... args) {
public static String varOverload(final Object... args) { return "Object..."; } return "Short...";
public static String varOverload(final String... args) { return "String..."; } }
public static String varOverload(final Boolean... args) {
return "Boolean...";
}
public static String varOverload(final Float... args) {
return "Float...";
}
public static String varOverload(final Double... args) {
return "Double...";
}
public static String varOverload(final Integer... args) {
return "Integer...";
}
public static String varOverload(final Long... args) {
return "Long...";
}
public static String varOverload(final Number... args) {
return "Number...";
}
public static String varOverload(final Object... args) {
return "Object...";
}
public static String varOverload(final String... args) {
return "String...";
}
// This method is overloaded for the wrapper class for every numeric primitive type, plus the common // This method is overloaded for the wrapper class for every numeric primitive type, plus the common
// supertype Number // supertype Number
public static String numOverload(final Byte... args) { return "Byte..."; } public static String numOverload(final Byte... args) {
public static String numOverload(final Short... args) { return "Short..."; } return "Byte...";
public static String numOverload(final Float... args) { return "Float..."; } }
public static String numOverload(final Double... args) { return "Double..."; }
public static String numOverload(final Integer... args) { return "Integer..."; } public static String numOverload(final Short... args) {
public static String numOverload(final Long... args) { return "Long..."; } return "Short...";
public static String numOverload(final Number... args) { return "Number..."; } }
public static String numOverload(final Float... args) {
return "Float...";
}
public static String numOverload(final Double... args) {
return "Double...";
}
public static String numOverload(final Integer... args) {
return "Integer...";
}
public static String numOverload(final Long... args) {
return "Long...";
}
public static String numOverload(final Number... args) {
return "Number...";
}
// These varOverloadEcho and varOverloadEchoStatic methods are designed to verify that // These varOverloadEcho and varOverloadEchoStatic methods are designed to verify that
// not only is the correct overloaded variant invoked, but that the varags arguments // not only is the correct overloaded variant invoked, but that the varags arguments
// are also delivered correctly to the method. // are also delivered correctly to the method.
public ImmutablePair<String, Object[]> varOverloadEcho(final String... args) { public ImmutablePair<String, Object[]> varOverloadEcho(final String... args) {
return new ImmutablePair<String, Object[]>("String...", args); return new ImmutablePair<String, Object[]>("String...", args);
} }
public ImmutablePair<String, Object[]> varOverloadEcho(final Number... args) { public ImmutablePair<String, Object[]> varOverloadEcho(final Number... args) {
return new ImmutablePair<String, Object[]>("Number...", args); return new ImmutablePair<String, Object[]>("Number...", args);
} }
public static ImmutablePair<String, Object[]> varOverloadEchoStatic(final String... args) { public static ImmutablePair<String, Object[]> varOverloadEchoStatic(final String... args) {
return new ImmutablePair<String, Object[]>("String...", args); return new ImmutablePair<String, Object[]>("String...", args);
} }
public static ImmutablePair<String, Object[]> varOverloadEchoStatic(final Number... args) { public static ImmutablePair<String, Object[]> varOverloadEchoStatic(final Number... args) {
return new ImmutablePair<String, Object[]>("Number...", args); return new ImmutablePair<String, Object[]>("Number...", args);
} }
static void verify(final ImmutablePair<String, Object[]> a, final ImmutablePair<String, Object[]> b) { static void verify(final ImmutablePair<String, Object[]> a, final ImmutablePair<String, Object[]> b) {
assertEquals(a.getLeft(), b.getLeft()); assertEquals(a.getLeft(), b.getLeft());
assertArrayEquals(a.getRight(), b.getRight()); assertArrayEquals(a.getRight(), b.getRight());
} }
static void verify(final ImmutablePair<String, Object[]> a, final Object _b) { static void verify(final ImmutablePair<String, Object[]> a, final Object _b) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked") final ImmutablePair<String, Object[]> b = (ImmutablePair<String, Object[]>) _b;
final ImmutablePair<String, Object[]> b = (ImmutablePair<String, Object[]>) _b; verify(a, b);
verify(a, b);
} }
} }
@ -389,13 +443,13 @@ public class MethodUtilsTest {
} }
TestBean.verify(new ImmutablePair<String, Object[]>("String...", new String[]{"x", "y"}), TestBean.verify(new ImmutablePair<String, Object[]>("String...", new String[]{"x", "y"}),
MethodUtils.invokeMethod(testBean, "varOverloadEcho", "x", "y")); MethodUtils.invokeMethod(testBean, "varOverloadEcho", "x", "y"));
TestBean.verify(new ImmutablePair<String, Object[]>("Number...", new Number[]{17, 23, 42}), TestBean.verify(new ImmutablePair<String, Object[]>("Number...", new Number[]{17, 23, 42}),
MethodUtils.invokeMethod(testBean, "varOverloadEcho", 17, 23, 42)); MethodUtils.invokeMethod(testBean, "varOverloadEcho", 17, 23, 42));
TestBean.verify(new ImmutablePair<String, Object[]>("String...", new String[]{"x", "y"}), TestBean.verify(new ImmutablePair<String, Object[]>("String...", new String[]{"x", "y"}),
MethodUtils.invokeMethod(testBean, "varOverloadEcho", "x", "y")); MethodUtils.invokeMethod(testBean, "varOverloadEcho", "x", "y"));
TestBean.verify(new ImmutablePair<String, Object[]>("Number...", new Number[]{17, 23, 42}), TestBean.verify(new ImmutablePair<String, Object[]>("Number...", new Number[]{17, 23, 42}),
MethodUtils.invokeMethod(testBean, "varOverloadEcho", 17, 23, 42)); MethodUtils.invokeMethod(testBean, "varOverloadEcho", 17, 23, 42));
} }
@Test @Test
@ -414,8 +468,8 @@ public class MethodUtilsTest {
assertEquals("foo(Integer)", MethodUtils.invokeExactMethod(testBean, assertEquals("foo(Integer)", MethodUtils.invokeExactMethod(testBean,
"foo", NumberUtils.INTEGER_ONE)); "foo", NumberUtils.INTEGER_ONE));
assertEquals("foo(double)", MethodUtils.invokeExactMethod(testBean, assertEquals("foo(double)", MethodUtils.invokeExactMethod(testBean,
"foo", new Object[] { NumberUtils.DOUBLE_ONE }, "foo", new Object[]{NumberUtils.DOUBLE_ONE},
new Class[] { Double.TYPE })); new Class[]{Double.TYPE}));
try { try {
MethodUtils MethodUtils
@ -464,13 +518,13 @@ public class MethodUtilsTest {
TestBean.class, "bar", NumberUtils.INTEGER_ONE, "a", "b")); TestBean.class, "bar", NumberUtils.INTEGER_ONE, "a", "b"));
TestBean.verify(new ImmutablePair<String, Object[]>("String...", new String[]{"x", "y"}), TestBean.verify(new ImmutablePair<String, Object[]>("String...", new String[]{"x", "y"}),
MethodUtils.invokeStaticMethod(TestBean.class, "varOverloadEchoStatic", "x", "y")); MethodUtils.invokeStaticMethod(TestBean.class, "varOverloadEchoStatic", "x", "y"));
TestBean.verify(new ImmutablePair<String, Object[]>("Number...", new Number[]{17, 23, 42}), TestBean.verify(new ImmutablePair<String, Object[]>("Number...", new Number[]{17, 23, 42}),
MethodUtils.invokeStaticMethod(TestBean.class, "varOverloadEchoStatic", 17, 23, 42)); MethodUtils.invokeStaticMethod(TestBean.class, "varOverloadEchoStatic", 17, 23, 42));
TestBean.verify(new ImmutablePair<String, Object[]>("String...", new String[]{"x", "y"}), TestBean.verify(new ImmutablePair<String, Object[]>("String...", new String[]{"x", "y"}),
MethodUtils.invokeStaticMethod(TestBean.class, "varOverloadEchoStatic", "x", "y")); MethodUtils.invokeStaticMethod(TestBean.class, "varOverloadEchoStatic", "x", "y"));
TestBean.verify(new ImmutablePair<String, Object[]>("Number...", new Number[]{17, 23, 42}), TestBean.verify(new ImmutablePair<String, Object[]>("Number...", new Number[]{17, 23, 42}),
MethodUtils.invokeStaticMethod(TestBean.class, "varOverloadEchoStatic", 17, 23, 42)); MethodUtils.invokeStaticMethod(TestBean.class, "varOverloadEchoStatic", 17, 23, 42));
try { try {
MethodUtils.invokeStaticMethod(TestBean.class, "does_not_exist"); MethodUtils.invokeStaticMethod(TestBean.class, "does_not_exist");
@ -494,8 +548,8 @@ public class MethodUtilsTest {
assertEquals("bar(Integer)", MethodUtils.invokeExactStaticMethod( assertEquals("bar(Integer)", MethodUtils.invokeExactStaticMethod(
TestBean.class, "bar", NumberUtils.INTEGER_ONE)); TestBean.class, "bar", NumberUtils.INTEGER_ONE));
assertEquals("bar(double)", MethodUtils.invokeExactStaticMethod( assertEquals("bar(double)", MethodUtils.invokeExactStaticMethod(
TestBean.class, "bar", new Object[] { NumberUtils.DOUBLE_ONE }, TestBean.class, "bar", new Object[]{NumberUtils.DOUBLE_ONE},
new Class[] { Double.TYPE })); new Class[]{Double.TYPE}));
try { try {
MethodUtils.invokeExactStaticMethod(TestBean.class, "bar", MethodUtils.invokeExactStaticMethod(TestBean.class, "bar",
@ -519,7 +573,7 @@ public class MethodUtilsTest {
@Test @Test
public void testGetAccessibleInterfaceMethod() throws Exception { public void testGetAccessibleInterfaceMethod() throws Exception {
final Class<?>[][] p = { ArrayUtils.EMPTY_CLASS_ARRAY, null }; final Class<?>[][] p = {ArrayUtils.EMPTY_CLASS_ARRAY, null};
for (final Class<?>[] element : p) { for (final Class<?>[] element : p) {
final Method method = TestMutable.class.getMethod("getValue", element); final Method method = TestMutable.class.getMethod("getValue", element);
final Method accessibleMethod = MethodUtils.getAccessibleMethod(method); final Method accessibleMethod = MethodUtils.getAccessibleMethod(method);
@ -539,7 +593,7 @@ public class MethodUtilsTest {
@Test @Test
public void testGetAccessibleInterfaceMethodFromDescription() public void testGetAccessibleInterfaceMethodFromDescription()
throws Exception { throws Exception {
final Class<?>[][] p = { ArrayUtils.EMPTY_CLASS_ARRAY, null }; final Class<?>[][] p = {ArrayUtils.EMPTY_CLASS_ARRAY, null};
for (final Class<?>[] element : p) { for (final Class<?>[] element : p) {
final Method accessibleMethod = MethodUtils.getAccessibleMethod( final Method accessibleMethod = MethodUtils.getAccessibleMethod(
TestMutable.class, "getValue", element); TestMutable.class, "getValue", element);
@ -562,14 +616,14 @@ public class MethodUtilsTest {
} }
@Test @Test
public void testGetAccessibleMethodInaccessible() throws Exception { public void testGetAccessibleMethodInaccessible() throws Exception {
final Method expected = TestBean.class.getDeclaredMethod("privateStuff"); final Method expected = TestBean.class.getDeclaredMethod("privateStuff");
final Method actual = MethodUtils.getAccessibleMethod(expected); final Method actual = MethodUtils.getAccessibleMethod(expected);
assertNull(actual); assertNull(actual);
} }
@Test @Test
public void testGetMatchingAccessibleMethod() throws Exception { public void testGetMatchingAccessibleMethod() throws Exception {
expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo",
ArrayUtils.EMPTY_CLASS_ARRAY, ArrayUtils.EMPTY_CLASS_ARRAY); ArrayUtils.EMPTY_CLASS_ARRAY, ArrayUtils.EMPTY_CLASS_ARRAY);
expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo",
@ -611,9 +665,9 @@ public class MethodUtilsTest {
expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo",
singletonArray(Double.TYPE), singletonArray(Double.TYPE)); singletonArray(Double.TYPE), singletonArray(Double.TYPE));
expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo",
new Class[] {String.class, String.class}, new Class[] {String[].class}); new Class[]{String.class, String.class}, new Class[]{String[].class});
expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo",
new Class[] {Integer.TYPE, String.class, String.class}, new Class[] {Integer.class, String[].class}); new Class[]{Integer.TYPE, String.class, String.class}, new Class[]{Integer.class, String[].class});
expectMatchingAccessibleMethodParameterTypes(InheritanceBean.class, "testOne", expectMatchingAccessibleMethodParameterTypes(InheritanceBean.class, "testOne",
singletonArray(ParentObject.class), singletonArray(ParentObject.class)); singletonArray(ParentObject.class), singletonArray(ParentObject.class));
expectMatchingAccessibleMethodParameterTypes(InheritanceBean.class, "testOne", expectMatchingAccessibleMethodParameterTypes(InheritanceBean.class, "testOne",
@ -634,10 +688,10 @@ public class MethodUtilsTest {
public void testGetOverrideHierarchyIncludingInterfaces() { public void testGetOverrideHierarchyIncludingInterfaces() {
final Method method = MethodUtils.getAccessibleMethod(StringParameterizedChild.class, "consume", String.class); final Method method = MethodUtils.getAccessibleMethod(StringParameterizedChild.class, "consume", String.class);
final Iterator<MethodDescriptor> expected = final Iterator<MethodDescriptor> expected =
Arrays.asList(new MethodDescriptor(StringParameterizedChild.class, "consume", String.class), Arrays.asList(new MethodDescriptor(StringParameterizedChild.class, "consume", String.class),
new MethodDescriptor(GenericParent.class, "consume", GenericParent.class.getTypeParameters()[0]), new MethodDescriptor(GenericParent.class, "consume", GenericParent.class.getTypeParameters()[0]),
new MethodDescriptor(GenericConsumer.class, "consume", GenericConsumer.class.getTypeParameters()[0])) new MethodDescriptor(GenericConsumer.class, "consume", GenericConsumer.class.getTypeParameters()[0]))
.iterator(); .iterator();
for (final Method m : MethodUtils.getOverrideHierarchy(method, Interfaces.INCLUDE)) { for (final Method m : MethodUtils.getOverrideHierarchy(method, Interfaces.INCLUDE)) {
assertTrue(expected.hasNext()); assertTrue(expected.hasNext());
final MethodDescriptor md = expected.next(); final MethodDescriptor md = expected.next();
@ -655,9 +709,9 @@ public class MethodUtilsTest {
public void testGetOverrideHierarchyExcludingInterfaces() { public void testGetOverrideHierarchyExcludingInterfaces() {
final Method method = MethodUtils.getAccessibleMethod(StringParameterizedChild.class, "consume", String.class); final Method method = MethodUtils.getAccessibleMethod(StringParameterizedChild.class, "consume", String.class);
final Iterator<MethodDescriptor> expected = final Iterator<MethodDescriptor> expected =
Arrays.asList(new MethodDescriptor(StringParameterizedChild.class, "consume", String.class), Arrays.asList(new MethodDescriptor(StringParameterizedChild.class, "consume", String.class),
new MethodDescriptor(GenericParent.class, "consume", GenericParent.class.getTypeParameters()[0])) new MethodDescriptor(GenericParent.class, "consume", GenericParent.class.getTypeParameters()[0]))
.iterator(); .iterator();
for (final Method m : MethodUtils.getOverrideHierarchy(method, Interfaces.EXCLUDE)) { for (final Method m : MethodUtils.getOverrideHierarchy(method, Interfaces.EXCLUDE)) {
assertTrue(expected.hasNext()); assertTrue(expected.hasNext());
final MethodDescriptor md = expected.next(); final MethodDescriptor md = expected.next();
@ -861,7 +915,7 @@ public class MethodUtilsTest {
} }
private void expectMatchingAccessibleMethodParameterTypes(final Class<?> cls, private void expectMatchingAccessibleMethodParameterTypes(final Class<?> cls,
final String methodName, final Class<?>[] requestTypes, final Class<?>[] actualTypes) { final String methodName, final Class<?>[] requestTypes, final Class<?>[] actualTypes) {
final Method m = MethodUtils.getMatchingAccessibleMethod(cls, methodName, final Method m = MethodUtils.getMatchingAccessibleMethod(cls, methodName,
requestTypes); requestTypes);
assertNotNull("could not find any matches for " + methodName assertNotNull("could not find any matches for " + methodName
@ -878,25 +932,43 @@ public class MethodUtilsTest {
private Class<?>[] singletonArray(final Class<?> c) { private Class<?>[] singletonArray(final Class<?> c) {
Class<?>[] result = classCache.get(c); Class<?>[] result = classCache.get(c);
if (result == null) { if (result == null) {
result = new Class[] { c }; result = new Class[]{c};
classCache.put(c, result); classCache.put(c, result);
} }
return result; return result;
} }
public static class InheritanceBean { public static class InheritanceBean {
public void testOne(final Object obj) {} public void testOne(final Object obj) {
public void testOne(final GrandParentObject obj) {} }
public void testOne(final ParentObject obj) {}
public void testTwo(final Object obj) {} public void testOne(final GrandParentObject obj) {
public void testTwo(final GrandParentObject obj) {} }
public void testTwo(final ChildInterface obj) {}
public void testOne(final ParentObject obj) {
}
public void testTwo(final Object obj) {
}
public void testTwo(final GrandParentObject obj) {
}
public void testTwo(final ChildInterface obj) {
}
} }
interface ChildInterface {} interface ChildInterface {
public static class GrandParentObject {} }
public static class ParentObject extends GrandParentObject {}
public static class ChildObject extends ParentObject implements ChildInterface {} public static class GrandParentObject {
}
public static class ParentObject extends GrandParentObject {
}
public static class ChildObject extends ParentObject implements ChildInterface {
}
private static class MethodDescriptor { private static class MethodDescriptor {
final Class<?> declaringClass; final Class<?> declaringClass;
@ -913,7 +985,7 @@ public class MethodUtilsTest {
@Test @Test
public void testVarArgsUnboxing() throws Exception { public void testVarArgsUnboxing() throws Exception {
final TestBean testBean = new TestBean(); final TestBean testBean = new TestBean();
final int[] actual = (int[])MethodUtils.invokeMethod(testBean, "unboxing", Integer.valueOf(1), Integer.valueOf(2)); final int[] actual = (int[]) MethodUtils.invokeMethod(testBean, "unboxing", Integer.valueOf(1), Integer.valueOf(2));
Assert.assertArrayEquals(new int[]{1, 2}, actual); Assert.assertArrayEquals(new int[]{1, 2}, actual);
} }

View File

@ -409,7 +409,9 @@ public class ExtendedMessageFormatTest {
return toAppendTo.append(((String)obj).toLowerCase()); return toAppendTo.append(((String)obj).toLowerCase());
} }
@Override @Override
public Object parseObject(final String source, final ParsePosition pos) {throw new UnsupportedOperationException();} public Object parseObject(final String source, final ParsePosition pos) {
throw new UnsupportedOperationException();
}
} }
/** /**
@ -423,7 +425,9 @@ public class ExtendedMessageFormatTest {
return toAppendTo.append(((String)obj).toUpperCase()); return toAppendTo.append(((String)obj).toUpperCase());
} }
@Override @Override
public Object parseObject(final String source, final ParsePosition pos) {throw new UnsupportedOperationException();} public Object parseObject(final String source, final ParsePosition pos) {
throw new UnsupportedOperationException();
}
} }

View File

@ -565,29 +565,25 @@ public class StrBuilderTest {
try { try {
sb.getChars(-1,0,a,0); sb.getChars(-1,0,a,0);
fail("no exception"); fail("no exception");
} } catch (final IndexOutOfBoundsException e) {
catch (final IndexOutOfBoundsException e) {
} }
try { try {
sb.getChars(0,-1,a,0); sb.getChars(0,-1,a,0);
fail("no exception"); fail("no exception");
} } catch (final IndexOutOfBoundsException e) {
catch (final IndexOutOfBoundsException e) {
} }
try { try {
sb.getChars(0,20,a,0); sb.getChars(0,20,a,0);
fail("no exception"); fail("no exception");
} } catch (final IndexOutOfBoundsException e) {
catch (final IndexOutOfBoundsException e) {
} }
try { try {
sb.getChars(4,2,a,0); sb.getChars(4,2,a,0);
fail("no exception"); fail("no exception");
} } catch (final IndexOutOfBoundsException e) {
catch (final IndexOutOfBoundsException e) {
} }
} }

View File

@ -206,8 +206,7 @@ public class FastDateParserTest {
cal.set(Calendar.ERA, 0); cal.set(Calendar.ERA, 0);
cal.set(Calendar.YEAR, 1868-year); cal.set(Calendar.YEAR, 1868-year);
} }
} } else {
else {
if (year < 0) { if (year < 0) {
cal.set(Calendar.ERA, GregorianCalendar.BC); cal.set(Calendar.ERA, GregorianCalendar.BC);
year= -year; year= -year;

View File

@ -40,8 +40,7 @@ public class FastDateParser_TimeZoneStrategyTest {
} }
try { try {
parser.parse(tzDisplay); parser.parse(tzDisplay);
} } catch(final Exception ex) {
catch(final Exception ex) {
Assert.fail("'" + tzDisplay + "'" Assert.fail("'" + tzDisplay + "'"
+ " Locale: '" + locale.getDisplayName() + "'" + " Locale: '" + locale.getDisplayName() + "'"
+ " TimeZone: " + zone[0] + " TimeZone: " + zone[0]

View File

@ -30,14 +30,17 @@ import org.junit.Test;
/** /**
* TestCase for StopWatch. * TestCase for StopWatch.
*/ */
public class StopWatchTest { public class StopWatchTest {
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
@Test @Test
public void testStopWatchSimple(){ public void testStopWatchSimple() {
final StopWatch watch = new StopWatch(); final StopWatch watch = new StopWatch();
watch.start(); watch.start();
try {Thread.sleep(550);} catch (final InterruptedException ex) {} try {
Thread.sleep(550);
} catch (final InterruptedException ex) {
}
watch.stop(); watch.stop();
final long time = watch.getTime(); final long time = watch.getTime();
assertEquals(time, watch.getTime()); assertEquals(time, watch.getTime());
@ -56,13 +59,16 @@ public class StopWatchTest {
} }
@Test @Test
public void testStopWatchSimpleGet(){ public void testStopWatchSimpleGet() {
final StopWatch watch = new StopWatch(); final StopWatch watch = new StopWatch();
assertEquals(0, watch.getTime()); assertEquals(0, watch.getTime());
assertEquals("00:00:00.000", watch.toString()); assertEquals("00:00:00.000", watch.toString());
watch.start(); watch.start();
try {Thread.sleep(500);} catch (final InterruptedException ex) {} try {
Thread.sleep(500);
} catch (final InterruptedException ex) {
}
assertTrue(watch.getTime() < 2000); assertTrue(watch.getTime() < 2000);
} }
@ -71,9 +77,9 @@ public class StopWatchTest {
// Create a mock StopWatch with a time of 2:59:01.999 // Create a mock StopWatch with a time of 2:59:01.999
final StopWatch watch = createMockStopWatch( final StopWatch watch = createMockStopWatch(
TimeUnit.HOURS.toNanos(2) TimeUnit.HOURS.toNanos(2)
+ TimeUnit.MINUTES.toNanos(59) + TimeUnit.MINUTES.toNanos(59)
+ TimeUnit.SECONDS.toNanos(1) + TimeUnit.SECONDS.toNanos(1)
+ TimeUnit.MILLISECONDS.toNanos(999)); + TimeUnit.MILLISECONDS.toNanos(999));
assertEquals(2L, watch.getTime(TimeUnit.HOURS)); assertEquals(2L, watch.getTime(TimeUnit.HOURS));
assertEquals(179L, watch.getTime(TimeUnit.MINUTES)); assertEquals(179L, watch.getTime(TimeUnit.MINUTES));
@ -82,21 +88,30 @@ public class StopWatchTest {
} }
@Test @Test
public void testStopWatchSplit(){ public void testStopWatchSplit() {
final StopWatch watch = new StopWatch(); final StopWatch watch = new StopWatch();
watch.start(); watch.start();
try {Thread.sleep(550);} catch (final InterruptedException ex) {} try {
Thread.sleep(550);
} catch (final InterruptedException ex) {
}
watch.split(); watch.split();
final long splitTime = watch.getSplitTime(); final long splitTime = watch.getSplitTime();
final String splitStr = watch.toSplitString(); final String splitStr = watch.toSplitString();
try {Thread.sleep(550);} catch (final InterruptedException ex) {} try {
Thread.sleep(550);
} catch (final InterruptedException ex) {
}
watch.unsplit(); watch.unsplit();
try {Thread.sleep(550);} catch (final InterruptedException ex) {} try {
Thread.sleep(550);
} catch (final InterruptedException ex) {
}
watch.stop(); watch.stop();
final long totalTime = watch.getTime(); final long totalTime = watch.getTime();
assertEquals("Formatted split string not the correct length", assertEquals("Formatted split string not the correct length",
splitStr.length(), 12); splitStr.length(), 12);
assertTrue(splitTime >= 500); assertTrue(splitTime >= 500);
assertTrue(splitTime < 700); assertTrue(splitTime < 700);
assertTrue(totalTime >= 1500); assertTrue(totalTime >= 1500);
@ -104,15 +119,24 @@ public class StopWatchTest {
} }
@Test @Test
public void testStopWatchSuspend(){ public void testStopWatchSuspend() {
final StopWatch watch = new StopWatch(); final StopWatch watch = new StopWatch();
watch.start(); watch.start();
try {Thread.sleep(550);} catch (final InterruptedException ex) {} try {
Thread.sleep(550);
} catch (final InterruptedException ex) {
}
watch.suspend(); watch.suspend();
final long suspendTime = watch.getTime(); final long suspendTime = watch.getTime();
try {Thread.sleep(550);} catch (final InterruptedException ex) {} try {
Thread.sleep(550);
} catch (final InterruptedException ex) {
}
watch.resume(); watch.resume();
try {Thread.sleep(550);} catch (final InterruptedException ex) {} try {
Thread.sleep(550);
} catch (final InterruptedException ex) {
}
watch.stop(); watch.stop();
final long totalTime = watch.getTime(); final long totalTime = watch.getTime();
@ -126,13 +150,19 @@ public class StopWatchTest {
public void testLang315() { public void testLang315() {
final StopWatch watch = new StopWatch(); final StopWatch watch = new StopWatch();
watch.start(); watch.start();
try {Thread.sleep(200);} catch (final InterruptedException ex) {} try {
Thread.sleep(200);
} catch (final InterruptedException ex) {
}
watch.suspend(); watch.suspend();
final long suspendTime = watch.getTime(); final long suspendTime = watch.getTime();
try {Thread.sleep(200);} catch (final InterruptedException ex) {} try {
Thread.sleep(200);
} catch (final InterruptedException ex) {
}
watch.stop(); watch.stop();
final long totalTime = watch.getTime(); final long totalTime = watch.getTime();
assertTrue( suspendTime == totalTime ); assertTrue(suspendTime == totalTime);
} }
// test bad states // test bad states
@ -142,42 +172,42 @@ public class StopWatchTest {
try { try {
watch.stop(); watch.stop();
fail("Calling stop on an unstarted StopWatch should throw an exception. "); fail("Calling stop on an unstarted StopWatch should throw an exception. ");
} catch(final IllegalStateException ise) { } catch (final IllegalStateException ise) {
// expected // expected
} }
try { try {
watch.stop(); watch.stop();
fail("Calling stop on an unstarted StopWatch should throw an exception. "); fail("Calling stop on an unstarted StopWatch should throw an exception. ");
} catch(final IllegalStateException ise) { } catch (final IllegalStateException ise) {
// expected // expected
} }
try { try {
watch.suspend(); watch.suspend();
fail("Calling suspend on an unstarted StopWatch should throw an exception. "); fail("Calling suspend on an unstarted StopWatch should throw an exception. ");
} catch(final IllegalStateException ise) { } catch (final IllegalStateException ise) {
// expected // expected
} }
try { try {
watch.split(); watch.split();
fail("Calling split on a non-running StopWatch should throw an exception. "); fail("Calling split on a non-running StopWatch should throw an exception. ");
} catch(final IllegalStateException ise) { } catch (final IllegalStateException ise) {
// expected // expected
} }
try { try {
watch.unsplit(); watch.unsplit();
fail("Calling unsplit on an unsplit StopWatch should throw an exception. "); fail("Calling unsplit on an unsplit StopWatch should throw an exception. ");
} catch(final IllegalStateException ise) { } catch (final IllegalStateException ise) {
// expected // expected
} }
try { try {
watch.resume(); watch.resume();
fail("Calling resume on an unsuspended StopWatch should throw an exception. "); fail("Calling resume on an unsuspended StopWatch should throw an exception. ");
} catch(final IllegalStateException ise) { } catch (final IllegalStateException ise) {
// expected // expected
} }
@ -186,28 +216,28 @@ public class StopWatchTest {
try { try {
watch.start(); watch.start();
fail("Calling start on a started StopWatch should throw an exception. "); fail("Calling start on a started StopWatch should throw an exception. ");
} catch(final IllegalStateException ise) { } catch (final IllegalStateException ise) {
// expected // expected
} }
try { try {
watch.unsplit(); watch.unsplit();
fail("Calling unsplit on an unsplit StopWatch should throw an exception. "); fail("Calling unsplit on an unsplit StopWatch should throw an exception. ");
} catch(final IllegalStateException ise) { } catch (final IllegalStateException ise) {
// expected // expected
} }
try { try {
watch.getSplitTime(); watch.getSplitTime();
fail("Calling getSplitTime on an unsplit StopWatch should throw an exception. "); fail("Calling getSplitTime on an unsplit StopWatch should throw an exception. ");
} catch(final IllegalStateException ise) { } catch (final IllegalStateException ise) {
// expected // expected
} }
try { try {
watch.resume(); watch.resume();
fail("Calling resume on an unsuspended StopWatch should throw an exception. "); fail("Calling resume on an unsuspended StopWatch should throw an exception. ");
} catch(final IllegalStateException ise) { } catch (final IllegalStateException ise) {
// expected // expected
} }
@ -216,7 +246,7 @@ public class StopWatchTest {
try { try {
watch.start(); watch.start();
fail("Calling start on a stopped StopWatch should throw an exception as it needs to be reset. "); fail("Calling start on a stopped StopWatch should throw an exception as it needs to be reset. ");
} catch(final IllegalStateException ise) { } catch (final IllegalStateException ise) {
// expected // expected
} }
} }
@ -275,7 +305,7 @@ public class StopWatchTest {
* Creates a suspended StopWatch object which appears to have elapsed * Creates a suspended StopWatch object which appears to have elapsed
* for the requested amount of time in nanoseconds. * for the requested amount of time in nanoseconds.
* <p> * <p>
* * <p>
* <pre> * <pre>
* // Create a mock StopWatch with a time of 2:59:01.999 * // Create a mock StopWatch with a time of 2:59:01.999
* final long nanos = TimeUnit.HOURS.toNanos(2) * final long nanos = TimeUnit.HOURS.toNanos(2)