diff options
author | kmoore | 2011-02-05 16:25:51 +0000 |
---|---|---|
committer | kmoore | 2011-02-05 16:25:51 +0000 |
commit | 06faf6fb95655c815a4252eb0066abfed07b7aad (patch) | |
tree | 1440efc762c4eec0f06160a2b7c19628ea677858 /common | |
parent | 824998d08071af6d9877fb5314aa25d360d1c172 (diff) | |
download | webtools.dali-06faf6fb95655c815a4252eb0066abfed07b7aad.tar.gz webtools.dali-06faf6fb95655c815a4252eb0066abfed07b7aad.tar.xz webtools.dali-06faf6fb95655c815a4252eb0066abfed07b7aad.zip |
rename org.eclipse.jpt.utility.tests to org.eclipse.jpt.common.utility.tests and move to common component
Diffstat (limited to 'common')
204 files changed, 53378 insertions, 0 deletions
diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/.classpath b/common/tests/org.eclipse.jpt.common.utility.tests/.classpath new file mode 100644 index 0000000000..ef8d91ca94 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/.classpath @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="UTF-8"?> +<classpath> + <classpathentry kind="src" path="src"/> + <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/> + <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"> + <accessrules> + <accessrule kind="accessible" pattern="org/eclipse/jpt/utility/**"/> + </accessrules> + </classpathentry> + <classpathentry kind="output" path="bin"/> +</classpath> diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/.cvsignore b/common/tests/org.eclipse.jpt.common.utility.tests/.cvsignore new file mode 100644 index 0000000000..c4ba612bad --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/.cvsignore @@ -0,0 +1,5 @@ +bin +@dot +temp.folder +build.xml +javaCompiler...args
\ No newline at end of file diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/.project b/common/tests/org.eclipse.jpt.common.utility.tests/.project new file mode 100644 index 0000000000..898e230aaf --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/.project @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipse.jpt.common.utility.tests</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.jdt.core.javabuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.ManifestBuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.SchemaBuilder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.pde.PluginNature</nature> + <nature>org.eclipse.jdt.core.javanature</nature> + </natures> +</projectDescription> diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/.settings/org.eclipse.core.resources.prefs b/common/tests/org.eclipse.jpt.common.utility.tests/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000000..f68f9c2597 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,3 @@ +#Tue Jan 15 11:12:26 EST 2008 +eclipse.preferences.version=1 +encoding/<project>=ISO-8859-1 diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/.settings/org.eclipse.jdt.core.prefs b/common/tests/org.eclipse.jpt.common.utility.tests/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..84b5c4c710 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,7 @@ +#Sun May 27 14:55:58 EDT 2007 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.compliance=1.5 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.5 diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/META-INF/MANIFEST.MF b/common/tests/org.eclipse.jpt.common.utility.tests/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..62256999d3 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/META-INF/MANIFEST.MF @@ -0,0 +1,21 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: %pluginName +Bundle-Vendor: %providerName +Bundle-SymbolicName: org.eclipse.jpt.common.utility.tests +Bundle-Version: 1.6.0.qualifier +Bundle-Localization: plugin +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Require-Bundle: org.eclipse.jpt.common.utility;bundle-version="[1.2.0,2.0.0)", + org.junit;bundle-version="3.8.0" +Export-Package: org.eclipse.jpt.common.utility.tests.internal;x-internal:=true, + org.eclipse.jpt.common.utility.tests.internal.enumerations;x-internal:=true, + org.eclipse.jpt.common.utility.tests.internal.iterables;x-internal:=true, + org.eclipse.jpt.common.utility.tests.internal.iterators;x-internal:=true, + org.eclipse.jpt.common.utility.tests.internal.model;x-internal:=true, + org.eclipse.jpt.common.utility.tests.internal.model.listener;x-internal:=true, + org.eclipse.jpt.common.utility.tests.internal.model.value;x-internal:=true, + org.eclipse.jpt.common.utility.tests.internal.model.value.prefs;x-internal:=true, + org.eclipse.jpt.common.utility.tests.internal.model.value.swing;x-internal:=true, + org.eclipse.jpt.common.utility.tests.internal.node;x-internal:=true, + org.eclipse.jpt.common.utility.tests.internal.synchronizers;x-internal:=true diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/about.html b/common/tests/org.eclipse.jpt.common.utility.tests/about.html new file mode 100644 index 0000000000..be534ba44f --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/about.html @@ -0,0 +1,34 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> +<HTML> + +<head> +<title>About</title> +<meta http-equiv=Content-Type content="text/html; charset=ISO-8859-1"> +</head> + +<BODY lang="EN-US"> + +<H3>About This Content</H3> + +<P>May 02, 2008</P> + +<H3>License</H3> + +<P>The Eclipse Foundation makes available all content in this plug-in +("Content"). Unless otherwise indicated below, the Content is provided to you +under the terms and conditions of the Eclipse Public License Version 1.0 +("EPL"). A copy of the EPL is available at +<A href="http://www.eclipse.org/org/documents/epl-v10.php">http://www.eclipse.org/org/documents/epl-v10.php</A>. +For purposes of the EPL, "Program" will mean the Content.</P> + +<P>If you did not receive this Content directly from the Eclipse Foundation, the +Content is being redistributed by another party ("Redistributor") and different +terms and conditions may apply to your use of any object code in the Content. +Check the Redistributor's license that was provided with the Content. If no such +license exists, contact the Redistributor. Unless otherwise indicated below, the +terms and conditions of the EPL still apply to any source code in the Content +and such source code may be obtained at +<A href="http://www.eclipse.org/">http://www.eclipse.org/</A>.</P> + +</BODY> +</HTML> diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/build.properties b/common/tests/org.eclipse.jpt.common.utility.tests/build.properties new file mode 100644 index 0000000000..ebe9c08ef9 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/build.properties @@ -0,0 +1,16 @@ +################################################################################ +# Copyright (c) 2006, 2007 Oracle. All rights reserved. +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License v1.0, which accompanies this distribution +# and is available at http://www.eclipse.org/legal/epl-v10.html. +# +# Contributors: +# Oracle - initial API and implementation +################################################################################ +source.. = src/ +output.. = bin/ +bin.includes = .,\ + META-INF/,\ + about.html,\ + test.xml,\ + plugin.properties diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/plugin.properties b/common/tests/org.eclipse.jpt.common.utility.tests/plugin.properties new file mode 100644 index 0000000000..bc1a18f302 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/plugin.properties @@ -0,0 +1,24 @@ +################################################################################ +# Copyright (c) 2006, 2009 Oracle. All rights reserved. +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License v1.0, which accompanies this distribution +# and is available at http://www.eclipse.org/legal/epl-v10.html. +# +# Contributors: +# Oracle - initial API and implementation +################################################################################ +# ==================================================================== +# To code developer: +# Do NOT change the properties between this line and the +# "%%% END OF TRANSLATED PROPERTIES %%%" line. +# Make a new property name, append to the end of the file and change +# the code to use the new property. +# ==================================================================== + +# ==================================================================== +# %%% END OF TRANSLATED PROPERTIES %%% +# ==================================================================== + +pluginName = Dali Java Persistence Tools - Utility Tests +providerName = Eclipse Web Tools Platform + diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/resource/ClassTools.java b/common/tests/org.eclipse.jpt.common.utility.tests/resource/ClassTools.java new file mode 100644 index 0000000000..aac17b6044 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/resource/ClassTools.java @@ -0,0 +1,1680 @@ +/******************************************************************************* + * Copyright (c) 2005, 2008 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package test; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Collections; +import java.util.Stack; + +/** + * Convenience methods related to the java.lang.reflect package. + * These methods provide shortcuts for manipulating objects via + * reflection; particularly when dealing with fields and/or methods that + * are not publicly accessible or are inherited. + * + * In most cases, all the exceptions are handled and + * wrapped in java.lang.RuntimeExceptions; so these methods should + * be used when you are confident that you will not having any problems + * using reflection. + * + * There are also a number of methods whose names + * begin with "attempt". These methods will throw a NoSuchMethodException + * or NoSuchFieldException when appropriate, allowing you to probe + * for methods that should be present but might not. + */ +public final class ClassTools { + + public static final Class<?>[] ZERO_PARAMETER_TYPES = new Class[0]; + public static final Object[] ZERO_PARAMETERS = new Object[0]; + private static final String CR = StringTools.CR; + + public static final char NESTED_CLASS_NAME_SEPARATOR = '$'; + + public static final char ARRAY_INDICATOR = '['; + public static final char TYPE_DECLARATION_ARRAY_OPEN = '['; + public static final char TYPE_DECLARATION_ARRAY_CLOSE = ']'; + + public static final char REFERENCE_CLASS_CODE = 'L'; + public static final char REFERENCE_CLASS_NAME_DELIMITER = ';'; + + private static Primitive[] PRIMITIVES; // pseudo-'final' - lazy-initialized + public static final char BYTE_CODE = 'B'; + public static final char CHAR_CODE = 'C'; + public static final char DOUBLE_CODE = 'D'; + public static final char FLOAT_CODE = 'F'; + public static final char INT_CODE = 'I'; + public static final char LONG_CODE = 'J'; + public static final char SHORT_CODE = 'S'; + public static final char BOOLEAN_CODE = 'Z'; + public static final char VOID_CODE = 'V'; + private static int MAX_PRIMITIVE_CLASS_NAME_LENGTH = -1; // pseudo-'final' - lazy-initialized + private static int MAX_PRIMITIVE_WRAPPER_CLASS_NAME_LENGTH = -1; // pseudo-'final' - lazy-initialized + + public static final String VOID_CLASS_NAME = void.class.getName(); + public static final String VOID_WRAPPER_CLASS_NAME = java.lang.Void.class.getName(); + + + /** + * Return all the fields for the + * specified class, including inherited fields. + * Class#allFields() + */ + @Deprecated + public static Field[] allFields(Class<?> javaClass) { + Stack<Field> stack = new Stack<Field>(); + for (Class<?> tempClass = javaClass; tempClass != null; tempClass = tempClass.getSuperclass()) { + pushDeclaredFields(tempClass, stack); + } + Collections.reverse(stack); + return stack.toArray(new Field[stack.size()]); + } + + /** + * Return all the methods for the + * specified class, including inherited methods. + * Class#allMethods() + */ + public static Method[] allMethods(Class<?> javaClass) { + Stack<Method> stack = new Stack<Method>(); + for (Class<?> tempClass = javaClass; tempClass != null; tempClass = tempClass.getSuperclass()) { + pushDeclaredMethods(tempClass, stack); + } + Collections.reverse(stack); + return stack.toArray(new Method[stack.size()]); + } + + /** + * Convenience method. + * Return a new instance of the specified class, + * using the class's default (zero-argument) constructor. + * Throw an exception if the default constructor is not defined. + * Class#newInstance() throws NoSuchMethodException + */ + @Deprecated + public static <T> T attemptNewInstance(Class<T> javaClass) throws NoSuchMethodException { + return attemptNewInstance(javaClass, ZERO_PARAMETER_TYPES, ZERO_PARAMETERS); + } + + /** + * Return a new instance of the specified class, + * given the constructor parameter types and parameters. + * Throw an exception if the constructor is not defined. + * Class#newInstance(Class<?>[] parameterTypes, Object[] parameters) throws NoSuchMethodException + */ + public static <T> T attemptNewInstance(Class<T> javaClass, Class<?>[] parameterTypes, Object[] parameters) throws NoSuchMethodException { + try { + return constructor(javaClass, parameterTypes).newInstance(parameters); + } catch (InstantiationException ie) { + throw new RuntimeException(ie + CR + fullyQualifiedConstructorSignature(javaClass, parameterTypes), ie); + } catch (IllegalAccessException iae) { + throw new RuntimeException(iae + CR + fullyQualifiedConstructorSignature(javaClass, parameterTypes), iae); + } catch (InvocationTargetException ite) { + throw new RuntimeException(fullyQualifiedConstructorSignature(javaClass, parameterTypes) + CR + ite.getTargetException(), ite); + } + } + + /** + * Convenience method. + * Return a new instance of the specified class, + * given the constructor parameter type and parameter. + * Throw an exception if the constructor is not defined. + * Class#newInstance(Class<?> parameterType, Object parameter) throws NoSuchMethodException + */ + public static <T> T attemptNewInstance(Class<T> javaClass, Class<?> parameterType, Object parameter) throws NoSuchMethodException { + return attemptNewInstance(javaClass, new Class[] {parameterType}, new Object[] {parameter}); + } + + /** + * Attempt to get a field value, given the containing object and field name. + * Return its result. + * Useful for accessing private, package, or protected fields. + * Throw an exception if the field is not defined. + * Object#getFieldValue(String fieldName) throws NoSuchFieldException + */ + public static Object attemptToGetFieldValue(Object object, String fieldName) throws NoSuchFieldException { + try { + return field(object, fieldName).get(object); + } catch (IllegalAccessException iae) { + throw new RuntimeException(iae + CR + fullyQualifiedFieldName(object, fieldName), iae); + } + } + + /** + * Attempt to get a static field value, given the containing object and field name. + * Return its result. + * Useful for accessing private, package, or protected fields. + * Throw an exception if the field is not defined. + * Class#getStaticFieldValue(String fieldName) throws NoSuchFieldException + */ + public static Object attemptToGetStaticFieldValue(Class<?> javaClass, String fieldName) throws NoSuchFieldException { + try { + return field(javaClass, fieldName).get(null); + } catch (IllegalAccessException iae) { + throw new RuntimeException(iae + CR + fullyQualifiedFieldName(javaClass, fieldName), iae); + } + } + + /** + * Convenience method. + * Attempt to execute a zero-argument method, + * given the receiver and method name. + * Return its result. + * Throw an exception if the method is not found. + * Useful for invoking private, package, or protected methods. + * Object#execute(String methodName) throws NoSuchMethodException + */ + public static Object attemptToExecuteMethod(Object receiver, String methodName) throws NoSuchMethodException { + return attemptToExecuteMethod(receiver, methodName, ZERO_PARAMETER_TYPES, ZERO_PARAMETERS); + } + + /** + * Convenience method. + * Attempt to execute a method, given the receiver, + * method name, parameter type, and parameter. + * Return its result. + * Throw an exception if the method is not found. + * Useful for invoking private, package, or protected methods. + * Object#execute(String methodName, Class<?> parameterType, Object parameter) throws NoSuchMethodException + */ + public static Object attemptToExecuteMethod(Object receiver, String methodName, Class<?> parameterType, Object parameter) throws NoSuchMethodException { + return attemptToExecuteMethod(receiver, methodName, new Class[] {parameterType}, new Object[] {parameter}); + } + + /** + * Attempt to execute a method, given the receiver, + * method name, parameter types, and parameters. + * Return its result. + * Throw an exception if the method is not found. + * Useful for invoking private, package, or protected methods. + * Object#execute(String methodName, Class<?>[] parameterTypes, Object[] parameters) throws NoSuchMethodException + */ + public static Object attemptToExecuteMethod(Object receiver, String methodName, Class<?>[] parameterTypes, Object[] parameters) throws NoSuchMethodException { + return executeMethod(method(receiver, methodName, parameterTypes), receiver, parameters); + } + + /** + * Attempt to execute a method, given the receiver, + * method name, parameter types, and parameters. + * Return its result. + * Throw an exception if the method is not found. + * If the executed method throws an exception, rethrow that exception. + * Useful for invoking private, package, or protected methods. + * Object#execute(String methodName, Class<?>[] parameterTypes, Object[] parameters) throws NoSuchMethodException + */ + public static Object attemptToExecuteMethodWithException(Object receiver, String methodName, Class<?>[] parameterTypes, Object[] parameters) + throws Throwable, NoSuchMethodException + { + return executeMethodWithException(method(receiver, methodName, parameterTypes), receiver, parameters); + } + + /** + * Convenience method. + * Attempt to execute a zero-argument static method, + * given the class and method name. + * Return its result. + * Throw an exception if the method is not found. + * Useful for invoking private, package, or protected methods. + * Class#executeStaticMethod(String methodName) throws NoSuchMethodException + */ + public static Object attemptToExecuteStaticMethod(Class<?> javaClass, String methodName) throws NoSuchMethodException { + return attemptToExecuteStaticMethod(javaClass, methodName, ZERO_PARAMETER_TYPES, ZERO_PARAMETERS); + } + + /** + * Attempt to execute a static method, given the class, + * method name, parameter types, and parameters. + * Return its result. + * Throw an exception if the method is not found. + * Useful for invoking private, package, or protected methods. + * Class#executeStaticMethod(String methodName, Class<?>[] parameterTypes, Object[] parameters) throws NoSuchMethodException + */ + public static Object attemptToExecuteStaticMethod(Class<?> javaClass, String methodName, Class<?>[] parameterTypes, Object[] parameters) throws NoSuchMethodException { + return executeStaticMethod(staticMethod(javaClass, methodName, parameterTypes), parameters); + } + + /** + * Convenience method. + * Attempt to execute a static method, given the class, + * method name, parameter type, and parameter. + * Return its result. + * Throw an exception if the method is not found. + * Useful for invoking private, package, or protected methods. + * Class#executeStaticMethod(String methodName, Class<?> parameterType, Object parameter) throws NoSuchMethodException + */ + public static Object attemptToExecuteStaticMethod(Class<?> javaClass, String methodName, Class<?> parameterType, Object parameter) throws NoSuchMethodException { + return attemptToExecuteStaticMethod(javaClass, methodName, new Class[] {parameterType}, new Object[] {parameter}); + } + + /** + * Attempt to set a field value, given the + * containing object, field name, and new field value. + * Useful for accessing private, package, or protected fields. + * Throw an exception if the field is not defined. + * Object#setFieldValue(String fieldName, Object fieldValue) throws NoSuchFieldException + */ + public static void attemptToSetFieldValue(Object object, String fieldName, Object fieldValue) throws NoSuchFieldException { + try { + field(object, fieldName).set(object, fieldValue); + } catch (IllegalAccessException iae) { + throw new RuntimeException(iae + CR + fullyQualifiedFieldName(object, fieldName), iae); + } + } + + /** + * Attempt to set a static field value, given the + * containing class, field name, and new field value. + * Useful for accessing private, package, or protected fields. + * Throw an exception if the field is not defined. + * Class#setStaticFieldValue(String fieldName, Object fieldValue) throws NoSuchFieldException + */ + public static void attemptToSetStaticFieldValue(Class<?> javaClass, String fieldName, Object fieldValue) throws NoSuchFieldException { + try { + field(javaClass, fieldName).set(null, fieldValue); + } catch (IllegalAccessException iae) { + throw new RuntimeException(iae + CR + fullyQualifiedFieldName(javaClass, fieldName), iae); + } + } + + /** + * Convenience method. + * Return the default (zero-argument) constructor + * for the specified class. + * Set accessible to true, so we can access + * private/package/protected constructors. + * Class#constructor() throws NoSuchMethodException + */ + public static <T> Constructor<T> constructor(Class<T> javaClass) throws NoSuchMethodException { + return constructor(javaClass, ZERO_PARAMETER_TYPES); + } + + /** + * Return the constructor for the specified class + * and formal parameter types. + * Set accessible to true, so we can access + * private/package/protected constructors. + * Class#constructor(Class<?>[] parameterTypes) throws NoSuchMethodException + */ + public static <T> Constructor<T> constructor(Class<T> javaClass, Class<?>[] parameterTypes) throws NoSuchMethodException { + Constructor<T> constructor = javaClass.getDeclaredConstructor(parameterTypes); + constructor.setAccessible(true); + return constructor; + } + + /** + * Convenience method. + * Return the constructor for the specified class + * and formal parameter type. + * Set accessible to true, so we can access + * private/package/protected constructors. + * Class#constructor(Class<?> parameterType) throws NoSuchMethodException + */ + public static <T> Constructor<T> constructor(Class<T> javaClass, Class<?> parameterType) throws NoSuchMethodException { + return constructor(javaClass, new Class[] {parameterType}); + } + + /** + * Return the declared fields for the specified class. + * Set accessible to true, so we can access + * private/package/protected fields. + * Class#accessibleDeclaredFields() + */ + public static Field[] declaredFields(Class<?> javaClass) { + Field[] fields = javaClass.getDeclaredFields(); + for (Field field : fields) { + field.setAccessible(true); + } + return fields; + } + + /** + * Return the declared methods for the + * specified class. + * Set accessible to true, so we can access + * private/package/protected methods. + * Class#accessibleDeclaredMethods() + */ + public static Method[] declaredMethods(Class<?> javaClass) { + Method[] methods = javaClass.getDeclaredMethods(); + for (Method method : methods) { + method.setAccessible(true); + } + return methods; + } + + /** + * Return the default (zero-argument) constructor + * for the specified class. + * Set accessible to true, so we can access + * private/package/protected constructors. + * Class#defaultConstructor() + */ + public static <T> Constructor<T> defaultConstructor(Class<T> javaClass) throws NoSuchMethodException { + return constructor(javaClass); + } + + /** + * Return a field for the specified class and field name. + * If the class does not directly + * define the field, look for it in the class's superclasses. + * Set accessible to true, so we can access + * private/package/protected fields. + */ + public static Field field(Class<?> javaClass, String fieldName) throws NoSuchFieldException { + Field field = null; + try { + field = javaClass.getDeclaredField(fieldName); + } catch (NoSuchFieldException ex) { + Class<?> superclass = javaClass.getSuperclass(); + if (superclass == null) { + throw ex; + } + // recurse + return field(superclass, fieldName); + } + field.setAccessible(true); + return field; + } + + /** + * Convenience method. + * Return a field for the specified object and field name. + * If the object's class does not directly + * define the field, look for it in the class's superclasses. + * Set accessible to true, so we can access + * private/package/protected fields. + */ + public static Field field(Object object, String fieldName) throws NoSuchFieldException { + return field(object.getClass(), fieldName); + } + + /* + * Return a string representation of the specified constructor. + */ + private static String fullyQualifiedConstructorSignature(Class<?> javaClass, Class<?>[] parameterTypes) { + return fullyQualifiedMethodSignature(javaClass, null, parameterTypes); + } + + /* + * Return a string representation of the specified field. + */ + private static String fullyQualifiedFieldName(Class<?> javaClass, String fieldName) { + StringBuilder sb = new StringBuilder(200); + sb.append(javaClass.getName()); + sb.append('.'); + sb.append(fieldName); + return sb.toString(); + } + + /* + * Return a string representation of the specified field. + */ + private static String fullyQualifiedFieldName(Object object, String fieldName) { + return fullyQualifiedFieldName(object.getClass(), fieldName); + } + + /* + * Return a string representation of the specified method. + */ + private static String fullyQualifiedMethodSignature(Class<?> javaClass, String methodName, Class<?>[] parameterTypes) { + StringBuilder sb = new StringBuilder(200); + sb.append(javaClass.getName()); + // this check allows us to use this code for constructors, where the methodName is null + if (methodName != null) { + sb.append('.'); + sb.append(methodName); + } + sb.append('('); + int max = parameterTypes.length - 1; + if (max != -1) { + // stop one short of the end of the array + for (int i = 0; i < max; i++) { + sb.append(parameterTypes[i].getName()); + sb.append(", "); + } + sb.append(parameterTypes[max].getName()); + } + sb.append(')'); + return sb.toString(); + } + + /* + * Return a string representation of the specified method. + */ + private static String fullyQualifiedMethodSignature(Object receiver, String methodName, Class<?>[] parameterTypes) { + return fullyQualifiedMethodSignature(receiver.getClass(), methodName, parameterTypes); + } + + /** + * Get a field value, given the containing object and field name. + * Return its result. + * Useful for accessing private, package, or protected fields. + * Object#getFieldValue(String fieldName) + */ + public static Object fieldValue(Object object, String fieldName) { + try { + return attemptToGetFieldValue(object, fieldName); + } catch (NoSuchFieldException nsfe) { + throw new RuntimeException(nsfe + CR + fullyQualifiedFieldName(object, fieldName), nsfe); + } + } + + /** + * Get a static field value, given the containing class and field name. + * Return its result. + * Useful for accessing private, package, or protected fields. + * Class#getStaticFieldValue(String fieldName) + */ + public static Object staticFieldValue(Class<?> javaClass, String fieldName) { + try { + return attemptToGetStaticFieldValue(javaClass, fieldName); + } catch (NoSuchFieldException nsfe) { + throw new RuntimeException(nsfe + CR + fullyQualifiedFieldName(javaClass, fieldName), nsfe); + } + } + + /** + * Convenience method. + * Execute a zero-argument method, given the receiver and method name. + * Return its result. + * Useful for invoking private, package, or protected methods. + * Object#execute(String methodName) + */ + public static Object executeMethod(Object receiver, String methodName) { + return executeMethod(receiver, methodName, ZERO_PARAMETER_TYPES, ZERO_PARAMETERS); + } + + /** + * Execute a method, given the receiver, + * method name, parameter types, and parameters. + * Return its result. + * Useful for invoking private, package, or protected methods. + * Object#execute(String methodName, Class<?>[] parameterTypes, Object[] parameters) + */ + public static Object executeMethod(Object receiver, String methodName, Class<?>[] parameterTypes, Object[] parameters) { + try { + return attemptToExecuteMethod(receiver, methodName, parameterTypes, parameters); + } catch (NoSuchMethodException nsme) { + throw new RuntimeException(nsme + CR + fullyQualifiedMethodSignature(receiver, methodName, parameterTypes), nsme); + } + } + + /** + * Convenience method. + * Execute a one-argument method, given the receiver, + * method name, parameter type, and parameter. + * Return its result. + * Useful for invoking private, package, or protected methods. + * Object#execute(String methodName, Class<?> parameterType, Object parameter) + */ + public static Object executeMethod(Object receiver, String methodName, Class<?> parameterType, Object parameter) { + return executeMethod(receiver, methodName, new Class[] {parameterType}, new Object[] {parameter}); + } + + /** + * Convenience method. + * Execute a zero-argument method, given the receiver and method name. + * Return its result. + * If the method throws an exception, rethrow that exception. + * Useful for invoking private, package, or protected methods. + * Object#execute(String methodName) + */ + public static Object executeMethodWithException(Object receiver, String methodName) + throws Throwable + { + return executeMethodWithException(receiver, methodName, ZERO_PARAMETER_TYPES, ZERO_PARAMETERS); + } + + /** + * Convenience method. + * Execute a one-argument method, given the receiver, + * method name, parameter type, and parameter. + * Return its result. + * If the method throws an exception, rethrow that exception. + * Useful for invoking private, package, or protected methods. + * Object#execute(String methodName, Class<?> parameterType, Object parameter) + */ + public static Object executeMethodWithException(Object receiver, String methodName, Class<?> parameterType, Object parameter) + throws Throwable + { + return executeMethodWithException(receiver, methodName, new Class[] {parameterType}, new Object[] {parameter}); + } + + /** + * Execute a method, given the receiver, + * method name, parameter types, and parameters. + * Return its result. + * If the method throws an exception, rethrow that exception. + * Useful for invoking private, package, or protected methods. + * Object#execute(String methodName, Class<?>[] parameterTypes, Object[] parameters) + */ + public static Object executeMethodWithException(Object receiver, String methodName, Class<?>[] parameterTypes, Object[] parameters) + throws Throwable + { + try { + return attemptToExecuteMethodWithException(receiver, methodName, parameterTypes, parameters); + } catch (NoSuchMethodException nsme) { + throw new RuntimeException(nsme + CR + fullyQualifiedMethodSignature(receiver, methodName, parameterTypes), nsme); + } + } + + /** + * Execute the specified method with the specified parameters. + * Return its result. + * Convert exceptions to RuntimeExceptions. + */ + public static Object executeMethod(Method method, Object receiver, Object[] parameters) { + try { + return method.invoke(receiver, parameters); + } catch (IllegalAccessException iae) { + throw new RuntimeException(iae + CR + method, iae); + } catch (InvocationTargetException ite) { + throw new RuntimeException(method + CR + ite.getTargetException(), ite); + } + } + + /** + * Execute the specified method with the specified parameters. + * Return its result. + * If the method throws an exception, rethrow that exception. + * Convert all other exceptions to RuntimeExceptions. + */ + public static Object executeMethodWithException(Method method, Object receiver, Object[] parameters) + throws Throwable + { + try { + return method.invoke(receiver, parameters); + } catch (IllegalAccessException iae) { + throw new RuntimeException(iae + CR + method, iae); + } catch (InvocationTargetException ite) { + Throwable cause = ite.getCause(); + if (cause == null) { + throw new RuntimeException(method.toString(), ite); + } + throw cause; + } + } + + /** + * Convenience method. + * Execute a zero-argument static method, + * given the class and method name. + * Return its result. + * Useful for invoking private, package, or protected methods. + * Class#executeStaticMethod(String methodName) + */ + public static Object executeStaticMethod(Class<?> javaClass, String methodName) { + return executeStaticMethod(javaClass, methodName, ZERO_PARAMETER_TYPES, ZERO_PARAMETERS); + } + + /** + * Execute a static method, given the class, + * method name, parameter types, and parameters. + * Return its result. + * Useful for invoking private, package, or protected methods. + * Class#executeStaticMethod(String methodName, Class<?>[] parameterTypes, Object[] parameters) + */ + public static Object executeStaticMethod(Class<?> javaClass, String methodName, Class<?>[] parameterTypes, Object[] parameters) { + try { + return attemptToExecuteStaticMethod(javaClass, methodName, parameterTypes, parameters); + } catch (NoSuchMethodException nsme) { + throw new RuntimeException(nsme + CR + fullyQualifiedMethodSignature(javaClass, methodName, parameterTypes), nsme); + } + } + + /** + * Convenience method. + * Execute a static method, given the class, + * method name, parameter type, and parameter. + * Return its result. + * Useful for invoking private, package, or protected methods. + * Class#executeStaticMethod(String methodName, Class<?> parameterType, Object parameter) + */ + public static Object executeStaticMethod(Class<?> javaClass, String methodName, Class<?> parameterType, Object parameter) { + return executeStaticMethod(javaClass, methodName, new Class[] {parameterType}, new Object[] {parameter}); + } + + /** + * Execute the specified static method with the specified parameters. + * Return its result. + * Convert exceptions to RuntimeExceptions. + */ + public static Object executeStaticMethod(Method method, Object[] parameters) { + return executeMethod(method, null, parameters); + } + + /** + * Convenience method. + * Return a zero-argument method for the specified class + * and method name. If the class does not directly + * implement the method, look for it in the class's superclasses. + * Set accessible to true, so we can access + * private/package/protected methods. + */ + public static Method method(Class<?> javaClass, String methodName) throws NoSuchMethodException { + return method(javaClass, methodName, ZERO_PARAMETER_TYPES); + } + + /** + * Return a method for the specified class, method name, + * and formal parameter types. If the class does not directly + * implement the method, look for it in the class's superclasses. + * Set accessible to true, so we can access + * private/package/protected methods. + */ + public static Method method(Class<?> javaClass, String methodName, Class<?>[] parameterTypes) throws NoSuchMethodException { + Method method = null; + try { + method = javaClass.getDeclaredMethod(methodName, parameterTypes); + } catch (NoSuchMethodException ex) { + Class<?> superclass = javaClass.getSuperclass(); + if (superclass == null) { + throw ex; + } + // recurse + return method(superclass, methodName, parameterTypes); + } + method.setAccessible(true); + return method; + } + + /** + * Convenience method. + * Return a method for the specified class, method name, + * and formal parameter type. If the class does not directly + * implement the method, look for it in the class's superclasses. + * Set accessible to true, so we can access + * private/package/protected methods. + */ + public static Method method(Class<?> javaClass, String methodName, Class<?> parameterType) throws NoSuchMethodException { + return method(javaClass, methodName, new Class[] {parameterType}); + } + + /** + * Convenience method. + * Return a zero-argument method for the specified object + * and method name. If the object's class does not directly + * implement the method, look for it in the class's superclasses. + * Set accessible to true, so we can access + * private/package/protected methods. + */ + public static Method method(Object object, String methodName) throws NoSuchMethodException { + return method(object.getClass(), methodName); + } + + /** + * Convenience method. + * Return a method for the specified object, method name, + * and formal parameter types. If the object's class does not directly + * implement the method, look for it in the class's superclasses. + * Set accessible to true, so we can access + * private/package/protected methods. + */ + public static Method method(Object object, String methodName, Class<?>[] parameterTypes) throws NoSuchMethodException { + return method(object.getClass(), methodName, parameterTypes); + } + + /** + * Convenience method. + * Return a method for the specified object, method name, + * and formal parameter type. If the object's class does not directly + * implement the method, look for it in the class's superclasses. + * Set accessible to true, so we can access + * private/package/protected methods. + */ + public static Method method(Object object, String methodName, Class<?> parameterType) throws NoSuchMethodException { + return method(object.getClass(), methodName, parameterType); + } + + /** + * Convenience method. + * Return the specified class (without the checked exception). + */ + public static Class<?> classForName(String className) { + try { + return Class.forName(className); + } catch (ClassNotFoundException ex) { + throw new RuntimeException(className, ex); + } + } + + /** + * Convenience method. + * Return a new instance of the specified class, + * using the class's default (zero-argument) constructor. + * Class#newInstance() + */ + public static <T> T newInstance(Class<T> javaClass) { + return newInstance(javaClass, ZERO_PARAMETER_TYPES, ZERO_PARAMETERS); + } + + /** + * Convenience method. + * Return a new instance of the specified class, + * using the class's default (zero-argument) constructor. + * Class#newInstance() + */ + public static Object newInstance(String className) throws ClassNotFoundException { + return newInstance(className, null); + } + + /** + * Convenience method. + * Return a new instance of the specified class, + * using the class's default (zero-argument) constructor. + * Class#newInstance() + */ + public static Object newInstance(String className, ClassLoader classLoader) throws ClassNotFoundException { + return newInstance(Class.forName(className, true, classLoader)); + } + + /** + * Return a new instance of the specified class, + * given the constructor parameter types and parameters. + * Class#newInstance(Class<?>[] parameterTypes, Object[] parameters) + */ + public static <T> T newInstance(Class<T> javaClass, Class<?>[] parameterTypes, Object[] parameters) { + try { + return attemptNewInstance(javaClass, parameterTypes, parameters); + } catch (NoSuchMethodException nsme) { + throw new RuntimeException(nsme + CR + fullyQualifiedConstructorSignature(javaClass, parameterTypes), nsme); + } + } + + /** + * Return a new instance of the specified class, + * given the constructor parameter types and parameters. + * Class#newInstance(Class<?>[] parameterTypes, Object[] parameters) + */ + public static Object newInstance(String className, Class<?>[] parameterTypes, Object[] parameters) throws ClassNotFoundException { + return newInstance(className, parameterTypes, parameters, null); + } + + /** + * Return a new instance of the specified class, + * given the constructor parameter types and parameters. + * Class#newInstance(Class<?>[] parameterTypes, Object[] parameters) + */ + public static Object newInstance(String className, Class<?>[] parameterTypes, Object[] parameters, ClassLoader classLoader) throws ClassNotFoundException { + return newInstance(Class.forName(className, true, classLoader), parameterTypes, parameters); + } + + /** + * Convenience method. + * Return a new instance of the specified class, + * given the constructor parameter type and parameter. + * Class#newInstance(Class<?> parameterType, Object parameter) + */ + public static <T> T newInstance(Class<T> javaClass, Class<?> parameterType, Object parameter) { + return newInstance(javaClass, new Class[] {parameterType}, new Object[] {parameter}); + } + + /** + * Return a new instance of the specified class, + * given the constructor parameter type and parameter. + * Class#newInstance(Class<?> parameterType, Object parameter) + */ + public static Object newInstance(String className, Class<?> parameterType, Object parameter) throws ClassNotFoundException { + return newInstance(className, parameterType, parameter, null); + } + + /** + * Return a new instance of the specified class, + * given the constructor parameter type and parameter. + * Class#newInstance(Class<?> parameterType, Object parameter) + */ + public static Object newInstance(String className, Class<?> parameterType, Object parameter, ClassLoader classLoader) throws ClassNotFoundException { + return newInstance(Class.forName(className, false, classLoader), parameterType, parameter); + } + + /* + * Push the declared fields for the specified class + * onto the top of the stack. + */ + private static void pushDeclaredFields(Class<?> javaClass, Stack<Field> stack) { + Field[] fields = declaredFields(javaClass); + for (int i = fields.length; i-- > 0; ) { + stack.push(fields[i]); + } + } + + /* + * Push the declared methods for the specified class + * onto the top of the stack. + */ + private static void pushDeclaredMethods(Class<?> javaClass, Stack<Method> stack) { + Method[] methods = declaredMethods(javaClass); + for (int i = methods.length; i-- > 0; ) { + stack.push(methods[i]); + } + } + + /** + * Set a field value, given the containing object, field name, and new field value. + * Useful for accessing private, package, or protected fields. + * Object#setFieldValue(String fieldName, Object fieldValue) + */ + public static void setFieldValue(Object object, String fieldName, Object fieldValue) { + try { + attemptToSetFieldValue(object, fieldName, fieldValue); + } catch (NoSuchFieldException nsfe) { + throw new RuntimeException(nsfe + CR + fullyQualifiedFieldName(object, fieldName), nsfe); + } + } + + /** + * Set a static field value, given the containing class, field name, and new field value. + * Useful for accessing private, package, or protected fields. + * Class#setStaticFieldValue(String fieldName, Object fieldValue) + */ + public static void setStaticFieldValue(Class<?> javaClass, String fieldName, Object fieldValue) { + try { + attemptToSetStaticFieldValue(javaClass, fieldName, fieldValue); + } catch (NoSuchFieldException nsfe) { + throw new RuntimeException(nsfe + CR + fullyQualifiedFieldName(javaClass, fieldName), nsfe); + } + } + + /** + * Return the short name of the object's class. + * Class#getShortName() + */ + public static String shortClassNameForObject(Object object) { + return shortNameFor(object.getClass()); + } + + /** + * Return the short name of the class (e.g. "Object"). + * Class#getShortName() + */ + public static String shortNameForClassNamed(String className) { + return className.substring(className.lastIndexOf('.') + 1); + } + + /** + * Return the short name of the class (e.g. "Object"). + * Class#getShortName() + */ + public static String shortNameFor(Class<?> javaClass) { + return shortNameForClassNamed(javaClass.getName()); + } + + /** + * Return the nested name of the object's class. + * Class#getNestedName() + */ + public static String nestedClassNameForObject(Object object) { + return nestedNameFor(object.getClass()); + } + + /** + * Return the nested name of the class (e.g. "Entry"). + * Class#getNestedName() + */ + public static String nestedNameForClassNamed(String className) { + return className.substring(className.lastIndexOf(NESTED_CLASS_NAME_SEPARATOR) + 1); + } + + /** + * Return the nested name of the class (e.g. "Entry"). + * Class#getNestedName() + */ + public static String nestedNameFor(Class<?> javaClass) { + return nestedNameForClassNamed(javaClass.getName()); + } + + /** + * Return the "toString()" name of the object's class. + */ + public static String toStringClassNameForObject(Object object) { + return toStringNameFor(object.getClass()); + } + + /** + * Return the "toString()" name of the class. + * "Member" classes will return only the final name: + * "com.foo.bar.TopLevelClass$MemberClass$NestedMemberClass" + * => "NestedMemberClass" + * "Local" and "anonymous" classes will still return the embedded '$'s: + * "com.foo.bar.TopLevelClass$1LocalClass" + * => "TopLevelClass$1LocalClass" + * "com.foo.bar.TopLevelClass$1" + * => "TopLevelClass$1" + */ + public static String toStringNameForClassNamed(String className) { + return classNamedIsMember(className) ? + className.substring(className.lastIndexOf(NESTED_CLASS_NAME_SEPARATOR) + 1) + : + className.substring(className.lastIndexOf('.') + 1); + } + + /** + * Return the "toString()" name of the class. + */ + public static String toStringNameFor(Class<?> javaClass) { + return toStringNameForClassNamed(javaClass.getName()); + } + + /** + * Return the package name of the class (e.g. "java.lang"). + * Class#getPackageName() + */ + public static String packageNameFor(Class<?> javaClass) { + return packageNameForClassNamed(javaClass.getName()); + } + + /** + * Return the package name of the class (e.g. "java.lang"). + * Class#getPackageName() + */ + public static String packageNameForClassNamed(String className) { + int lastPeriod = className.lastIndexOf('.'); + if (lastPeriod == -1) { + return ""; + } + return className.substring(0, lastPeriod); + } + + /** + * Return the short name of the class, + * followed by its package name (e.g. "Object (java.lang)"). + * Class#getShortNameWithPackage() + */ + public static String shortNameWithPackage(Class<?> javaClass) { + StringBuilder sb = new StringBuilder(200); + sb.append(shortNameFor(javaClass)); + if ( ! javaClass.isPrimitive()) { + sb.append(" ("); + sb.append(packageNameFor(javaClass)); + sb.append(')'); + } + return sb.toString(); + } + + /** + * Convenience method. + * Return a zero-argument, static method for the specified class + * and method name. If the class does not directly + * implement the method, look for it in the class's superclasses. + * Set accessible to true, so we can access + * private/package/protected methods. + */ + public static Method staticMethod(Class<?> javaClass, String methodName) throws NoSuchMethodException { + return staticMethod(javaClass, methodName, ZERO_PARAMETER_TYPES); + } + + /** + * Return a static method for the specified class, method name, + * and formal parameter types. If the class does not directly + * implement the method, look for it in the class's superclasses. + * Set accessible to true, so we can access + * private/package/protected methods. + */ + public static Method staticMethod(Class<?> javaClass, String methodName, Class<?>[] parameterTypes) throws NoSuchMethodException { + Method method = method(javaClass, methodName, parameterTypes); + if (Modifier.isStatic(method.getModifiers())) { + return method; + } + throw new NoSuchMethodException(fullyQualifiedMethodSignature(javaClass, methodName, parameterTypes)); + } + + /** + * Convenience method. + * Return a static method for the specified class, method name, + * and formal parameter type. If the class does not directly + * implement the method, look for it in the class's superclasses. + * Set accessible to true, so we can access + * private/package/protected methods. + */ + public static Method staticMethod(Class<?> javaClass, String methodName, Class<?> parameterTypes) throws NoSuchMethodException { + return staticMethod(javaClass, methodName, new Class[] {parameterTypes}); + } + + /** + * Return whether the specified class can be "declared" in code; + * i.e. it is either a "top-level" class or a "member" class, but it + * is not an "array" class. This method rolls together all the checks + * from the other methods for a bit of a performance tweak. + * Class#isDeclarable() + */ + public static boolean classNamedIsDeclarable(String className) { + if (className.charAt(0) == ARRAY_INDICATOR) { + return false; // it is an "array" class + } + int index = className.indexOf(NESTED_CLASS_NAME_SEPARATOR); + if (index == -1) { + return true; // it is a "top-level" class + } + do { + // the character immediately after each dollar sign cannot be a digit + index++; + if (Character.isDigit(className.charAt(index))) { + return false; + } + index = className.indexOf(NESTED_CLASS_NAME_SEPARATOR, index); + } while (index != -1); + return true; + } + + /** + * Return whether the specified class is a "top-level" class, + * as opposed to a "member", "local", or "anonymous" class, + * using the standard jdk naming conventions (i.e. the class + * name does NOT contain a '$': "TopLevelClass"). + * Class#isTopLevel() + */ + public static boolean classNamedIsTopLevel(String className) { + if (classNamedIsArray(className)) { + return false; + } + return className.indexOf(NESTED_CLASS_NAME_SEPARATOR) == -1; + } + + /** + * Return whether the specified class is a "member" class, + * as opposed to a "top-level", "local", or "anonymous" class, + * using the standard jdk naming conventions (i.e. the class + * name contains at least one '$' and all the names between + * each '$' are legal class names: + * "TopLevelClass$MemberClass$NestedMemberClass"). + * Class#isMember() + */ + public static boolean classNamedIsMember(String className) { + if (classNamedIsArray(className)) { + return false; + } + int index = className.indexOf(NESTED_CLASS_NAME_SEPARATOR); + if (index == -1) { + return false; // it is a "top-level" class + } + do { + // the character immediately after each dollar sign cannot be a digit + index++; + if (Character.isDigit(className.charAt(index))) { + return false; + } + index = className.indexOf(NESTED_CLASS_NAME_SEPARATOR, index); + } while (index != -1); + return true; + } + + /** + * Return whether the specified class is a "local" class, + * as opposed to a "top-level", "member", or "anonymous" class, + * using the standard jdk (or Eclipse) naming conventions. + * In the jdk, the class name ends with '$nnnXXX' where the '$' is + * followed by a series of numeric digits which are followed by the + * local class name: "TopLevelClass$1LocalClass". + * In Eclipse, the class name ends with '$nnn$XXX' where the '$' is + * followed by a series of numeric digits which are separated from + * the local class name by another '$': "TopLevelClass$1$LocalClass". + * Class#isLocal() + */ + public static boolean classNamedIsLocal(String className) { + if (classNamedIsArray(className)) { + return false; + } + int dollar = className.indexOf(NESTED_CLASS_NAME_SEPARATOR); + if (dollar == -1) { + return false; + } + if ( ! Character.isDigit(className.charAt(dollar + 1))) { + return false; + } + int len = className.length(); + for (int i = dollar + 2; i < len; i++) { + if (Character.isJavaIdentifierStart(className.charAt(i))) { + return true; + } + } + // all the characters past the $ are digits (anonymous) + return false; + } + + /** + * Return whether the specified class is an "anonymous" class, + * as opposed to a "top-level", "member", or "local" class, + * using the standard jdk naming conventions (i.e. the class + * name ends with '$nnn' where all the characters past the + * last '$' are numeric digits: "TopLevelClass$1"). + * Class#isAnonymous() + */ + public static boolean classNamedIsAnonymous(String className) { + if (classNamedIsArray(className)) { + return false; + } + int dollar = className.indexOf(NESTED_CLASS_NAME_SEPARATOR); + if (dollar == -1) { + return false; + } + int start = dollar + 1; + for (int i = className.length(); i-- > start; ) { + if ( ! Character.isDigit(className.charAt(i))) { + return false; + } + } + // all the characters past the $ are digits + return true; + } + + /** + * Return the "array depth" of the specified class. + * The depth is the number of dimensions for an array type. + * Non-array types have a depth of zero. + * Class#getArrayDepth() + */ + public static int arrayDepthFor(Class<?> javaClass) { + int depth = 0; + while (javaClass.isArray()) { + depth++; + javaClass = javaClass.getComponentType(); + } + return depth; + } + + /** + * Return the "array depth" of the specified object. + * The depth is the number of dimensions for an array. + * Non-arrays have a depth of zero. + */ + public static int arrayDepthForObject(Object object) { + return arrayDepthFor(object.getClass()); + } + + /** + * Return the "array depth" of the specified class. + * The depth is the number of dimensions for an array type. + * Non-array types have a depth of zero. + * @see java.lang.Class#getName() + * Class#getArrayDepth() + */ + public static int arrayDepthForClassNamed(String className) { + int depth = 0; + while (className.charAt(depth) == ARRAY_INDICATOR) { + depth++; + } + return depth; + } + + /** + * Return whether the specified class is an array type. + * @see java.lang.Class#getName() + */ + public static boolean classNamedIsArray(String className) { + return className.charAt(0) == ARRAY_INDICATOR; + } + + /** + * Return the "element type" of the specified class. + * The element type is the base type held by an array type. + * A non-array type simply returns itself. + * Class#getElementType() + */ + public static Class<?> elementTypeFor(Class<?> javaClass) { + while (javaClass.isArray()) { + javaClass = javaClass.getComponentType(); + } + return javaClass; + } + + /** + * Return the "element type" of the specified object. + * The element type is the base type held by an array. + * A non-array simply returns its class. + */ + public static Class<?> elementTypeForObject(Object object) { + return elementTypeFor(object.getClass()); + } + + /** + * Return the "element type" of the specified class. + * The element type is the base type held by an array type. + * Non-array types simply return themselves. + * Class#getElementType() + */ + public static String elementTypeNameFor(Class<?> javaClass) { + return elementTypeFor(javaClass).getName(); + } + + /** + * Return the "element type" of the specified class. + * The element type is the base type held by an array type. + * Non-array types simply return themselves. + * @see java.lang.Class#getName() + * Class#getElementType() + */ + public static String elementTypeNameForClassNamed(String className) { + int depth = arrayDepthForClassNamed(className); + if (depth == 0) { + // the name is in the form: "java.lang.Object" or "int" + return className; + } + int last = className.length() - 1; + if (className.charAt(depth) == REFERENCE_CLASS_CODE) { + // the name is in the form: "[[[Ljava.lang.Object;" + return className.substring(depth + 1, last); // drop the trailing ';' + } + // the name is in the form: "[[[I" + return classNameForCode(className.charAt(last)); + } + + /** + * Return whether the specified class is a "reference" + * class (i.e. neither 'void' nor one of the primitive variable classes, + * ['boolean', 'int', 'float', etc.]). + * NB: void.class.isPrimitive() == true + */ + public static boolean classNamedIsReference(String className) { + return ! classNamedIsPrimitive(className); + } + + /** + * Return whether the specified class is a primitive + * class (i.e. 'void' or one of the primitive variable classes, + * ['boolean', 'int', 'float', etc.]). + * NB: void.class.isPrimitive() == true + */ + public static boolean classNamedIsPrimitive(String className) { + if (classNamedIsArray(className) || (className.length() > maxPrimitiveClassNameLength())) { + return false; // performance tweak + } + Primitive[] codes = primitives(); + for (int i = codes.length; i-- > 0; ) { + if (codes[i].javaClass.getName().equals(className)) { + return true; + } + } + return false; + } + + /** + * Return whether the specified class is a "variable" primitive + * class (i.e. 'boolean', 'int', 'float', etc., but not 'void'). + * NB: void.class.isPrimitive() == true + */ + public static boolean classNamedIsVariablePrimitive(String className) { + return classNamedIsPrimitive(className) + && ( ! className.equals(VOID_CLASS_NAME)); + } + + /** + * Return whether the specified class is a primitive wrapper + * class (i.e. 'java.lang.Void' or one of the primitive variable wrapper classes, + * ['java.lang.Boolean', 'java.lang.Integer', 'java.lang.Float', etc.]). + * NB: void.class.isPrimitive() == true + */ + public static boolean classNamedIsPrimitiveWrapperClass(String className) { + if (classNamedIsArray(className) || (className.length() > maxPrimitiveWrapperClassNameLength())) { + return false; // performance tweak + } + Primitive[] codes = primitives(); + for (int i = codes.length; i-- > 0; ) { + if (codes[i].wrapperClass.getName().equals(className)) { + return true; + } + } + return false; + } + + /** + * Return whether the specified class is a "variable" primitive + * class (i.e. 'boolean', 'int', 'float', etc., but not 'void'). + * NB: void.class.isPrimitive() == true + */ + public static boolean classNamedIsVariablePrimitiveWrapperClass(String className) { + return classNamedIsPrimitiveWrapperClass(className) + && ( ! className.equals(VOID_WRAPPER_CLASS_NAME)); + } + + /** + * Return whether the specified class is a primitive wrapper + * class (i.e. 'java.lang.Void' or one of the primitive variable wrapper classes, + * ['java.lang.Boolean', 'java.lang.Integer', 'java.lang.Float', etc.]). + * NB: void.class.isPrimitive() == true + */ + public static boolean classIsPrimitiveWrapperClass(Class<?> javaClass) { + if (javaClass.isArray() || (javaClass.getName().length() > maxPrimitiveWrapperClassNameLength())) { + return false; // performance tweak + } + Primitive[] codes = primitives(); + for (int i = codes.length; i-- > 0; ) { + if (codes[i].wrapperClass == javaClass) { + return true; + } + } + return false; + } + + /** + * Return whether the specified class is a "variable" primitive + * class (i.e. 'boolean', 'int', 'float', etc., but not 'void'). + * NB: void.class.isPrimitive() == true + */ + public static boolean classIsVariablePrimitiveWrapperClass(Class<?> javaClass) { + return classIsPrimitiveWrapperClass(javaClass) + && (javaClass != java.lang.Void.class); + } + + /** + * Return the class name for the specified class code. + * @see java.lang.Class#getName() + */ + public static String classNameForCode(char classCode) { + return classForCode(classCode).getName(); + } + + /** + * Return the class name for the specified class code. + * @see java.lang.Class#getName() + */ + public static String classNameForCode(int classCode) { + return classNameForCode((char) classCode); + } + + /** + * Return the class for the specified class code. + * @see java.lang.Class#getName() + */ + public static Class<?> classForCode(char classCode) { + Primitive[] codes = primitives(); + for (int i = codes.length; i-- > 0; ) { + if (codes[i].code == classCode) { + return codes[i].javaClass; + } + } + throw new IllegalArgumentException(String.valueOf(classCode)); + } + + /** + * Return the class for the specified class code. + * @see java.lang.Class#getName() + */ + public static Class<?> classForCode(int classCode) { + return classForCode((char) classCode); + } + + /** + * Return the class code for the specified class. + * @see java.lang.Class#getName() + */ + public static char codeForClass(Class<?> javaClass) { + if (( ! javaClass.isArray()) && (javaClass.getName().length() <= maxPrimitiveClassNameLength())) { + Primitive[] codes = primitives(); + for (int i = codes.length; i-- > 0; ) { + if (codes[i].javaClass == javaClass) { + return codes[i].code; + } + } + } + throw new IllegalArgumentException(javaClass.getName()); + } + + /** + * Return the class code for the specified class. + * @see java.lang.Class#getName() + */ + public static char codeForClassNamed(String className) { + if (( ! classNamedIsArray(className)) && (className.length() <= maxPrimitiveClassNameLength())) { + Primitive[] codes = primitives(); + for (int i = codes.length; i-- > 0; ) { + if (codes[i].javaClass.getName().equals(className)) { + return codes[i].code; + } + } + } + throw new IllegalArgumentException(className); + } + + /** + * Return the class for the specified "type declaration". + */ + public static Class<?> classForTypeDeclaration(String typeDeclaration) throws ClassNotFoundException { + return classForTypeDeclaration(typeDeclaration, ClassTools.class.getClassLoader()); + } + + /** + * Return the class for the specified "type declaration", + * using the specified class loader. + */ + public static Class<?> classForTypeDeclaration(String typeDeclaration, ClassLoader classLoader) throws ClassNotFoundException { + TypeDeclaration td = typeDeclaration(typeDeclaration); + return classForTypeDeclaration(td.elementTypeName, td.arrayDepth); + } + + private static TypeDeclaration typeDeclaration(String typeDeclaration) { + typeDeclaration = StringTools.removeAllWhitespace(typeDeclaration); + int arrayDepth = arrayDepthForTypeDeclaration_(typeDeclaration); + String elementTypeName = typeDeclaration.substring(0, typeDeclaration.length() - (arrayDepth * 2)); + return new TypeDeclaration(elementTypeName, arrayDepth); + } + + /** + * Return the class for the specified "type declaration". + */ + public static Class<?> classForTypeDeclaration(String elementTypeName, int arrayDepth) throws ClassNotFoundException { + return classForTypeDeclaration(elementTypeName, arrayDepth, null); + } + + /** + * Return the class for the specified "type declaration", + * using the specified class loader. + */ + // see the "Evaluation" of jdk bug 6446627 for a discussion of loading classes + public static Class<?> classForTypeDeclaration(String elementTypeName, int arrayDepth, ClassLoader classLoader) throws ClassNotFoundException { + // primitives cannot be loaded via Class#forName(), + // so check for a primitive class name first + Primitive pcc = null; + if (elementTypeName.length() <= maxPrimitiveClassNameLength()) { // performance tweak + Primitive[] codes = primitives(); + for (int i = codes.length; i-- > 0; ) { + if (codes[i].javaClass.getName().equals(elementTypeName)) { + pcc = codes[i]; + break; + } + } + } + + // non-array + if (arrayDepth == 0) { + return (pcc == null) ? Class.forName(elementTypeName, false, classLoader) : pcc.javaClass; + } + + // array + StringBuilder sb = new StringBuilder(100); + for (int i = arrayDepth; i-- > 0; ) { + sb.append(ARRAY_INDICATOR); + } + if (pcc == null) { + sb.append(REFERENCE_CLASS_CODE); + sb.append(elementTypeName); + sb.append(REFERENCE_CLASS_NAME_DELIMITER); + } else { + sb.append(pcc.code); + } + return Class.forName(sb.toString(), false, classLoader); + } + + /** + * Return the class name for the specified "type declaration"; e.g. + * "int[]" -> "[I" + * @see java.lang.Class#getName() + */ + public static String classNameForTypeDeclaration(String typeDeclaration) { + TypeDeclaration td = typeDeclaration(typeDeclaration); + return classNameForTypeDeclaration(td.elementTypeName, td.arrayDepth); + } + + /** + * Return the array depth for the specified "type declaration"; e.g. + * "int[]" -> 1 + */ + public static int arrayDepthForTypeDeclaration(String typeDeclaration) { + return arrayDepthForTypeDeclaration_(StringTools.removeAllWhitespace(typeDeclaration)); + } + + /* + * Assume no whitespace in the type declaration. + */ + private static int arrayDepthForTypeDeclaration_(String typeDeclaration) { + int last = typeDeclaration.length() - 1; + int depth = 0; + int close = last; + while (typeDeclaration.charAt(close) == TYPE_DECLARATION_ARRAY_CLOSE) { + if (typeDeclaration.charAt(close - 1) == TYPE_DECLARATION_ARRAY_OPEN) { + depth++; + } else { + throw new IllegalArgumentException("invalid type declaration: " + typeDeclaration); + } + close = last - (depth * 2); + } + return depth; + } + + /** + * Return the class name for the specified "type declaration". + * @see java.lang.Class#getName() + */ + public static String classNameForTypeDeclaration(String elementTypeName, int arrayDepth) { + // non-array + if (arrayDepth == 0) { + return elementTypeName; + } + + if (elementTypeName.equals(VOID_CLASS_NAME)) { + throw new IllegalArgumentException("'" + VOID_CLASS_NAME + "' must have an array depth of zero: " + arrayDepth + '.'); + } + // array + StringBuilder sb = new StringBuilder(100); + for (int i = arrayDepth; i-- > 0; ) { + sb.append(ARRAY_INDICATOR); + } + + // look for a primitive first + Primitive pcc = null; + if (elementTypeName.length() <= maxPrimitiveClassNameLength()) { // performance tweak + Primitive[] codes = primitives(); + for (int i = codes.length; i-- > 0; ) { + if (codes[i].javaClass.getName().equals(elementTypeName)) { + pcc = codes[i]; + break; + } + } + } + + if (pcc == null) { + sb.append(REFERENCE_CLASS_CODE); + sb.append(elementTypeName); + sb.append(REFERENCE_CLASS_NAME_DELIMITER); + } else { + sb.append(pcc.code); + } + + return sb.toString(); + } + + private static int maxPrimitiveClassNameLength() { + if (MAX_PRIMITIVE_CLASS_NAME_LENGTH == -1) { + MAX_PRIMITIVE_CLASS_NAME_LENGTH = calculateMaxPrimitiveClassNameLength(); + } + return MAX_PRIMITIVE_CLASS_NAME_LENGTH; + } + + private static int calculateMaxPrimitiveClassNameLength() { + int max = -1; + Primitive[] codes = primitives(); + for (int i = codes.length; i-- > 0; ) { + int len = codes[i].javaClass.getName().length(); + if (len > max) { + max = len; + } + } + return max; + } + + private static int maxPrimitiveWrapperClassNameLength() { + if (MAX_PRIMITIVE_WRAPPER_CLASS_NAME_LENGTH == -1) { + MAX_PRIMITIVE_WRAPPER_CLASS_NAME_LENGTH = calculateMaxPrimitiveWrapperClassNameLength(); + } + return MAX_PRIMITIVE_WRAPPER_CLASS_NAME_LENGTH; + } + + private static int calculateMaxPrimitiveWrapperClassNameLength() { + int max = -1; + Primitive[] codes = primitives(); + for (int i = codes.length; i-- > 0; ) { + int len = codes[i].wrapperClass.getName().length(); + if (len > max) { + max = len; + } + } + return max; + } + + private static Primitive[] primitives() { + if (PRIMITIVES == null) { + PRIMITIVES = buildPrimitives(); + } + return PRIMITIVES; + } + + /** + * NB: void.class.isPrimitive() == true + */ + private static Primitive[] buildPrimitives() { + Primitive[] result = new Primitive[9]; + result[0] = new Primitive(BYTE_CODE, java.lang.Byte.class); + result[1] = new Primitive(CHAR_CODE, java.lang.Character.class); + result[2] = new Primitive(DOUBLE_CODE, java.lang.Double.class); + result[3] = new Primitive(FLOAT_CODE, java.lang.Float.class); + result[4] = new Primitive(INT_CODE, java.lang.Integer.class); + result[5] = new Primitive(LONG_CODE, java.lang.Long.class); + result[6] = new Primitive(SHORT_CODE, java.lang.Short.class); + result[7] = new Primitive(BOOLEAN_CODE, java.lang.Boolean.class); + result[8] = new Primitive(VOID_CODE, java.lang.Void.class); + return result; + } + + /** + * Suppress default constructor, ensuring non-instantiability. + */ + private ClassTools() { + super(); + throw new UnsupportedOperationException(); + } + + + // ********** member classes ********** + + private static class Primitive { + final char code; + final Class<?> javaClass; + final Class<?> wrapperClass; + private static final String WRAPPER_CLASS_TYPE_FIELD_NAME = "TYPE"; + // e.g. java.lang.Boolean.TYPE => boolean.class + Primitive(char code, Class<?> wrapperClass) { + this.code = code; + this.wrapperClass = wrapperClass; + this.javaClass = (Class<?>) staticFieldValue(wrapperClass, WRAPPER_CLASS_TYPE_FIELD_NAME); + } + } + + private static class TypeDeclaration { + final String elementTypeName; + final int arrayDepth; + TypeDeclaration(String elementTypeName, int arrayDepth) { + this.elementTypeName = elementTypeName; + this.arrayDepth = arrayDepth; + } + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ArrayToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ArrayToolsTests.java new file mode 100644 index 0000000000..b5f840729f --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ArrayToolsTests.java @@ -0,0 +1,3523 @@ +/******************************************************************************* + * Copyright (c) 2005, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.Vector; + +import junit.framework.TestCase; + +import org.eclipse.jpt.common.utility.internal.ArrayTools; +import org.eclipse.jpt.common.utility.internal.Range; +import org.eclipse.jpt.common.utility.internal.ReflectionTools; +import org.eclipse.jpt.common.utility.internal.ReverseComparator; +import org.eclipse.jpt.common.utility.internal.iterators.EmptyIterator; + +@SuppressWarnings("nls") +public class ArrayToolsTests extends TestCase { + + public ArrayToolsTests(String name) { + super(name); + } + + + // ********** instantiation ********** + + public void testNewArrayObjectArray() { + String[] array1 = new String[2]; + String[] array2 = ArrayTools.newArray(array1); + array2[0] = "foo"; + array2[1] = "bar"; + assertEquals(String.class, array2.getClass().getComponentType()); + assertEquals(2, array2.length); + } + + public void testNewArrayObjectArrayInt() { + String[] array1 = new String[2]; + String[] array2 = ArrayTools.newArray(array1, 5); + array2[0] = "foo"; + array2[4] = "bar"; + assertEquals(String.class, array2.getClass().getComponentType()); + assertEquals(5, array2.length); + } + + public void testNewArrayObjectArrayInt_Exception() { + String[] array1 = new String[2]; + Object[] array2 = ArrayTools.newArray(array1, 5); + boolean exCaught = false; + try { + array2[1] = Integer.valueOf(7); + fail("bogus array: " + Arrays.toString(array2)); + } catch (ArrayStoreException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testComponentType() { + String[] array = new String[2]; + Class<? extends String> javaClass = ArrayTools.componentType(array); + assertEquals(String.class, javaClass); + } + + public void testNewArrayClassInt() { + String[] array = ArrayTools.newArray(String.class, 5); + array[0] = "foo"; + array[4] = "bar"; + assertEquals(String.class, array.getClass().getComponentType()); + assertEquals(5, array.length); + } + + public void testNewArrayClassInt_Exception() { + Object[] array = ArrayTools.newArray(String.class, 5); + boolean exCaught = false; + try { + array[1] = Integer.valueOf(7); + fail("bogus array: " + Arrays.toString(array)); + } catch (ArrayStoreException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testNewArrayClassInt_Primitive() { + boolean exCaught = false; + try { + Object[] array = ArrayTools.newArray(int.class, 5); + fail("bogus array: " + Arrays.toString(array)); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + + // ********** conversion ********** + + public void testArrayIterable() { + Iterable<String> iterable = this.buildStringList1(); + Object[] a = ArrayTools.array(iterable); + assertEquals(3, a.length); + assertTrue(ArrayTools.containsAll(a, this.buildStringList1().iterator())); + } + + public void testArrayIterableInt() { + Iterable<String> iterable = this.buildStringList1(); + Object[] a = ArrayTools.array(iterable, 3); + assertEquals(3, a.length); + assertTrue(ArrayTools.containsAll(a, this.buildStringList1().iterator())); + } + + public void testArrayIterableObjectArray_String() { + Iterable<String> iterable = this.buildStringList1(); + String[] a = ArrayTools.array(iterable, new String[0]); + assertEquals(3, a.length); + assertTrue(ArrayTools.containsAll(a, this.buildStringList1().iterator())); + } + + public void testArrayIterableObjectArray_Object() { + Iterable<String> iterable = this.buildStringList1(); + Object[] a = ArrayTools.array(iterable, new Object[0]); + assertEquals(3, a.length); + assertTrue(ArrayTools.containsAll(a, this.buildStringList1().iterator())); + } + + public void testArrayIterableIntObjectArray() { + Iterable<String> iterable = this.buildStringList1(); + String[] a = ArrayTools.array(iterable, 3, new String[0]); + assertEquals(3, a.length); + assertTrue(ArrayTools.containsAll(a, this.buildStringList1().iterator())); + } + + public void testArrayIterator() { + Object[] a = ArrayTools.array(this.buildStringList1().iterator()); + assertEquals(3, a.length); + assertTrue(ArrayTools.containsAll(a, this.buildStringList1().iterator())); + } + + public void testArrayIterator_Empty() { + Object[] a = ArrayTools.array(EmptyIterator.instance()); + assertEquals(0, a.length); + } + + public void testArrayIteratorInt() { + Object[] a = ArrayTools.array(this.buildStringList1().iterator(), 3); + assertEquals(3, a.length); + assertTrue(ArrayTools.containsAll(a, this.buildStringList1().iterator())); + } + + public void testArrayIteratorInt_Empty() { + Object[] a = ArrayTools.array(EmptyIterator.instance(), 3); + assertEquals(0, a.length); + } + + public void testArrayIteratorObjectArray_String() { + String[] a = ArrayTools.array(this.buildStringList1().iterator(), new String[0]); + assertEquals(3, a.length); + assertTrue(ArrayTools.containsAll(a, this.buildStringList1().iterator())); + } + + public void testArrayIteratorObjectArray_Empty() { + String[] a = ArrayTools.array(EmptyIterator.<String>instance(), new String[0]); + assertEquals(0, a.length); + } + + public void testArrayIteratorObjectArray_Empty_ClearArray() { + String[] a = ArrayTools.array(EmptyIterator.<String>instance(), new String[5]); + assertEquals(5, a.length); + assertNull(a[0]); + } + + public void testArrayIteratorObjectArray_Object() { + Object[] a = ArrayTools.array(this.buildStringList1().iterator(), new Object[0]); + assertEquals(3, a.length); + assertTrue(ArrayTools.containsAll(a, this.buildStringList1().iterator())); + } + + public void testArrayIteratorIntObjectArray() { + String[] a = ArrayTools.array(this.buildStringList1().iterator(), 3, new String[0]); + assertEquals(3, a.length); + assertTrue(ArrayTools.containsAll(a, this.buildStringList1().iterator())); + } + + public void testArrayIteratorIntObjectArray_Empty() { + String[] a = ArrayTools.array(EmptyIterator.<String>instance(), 3, new String[0]); + assertEquals(0, a.length); + } + + + // ********** add ********** + + public void testAddObjectArrayObject_Object() { + Object[] a = ArrayTools.add(this.buildObjectArray1(), "twenty"); + assertEquals(4, a.length); + assertTrue(ArrayTools.contains(a, "twenty")); + assertEquals("twenty", a[a.length-1]); + } + + public void testAddObjectArrayObject_String() { + String[] a = ArrayTools.add(this.buildStringArray1(), "twenty"); + assertEquals(4, a.length); + assertTrue(ArrayTools.contains(a, "twenty")); + assertEquals("twenty", a[a.length-1]); + } + + public void testAddObjectArrayObject_EmptyArray() { + String[] a = new String[0]; + a = ArrayTools.add(a, "twenty"); + assertEquals(1, a.length); + assertTrue(ArrayTools.contains(a, "twenty")); + assertEquals("twenty", a[0]); + } + + public void testAddObjectArrayIntObject_Object() { + Object[] a = new Object[] { "a", "b", "c", "d" }; + a = ArrayTools.add(a, 2, "X"); + assertEquals(5, a.length); + assertTrue(ArrayTools.contains(a, "X")); + assertTrue(Arrays.equals(new Object[] { "a", "b", "X", "c", "d" }, a)); + } + + public void testAddObjectArrayIntObject_String() { + String[] a = new String[] { "a", "b", "c", "d" }; + a = ArrayTools.add(a, 2, "X"); + assertEquals(5, a.length); + assertTrue(ArrayTools.contains(a, "X")); + assertTrue(Arrays.equals(new String[] { "a", "b", "X", "c", "d" }, a)); + } + + public void testAddObjectArrayIntObject_End() { + String[] a = new String[] { "a", "b", "c", "d" }; + a = ArrayTools.add(a, 4, "X"); + assertEquals(5, a.length); + assertTrue(ArrayTools.contains(a, "X")); + assertTrue(Arrays.equals(new String[] { "a", "b", "c", "d", "X" }, a)); + } + + public void testAddObjectArrayIntObject_Zero() { + String[] a = new String[] { "a", "b", "c", "d" }; + a = ArrayTools.add(a, 0, "X"); + assertEquals(5, a.length); + assertTrue(ArrayTools.contains(a, "X")); + assertTrue(Arrays.equals(new String[] { "X", "a", "b", "c", "d" }, a)); + } + + public void testAddObjectArrayIntObject_Exception() { + Object[] a = new Object[] { "a", "b", "c", "d" }; + boolean exCaught = false; + try { + a = ArrayTools.add(a, 33, "X"); + } catch (IndexOutOfBoundsException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testAddCharArrayChar() { + char[] a = ArrayTools.add(this.buildCharArray(), 'd'); + assertEquals(4, a.length); + assertTrue(ArrayTools.contains(a, 'd')); + } + + public void testAddCharArrayChar_Empty() { + char[] a = new char[0]; + a = ArrayTools.add(a, 'd'); + assertEquals(1, a.length); + assertTrue(ArrayTools.contains(a, 'd')); + assertTrue(Arrays.equals(new char[] { 'd' }, a)); + } + + public void testAddCharArrayIntChar() { + char[] a = new char[] { 'a', 'b', 'c', 'd' }; + a = ArrayTools.add(a, 2, 'X'); + assertEquals(5, a.length); + assertTrue(ArrayTools.contains(a, 'X')); + assertTrue(Arrays.equals(new char[] { 'a', 'b', 'X', 'c', 'd' }, a)); + } + + public void testAddCharArrayIntChar_Zero() { + char[] a = new char[] { 'a', 'b', 'c', 'd' }; + a = ArrayTools.add(a, 0, 'X'); + assertEquals(5, a.length); + assertTrue(ArrayTools.contains(a, 'X')); + assertTrue(Arrays.equals(new char[] { 'X', 'a', 'b', 'c', 'd' }, a)); + } + + public void testAddCharArrayIntChar_End() { + char[] a = new char[] { 'a', 'b', 'c', 'd' }; + a = ArrayTools.add(a, 4, 'X'); + assertEquals(5, a.length); + assertTrue(ArrayTools.contains(a, 'X')); + assertTrue(Arrays.equals(new char[] { 'a', 'b', 'c', 'd', 'X' }, a)); + } + + public void testAddIntArrayInt() { + int[] a = ArrayTools.add(this.buildIntArray(), 30); + assertEquals(4, a.length); + assertTrue(ArrayTools.contains(a, 30)); + } + + public void testAddIntArrayInt_Empty() { + int[] a = new int[0]; + a = ArrayTools.add(a, 30); + assertEquals(1, a.length); + assertTrue(ArrayTools.contains(a, 30)); + assertTrue(Arrays.equals(new int[] { 30 }, a)); + } + + public void testAddIntArrayIntInt() { + int[] a = new int[] { 1, 2, 3, 4 }; + a = ArrayTools.add(a, 2, 99); + assertEquals(5, a.length); + assertTrue(ArrayTools.contains(a, 99)); + assertTrue(Arrays.equals(new int[] { 1, 2, 99, 3, 4 }, a)); + } + + public void testAddIntArrayIntInt_Zero() { + int[] a = new int[] { 1, 2, 3, 4 }; + a = ArrayTools.add(a, 0, 99); + assertEquals(5, a.length); + assertTrue(ArrayTools.contains(a, 99)); + assertTrue(Arrays.equals(new int[] { 99, 1, 2, 3, 4 }, a)); + } + + public void testAddIntArrayIntInt_End() { + int[] a = new int[] { 1, 2, 3, 4 }; + a = ArrayTools.add(a, 4, 99); + assertEquals(5, a.length); + assertTrue(ArrayTools.contains(a, 99)); + assertTrue(Arrays.equals(new int[] { 1, 2, 3, 4, 99 }, a)); + } + + + // ********** add all ********** + + public void testAddAllObjectArrayCollection_String() { + String[] a = this.buildStringArray1(); + Collection<String> c = this.buildStringList2(); + String[] newArray = ArrayTools.addAll(a, c); + + assertEquals(6, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, c)); + } + + public void testAddAllObjectArrayCollection_Object() { + Object[] a = this.buildObjectArray1(); + Collection<String> c = this.buildStringList2(); + Object[] newArray = ArrayTools.addAll(a, c); + + assertEquals(6, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, c)); + } + + public void testAddAllObjectArrayCollection_EmptyArray() { + String[] a = new String[0]; + Collection<String> c = this.buildStringList2(); + String[] newArray = ArrayTools.addAll(a, c); + + assertEquals(3, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, c)); + } + + public void testAddAllObjectArrayCollection_EmptyCollection() { + String[] a = this.buildStringArray1(); + Collection<String> c = new ArrayList<String>(); + String[] newArray = ArrayTools.addAll(a, c); + + assertEquals(3, newArray.length); + } + + public void testAddAllObjectArrayIntCollection_String() { + String[] a = this.buildStringArray1(); + Collection<String> c = this.buildStringList2(); + String[] newArray = ArrayTools.addAll(a, 1, c); + + assertEquals(6, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, c)); + } + + public void testAddAllObjectArrayIntCollection_String_End() { + String[] a = this.buildStringArray1(); + Collection<String> c = this.buildStringList2(); + String[] newArray = ArrayTools.addAll(a, 3, c); + + assertEquals(6, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, c)); + } + + public void testAddAllObjectArrayIntCollection_EmptyArray() { + String[] a = new String[0]; + Collection<String> c = this.buildStringList2(); + String[] newArray = ArrayTools.addAll(a, 0, c); + + assertEquals(3, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, c)); + } + + public void testAddAllObjectArrayIntCollection_EmptyArray_Exception() { + String[] a = new String[0]; + Collection<String> c = this.buildStringList2(); + boolean exCaught = false; + try { + String[] newArray = ArrayTools.addAll(a, 3, c); + fail("bogus array: " + Arrays.toString(newArray)); + } catch (IndexOutOfBoundsException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testAddAllObjectArrayIntCollection_EmptyCollection() { + String[] a = this.buildStringArray1(); + Collection<String> c = new ArrayList<String>(); + String[] newArray = ArrayTools.addAll(a, 1, c); + + assertEquals(3, newArray.length); + } + + public void testAddAllObjectArrayIntIterable_String() { + String[] a = this.buildStringArray1(); + Iterable<String> iterable = this.buildStringList2(); + String[] newArray = ArrayTools.addAll(a, 1, iterable); + + assertEquals(6, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, iterable)); + } + + public void testAddAllObjectArrayIntIterable_EmptyArray() { + String[] a = new String[0]; + Iterable<String> iterable = this.buildStringList2(); + String[] newArray = ArrayTools.addAll(a, 0, iterable); + + assertEquals(3, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, iterable)); + } + + public void testAddAllObjectArrayIntIterable_EmptyIterable() { + String[] a = this.buildStringArray1(); + Iterable<String> iterable = new ArrayList<String>(); + String[] newArray = ArrayTools.addAll(a, 1, iterable); + + assertEquals(3, newArray.length); + } + + public void testAddAllObjectArrayIntIterableInt_String() { + String[] a = this.buildStringArray1(); + Iterable<String> iterable = this.buildStringList2(); + String[] newArray = ArrayTools.addAll(a, 1, iterable, 3); + + assertEquals(6, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, iterable)); + } + + public void testAddAllObjectArrayIntIterableInt_EmptyArray() { + String[] a = new String[0]; + Iterable<String> iterable = this.buildStringList2(); + String[] newArray = ArrayTools.addAll(a, 0, iterable, 3); + + assertEquals(3, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, iterable)); + } + + public void testAddAllObjectArrayIntIterableInt_EmptyIterable() { + String[] a = this.buildStringArray1(); + Iterable<String> iterable = new ArrayList<String>(); + String[] newArray = ArrayTools.addAll(a, 1, iterable, 0); + + assertEquals(3, newArray.length); + } + + public void testAddAllObjectArrayIntIterator_String() { + String[] a = this.buildStringArray1(); + Iterator<String> iterator = this.buildStringList2().iterator(); + String[] newArray = ArrayTools.addAll(a, 1, iterator); + + assertEquals(6, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, this.buildStringList2())); + } + + public void testAddAllObjectArrayIntIterator_EmptyArray() { + String[] a = new String[0]; + Iterator<String> iterator = this.buildStringList2().iterator(); + String[] newArray = ArrayTools.addAll(a, 0, iterator); + + assertEquals(3, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, this.buildStringList2())); + } + + public void testAddAllObjectArrayIntIterator_EmptyIterable() { + String[] a = this.buildStringArray1(); + Iterator<String> iterator = EmptyIterator.instance(); + String[] newArray = ArrayTools.addAll(a, 1, iterator); + + assertEquals(3, newArray.length); + } + + public void testAddAllObjectArrayIntIteratorInt_String() { + String[] a = this.buildStringArray1(); + Iterator<String> iterator = this.buildStringList2().iterator(); + String[] newArray = ArrayTools.addAll(a, 1, iterator, 3); + + assertEquals(6, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, this.buildStringList2())); + } + + public void testAddAllObjectArrayIntIteratorInt_EmptyArray() { + String[] a = new String[0]; + Iterator<String> iterator = this.buildStringList2().iterator(); + String[] newArray = ArrayTools.addAll(a, 0, iterator, 3); + + assertEquals(3, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, this.buildStringList2())); + } + + public void testAddAllObjectArrayIntIteratorInt_EmptyIterator() { + String[] a = this.buildStringArray1(); + Iterator<String> iterator = EmptyIterator.instance(); + String[] newArray = ArrayTools.addAll(a, 1, iterator, 0); + + assertEquals(3, newArray.length); + } + + public void testAddAllObjectArrayIterable() { + String[] a = this.buildStringArray1(); + Iterable<String> iterable = this.buildStringList1(); + String[] newArray = ArrayTools.addAll(a, iterable); + + assertEquals(6, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, this.buildStringList1())); + } + + public void testAddAllObjectArrayIterableInt() { + String[] a = this.buildStringArray1(); + Iterable<String> iterable = this.buildStringList1(); + String[] newArray = ArrayTools.addAll(a, iterable, 33); + + assertEquals(6, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, this.buildStringList1())); + } + + public void testAddAllObjectArrayIterator_String() { + String[] a = this.buildStringArray1(); + Iterator<String> iterator = this.buildStringList1().iterator(); + String[] newArray = ArrayTools.addAll(a, iterator); + + assertEquals(6, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, this.buildStringList1())); + } + + public void testAddAllObjectArrayIterator_Object() { + String[] a = this.buildStringArray1(); + Iterator<Object> iterator = this.buildObjectList1().iterator(); + Object[] newArray = ArrayTools.addAll(a, iterator); + + assertEquals(6, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, this.buildObjectList1())); + } + + public void testAddAllObjectArrayIterator_EmptyIterator() { + String[] a = this.buildStringArray1(); + Iterator<String> iterator = EmptyIterator.instance(); + String[] newArray = ArrayTools.addAll(a, iterator); + + assertEquals(3, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, this.buildStringList1())); + } + + public void testAddAllObjectArrayIteratorInt() { + String[] a = this.buildStringArray1(); + Iterator<Object> iterator = this.buildObjectList1().iterator(); + Object[] newArray = ArrayTools.addAll(a, iterator, 3); + + assertEquals(6, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, this.buildObjectList1())); + } + + public void testAddAllObjectArrayIteratorInt_EmptyIterator() { + String[] a = this.buildStringArray1(); + Iterator<String> iterator = EmptyIterator.instance(); + String[] newArray = ArrayTools.addAll(a, iterator, 0); + + assertEquals(3, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, this.buildStringList1())); + } + + public void testAddAllObjectArrayObjectArray_Object() { + Object[] a1 = this.buildObjectArray1(); + Object[] a2 = this.buildObjectArray2(); + Object[] newArray = ArrayTools.addAll(a1, a2); + + assertEquals(6, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, a1)); + assertTrue(ArrayTools.containsAll(newArray, a2)); + } + + public void testAddAllObjectArrayObjectArray_String() { + String[] a1 = this.buildStringArray1(); + String[] a2 = this.buildStringArray2(); + String[] newArray = ArrayTools.addAll(a1, a2); + + assertEquals(6, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, (Object[]) a1)); + assertTrue(ArrayTools.containsAll(newArray, (Object[]) a2)); + } + + public void testAddAllObjectArrayObjectArray_ObjectString() { + Object[] a1 = this.buildObjectArray1(); + String[] a2 = this.buildStringArray2(); + Object[] newArray = ArrayTools.addAll(a1, (Object[]) a2); + + assertEquals(6, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, a1)); + assertTrue(ArrayTools.containsAll(newArray, (Object[]) a2)); + } + + public void testAddAllObjectArrayObjectArray_EmptyArray1() { + Object[] a1 = new Object[0]; + Object[] a2 = this.buildObjectArray2(); + Object[] newArray = ArrayTools.addAll(a1, a2); + + assertEquals(3, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, a2)); + } + + public void testAddAllObjectArrayObjectArray_EmptyArray2() { + Object[] a1 = this.buildObjectArray1(); + Object[] a2 = new Object[0]; + Object[] newArray = ArrayTools.addAll(a1, a2); + + assertEquals(3, newArray.length); + assertTrue(ArrayTools.containsAll(newArray, a1)); + } + + public void testAddAllObjectArrayIntObjectArray_Object() { + Object[] a = new Object[] { "a", "b", "c", "d" }; + a = ArrayTools.addAll(a, 2, new Object[] { "X", "X", "X" }); + assertEquals(7, a.length); + assertTrue(ArrayTools.contains(a, "X")); + assertTrue(Arrays.equals(new Object[] { "a", "b", "X", "X", "X", "c", "d" }, a)); + } + + public void testAddAllObjectArrayIntObjectArray_String() { + String[] a = new String[] { "a", "b", "c", "d" }; + a = ArrayTools.addAll(a, 2, new String[] { "X", "X", "X" }); + assertEquals(7, a.length); + assertTrue(ArrayTools.contains(a, "X")); + assertTrue(Arrays.equals(new String[] { "a", "b", "X", "X", "X", "c", "d" }, a)); + } + + public void testAddAllObjectArrayIntObjectArray_ObjectString() { + Object[] a = new Object[] { "a", "b", "c", "d" }; + a = ArrayTools.addAll(a, 2, (Object[]) new String[] { "X", "X", "X" }); + assertEquals(7, a.length); + assertTrue(ArrayTools.contains(a, "X")); + assertTrue(Arrays.equals(new Object[] { "a", "b", "X", "X", "X", "c", "d" }, a)); + } + + public void testAddAllObjectArrayIntObjectArray_End() { + Object[] a = new Object[] { "a", "b", "c", "d" }; + a = ArrayTools.addAll(a, 4, (Object[]) new String[] { "X", "X", "X" }); + assertEquals(7, a.length); + assertTrue(ArrayTools.contains(a, "X")); + assertTrue(Arrays.equals(new Object[] { "a", "b", "c", "d", "X", "X", "X" }, a)); + } + + public void testAddAllObjectArrayIntObjectArray_Zero() { + Object[] a = new Object[0]; + a = ArrayTools.addAll(a, 0, (Object[]) new String[] { "X", "X", "X" }); + assertEquals(3, a.length); + assertTrue(ArrayTools.contains(a, "X")); + assertTrue(Arrays.equals(new Object[] { "X", "X", "X" }, a)); + } + + public void testAddAllObjectArrayIntObjectArray_EmptyArray2() { + Object[] a = new Object[] { "a", "b", "c", "d" }; + a = ArrayTools.addAll(a, 4, (Object[]) new String[0]); + assertEquals(4, a.length); + assertTrue(Arrays.equals(new Object[] { "a", "b", "c", "d" }, a)); + } + + public void testAddAllObjectArrayIntObjectArray_EmptyArray1() { + Object[] a = new String[0]; + a = ArrayTools.addAll(a, 0, new Object[] { "a", "b", "c", "d" }); + assertEquals(4, a.length); + assertTrue(Arrays.equals(new Object[] { "a", "b", "c", "d" }, a)); + } + + public void testAddAllCharArrayCharArray() { + char[] a = ArrayTools.addAll(this.buildCharArray(), new char[] { 'd', 'e' }); + assertEquals(5, a.length); + assertTrue(ArrayTools.contains(a, 'd')); + assertTrue(ArrayTools.contains(a, 'e')); + } + + public void testAddAllCharArrayCharArray_EmptyArray2() { + char[] a = ArrayTools.addAll(this.buildCharArray(), new char[0]); + assertEquals(3, a.length); + } + + public void testAddAllCharArrayCharArrayEmptyArray1() { + char[] a = ArrayTools.addAll(new char[0], new char[] { 'd', 'e' }); + assertEquals(2, a.length); + assertTrue(ArrayTools.contains(a, 'd')); + assertTrue(ArrayTools.contains(a, 'e')); + } + + public void testAddAllCharArrayIntCharArray() { + char[] a = new char[] { 'a', 'b', 'c', 'd' }; + a = ArrayTools.addAll(a, 2, new char[] { 'X', 'X', 'X' }); + assertEquals(7, a.length); + assertTrue(ArrayTools.contains(a, 'X')); + assertTrue(Arrays.equals(new char[] { 'a', 'b', 'X', 'X', 'X', 'c', 'd' }, a)); + } + + public void testAddAllCharArrayIntCharArray_End() { + char[] a = new char[] { 'a', 'b', 'c', 'd' }; + a = ArrayTools.addAll(a, 4, new char[] { 'X', 'X', 'X' }); + assertEquals(7, a.length); + assertTrue(ArrayTools.contains(a, 'X')); + assertTrue(Arrays.equals(new char[] { 'a', 'b', 'c', 'd', 'X', 'X', 'X' }, a)); + } + + public void testAddAllCharArrayIntCharArray_EmptyArray1() { + char[] a = new char[0]; + a = ArrayTools.addAll(a, 0, new char[] { 'X', 'X', 'X' }); + assertEquals(3, a.length); + assertTrue(ArrayTools.contains(a, 'X')); + assertTrue(Arrays.equals(new char[] { 'X', 'X', 'X' }, a)); + } + + public void testAddAllCharArrayIntCharArray_EmptyArray2() { + char[] a = new char[] { 'a', 'b', 'c', 'd' }; + a = ArrayTools.addAll(a, 2, new char[0]); + assertEquals(4, a.length); + assertTrue(Arrays.equals(new char[] { 'a', 'b', 'c', 'd' }, a)); + } + + public void testAddAllIntArrayIntArray() { + int[] a = ArrayTools.addAll(this.buildIntArray(), new int[] { 30, 40 }); + assertEquals(5, a.length); + assertTrue(ArrayTools.contains(a, 30)); + assertTrue(ArrayTools.contains(a, 40)); + } + + public void testAddAllIntArrayIntArray_EmptyArray2() { + int[] a = ArrayTools.addAll(this.buildIntArray(), new int[0]); + assertEquals(3, a.length); + } + + public void testAddAllIntArrayIntArray_EmptyArray1() { + int[] a = ArrayTools.addAll(new int[0], new int[] { 30, 40 }); + assertEquals(2, a.length); + assertTrue(ArrayTools.contains(a, 30)); + assertTrue(ArrayTools.contains(a, 40)); + } + + public void testAddAllIntArrayIntIntArray() { + int[] a = new int[] { 1, 2, 3, 4 }; + a = ArrayTools.addAll(a, 2, new int[] { 99, 99, 99 }); + assertEquals(7, a.length); + assertTrue(ArrayTools.contains(a, 99)); + assertTrue(Arrays.equals(new int[] { 1, 2, 99, 99, 99, 3, 4 }, a)); + } + + public void testAddAllIntArrayIntIntArray_End() { + int[] a = new int[] { 1, 2, 3, 4 }; + a = ArrayTools.addAll(a, 4, new int[] { 99, 99, 99 }); + assertEquals(7, a.length); + assertTrue(ArrayTools.contains(a, 99)); + assertTrue(Arrays.equals(new int[] { 1, 2, 3, 4, 99, 99, 99 }, a)); + } + + public void testAddAllIntArrayIntIntArray_EmptyArray2() { + int[] a = new int[] { 1, 2, 3, 4 }; + a = ArrayTools.addAll(a, 2, new int[0]); + assertEquals(4, a.length); + assertTrue(Arrays.equals(new int[] { 1, 2, 3, 4 }, a)); + } + + public void testAddAllIntArrayIntIntArray_EmptyArray1() { + int[] a = new int[0]; + a = ArrayTools.addAll(a, 0, new int[] { 99, 99, 99 }); + assertEquals(3, a.length); + assertTrue(ArrayTools.contains(a, 99)); + assertTrue(Arrays.equals(new int[] { 99, 99, 99 }, a)); + } + + + // ********** clear ********** + + public void testClearObjectArray() { + String[] a = this.buildStringArray1(); + assertEquals(3, a.length); + a = ArrayTools.clear(a); + assertEquals(0, a.length); + } + + public void testClearObjectArray_Empty() { + String[] a = new String[0]; + assertEquals(0, a.length); + a = ArrayTools.clear(a); + assertEquals(0, a.length); + } + + + // ********** concatenate ********** + + public void testConcatenateObjectArrayArray() { + String[] aArray = new String[] { "a", "b", "c", "d" }; + String[] eArray = new String[] { "e", "f", "g", "h" }; + String[] iArray = new String[] { "i", "j", "k", "l" }; + + String[] expected = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l" }; + String[] actual = ArrayTools.concatenate(aArray, eArray, iArray); + assertTrue(Arrays.equals(expected, actual)); + } + + public void testConcatenateObjectArrayArray_Empty() { + String[] aArray = new String[] { }; + String[] eArray = new String[0]; + String[] iArray = new String[0]; + + String[] expected = new String[0]; + String[] actual = ArrayTools.concatenate(aArray, eArray, iArray); + assertEquals(0, actual.length); + assertTrue(Arrays.equals(expected, actual)); + } + + public void testConcatenateCharArrayArray() { + char[] aArray = new char[] { 'a', 'b', 'c', 'd' }; + char[] eArray = new char[] { 'e', 'f', 'g', 'h' }; + char[] iArray = new char[] { 'i', 'j', 'k', 'l' }; + + char[] expected = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l' }; + char[] actual = ArrayTools.concatenate(aArray, eArray, iArray); + assertTrue(Arrays.equals(expected, actual)); + } + + public void testConcatenateCharArrayArray_Empty() { + char[] aArray = new char[] { }; + char[] eArray = new char[0]; + char[] iArray = new char[0]; + + char[] expected = new char[0]; + char[] actual = ArrayTools.concatenate(aArray, eArray, iArray); + assertEquals(0, actual.length); + assertTrue(Arrays.equals(expected, actual)); + } + + public void testConcatenateIntArrayArray() { + int[] aArray = new int[] { 'a', 'b', 'c', 'd' }; + int[] eArray = new int[] { 'e', 'f', 'g', 'h' }; + int[] iArray = new int[] { 'i', 'j', 'k', 'l' }; + + int[] expected = new int[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l' }; + int[] actual = ArrayTools.concatenate(aArray, eArray, iArray); + assertTrue(Arrays.equals(expected, actual)); + } + + public void testConcatenateIntArrayArray_Empty() { + int[] aArray = new int[] { }; + int[] eArray = new int[0]; + int[] iArray = new int[0]; + + int[] expected = new int[0]; + int[] actual = ArrayTools.concatenate(aArray, eArray, iArray); + assertEquals(0, actual.length); + assertTrue(Arrays.equals(expected, actual)); + } + + + // ********** contains ********** + + public void testContainsObjectArrayObject() { + Object[] a = this.buildObjectArray1(); + assertTrue(ArrayTools.contains(a, "one")); + assertFalse(ArrayTools.contains(a, null)); + Object[] a2 = ArrayTools.add(a, null); + assertTrue(ArrayTools.contains(a2, null)); + } + + public void testContainsObjectArrayObject_EmptyArray() { + Object[] a = new Object[0]; + assertFalse(ArrayTools.contains(a, "one")); + assertFalse(ArrayTools.contains(a, null)); + } + + public void testContainsCharArrayChar() { + char[] a = this.buildCharArray(); + assertTrue(ArrayTools.contains(a, 'a')); + assertFalse(ArrayTools.contains(a, 'z')); + char[] a2 = ArrayTools.add(a, 'z'); + assertTrue(ArrayTools.contains(a2, 'z')); + } + + public void testContainsCharArrayObject_EmptyArray() { + char[] a = new char[0]; + assertFalse(ArrayTools.contains(a, 'a')); + } + + public void testContainsIntArrayInt() { + int[] a = this.buildIntArray(); + assertTrue(ArrayTools.contains(a, 10)); + assertFalse(ArrayTools.contains(a, 55)); + int[] a2 = ArrayTools.add(a, 55); + assertTrue(ArrayTools.contains(a2, 55)); + } + + public void testContainsIntArrayObject_EmptyArray() { + int[] a = new int[0]; + assertFalse(ArrayTools.contains(a, 'a')); + } + + + // ********** contains all ********** + + public void testContainsAllObjectArrayCollection() { + assertTrue(ArrayTools.containsAll(this.buildObjectArray1(), this.buildStringList1())); + assertFalse(ArrayTools.containsAll(this.buildObjectArray1(), this.buildStringList2())); + } + + public void testContainsAllObjectArrayIterable() { + Iterable<String> iterable = this.buildStringList1(); + assertTrue(ArrayTools.containsAll(this.buildObjectArray1(), iterable)); + iterable = this.buildStringList2(); + assertFalse(ArrayTools.containsAll(this.buildObjectArray1(), iterable)); + } + + public void testContainsAllObjectArrayIterator() { + assertTrue(ArrayTools.containsAll(this.buildObjectArray1(), this.buildStringList1().iterator())); + assertFalse(ArrayTools.containsAll(this.buildObjectArray1(), this.buildStringList2().iterator())); + } + + public void testContainsAllObjectArrayIterator_Empty() { + assertTrue(ArrayTools.containsAll(this.buildObjectArray1(), EmptyIterator.instance())); + } + + public void testContainsAllObjectArrayObjectArray() { + assertTrue(ArrayTools.containsAll(this.buildObjectArray1(), this.buildObjectArray1())); + assertFalse(ArrayTools.containsAll(this.buildObjectArray1(), this.buildObjectArray2())); + } + + public void testContainsAllCharArrayCharArray() { + assertTrue(ArrayTools.containsAll(this.buildCharArray(), this.buildCharArray())); + assertFalse(ArrayTools.containsAll(this.buildCharArray(), new char[] { 'x', 'y' })); + } + + public void testContainsAllIntArrayIntArray() { + assertTrue(ArrayTools.containsAll(this.buildIntArray(), this.buildIntArray())); + assertFalse(ArrayTools.containsAll(this.buildIntArray(), new int[] { 444, 888 })); + } + + + // ********** diff ********** + + public void testDiffEnd() { + String a = "a"; + String b = "b"; + String c = "c"; + String d = "d"; + String e = "e"; + String a_ = new String("a"); + String b_ = new String("b"); + String c_ = new String("c"); + String d_ = new String("d"); + String e_ = new String("e"); + assertTrue((a != a_) && a.equals(a_)); + assertTrue((b != b_) && b.equals(b_)); + assertTrue((c != c_) && c.equals(c_)); + assertTrue((d != d_) && d.equals(d_)); + assertTrue((e != e_) && e.equals(e_)); + String[] array1; + String[] array2; + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(-1, ArrayTools.diffEnd(array1, array2)); + + array1 = new String[] { a }; + array2 = new String[] { a_ }; + assertEquals(-1, ArrayTools.diffEnd(array1, array2)); + + array1 = new String[] { b, c, d, e }; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(4, ArrayTools.diffEnd(array1, array2)); + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { b_, c_, d_, e_ }; + assertEquals(4, ArrayTools.diffEnd(array1, array2)); + + array1 = new String[0]; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(4, ArrayTools.diffEnd(array1, array2)); + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[0]; + assertEquals(4, ArrayTools.diffEnd(array1, array2)); + + array1 = new String[0]; + array2 = new String[0]; + assertEquals(-1, ArrayTools.diffEnd(array1, array2)); + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { b_, c_, a_, d_, e_ }; + assertEquals(2, ArrayTools.diffEnd(array1, array2)); + + array1 = new String[] { b, c, d, e }; + array2 = new String[] { a_, c_, d_, e_ }; + assertEquals(0, ArrayTools.diffEnd(array1, array2)); + + array1 = new String[] { a, b, c, e }; + array2 = new String[] { a_, b_, c_, d_ }; + assertEquals(3, ArrayTools.diffEnd(array1, array2)); + + String c__ = new String(c); + assertTrue((c != c__) && c.equals(c_)); + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { a_, b_, c__, d_, e_ }; + assertEquals(-1, ArrayTools.diffEnd(array1, array2)); + + array1 = new String[] { a, b, null, d, e }; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(2, ArrayTools.diffEnd(array1, array2)); + + array1 = new String[] { a, b, null, d, e }; + array2 = new String[] { a_, b_, null, d_, e_ }; + assertEquals(-1, ArrayTools.diffEnd(array1, array2)); + } + + public void testDiffRange() { + String a = "a"; + String b = "b"; + String c = "c"; + String d = "d"; + String e = "e"; + String a_ = a; + String b_ = b; + String c_ = c; + String d_ = d; + String e_ = e; + assertTrue((a == a_) && a.equals(a_)); + assertTrue((b == b_) && b.equals(b_)); + assertTrue((c == c_) && c.equals(c_)); + assertTrue((d == d_) && d.equals(d_)); + assertTrue((e == e_) && e.equals(e_)); + String[] array1; + String[] array2; + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(new Range(5, -1), ArrayTools.diffRange(array1, array2)); + + array1 = new String[] { a }; + array2 = new String[] { a_ }; + assertEquals(new Range(1, -1), ArrayTools.diffRange(array1, array2)); + + array1 = new String[] { b, c, d, e }; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(new Range(0, 4), ArrayTools.diffRange(array1, array2)); + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { b_, c_, d_, e_ }; + assertEquals(new Range(0, 4), ArrayTools.diffRange(array1, array2)); + + array1 = new String[0]; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(new Range(0, 4), ArrayTools.diffRange(array1, array2)); + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[0]; + assertEquals(new Range(0, 4), ArrayTools.diffRange(array1, array2)); + + array1 = new String[0]; + array2 = new String[0]; + assertEquals(new Range(0, -1), ArrayTools.diffRange(array1, array2)); + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { b_, c_, a_, d_, e_ }; + assertEquals(new Range(0, 2), ArrayTools.diffRange(array1, array2)); + + array1 = new String[] { b, c, d, e }; + array2 = new String[] { a_, c_, d_, e_ }; + assertEquals(new Range(0, 0), ArrayTools.diffRange(array1, array2)); + + array1 = new String[] { a, b, c, e }; + array2 = new String[] { a_, b_, c_, d_ }; + assertEquals(new Range(3, 3), ArrayTools.diffRange(array1, array2)); + + String c__ = new String(c); + assertTrue((c != c__) && c.equals(c_)); + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { a_, b_, c__, d_, e_ }; + assertEquals(new Range(5, -1), ArrayTools.diffRange(array1, array2)); + + array1 = new String[] { a, b, null, d, e }; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(new Range(2, 2), ArrayTools.diffRange(array1, array2)); + + array1 = new String[] { a, b, null, d, e }; + array2 = new String[] { a_, b_, null, d_, e_ }; + assertEquals(new Range(5, -1), ArrayTools.diffRange(array1, array2)); + } + + public void testDiffStart() { + String a = "a"; + String b = "b"; + String c = "c"; + String d = "d"; + String e = "e"; + String a_ = new String("a"); + String b_ = new String("b"); + String c_ = new String("c"); + String d_ = new String("d"); + String e_ = new String("e"); + assertTrue((a != a_) && a.equals(a_)); + assertTrue((b != b_) && b.equals(b_)); + assertTrue((c != c_) && c.equals(c_)); + assertTrue((d != d_) && d.equals(d_)); + assertTrue((e != e_) && e.equals(e_)); + String[] array1; + String[] array2; + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(5, ArrayTools.diffStart(array1, array2)); + + array1 = new String[] { a }; + array2 = new String[] { a_ }; + assertEquals(1, ArrayTools.diffStart(array1, array2)); + + array1 = new String[] { a, b, c, d }; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(4, ArrayTools.diffStart(array1, array2)); + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { a_, b_, c_, d_ }; + assertEquals(4, ArrayTools.diffStart(array1, array2)); + + array1 = new String[0]; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(0, ArrayTools.diffStart(array1, array2)); + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[0]; + assertEquals(0, ArrayTools.diffStart(array1, array2)); + + array1 = new String[0]; + array2 = new String[0]; + assertEquals(0, ArrayTools.diffStart(array1, array2)); + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { a_, b_, e_, c_, d_ }; + assertEquals(2, ArrayTools.diffStart(array1, array2)); + + array1 = new String[] { a, b, c, e }; + array2 = new String[] { a_, b_, c_, d_ }; + assertEquals(3, ArrayTools.diffStart(array1, array2)); + + array1 = new String[] { b, c, d, e }; + array2 = new String[] { a_, c_, d_, e_ }; + assertEquals(0, ArrayTools.diffStart(array1, array2)); + + String c__ = new String(c); + assertTrue((c != c__) && c.equals(c__)); + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { a_, b_, c__, d_, e_ }; + assertEquals(5, ArrayTools.diffStart(array1, array2)); + + array1 = new String[] { a, b, null, d, e }; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(2, ArrayTools.diffStart(array1, array2)); + + array1 = new String[] { a, b, null, d, e }; + array2 = new String[] { a_, b_, null, d_, e_ }; + assertEquals(5, ArrayTools.diffStart(array1, array2)); + } + + + // ********** identity diff ********** + + public void testIdentityDiffEnd() { + String a = "a"; + String b = "b"; + String c = "c"; + String d = "d"; + String e = "e"; + String a_ = a; + String b_ = b; + String c_ = c; + String d_ = d; + String e_ = e; + assertTrue((a == a_) && a.equals(a_)); + assertTrue((b == b_) && b.equals(b_)); + assertTrue((c == c_) && c.equals(c_)); + assertTrue((d == d_) && d.equals(d_)); + assertTrue((e == e_) && e.equals(e_)); + String[] array1; + String[] array2; + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(-1, ArrayTools.identityDiffEnd(array1, array2)); + + array1 = new String[] { a }; + array2 = new String[] { a_ }; + assertEquals(-1, ArrayTools.identityDiffEnd(array1, array2)); + + array1 = new String[] { b, c, d, e }; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(4, ArrayTools.identityDiffEnd(array1, array2)); + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { b_, c_, d_, e_ }; + assertEquals(4, ArrayTools.identityDiffEnd(array1, array2)); + + array1 = new String[0]; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(4, ArrayTools.identityDiffEnd(array1, array2)); + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[0]; + assertEquals(4, ArrayTools.identityDiffEnd(array1, array2)); + + array1 = new String[0]; + array2 = new String[0]; + assertEquals(-1, ArrayTools.identityDiffEnd(array1, array2)); + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { b_, c_, a_, d_, e_ }; + assertEquals(2, ArrayTools.identityDiffEnd(array1, array2)); + + array1 = new String[] { b, c, d, e }; + array2 = new String[] { a_, c_, d_, e_ }; + assertEquals(0, ArrayTools.identityDiffEnd(array1, array2)); + + array1 = new String[] { a, b, c, e }; + array2 = new String[] { a_, b_, c_, d_ }; + assertEquals(3, ArrayTools.identityDiffEnd(array1, array2)); + + String c__ = new String(c); + assertTrue((c != c__) && c.equals(c_)); + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { a_, b_, c__, d_, e_ }; + assertEquals(2, ArrayTools.identityDiffEnd(array1, array2)); + + array1 = new String[] { a, b, null, d, e }; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(2, ArrayTools.identityDiffEnd(array1, array2)); + + array1 = new String[] { a, b, null, d, e }; + array2 = new String[] { a_, b_, null, d_, e_ }; + assertEquals(-1, ArrayTools.identityDiffEnd(array1, array2)); + } + + public void testIdentityDiffRange() { + String a = "a"; + String b = "b"; + String c = "c"; + String d = "d"; + String e = "e"; + String a_ = a; + String b_ = b; + String c_ = c; + String d_ = d; + String e_ = e; + assertTrue((a == a_) && a.equals(a_)); + assertTrue((b == b_) && b.equals(b_)); + assertTrue((c == c_) && c.equals(c_)); + assertTrue((d == d_) && d.equals(d_)); + assertTrue((e == e_) && e.equals(e_)); + String[] array1; + String[] array2; + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(new Range(5, -1), ArrayTools.identityDiffRange(array1, array2)); + + array1 = new String[] { a }; + array2 = new String[] { a_ }; + assertEquals(new Range(1, -1), ArrayTools.identityDiffRange(array1, array2)); + + array1 = new String[] { b, c, d, e }; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(new Range(0, 4), ArrayTools.identityDiffRange(array1, array2)); + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { b_, c_, d_, e_ }; + assertEquals(new Range(0, 4), ArrayTools.identityDiffRange(array1, array2)); + + array1 = new String[0]; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(new Range(0, 4), ArrayTools.identityDiffRange(array1, array2)); + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[0]; + assertEquals(new Range(0, 4), ArrayTools.identityDiffRange(array1, array2)); + + array1 = new String[0]; + array2 = new String[0]; + assertEquals(new Range(0, -1), ArrayTools.identityDiffRange(array1, array2)); + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { b_, c_, a_, d_, e_ }; + assertEquals(new Range(0, 2), ArrayTools.identityDiffRange(array1, array2)); + + array1 = new String[] { b, c, d, e }; + array2 = new String[] { a_, c_, d_, e_ }; + assertEquals(new Range(0, 0), ArrayTools.identityDiffRange(array1, array2)); + + array1 = new String[] { a, b, c, e }; + array2 = new String[] { a_, b_, c_, d_ }; + assertEquals(new Range(3, 3), ArrayTools.identityDiffRange(array1, array2)); + + String c__ = new String(c); + assertTrue((c != c__) && c.equals(c_)); + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { a_, b_, c__, d_, e_ }; + assertEquals(new Range(2, 2), ArrayTools.identityDiffRange(array1, array2)); + + array1 = new String[] { a, b, null, d, e }; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(new Range(2, 2), ArrayTools.identityDiffRange(array1, array2)); + + array1 = new String[] { a, b, null, d, e }; + array2 = new String[] { a_, b_, null, d_, e_ }; + assertEquals(new Range(5, -1), ArrayTools.identityDiffRange(array1, array2)); + } + + public void testIdentityDiffStart() { + String a = "a"; + String b = "b"; + String c = "c"; + String d = "d"; + String e = "e"; + String a_ = a; + String b_ = b; + String c_ = c; + String d_ = d; + String e_ = e; + assertTrue((a == a_) && a.equals(a_)); + assertTrue((b == b_) && b.equals(b_)); + assertTrue((c == c_) && c.equals(c_)); + assertTrue((d == d_) && d.equals(d_)); + assertTrue((e == e_) && e.equals(e_)); + String[] array1; + String[] array2; + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(5, ArrayTools.identityDiffStart(array1, array2)); + + array1 = new String[] { a }; + array2 = new String[] { a_ }; + assertEquals(1, ArrayTools.identityDiffStart(array1, array2)); + + array1 = new String[] { a, b, c, d }; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(4, ArrayTools.identityDiffStart(array1, array2)); + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { a_, b_, c_, d_ }; + assertEquals(4, ArrayTools.identityDiffStart(array1, array2)); + + array1 = new String[0]; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(0, ArrayTools.identityDiffStart(array1, array2)); + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[0]; + assertEquals(0, ArrayTools.identityDiffStart(array1, array2)); + + array1 = new String[0]; + array2 = new String[0]; + assertEquals(0, ArrayTools.identityDiffStart(array1, array2)); + + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { a_, b_, e_, c_, d_ }; + assertEquals(2, ArrayTools.identityDiffStart(array1, array2)); + + array1 = new String[] { a, b, c, e }; + array2 = new String[] { a_, b_, c_, d_ }; + assertEquals(3, ArrayTools.identityDiffStart(array1, array2)); + + array1 = new String[] { b, c, d, e }; + array2 = new String[] { a_, c_, d_, e_ }; + assertEquals(0, ArrayTools.identityDiffStart(array1, array2)); + + String c__ = new String(c); + assertTrue((c != c__) && c.equals(c_)); + array1 = new String[] { a, b, c, d, e }; + array2 = new String[] { a_, b_, c__, d_, e_ }; + assertEquals(2, ArrayTools.identityDiffStart(array1, array2)); + + array1 = new String[] { a, b, null, d, e }; + array2 = new String[] { a_, b_, c_, d_, e_ }; + assertEquals(2, ArrayTools.identityDiffStart(array1, array2)); + + array1 = new String[] { a, b, null, d, e }; + array2 = new String[] { a_, b_, null, d_, e_ }; + assertEquals(5, ArrayTools.identityDiffStart(array1, array2)); + } + + + // ********** elements are identical ********** + + public void testElementsAreIdenticalObjectArrayObjectArray() { + Object[] a1 = new Object[4]; + for (int i = 0; i < a1.length; i++) { + a1[i] = String.valueOf(i * 1000); + } + + Object[] a2 = new Object[a1.length]; + for (int i = 0; i < a2.length; i++) { + a2[i] = a1[i]; + } + + assertTrue(ArrayTools.elementsAreIdentical(a1, a2)); + a2[2] = "2000"; + assertFalse(ArrayTools.elementsAreIdentical(a1, a2)); + assertTrue(Arrays.equals(a1, a2)); + } + + public void testElementsAreIdenticalObjectArrayObjectArray_BothNull() { + Object[] a1 = null; + Object[] a2 = null; + assertTrue(ArrayTools.elementsAreIdentical(a1, a2)); + } + + public void testElementsAreIdenticalObjectArrayObjectArray_OneNull() { + Object[] a1 = null; + Object[] a2 = new Object[0]; + assertFalse(ArrayTools.elementsAreIdentical(a1, a2)); + } + + public void testElementsAreIdenticalObjectArrayObjectArray_DifferentLengths() { + Object[] a1 = new String[] {"foo", "bar"}; + Object[] a2 = new String[] {"foo", "bar", "baz"}; + assertFalse(ArrayTools.elementsAreIdentical(a1, a2)); + } + + + // ********** index of ********** + + public void testIndexOfObjectArrayObject() { + Object[] a = this.buildObjectArray1(); + assertEquals(1, ArrayTools.indexOf(a, "one")); + } + + public void testIndexOfObjectArrayObject_NotFound() { + Object[] a = this.buildObjectArray1(); + assertEquals(-1, ArrayTools.indexOf(a, "twenty")); + } + + public void testIndexOfObjectArrayObject_Null() { + Object[] a = this.buildObjectArray1(); + a = ArrayTools.add(a, null); + assertEquals(a.length - 1, ArrayTools.indexOf(a, null)); + } + + public void testIndexOfObjectArrayObject_Null_NotFound() { + Object[] a = this.buildObjectArray1(); + assertEquals(-1, ArrayTools.indexOf(a, null)); + } + + public void testIdentityIndexOfObjectArrayObject() { + String foo = "foo"; + String bar = "bar"; + String baz = "baz"; + Object[] a = new Object[3]; + a[0] = foo; + a[1] = bar; + a[2] = baz; + assertEquals(1, ArrayTools.identityIndexOf(a, bar)); + } + + public void testIdentityIndexOfObjectArrayObject_NotFound() { + String foo = "foo"; + String bar = "bar"; + String baz = "baz"; + Object[] a = new Object[3]; + a[0] = foo; + a[1] = bar; + a[2] = baz; + assertEquals(-1, ArrayTools.identityIndexOf(a, new String("bar"))); + } + + public void testIndexOfCharArrayChar() { + char[] a = this.buildCharArray(); + assertEquals(1, ArrayTools.indexOf(a, 'b')); + a = ArrayTools.add(a, 'd'); + assertEquals(a.length - 1, ArrayTools.indexOf(a, 'd')); + } + + public void testIndexOfCharArrayChar_NotFound() { + char[] a = this.buildCharArray(); + assertEquals(-1, ArrayTools.indexOf(a, 'z')); + } + + public void testIndexOfIntArrayInt() { + int[] a = this.buildIntArray(); + assertEquals(1, ArrayTools.indexOf(a, 10)); + a = ArrayTools.add(a, 30); + assertEquals(a.length - 1, ArrayTools.indexOf(a, 30)); + } + + public void testIndexOfIntArrayInt_NotFound() { + int[] a = this.buildIntArray(); + assertEquals(-1, ArrayTools.indexOf(a, 1000)); + } + + + // ********** insertion index of ********** + + public void testInsertionIndexOfObjectArrayComparable() { + String[] a = new String[] { "A", "C", "D" }; + assertEquals(1, ArrayTools.insertionIndexOf(a, "B")); + + a = new String[] { "A", "B", "C", "D" }; + assertEquals(2, ArrayTools.insertionIndexOf(a, "B")); + + a = new String[] { "A", "B", "B", "B", "C", "D" }; + assertEquals(4, ArrayTools.insertionIndexOf(a, "B")); + + a = new String[] { "A", "B", "B", "B", "C", "D" }; + assertEquals(6, ArrayTools.insertionIndexOf(a, "E")); + + a = new String[] { "B", "B", "B", "C", "D" }; + assertEquals(0, ArrayTools.insertionIndexOf(a, "A")); + + a = new String[] { "A", "A", "B", "B", "C", "D" }; + assertEquals(2, ArrayTools.insertionIndexOf(a, "A")); + } + + public void testInsertionIndexOfObjectArrayObjectComparator() { + Comparator<String> c = new ReverseComparator<String>(); + String[] a = new String[] { "D", "C", "A" }; + assertEquals(2, ArrayTools.insertionIndexOf(a, "B", c)); + + a = new String[] { "D", "C", "B", "A" }; + assertEquals(3, ArrayTools.insertionIndexOf(a, "B", c)); + + a = new String[] { "D", "C", "B", "B", "B", "A" }; + assertEquals(5, ArrayTools.insertionIndexOf(a, "B", c)); + + a = new String[] { "D", "C", "B", "B", "B", "A" }; + assertEquals(0, ArrayTools.insertionIndexOf(a, "E", c)); + + a = new String[] { "D", "C", "B", "B", "B" }; + assertEquals(5, ArrayTools.insertionIndexOf(a, "A", c)); + + a = new String[] { "D", "C", "B", "B", "A", "A" }; + assertEquals(6, ArrayTools.insertionIndexOf(a, "A", c)); + } + + + // ********** last index of ********** + + public void testLastIndexOfObjectArrayObject() { + Object[] a = this.buildObjectArray1(); + assertEquals(1, ArrayTools.lastIndexOf(a, "one")); + } + + public void testLastIndexOfObjectArrayObject_NotFound() { + Object[] a = this.buildObjectArray1(); + assertEquals(-1, ArrayTools.lastIndexOf(a, "twenty")); + } + + public void testLastIndexOfObjectArrayObject_Null() { + Object[] a = this.buildObjectArray1(); + a = ArrayTools.add(a, null); + assertEquals(a.length - 1, ArrayTools.lastIndexOf(a, null)); + } + + public void testLastIndexOfObjectArrayObject_Null_NotFound() { + Object[] a = this.buildObjectArray1(); + assertEquals(-1, ArrayTools.lastIndexOf(a, null)); + } + + public void testLastIndexOfCharArrayChar() { + char[] a = this.buildCharArray(); + assertEquals(1, ArrayTools.lastIndexOf(a, 'b')); + a = ArrayTools.add(a, 'd'); + assertEquals(a.length - 1, ArrayTools.lastIndexOf(a, 'd')); + } + + public void testLastIndexOfCharArrayChar_NotFound() { + char[] a = this.buildCharArray(); + assertEquals(-1, ArrayTools.lastIndexOf(a, 'z')); + } + + public void testLastIndexOfIntArrayInt() { + int[] a = this.buildIntArray(); + assertEquals(1, ArrayTools.lastIndexOf(a, 10)); + a = ArrayTools.add(a, 30); + assertEquals(a.length - 1, ArrayTools.lastIndexOf(a, 30)); + } + + public void testLastIndexOfIntArrayInt_NotFound() { + int[] a = this.buildIntArray(); + assertEquals(-1, ArrayTools.lastIndexOf(a, 1000)); + } + + + // ********** min/max ********** + + public void testMinCharArray() { + assertEquals('a', ArrayTools.min(this.buildCharArray())); + } + + public void testMinCharArray_Exception() { + char[] array = new char[0]; + boolean exCaught = false; + try { + char c = ArrayTools.min(array); + fail("bogus char: " + c); + } catch (IndexOutOfBoundsException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testMinIntArray() { + assertEquals(0, ArrayTools.min(this.buildIntArray())); + } + + public void testMinIntArray_Exception() { + int[] array = new int[0]; + boolean exCaught = false; + try { + int i = ArrayTools.min(array); + fail("bogus int: " + i); + } catch (IndexOutOfBoundsException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testMaxCharArray1() { + assertEquals('c', ArrayTools.max(this.buildCharArray())); + } + + public void testMaxCharArray2() { + char[] array = new char[] { 'x', 'a', 'b', 'c' }; + assertEquals('x', ArrayTools.max(array)); + } + + public void testMaxCharArray_Exception() { + char[] array = new char[0]; + boolean exCaught = false; + try { + char c = ArrayTools.max(array); + fail("bogus char: " + c); + } catch (IndexOutOfBoundsException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testMaxIntArray1() { + assertEquals(20, ArrayTools.max(this.buildIntArray())); + } + + public void testMaxIntArray2() { + int[] array = new int[] { 77, 3, 1, -3 }; + assertEquals(77, ArrayTools.max(array)); + } + + public void testMaxIntArray_Exception() { + int[] array = new int[0]; + boolean exCaught = false; + try { + int i = ArrayTools.max(array); + fail("bogus int: " + i); + } catch (IndexOutOfBoundsException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + + // ********** move ********** + + public void testMoveObjectArrayIntInt() { + String[] array = new String[] { "0", "1", "2", "3", "4", "5" }; + + String[] result = ArrayTools.move(array, 4, 2); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "0", "1", "3", "4", "2", "5" }, result)); + + result = ArrayTools.move(array, 0, 5); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "1", "3", "4", "2" }, result)); + + result = ArrayTools.move(array, 2, 4); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "4", "1", "3", "2" }, result)); + + result = ArrayTools.move(array, 4, 4); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "4", "1", "3", "2" }, result)); + } + + public void testMoveObjectArrayIntIntInt() { + String[] array = new String[] { "0", "1", "2", "3", "4", "5" }; + + String[] result = ArrayTools.move(array, 4, 2, 1); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "0", "1", "3", "4", "2", "5" }, result)); + + result = ArrayTools.move(array, 0, 5, 1); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "1", "3", "4", "2" }, result)); + + result = ArrayTools.move(array, 2, 4, 1); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "4", "1", "3", "2" }, result)); + + result = ArrayTools.move(array, 2, 4, 2); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result)); + + result = ArrayTools.move(array, 0, 1, 4); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "0", "3", "2", "4", "5", "1" }, result)); + + result = ArrayTools.move(array, 1, 0, 4); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result)); + + result = ArrayTools.move(array, 1, 1, 4); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result)); + + result = ArrayTools.move(array, 1, 0, 0); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result)); + } + + public void testMoveIntArrayIntInt() { + int[] array = new int[] { 0, 1, 2, 3, 4, 5 }; + + int[] result = ArrayTools.move(array, 4, 2); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new int[] { 0, 1, 3, 4, 2, 5 }, result)); + + result = ArrayTools.move(array, 0, 5); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new int[] { 5, 0, 1, 3, 4, 2 }, result)); + + result = ArrayTools.move(array, 2, 4); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new int[] { 5, 0, 4, 1, 3, 2 }, result)); + + result = ArrayTools.move(array, 2, 2); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new int[] { 5, 0, 4, 1, 3, 2 }, result)); + } + + public void testMoveIntArrayIntIntInt() { + int[] array = new int[] { 0, 1, 2, 3, 4, 5 }; + + int[] result = ArrayTools.move(array, 4, 2, 1); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new int[] { 0, 1, 3, 4, 2, 5 }, result)); + + result = ArrayTools.move(array, 0, 5, 1); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new int[] { 5, 0, 1, 3, 4, 2 }, result)); + + result = ArrayTools.move(array, 2, 4, 1); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new int[] { 5, 0, 4, 1, 3, 2 }, result)); + + result = ArrayTools.move(array, 2, 4, 2); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new int[] { 5, 0, 3, 2, 4, 1 }, result)); + + result = ArrayTools.move(array, 0, 1, 4); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new int[] { 0, 3, 2, 4, 5, 1 }, result)); + + result = ArrayTools.move(array, 1, 0, 4); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new int[] { 5, 0, 3, 2, 4, 1 }, result)); + + result = ArrayTools.move(array, 1, 1, 4); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new int[] { 5, 0, 3, 2, 4, 1 }, result)); + + result = ArrayTools.move(array, 1, 0, 0); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new int[] { 5, 0, 3, 2, 4, 1 }, result)); + } + + public void testMoveCharArrayIntInt() { + char[] array = new char[] { 'a', 'b', 'c', 'd', 'e', 'f' }; + + char[] result = ArrayTools.move(array, 4, 2); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new char[] { 'a', 'b', 'd', 'e', 'c', 'f' }, result)); + + result = ArrayTools.move(array, 0, 5); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new char[] { 'f', 'a', 'b', 'd', 'e', 'c' }, result)); + + result = ArrayTools.move(array, 2, 4); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new char[] { 'f', 'a', 'e', 'b', 'd', 'c' }, result)); + + result = ArrayTools.move(array, 2, 2); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new char[] { 'f', 'a', 'e', 'b', 'd', 'c' }, result)); + } + + public void testMoveCharArrayIntIntInt() { + char[] array = new char[] { 'a', 'b', 'b', 'c', 'd', 'e' }; + + char[] result = ArrayTools.move(array, 4, 2, 1); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new char[] { 'a', 'b', 'c', 'd', 'b', 'e' }, result)); + + result = ArrayTools.move(array, 0, 5, 1); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new char[] { 'e', 'a', 'b', 'c', 'd', 'b' }, result)); + + result = ArrayTools.move(array, 2, 4, 1); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new char[] { 'e', 'a', 'd', 'b', 'c', 'b' }, result)); + + result = ArrayTools.move(array, 2, 4, 2); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new char[] { 'e', 'a', 'c', 'b', 'd', 'b' }, result)); + + result = ArrayTools.move(array, 0, 1, 4); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new char[] { 'a', 'c', 'b', 'd', 'e', 'b' }, result)); + + result = ArrayTools.move(array, 1, 0, 4); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new char[] { 'e', 'a', 'c', 'b', 'd', 'b' }, result)); + + result = ArrayTools.move(array, 1, 1, 4); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new char[] { 'e', 'a', 'c', 'b', 'd', 'b' }, result)); + + result = ArrayTools.move(array, 1, 0, 0); + assertSame(array, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new char[] { 'e', 'a', 'c', 'b', 'd', 'b' }, result)); + } + + + // ********** remove ********** + + public void testRemoveObjectArrayObject_Object() { + Object[] a = this.buildObjectArray1(); + a = ArrayTools.add(a, "three"); + a = ArrayTools.add(a, "four"); + a = ArrayTools.add(a, "five"); + + assertEquals(6, a.length); + assertTrue(ArrayTools.contains(a, "three")); + a = ArrayTools.remove(a, "three"); + assertEquals(5, a.length); + assertFalse(ArrayTools.contains(a, "three")); + assertTrue(ArrayTools.contains(a, "four")); + assertTrue(ArrayTools.contains(a, "five")); + } + + public void testRemoveObjectArrayObject_String() { + String[] a = this.buildStringArray1(); + a = ArrayTools.add(a, "three"); + a = ArrayTools.add(a, "four"); + a = ArrayTools.add(a, "five"); + + assertEquals(6, a.length); + assertTrue(ArrayTools.contains(a, "three")); + a = ArrayTools.remove(a, "three"); + assertEquals(5, a.length); + assertFalse(ArrayTools.contains(a, "three")); + assertTrue(ArrayTools.contains(a, "four")); + assertTrue(ArrayTools.contains(a, "five")); + } + + public void testRemoveCharArrayChar() { + char[] a = this.buildCharArray(); + a = ArrayTools.add(a, 'd'); + a = ArrayTools.add(a, 'e'); + a = ArrayTools.add(a, 'f'); + + assertEquals(6, a.length); + assertTrue(ArrayTools.contains(a, 'd')); + a = ArrayTools.remove(a, 'd'); + assertEquals(5, a.length); + assertFalse(ArrayTools.contains(a, 'd')); + assertTrue(ArrayTools.contains(a, 'e')); + assertTrue(ArrayTools.contains(a, 'f')); + } + + public void testRemoveIntArrayInt() { + int[] a = this.buildIntArray(); + a = ArrayTools.add(a, 30); + a = ArrayTools.add(a, 40); + a = ArrayTools.add(a, 50); + + assertEquals(6, a.length); + assertTrue(ArrayTools.contains(a, 30)); + a = ArrayTools.remove(a, 30); + assertEquals(5, a.length); + assertFalse(ArrayTools.contains(a, 30)); + assertTrue(ArrayTools.contains(a, 40)); + assertTrue(ArrayTools.contains(a, 50)); + } + + + // ********** remove all ********** + + public void testRemoveAllObjectArrayObjectArray() { + String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; + String[] a2 = new String[] { "E", "B" }; + String[] a3 = ArrayTools.removeAll(a1, (Object[]) a2); + assertTrue(Arrays.equals(new String[] { "A", "A", "C", "C", "D", "D", "F", "F" }, a3)); + } + + public void testRemoveAllObjectArrayObjectArray_Empty() { + String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; + String[] a2 = new String[0]; + String[] a3 = ArrayTools.removeAll(a1, (Object[]) a2); + assertTrue(Arrays.equals(a1, a3)); + } + + public void testRemoveAllObjectArrayObjectArray_NoMatches() { + String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; + String[] a2 = new String[] { "X", "Y", "Z" }; + String[] a3 = ArrayTools.removeAll(a1, (Object[]) a2); + assertTrue(Arrays.equals(a1, a3)); + } + + public void testRemoveAllObjectArrayIterable() { + String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; + Iterable<?> iterable = Arrays.asList(new String[] { "E", "B" }); + String[] a3 = ArrayTools.removeAll(a1, iterable); + assertTrue(Arrays.equals(new String[] { "A", "A", "C", "C", "D", "D", "F", "F" }, a3)); + } + + public void testRemoveAllObjectArrayIterableInt() { + String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; + Iterable<?> iterable = Arrays.asList(new String[] { "E", "B" }); + String[] a3 = ArrayTools.removeAll(a1, iterable, 7); + assertTrue(Arrays.equals(new String[] { "A", "A", "C", "C", "D", "D", "F", "F" }, a3)); + } + + public void testRemoveAllObjectArrayIterator() { + String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; + Iterable<?> iterable = Arrays.asList(new String[] { "E", "B" }); + String[] a3 = ArrayTools.removeAll(a1, iterable.iterator()); + assertTrue(Arrays.equals(new String[] { "A", "A", "C", "C", "D", "D", "F", "F" }, a3)); + } + + public void testRemoveAllObjectArrayIterator_Empty() { + String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; + String[] a3 = ArrayTools.removeAll(a1, EmptyIterator.instance()); + assertTrue(Arrays.equals(a1, a3)); + } + + public void testRemoveAllObjectArrayIteratorInt() { + String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; + Iterable<?> iterable = Arrays.asList(new String[] { "E", "B" }); + String[] a3 = ArrayTools.removeAll(a1, iterable.iterator(), 7); + assertTrue(Arrays.equals(new String[] { "A", "A", "C", "C", "D", "D", "F", "F" }, a3)); + } + + public void testRemoveAllObjectArrayIteratorInt_Empty() { + String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; + String[] a3 = ArrayTools.removeAll(a1, EmptyIterator.instance(), 7); + assertTrue(Arrays.equals(a1, a3)); + } + + public void testRemoveAllObjectArrayCollection() { + String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; + Collection<String> collection = Arrays.asList(new String[] { "E", "B" }); + String[] a3 = ArrayTools.removeAll(a1, collection); + assertTrue(Arrays.equals(new String[] { "A", "A", "C", "C", "D", "D", "F", "F" }, a3)); + } + + public void testRemoveAllObjectArrayCollection_Empty() { + String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; + Collection<String> collection = new ArrayList<String>(); + String[] a3 = ArrayTools.removeAll(a1, collection); + assertTrue(Arrays.equals(a1, a3)); + } + + public void testRemoveAllObjectArrayCollection_EmptyArray() { + String[] a1 = new String[0]; + Collection<String> collection = Arrays.asList(new String[] { "E", "B" }); + String[] a3 = ArrayTools.removeAll(a1, collection); + assertTrue(Arrays.equals(a1, a3)); + assertEquals(0, a3.length); + } + + public void testRemoveAllObjectArrayCollection_NoMatches() { + String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; + Collection<String> collection = Arrays.asList(new String[] { "X", "Y", "Z" }); + String[] a3 = ArrayTools.removeAll(a1, collection); + assertTrue(Arrays.equals(a1, a3)); + } + + public void testRemoveAllCharArrayCharArray() { + char[] a1 = new char[] { 'A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F' }; + char[] a2 = new char[] { 'E', 'B' }; + assertTrue(Arrays.equals(new char[] { 'A', 'A', 'C', 'C', 'D', 'D', 'F', 'F' }, ArrayTools.removeAll(a1, a2))); + } + + public void testRemoveAllCharArrayCharArray_Empty1() { + char[] a1 = new char[0]; + char[] a2 = new char[] { 'E', 'B' }; + assertTrue(Arrays.equals(a1, ArrayTools.removeAll(a1, a2))); + } + + public void testRemoveAllCharArrayCharArray_Empty2() { + char[] a1 = new char[] { 'A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F' }; + char[] a2 = new char[0]; + assertTrue(Arrays.equals(a1, ArrayTools.removeAll(a1, a2))); + } + + public void testRemoveAllCharArrayCharArray_NoMatches() { + char[] a1 = new char[] { 'A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F' }; + char[] a2 = new char[] { 'X', 'Z' }; + assertTrue(Arrays.equals(a1, ArrayTools.removeAll(a1, a2))); + } + + public void testRemoveAllIntArrayIntArray() { + int[] a1 = new int[] { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6 }; + int[] a2 = new int[] { 5, 2 }; + assertTrue(Arrays.equals(new int[] { 1, 1, 3, 3, 4, 4, 6, 6 }, ArrayTools.removeAll(a1, a2))); + } + + public void testRemoveAllIntArrayIntArray_Empty1() { + int[] a1 = new int[0]; + int[] a2 = new int[] { 5, 2 }; + assertTrue(Arrays.equals(a1, ArrayTools.removeAll(a1, a2))); + } + + public void testRemoveAllIntArrayIntArray_Empty2() { + int[] a1 = new int[] { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6 }; + int[] a2 = new int[0]; + assertTrue(Arrays.equals(a1, ArrayTools.removeAll(a1, a2))); + } + + public void testRemoveAllIntArrayIntArray_NoMatches() { + int[] a1 = new int[] { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6 }; + int[] a2 = new int[] { 52, 67 }; + assertTrue(Arrays.equals(a1, ArrayTools.removeAll(a1, a2))); + } + + + // ********** remove all occurrences ********** + + public void testRemoveAllOccurrencesObjectArrayObject() { + String[] a = this.buildStringArray1(); + assertEquals(3, a.length); + a = ArrayTools.removeAllOccurrences(a, "three"); + assertEquals(3, a.length); + a = ArrayTools.removeAllOccurrences(a, "two"); + assertEquals(2, a.length); + a = ArrayTools.removeAllOccurrences(a, "two"); + assertEquals(2, a.length); + + a = ArrayTools.add(a, "five"); + a = ArrayTools.add(a, "five"); + a = ArrayTools.add(a, "five"); + assertEquals(5, a.length); + a = ArrayTools.removeAllOccurrences(a, "five"); + assertEquals(2, a.length); + a = ArrayTools.removeAllOccurrences(a, "five"); + assertEquals(2, a.length); + + a = ArrayTools.add(a, null); + a = ArrayTools.add(a, null); + a = ArrayTools.add(a, null); + assertEquals(5, a.length); + a = ArrayTools.removeAllOccurrences(a, null); + assertEquals(2, a.length); + a = ArrayTools.removeAllOccurrences(a, null); + assertEquals(2, a.length); + } + + public void testRemoveAllOccurrencesObjectArrayObject_Empty() { + String[] a = new String[0]; + a = ArrayTools.removeAllOccurrences(a, "three"); + assertEquals(0, a.length); + } + + public void testRemoveAllOccurrencesCharArrayChar() { + char[] a = this.buildCharArray(); + assertEquals(3, a.length); + a = ArrayTools.removeAllOccurrences(a, 'd'); + assertEquals(3, a.length); + a = ArrayTools.removeAllOccurrences(a, 'b'); + assertEquals(2, a.length); + a = ArrayTools.removeAllOccurrences(a, 'b'); + assertEquals(2, a.length); + + a = ArrayTools.add(a, 'g'); + a = ArrayTools.add(a, 'g'); + a = ArrayTools.add(a, 'g'); + assertEquals(5, a.length); + a = ArrayTools.removeAllOccurrences(a, 'g'); + assertEquals(2, a.length); + a = ArrayTools.removeAllOccurrences(a, 'g'); + assertEquals(2, a.length); + } + + public void testRemoveAllOccurrencesCharArrayChar_Empty() { + char[] a = new char[0]; + a = ArrayTools.removeAllOccurrences(a, 'a'); + assertEquals(0, a.length); + } + + public void testRemoveAllOccurrencesIntArrayInt() { + int[] a = this.buildIntArray(); + assertEquals(3, a.length); + a = ArrayTools.removeAllOccurrences(a, 55); + assertEquals(3, a.length); + a = ArrayTools.removeAllOccurrences(a, 10); + assertEquals(2, a.length); + a = ArrayTools.removeAllOccurrences(a, 10); + assertEquals(2, a.length); + + a = ArrayTools.add(a, 77); + a = ArrayTools.add(a, 77); + a = ArrayTools.add(a, 77); + assertEquals(5, a.length); + a = ArrayTools.removeAllOccurrences(a, 77); + assertEquals(2, a.length); + a = ArrayTools.removeAllOccurrences(a, 77); + assertEquals(2, a.length); + } + + public void testRemoveAllOccurrencesIntArrayInt_Empty() { + int[] a = new int[0]; + a = ArrayTools.removeAllOccurrences(a, 22); + assertEquals(0, a.length); + } + + + // ********** remove duplicate elements ********** + + public void testRemoveDuplicateElementsObjectArray() { + List<String> list = this.buildStringVector1(); + list.add("zero"); + list.add("zero"); + list.add("two"); + list.add("zero"); + String[] array = ArrayTools.removeDuplicateElements(list.toArray(new String[list.size()])); + int i = 0; + assertEquals("zero", array[i++]); + assertEquals("one", array[i++]); + assertEquals("two", array[i++]); + assertEquals(i, array.length); + } + + public void testRemoveDuplicateElementsObjectArray_Empty() { + String[] array = ArrayTools.removeDuplicateElements(new String[0]); + assertEquals(0, array.length); + } + + public void testRemoveDuplicateElementsObjectArray_SingleElement() { + String[] array = ArrayTools.removeDuplicateElements(new String[] { "foo" }); + assertEquals(1, array.length); + } + + public void testRemoveDuplicateElementsObjectArray_NoDuplicates() { + String[] a1 = new String[] { "foo", "bar", "baz" }; + String[] a2 = ArrayTools.removeDuplicateElements(a1); + assertEquals(3, a2.length); + assertTrue(Arrays.equals(a1, a2)); + } + + + // ********** remove element at index ********** + + public void testRemoveElementAtIndexObjectArrayInt() { + String[] a = new String[] { "A", "B", "A", "C", "A", "D" }; + a = ArrayTools.removeElementAtIndex(a, 3); + assertTrue(Arrays.equals(new String[] { "A", "B", "A", "A", "D" }, a)); + } + + public void testRemoveElementAtIndexCharArrayInt() { + char[] a = new char[] { 'A', 'B', 'A', 'C', 'A', 'D' }; + a = ArrayTools.removeElementAtIndex(a, 3); + assertTrue(Arrays.equals(new char[] { 'A', 'B', 'A', 'A', 'D' }, a)); + } + + public void testRemoveElementAtIndexIntArrayInt() { + int[] a = new int[] { 8, 6, 7, 33, 2, 11 }; + a = ArrayTools.removeElementsAtIndex(a, 3, 3); + assertTrue(Arrays.equals(new int[] { 8, 6, 7 }, a)); + } + + public void testRemoveFirstObjectArray() { + String[] a = new String[] { "A", "B", "A", "C", "A", "D" }; + a = ArrayTools.removeFirst(a); + assertTrue(Arrays.equals(new String[] { "B", "A", "C", "A", "D" }, a)); + } + + public void testRemoveFirstCharArray() { + char[] a = new char[] { 'A', 'B', 'A', 'C', 'A', 'D' }; + a = ArrayTools.removeFirst(a); + assertTrue(Arrays.equals(new char[] { 'B', 'A', 'C', 'A', 'D' }, a)); + } + + public void testRemoveFirstIntArray() { + int[] a = new int[] { 8, 6, 7, 33, 2, 11 }; + a = ArrayTools.removeFirst(a); + assertTrue(Arrays.equals(new int[] { 6, 7, 33, 2, 11 }, a)); + } + + public void testRemoveLastObjectArray() { + String[] a = new String[] { "A", "B", "A", "C", "A", "D" }; + a = ArrayTools.removeLast(a); + assertTrue(Arrays.equals(new String[] { "A", "B", "A", "C", "A" }, a)); + } + + public void testRemoveLastCharArray() { + char[] a = new char[] { 'A', 'B', 'A', 'C', 'A', 'D' }; + a = ArrayTools.removeLast(a); + assertTrue(Arrays.equals(new char[] { 'A', 'B', 'A', 'C', 'A' }, a)); + } + + public void testRemoveLastIntArray() { + int[] a = new int[] { 8, 6, 7, 33, 2, 11 }; + a = ArrayTools.removeLast(a); + assertTrue(Arrays.equals(new int[] { 8, 6, 7, 33, 2 }, a)); + } + + + // ********** remove elements at index ********** + + public void testRemoveElementsAtIndexObjectArrayIntInt() { + String[] a = new String[] { "A", "B", "A", "C", "A", "D" }; + a = ArrayTools.removeElementsAtIndex(a, 3, 2); + assertTrue(Arrays.equals(new String[] { "A", "B", "A", "D" }, a)); + } + + public void testRemoveElementsAtIndexObjectArrayIntInt_ZeroLength() { + String[] a1 = new String[] { "A", "B", "A", "C", "A", "D" }; + String[] a2 = ArrayTools.removeElementsAtIndex(a1, 3, 0); + assertTrue(Arrays.equals(a1, a2)); + } + + public void testRemoveElementsAtIndexObjectArrayIntInt_Empty() { + String[] a = new String[] { "A", "B", "A", "C", "A", "D" }; + a = ArrayTools.removeElementsAtIndex(a, 0, 6); + assertEquals(0, a.length); + } + + public void testRemoveElementsAtIndexCharArrayIntInt() { + char[] a = new char[] { 'A', 'B', 'A', 'C', 'A', 'D' }; + a = ArrayTools.removeElementsAtIndex(a, 0, 5); + assertTrue(Arrays.equals(new char[] { 'D' }, a)); + } + + public void testRemoveElementsAtIndexCharArrayIntInt_ZeroLength() { + char[] a1 = new char[] { 'A', 'B', 'A', 'C', 'A', 'D' }; + char[] a2 = ArrayTools.removeElementsAtIndex(a1, 3, 0); + assertTrue(Arrays.equals(a1, a2)); + } + + public void testRemoveElementsAtIndexCharArrayIntInt_Empty() { + char[] a = new char[] { 'A', 'B', 'A', 'C', 'A', 'D' }; + a = ArrayTools.removeElementsAtIndex(a, 0, 6); + assertEquals(0, a.length); + } + + public void testRemoveElementsAtIndexIntArrayIntInt() { + int[] a = new int[] { 8, 6, 7, 33, 2, 11 }; + a = ArrayTools.removeElementsAtIndex(a, 3, 3); + assertTrue(Arrays.equals(new int[] { 8, 6, 7 }, a)); + } + + public void testRemoveElementsAtIndexIntArrayIntInt_ZeroLength() { + int[] a1 = new int[] { 8, 6, 7, 33, 2, 11 }; + int[] a2 = ArrayTools.removeElementsAtIndex(a1, 3, 0); + assertTrue(Arrays.equals(a1, a2)); + } + + public void testRemoveElementsAtIndexIntArrayIntInt_Empty() { + int[] a = new int[] { 8, 6, 7, 33, 2, 11 }; + a = ArrayTools.removeElementsAtIndex(a, 0, 6); + assertEquals(0, a.length); + } + + + // ********** replace all ********** + + public void testReplaceAllObjectArrayObjectObject_Object() { + Object[] a = new Object[] { "A", "B", "A", "C", "A", "D" }; + a = ArrayTools.replaceAll(a, "A", "Z"); + assertTrue(Arrays.equals(new Object[] { "Z", "B", "Z", "C", "Z", "D" }, a)); + } + + public void testReplaceAllObjectArrayObjectObject_String() { + String[] a = new String[] { "A", "B", "A", "C", "A", "D" }; + a = ArrayTools.replaceAll(a, "A", "Z"); + assertTrue(Arrays.equals(new String[] { "Z", "B", "Z", "C", "Z", "D" }, a)); + } + + public void testReplaceAllObjectArrayObjectObject_Null() { + String[] a = new String[] { null, "B", null, "C", null, "D" }; + a = ArrayTools.replaceAll(a, null, "Z"); + assertTrue(Arrays.equals(new String[] { "Z", "B", "Z", "C", "Z", "D" }, a)); + } + + public void testReplaceAllCharArrayCharChar() { + char[] a = new char[] { 'A', 'B', 'A', 'C', 'A', 'D' }; + a = ArrayTools.replaceAll(a, 'A', 'Z'); + assertTrue(Arrays.equals(new char[] { 'Z', 'B', 'Z', 'C', 'Z', 'D' }, a)); + } + + public void testReplaceAllIntArrayIntInt() { + int[] a = new int[] { 0, 1, 0, 7, 0, 99 }; + a = ArrayTools.replaceAll(a, 0, 13); + assertTrue(Arrays.equals(new int[] { 13, 1, 13, 7, 13, 99 }, a)); + } + + + // ********** retain all ********** + + public void testRetainAllObjectArrayObjectArray() { + String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; + Object[] a2 = new Object[] { "E", "B", new Integer(7) }; + assertTrue(Arrays.equals(new String[] { "B", "B", "E", "E" }, ArrayTools.retainAll(a1, a2))); + } + + public void testRetainAllObjectArrayObjectArray_EmptyObjectArray1() { + String[] a1 = new String[0]; + String[] a2 = new String[] { "E", "B", "" }; + String[] a3 = ArrayTools.retainAll(a1, a2); + assertEquals(0, a3.length); + } + + public void testRetainAllObjectArrayObjectArray_EmptyObjectArray2() { + String[] a1 = new String[] { "E", "B", "" }; + String[] a2 = new String[0]; + String[] a3 = ArrayTools.retainAll(a1, a2); + assertEquals(0, a3.length); + } + + public void testRetainAllObjectArrayObjectArray_BothEmpty() { + String[] a1 = new String[0]; + String[] a2 = new String[0]; + String[] a3 = ArrayTools.retainAll(a1, a2); + assertEquals(0, a3.length); + } + + public void testRetainAllObjectArrayIterable() { + String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; + Iterable<String> iterable = Arrays.asList(new String[] { "E", "B", "" }); + assertTrue(Arrays.equals(new String[] { "B", "B", "E", "E" }, ArrayTools.retainAll(a1, iterable))); + } + + public void testRetainAllObjectArrayIterable_EmptyObjectArray() { + String[] a1 = new String[0]; + Iterable<String> iterable = Arrays.asList(new String[] { "E", "B", "" }); + String[] a3 = ArrayTools.retainAll(a1, iterable); + assertEquals(0, a3.length); + } + + public void testRetainAllObjectArrayIterableInt() { + String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; + Iterable<String> iterable = Arrays.asList(new String[] { "E", "B", "" }); + assertTrue(Arrays.equals(new String[] { "B", "B", "E", "E" }, ArrayTools.retainAll(a1, iterable, 3))); + } + + public void testRetainAllObjectArrayIterableInt_EmptyObjectArray() { + String[] a1 = new String[0]; + Iterable<String> iterable = Arrays.asList(new String[] { "E", "B", "" }); + String[] a3 = ArrayTools.retainAll(a1, iterable, 3); + assertEquals(0, a3.length); + } + + public void testRetainAllObjectArrayIterator() { + String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; + Iterator<String> iterator = Arrays.asList(new String[] { "E", "B", "" }).iterator(); + assertTrue(Arrays.equals(new String[] { "B", "B", "E", "E" }, ArrayTools.retainAll(a1, iterator))); + } + + public void testRetainAllObjectArrayIterator_EmptyObjectArray() { + String[] a1 = new String[0]; + Iterator<String> iterator = Arrays.asList(new String[] { "E", "B", "" }).iterator(); + String[] a3 = ArrayTools.retainAll(a1, iterator); + assertEquals(0, a3.length); + } + + public void testRetainAllObjectArrayIterator_EmptyIterator() { + String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; + assertTrue(Arrays.equals(new String[0], ArrayTools.retainAll(a1, EmptyIterator.instance()))); + } + + public void testRetainAllObjectArrayIteratorInt() { + String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; + Iterator<String> iterator = Arrays.asList(new String[] { "E", "B", "" }).iterator(); + assertTrue(Arrays.equals(new String[] { "B", "B", "E", "E" }, ArrayTools.retainAll(a1, iterator, 3))); + } + + public void testRetainAllObjectArrayIteratorInt_EmptyIterator() { + String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; + assertTrue(Arrays.equals(new String[0], ArrayTools.retainAll(a1, EmptyIterator.instance(), 3))); + } + + public void testRetainAllObjectArrayIteratorInt_EmptyObjectArray() { + String[] a1 = new String[0]; + Iterator<String> iterator = Arrays.asList(new String[] { "E", "B", "" }).iterator(); + String[] a3 = ArrayTools.retainAll(a1, iterator, 3); + assertEquals(0, a3.length); + } + + public void testRetainAllObjectArrayCollection() { + String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; + Collection<String> collection = Arrays.asList(new String[] { "E", "B", "" }); + assertTrue(Arrays.equals(new String[] { "B", "B", "E", "E" }, ArrayTools.retainAll(a1, collection))); + } + + public void testRetainAllObjectArrayCollection_EmptyObjectArray() { + String[] a1 = new String[0]; + Collection<String> collection = Arrays.asList(new String[] { "E", "B", "" }); + String[] a3 = ArrayTools.retainAll(a1, collection); + assertEquals(0, a3.length); + } + + public void testRetainAllObjectArrayCollection_EmptyCollection() { + String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; + Collection<String> collection = new ArrayList<String>(); + String[] a3 = ArrayTools.retainAll(a1, collection); + assertEquals(0, a3.length); + } + + public void testRetainAllObjectArrayCollection_All() { + String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; + Collection<String> collection = Arrays.asList(new String[] { "A", "B", "C", "D", "E", "F" }); + assertTrue(Arrays.equals(a1, ArrayTools.retainAll(a1, collection))); + } + + public void testRetainAllCharArrayCharArray() { + char[] a1 = new char[] { 'A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F' }; + char[] a2 = new char[] { 'E', 'B' }; + assertTrue(Arrays.equals(new char[] { 'B', 'B', 'E', 'E' }, ArrayTools.retainAll(a1, a2))); + } + + public void testRetainAllCharArrayCharArray_EmptyCharArray1() { + char[] a1 = new char[0]; + char[] a2 = new char[] { 'E', 'B' }; + assertSame(a1, ArrayTools.retainAll(a1, a2)); + } + + public void testRetainAllCharArrayCharArray_EmptyCharArray2() { + char[] a1 = new char[] { 'E', 'B' }; + char[] a2 = new char[0]; + assertEquals(0, ArrayTools.retainAll(a1, a2).length); + } + + public void testRetainAllCharArrayCharArray_RetainAll() { + char[] a1 = new char[] { 'E', 'B', 'E', 'B', 'E', 'B', 'E', 'B', 'E' }; + char[] a2 = new char[] { 'E', 'B' }; + assertSame(a1, ArrayTools.retainAll(a1, a2)); + } + + public void testRetainAllIntArrayIntArray() { + int[] a1 = new int[] { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6 }; + int[] a2 = new int[] { 5, 2 }; + assertTrue(Arrays.equals(new int[] { 2, 2, 5, 5 }, ArrayTools.retainAll(a1, a2))); + } + + public void testRetainAllIntArrayIntArray_EmptyIntArray1() { + int[] a1 = new int[0]; + int[] a2 = new int[] { 5, 2 }; + assertSame(a1, ArrayTools.retainAll(a1, a2)); + } + + public void testRetainAllIntArrayIntArray_EmptyIntArray2() { + int[] a1 = new int[] { 5, 2 }; + int[] a2 = new int[0]; + assertEquals(0, ArrayTools.retainAll(a1, a2).length); + } + + public void testRetainAllIntArrayIntArray_RetainAll() { + int[] a1 = new int[] { 5, 2, 5, 2, 5, 2, 5, 2, 5, 2, 5 }; + int[] a2 = new int[] { 5, 2 }; + assertSame(a1, ArrayTools.retainAll(a1, a2)); + } + + + // ********** reverse ********** + + public void testReverseObjectArray_Object() { + Object[] a = this.buildObjectArray1(); + a = ArrayTools.reverse(a); + assertEquals("two", a[0]); + assertEquals("one", a[1]); + assertEquals("zero", a[2]); + } + + public void testReverseObjectArray_String() { + String[] a = this.buildStringArray1(); + a = ArrayTools.reverse(a); + assertEquals("two", a[0]); + assertEquals("one", a[1]); + assertEquals("zero", a[2]); + } + + public void testReverseObjectArray_Singleton() { + String[] a1 = new String[] { "foo" }; + String[] a2 = ArrayTools.reverse(a1); + assertTrue(Arrays.equals(a1, a2)); + } + + public void testReverseCharArray() { + char[] a = this.buildCharArray(); + a = ArrayTools.reverse(a); + assertEquals('c', a[0]); + assertEquals('b', a[1]); + assertEquals('a', a[2]); + } + + public void testReverseCharArray_Singleton() { + char[] a1 = new char[] { 'f' }; + char[] a2 = ArrayTools.reverse(a1); + assertTrue(Arrays.equals(a1, a2)); + } + + public void testReverseIntArray() { + int[] a = this.buildIntArray(); + a = ArrayTools.reverse(a); + assertEquals(20, a[0]); + assertEquals(10, a[1]); + assertEquals(0, a[2]); + } + + public void testReverseIntArray_Singleton() { + int[] a1 = new int[] { 7 }; + int[] a2 = ArrayTools.reverse(a1); + assertTrue(Arrays.equals(a1, a2)); + } + + + // ********** rotate ********** + + public void testRotateObjectArray() { + String[] a = this.buildStringArray1(); + a = ArrayTools.rotate(a); + assertEquals("two", a[0]); + assertEquals("zero", a[1]); + assertEquals("one", a[2]); + } + + public void testRotateObjectArray_Zero() { + String[] a1 = new String[0]; + String[] a2 = ArrayTools.rotate(a1); + assertSame(a1, a2); + } + + public void testRotateObjectArray_One() { + String[] a1 = new String[] { "foo " }; + String[] a2 = ArrayTools.rotate(a1); + assertSame(a1, a2); + } + + public void testRotateObjectArrayInt() { + String[] a = this.buildStringArray1(); + a = ArrayTools.rotate(a, 2); + assertEquals("one", a[0]); + assertEquals("two", a[1]); + assertEquals("zero", a[2]); + } + + public void testRotateObjectArrayInt_ZeroDistance() { + String[] a1 = this.buildStringArray1(); + String[] a2 = ArrayTools.rotate(a1, 0); + assertSame(a1, a2); + } + + public void testRotateObjectArrayInt_NegativeDistance() { + String[] a1 = this.buildStringArray1(); + String[] a2 = ArrayTools.rotate(a1, -1); + assertEquals("one", a2[0]); + assertEquals("two", a2[1]); + assertEquals("zero", a2[2]); + } + + public void testRotateObjectArrayInt_Zero() { + String[] a1 = new String[0]; + String[] a2 = ArrayTools.rotate(a1, 7); + assertSame(a1, a2); + } + + public void testRotateObjectArrayInt_One() { + String[] a1 = new String[] { "foo " }; + String[] a2 = ArrayTools.rotate(a1, 8); + assertSame(a1, a2); + } + + public void testRotateCharArray() { + char[] a = this.buildCharArray(); + a = ArrayTools.rotate(a); + assertEquals('c', a[0]); + assertEquals('a', a[1]); + assertEquals('b', a[2]); + } + + public void testRotateCharArray_Zero() { + char[] a1 = new char[0]; + char[] a2 = ArrayTools.rotate(a1); + assertSame(a1, a2); + } + + public void testRotateCharArray_One() { + char[] a1 = new char[] { 'a' }; + char[] a2 = ArrayTools.rotate(a1); + assertSame(a1, a2); + } + + public void testRotateCharArrayInt() { + char[] a = this.buildCharArray(); + a = ArrayTools.rotate(a, 2); + assertEquals('b', a[0]); + assertEquals('c', a[1]); + assertEquals('a', a[2]); + } + + public void testRotateCharArrayInt_ZeroDistance() { + char[] a1 = new char[] { 'a', 'b', 'c' }; + char[] a2 = ArrayTools.rotate(a1, 0); + assertSame(a1, a2); + } + + public void testRotateCharArrayInt_NegativeDistance() { + char[] a = this.buildCharArray(); + a = ArrayTools.rotate(a, -1); + assertEquals('b', a[0]); + assertEquals('c', a[1]); + assertEquals('a', a[2]); + } + + public void testRotateCharArrayInt_Zero() { + char[] a1 = new char[0]; + char[] a2 = ArrayTools.rotate(a1, 2001); + assertSame(a1, a2); + } + + public void testRotateCharArrayInt_One() { + char[] a1 = new char[] { 'a' }; + char[] a2 = ArrayTools.rotate(a1, 22); + assertSame(a1, a2); + } + + public void testRotateIntArray() { + int[] a = this.buildIntArray(); + a = ArrayTools.rotate(a); + assertEquals(20, a[0]); + assertEquals(0, a[1]); + assertEquals(10, a[2]); + } + + public void testRotateIntArray_Zero() { + int[] a1 = new int[0]; + int[] a2 = ArrayTools.rotate(a1); + assertSame(a1, a2); + } + + public void testRotateIntArray_One() { + int[] a1 = new int[] { 77 }; + int[] a2 = ArrayTools.rotate(a1); + assertSame(a1, a2); + } + + public void testRotateIntArrayInt() { + int[] a = this.buildIntArray(); + a = ArrayTools.rotate(a, 2); + assertEquals(10, a[0]); + assertEquals(20, a[1]); + assertEquals(0, a[2]); + } + + public void testRotateIntArrayInt_ZeroDistance() { + int[] a1 = new int[] { 3, 2, 1 }; + int[] a2 = ArrayTools.rotate(a1, 0); + assertSame(a1, a2); + } + + public void testRotateIntArrayInt_NegativeDistance() { + int[] a = this.buildIntArray(); + a = ArrayTools.rotate(a, -1); + assertEquals(10, a[0]); + assertEquals(20, a[1]); + assertEquals(0, a[2]); + } + + public void testRotateIntArrayInt_Zero() { + int[] a1 = new int[0]; + int[] a2 = ArrayTools.rotate(a1, 3); + assertSame(a1, a2); + } + + public void testRotateIntArrayInt_One() { + int[] a1 = new int[] { 77 }; + int[] a2 = ArrayTools.rotate(a1, 44); + assertSame(a1, a2); + } + + + // ********** shuffle ********** + + public void testShuffleObjectArray() { + String[] array1 = this.buildStringArray1(); + String[] array2 = ArrayTools.shuffle(this.buildStringArray1()); + assertEquals(array1.length, array2.length); + assertTrue(ArrayTools.containsAll(array1, (Object[]) array2)); + } + + public void testShuffleObjectArray_Singleton() { + String[] array1 = new String[] { "foo" }; + String[] array2 = ArrayTools.shuffle(new String[] { "foo" }); + assertEquals(array1.length, array2.length); + assertTrue(ArrayTools.containsAll(array1, (Object[]) array2)); + } + + public void testShuffleCharArray() { + char[] array1 = this.buildCharArray(); + char[] array2 = ArrayTools.shuffle(this.buildCharArray()); + assertEquals(array1.length, array2.length); + assertTrue(ArrayTools.containsAll(array1, array2)); + } + + public void testShuffleCharArray_Singleton() { + char[] array1 = new char[] { 'f' }; + char[] array2 = ArrayTools.shuffle(new char[] { 'f' }); + assertEquals(array1.length, array2.length); + assertTrue(ArrayTools.containsAll(array1, array2)); + } + + public void testShuffleIntArray() { + int[] array1 = this.buildIntArray(); + int[] array2 = ArrayTools.shuffle(this.buildIntArray()); + assertEquals(array1.length, array2.length); + assertTrue(ArrayTools.containsAll(array1, array2)); + } + + public void testShuffleIntArray_Singleton() { + int[] array1 = new int[] { 7 }; + int[] array2 = ArrayTools.shuffle(new int[] { 7 }); + assertEquals(array1.length, array2.length); + assertTrue(ArrayTools.containsAll(array1, array2)); + } + + + // ********** sub-array ********** + + public void testSubArrayObjectArrayIntInt() { + String[] array = new String[] {"foo", "bar", "baz", "joo", "jar", "jaz"}; + String[] result = new String[] {"foo", "bar", "baz", "joo"}; + assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 0, 4))); + + result = new String[] {"jar"}; + assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 4, 5))); + + result = new String[0]; + assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 5, 5))); + + result = new String[] {"joo", "jar", "jaz"}; + assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 3, 6))); + } + + public void testSubArrayIntArrayIntInt() { + int[] array = new int[] {77, 99, 333, 4, 9090, 42}; + int[] result = new int[] {77, 99, 333, 4}; + assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 0, 4))); + + result = new int[] {9090}; + assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 4, 5))); + + result = new int[0]; + assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 5, 5))); + + result = new int[] {4, 9090, 42}; + assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 3, 6))); + } + + public void testSubArrayCharArrayIntInt() { + char[] array = new char[] {'a', 'b', 'c', 'd', 'e', 'f'}; + char[] result = new char[] {'a', 'b', 'c', 'd'}; + assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 0, 4))); + + result = new char[] {'e'}; + assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 4, 5))); + + result = new char[0]; + assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 5, 5))); + + result = new char[] {'d', 'e', 'f'}; + assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 3, 6))); + } + + + // ********** swap ********** + + public void testSwapObjectArray() { + String[] a = this.buildStringArray1(); + a = ArrayTools.swap(a, 1, 2); + assertEquals("zero", a[0]); + assertEquals("two", a[1]); + assertEquals("one", a[2]); + } + + public void testSwapObjectArray_SameIndices() { + String[] a1 = this.buildStringArray1(); + String[] a2 = this.buildStringArray1(); + a1 = ArrayTools.swap(a1, 1, 1); + assertTrue(Arrays.equals(a1, a2)); + } + + public void testSwapCharArray() { + char[] a = this.buildCharArray(); + a = ArrayTools.swap(a, 1, 2); + assertEquals('a', a[0]); + assertEquals('c', a[1]); + assertEquals('b', a[2]); + } + + public void testSwapCharArray_SameIndices() { + char[] a1 = this.buildCharArray(); + char[] a2 = this.buildCharArray(); + a1 = ArrayTools.swap(a1, 1, 1); + assertTrue(Arrays.equals(a1, a2)); + } + + public void testSwapIntArray() { + int[] a = this.buildIntArray(); + a = ArrayTools.swap(a, 1, 2); + assertEquals(0, a[0]); + assertEquals(20, a[1]); + assertEquals(10, a[2]); + } + + public void testSwapIntArray_SameIndices() { + int[] a1 = this.buildIntArray(); + int[] a2 = this.buildIntArray(); + a1 = ArrayTools.swap(a1, 1, 1); + assertTrue(Arrays.equals(a1, a2)); + } + + + // ********** Arrays enhancements ********** + + public void testFillBooleanArrayBoolean() { + boolean[] a1 = new boolean[9]; + boolean[] a2 = ArrayTools.fill(a1, true); + for (boolean x : a1) { + assertTrue(x); + } + assertSame(a1, a2); + } + + public void testFillBooleanArrayIntIntBoolean() { + boolean[] a1 = new boolean[9]; + boolean[] a2 = ArrayTools.fill(a1, false); + int from = 3; + int to = 6; + boolean[] a3 = ArrayTools.fill(a2, from, to, true); + for (int i = 0; i < a1.length; i++) { + boolean x = a1[i]; + if (i < from || i >= to) { + assertFalse(x); + } else { + assertTrue(x); + } + } + assertSame(a1, a2); + assertSame(a1, a3); + } + + public void testFillByteArrayByte() { + byte[] a1 = new byte[9]; + byte[] a2 = ArrayTools.fill(a1, (byte) 77); + for (byte x : a1) { + assertEquals(77, x); + } + assertSame(a1, a2); + } + + public void testFillByteArrayIntIntByte() { + byte[] a1 = new byte[9]; + byte[] a2 = ArrayTools.fill(a1, (byte) 3); + int from = 3; + int to = 6; + byte[] a3 = ArrayTools.fill(a2, from, to, (byte) 77); + for (int i = 0; i < a1.length; i++) { + byte x = a1[i]; + if (i < from || i >= to) { + assertEquals(3, x); + } else { + assertEquals(77, x); + } + } + assertSame(a1, a2); + assertSame(a1, a3); + } + + public void testFillCharArrayChar() { + char[] a1 = new char[9]; + char[] a2 = ArrayTools.fill(a1, 'c'); + for (char x : a1) { + assertEquals('c', x); + } + assertSame(a1, a2); + } + + public void testFillCharArrayIntIntChar() { + char[] a1 = new char[9]; + char[] a2 = ArrayTools.fill(a1, 'a'); + int from = 3; + int to = 6; + char[] a3 = ArrayTools.fill(a2, from, to, 'c'); + for (int i = 0; i < a1.length; i++) { + char x = a1[i]; + if (i < from || i >= to) { + assertEquals('a', x); + } else { + assertEquals('c', x); + } + } + assertSame(a1, a2); + assertSame(a1, a3); + } + + public void testFillDoubleArrayDouble() { + double[] a1 = new double[9]; + double[] a2 = ArrayTools.fill(a1, 77.77); + for (double x : a1) { + assertEquals(77.77, x, 0.0); + } + assertSame(a1, a2); + } + + public void testFillDoubleArrayIntIntDouble() { + double[] a1 = new double[9]; + double[] a2 = ArrayTools.fill(a1, 3.3); + int from = 3; + int to = 6; + double[] a3 = ArrayTools.fill(a2, from, to, 77.77); + for (int i = 0; i < a1.length; i++) { + double x = a1[i]; + if (i < from || i >= to) { + assertEquals(3.3, x, 0.0); + } else { + assertEquals(77.77, x, 0.0); + } + } + assertSame(a1, a2); + assertSame(a1, a3); + } + + public void testFillFloatArrayFloat() { + float[] a1 = new float[9]; + float[] a2 = ArrayTools.fill(a1, 77.77f); + for (float x : a1) { + assertEquals(77.77f, x, 0.0); + } + assertSame(a1, a2); + } + + public void testFillFloatArrayIntIntFloat() { + float[] a1 = new float[9]; + float[] a2 = ArrayTools.fill(a1, 3.3f); + int from = 3; + int to = 6; + float[] a3 = ArrayTools.fill(a2, from, to, 77.77f); + for (int i = 0; i < a1.length; i++) { + float x = a1[i]; + if (i < from || i >= to) { + assertEquals(3.3f, x, 0.0); + } else { + assertEquals(77.77f, x, 0.0); + } + } + assertSame(a1, a2); + assertSame(a1, a3); + } + + public void testFillIntArrayInt() { + int[] a1 = new int[9]; + int[] a2 = ArrayTools.fill(a1, 77); + for (int x : a1) { + assertEquals(77, x); + } + assertSame(a1, a2); + } + + public void testFillIntArrayIntIntInt() { + int[] a1 = new int[9]; + int[] a2 = ArrayTools.fill(a1, 3); + int from = 3; + int to = 6; + int[] a3 = ArrayTools.fill(a2, from, to, 77); + for (int i = 0; i < a1.length; i++) { + int x = a1[i]; + if (i < from || i >= to) { + assertEquals(3, x); + } else { + assertEquals(77, x); + } + } + assertSame(a1, a2); + assertSame(a1, a3); + } + + public void testFillObjectArrayObject() { + String[] a1 = new String[9]; + String[] a2 = ArrayTools.fill(a1, "77"); + for (String x : a1) { + assertEquals("77", x); + } + assertSame(a1, a2); + } + + public void testFillObjectArrayIntIntObject() { + String[] a1 = new String[9]; + String[] a2 = ArrayTools.fill(a1, "3"); + int from = 3; + int to = 6; + String[] a3 = ArrayTools.fill(a2, from, to, "77"); + for (int i = 0; i < a1.length; i++) { + String x = a1[i]; + if (i < from || i >= to) { + assertEquals("3", x); + } else { + assertEquals("77", x); + } + } + assertSame(a1, a2); + assertSame(a1, a3); + } + + public void testFillLongArrayLong() { + long[] a1 = new long[9]; + long[] a2 = ArrayTools.fill(a1, 77); + for (long x : a1) { + assertEquals(77, x); + } + assertSame(a1, a2); + } + + public void testFillLongArrayIntIntLong() { + long[] a1 = new long[9]; + long[] a2 = ArrayTools.fill(a1, 3); + int from = 3; + int to = 6; + long[] a3 = ArrayTools.fill(a2, from, to, 77); + for (int i = 0; i < a1.length; i++) { + long x = a1[i]; + if (i < from || i >= to) { + assertEquals(3, x); + } else { + assertEquals(77, x); + } + } + assertSame(a1, a2); + assertSame(a1, a3); + } + + public void testFillShortArrayShort() { + short[] a1 = new short[9]; + short[] a2 = ArrayTools.fill(a1, (short) 77); + for (short x : a1) { + assertEquals(77, x); + } + assertSame(a1, a2); + } + + public void testFillShortArrayIntIntShort() { + short[] a1 = new short[9]; + short[] a2 = ArrayTools.fill(a1, (short) 3); + int from = 3; + int to = 6; + short[] a3 = ArrayTools.fill(a2, from, to, (short) 77); + for (int i = 0; i < a1.length; i++) { + short x = a1[i]; + if (i < from || i >= to) { + assertEquals(3, x); + } else { + assertEquals(77, x); + } + } + assertSame(a1, a2); + assertSame(a1, a3); + } + + public void testSortByteArray() { + byte[] a1 = new byte[3]; + a1[0] = (byte) 33; + a1[1] = (byte) 11; + a1[2] = (byte) 22; + byte[] a2 = ArrayTools.sort(a1); + byte last = (byte) 0; + for (byte x : a1) { + assertTrue(last < x); + last = x; + } + assertSame(a1, a2); + } + + public void testSortByteArrayIntInt() { + byte[] a1 = new byte[9]; + byte[] a2 = ArrayTools.fill(a1, (byte) 3); + a2[3] = (byte) 33; + a2[4] = (byte) 11; + a2[5] = (byte) 22; + int from = 3; + int to = 6; + byte[] a3 = ArrayTools.sort(a2, from, to); + byte last = (byte) 0; + for (int i = 0; i < a1.length; i++) { + byte x = a1[i]; + if (i < from || i >= to) { + assertEquals(3, x); + } else { + assertTrue(last < x); + last = x; + } + } + assertSame(a1, a2); + assertSame(a1, a3); + } + + public void testSortCharArray() { + char[] a1 = new char[3]; + a1[0] = 'z'; + a1[1] = 'b'; + a1[2] = 'm'; + char[] a2 = ArrayTools.sort(a1); + char last = 'a'; + for (char x : a1) { + assertTrue(last < x); + last = x; + } + assertSame(a1, a2); + } + + public void testSortCharArrayIntInt() { + char[] a1 = new char[9]; + char[] a2 = ArrayTools.fill(a1, 'c'); + a2[3] = 'z'; + a2[4] = 'b'; + a2[5] = 'm'; + int from = 3; + int to = 6; + char[] a3 = ArrayTools.sort(a2, from, to); + char last = 'a'; + for (int i = 0; i < a1.length; i++) { + char x = a1[i]; + if (i < from || i >= to) { + assertEquals('c', x); + } else { + assertTrue(last < x); + last = x; + } + } + assertSame(a1, a2); + assertSame(a1, a3); + } + + public void testSortDoubleArray() { + double[] a1 = new double[3]; + a1[0] = 33.33; + a1[1] = 11.11; + a1[2] = 22.22; + double[] a2 = ArrayTools.sort(a1); + double last = 0; + for (double x : a1) { + assertTrue(last < x); + last = x; + } + assertSame(a1, a2); + } + + public void testSortDoubleArrayIntInt() { + double[] a1 = new double[9]; + double[] a2 = ArrayTools.fill(a1, 3.3); + a2[3] = 33.33; + a2[4] = 11.11; + a2[5] = 22.22; + int from = 3; + int to = 6; + double[] a3 = ArrayTools.sort(a2, from, to); + double last = 0; + for (int i = 0; i < a1.length; i++) { + double x = a1[i]; + if (i < from || i >= to) { + assertEquals(3.3, x, 0.0); + } else { + assertTrue(last < x); + last = x; + } + } + assertSame(a1, a2); + assertSame(a1, a3); + } + + public void testSortFloatArray() { + float[] a1 = new float[3]; + a1[0] = 33.33f; + a1[1] = 11.11f; + a1[2] = 22.22f; + float[] a2 = ArrayTools.sort(a1); + float last = 0; + for (float x : a1) { + assertTrue(last < x); + last = x; + } + assertSame(a1, a2); + } + + public void testSortFloatArrayIntInt() { + float[] a1 = new float[9]; + float[] a2 = ArrayTools.fill(a1, 3.3f); + a2[3] = 33.33f; + a2[4] = 11.11f; + a2[5] = 22.22f; + int from = 3; + int to = 6; + float[] a3 = ArrayTools.sort(a2, from, to); + float last = 0; + for (int i = 0; i < a1.length; i++) { + float x = a1[i]; + if (i < from || i >= to) { + assertEquals(3.3f, x, 0.0); + } else { + assertTrue(last < x); + last = x; + } + } + assertSame(a1, a2); + assertSame(a1, a3); + } + + public void testSortIntArray() { + int[] a1 = new int[3]; + a1[0] = 33; + a1[1] = 11; + a1[2] = 22; + int[] a2 = ArrayTools.sort(a1); + int last = 0; + for (int x : a1) { + assertTrue(last < x); + last = x; + } + assertSame(a1, a2); + } + + public void testSortIntArrayIntInt() { + int[] a1 = new int[9]; + int[] a2 = ArrayTools.fill(a1, 3); + a2[3] = 33; + a2[4] = 11; + a2[5] = 22; + int from = 3; + int to = 6; + int[] a3 = ArrayTools.sort(a2, from, to); + int last = 0; + for (int i = 0; i < a1.length; i++) { + int x = a1[i]; + if (i < from || i >= to) { + assertEquals(3, x); + } else { + assertTrue(last < x); + last = x; + } + } + assertSame(a1, a2); + assertSame(a1, a3); + } + + public void testSortObjectArray() { + String[] a1 = new String[3]; + a1[0] = "y"; + a1[1] = "b"; + a1[2] = "m"; + String[] a2 = ArrayTools.sort(a1); + String last = "a"; + for (String x : a1) { + assertTrue(last.compareTo(x) < 0); + last = x; + } + assertSame(a1, a2); + } + + public void testSortObjectArrayComparator() { + String[] a1 = new String[3]; + a1[0] = "y"; + a1[1] = "b"; + a1[2] = "m"; + String[] a2 = ArrayTools.sort(a1, new ReverseComparator<String>()); + String last = "z"; + for (String x : a1) { + assertTrue(last.compareTo(x) > 0); + last = x; + } + assertSame(a1, a2); + } + + public void testSortObjectArrayIntInt() { + String[] a1 = new String[9]; + String[] a2 = ArrayTools.fill(a1, "c"); + a2[3] = "y"; + a2[4] = "b"; + a2[5] = "m"; + int from = 3; + int to = 6; + String[] a3 = ArrayTools.sort(a2, from, to); + String last = "a"; + for (int i = 0; i < a1.length; i++) { + String x = a1[i]; + if (i < from || i >= to) { + assertEquals("c", x); + } else { + assertTrue(last.compareTo(x) < 0); + last = x; + } + } + assertSame(a1, a2); + assertSame(a1, a3); + } + + public void testSortObjectArrayIntIntComparator() { + String[] a1 = new String[9]; + String[] a2 = ArrayTools.fill(a1, "c"); + a2[3] = "y"; + a2[4] = "b"; + a2[5] = "m"; + int from = 3; + int to = 6; + String[] a3 = ArrayTools.sort(a2, from, to, new ReverseComparator<String>()); + String last = "z"; + for (int i = 0; i < a1.length; i++) { + String x = a1[i]; + if (i < from || i >= to) { + assertEquals("c", x); + } else { + assertTrue(last.compareTo(x) > 0); + last = x; + } + } + assertSame(a1, a2); + assertSame(a1, a3); + } + + public void testSortLongArray() { + long[] a1 = new long[3]; + a1[0] = 33; + a1[1] = 11; + a1[2] = 22; + long[] a2 = ArrayTools.sort(a1); + long last = 0; + for (long x : a1) { + assertTrue(last < x); + last = x; + } + assertSame(a1, a2); + } + + public void testSortLongArrayIntInt() { + long[] a1 = new long[9]; + long[] a2 = ArrayTools.fill(a1, 3); + a2[3] = 33; + a2[4] = 11; + a2[5] = 22; + int from = 3; + int to = 6; + long[] a3 = ArrayTools.sort(a2, from, to); + long last = 0; + for (int i = 0; i < a1.length; i++) { + long x = a1[i]; + if (i < from || i >= to) { + assertEquals(3, x); + } else { + assertTrue(last < x); + last = x; + } + } + assertSame(a1, a2); + assertSame(a1, a3); + } + + public void testSortShortArray() { + short[] a1 = new short[3]; + a1[0] = (short) 33; + a1[1] = (short) 11; + a1[2] = (short) 22; + short[] a2 = ArrayTools.sort(a1); + short last = (short) 0; + for (short x : a1) { + assertTrue(last < x); + last = x; + } + assertSame(a1, a2); + } + + public void testSortShortArrayIntInt() { + short[] a1 = new short[9]; + short[] a2 = ArrayTools.fill(a1, (short) 3); + a2[3] = (short) 33; + a2[4] = (short) 11; + a2[5] = (short) 22; + int from = 3; + int to = 6; + short[] a3 = ArrayTools.sort(a2, from, to); + short last = (short) 0; + for (int i = 0; i < a1.length; i++) { + short x = a1[i]; + if (i < from || i >= to) { + assertEquals(3, x); + } else { + assertTrue(last < x); + last = x; + } + } + assertSame(a1, a2); + assertSame(a1, a3); + } + + + // ********** constructor ********** + + public void testConstructor() { + boolean exCaught = false; + try { + Object at = ReflectionTools.newInstance(ArrayTools.class); + fail("bogus: " + at); + } catch (RuntimeException ex) { + if (ex.getCause() instanceof InvocationTargetException) { + if (ex.getCause().getCause() instanceof UnsupportedOperationException) { + exCaught = true; + } + } + } + assertTrue(exCaught); + } + + + // ********** utility ********** + + private Object[] buildObjectArray1() { + return new Object[] { "zero", "one", "two" }; + } + + private String[] buildStringArray1() { + return new String[] { "zero", "one", "two" }; + } + + private char[] buildCharArray() { + return new char[] { 'a', 'b', 'c' }; + } + + private int[] buildIntArray() { + return new int[] { 0, 10, 20 }; + } + + private Object[] buildObjectArray2() { + return new Object[] { "three", "four", "five" }; + } + + private String[] buildStringArray2() { + return new String[] { "three", "four", "five" }; + } + + private List<String> buildStringList1() { + List<String> l = new ArrayList<String>(); + this.addToCollection1(l); + return l; + } + + private List<Object> buildObjectList1() { + List<Object> l = new ArrayList<Object>(); + this.addToCollection1(l); + return l; + } + + private void addToCollection1(Collection<? super String> c) { + c.add("zero"); + c.add("one"); + c.add("two"); + } + + private List<String> buildStringList2() { + List<String> l = new ArrayList<String>(); + this.addToCollection2(l); + return l; + } + + private void addToCollection2(Collection<? super String> c) { + c.add("three"); + c.add("four"); + c.add("five"); + } + + private Vector<String> buildStringVector1() { + Vector<String> v = new Vector<String>(); + this.addToCollection1(v); + return v; + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/AsynchronousCommandExecutorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/AsynchronousCommandExecutorTests.java new file mode 100644 index 0000000000..f8b32dcd28 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/AsynchronousCommandExecutorTests.java @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (c) 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import org.eclipse.jpt.common.utility.Command; +import org.eclipse.jpt.common.utility.internal.AsynchronousCommandExecutor; +import org.eclipse.jpt.common.utility.internal.StatefulCommandExecutor; + +public class AsynchronousCommandExecutorTests + extends MultiThreadedTestCase +{ + public AsynchronousCommandExecutorTests(String name) { + super(name); + } + + public void testExecution() throws Exception { + TestCommand command = new TestCommand(); + StatefulCommandExecutor commandExecutor = new AsynchronousCommandExecutor(this.buildThreadFactory()); + commandExecutor.start(); + commandExecutor.execute(command); + commandExecutor.execute(command); + commandExecutor.execute(command); + Thread.sleep(TWO_TICKS); // wait for the command to execute + commandExecutor.stop(); + assertEquals(3, command.count); + } + + static class TestCommand implements Command { + int count = 0; + public void execute() { + this.count++; + } + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BagTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BagTests.java new file mode 100644 index 0000000000..e018dfaeea --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BagTests.java @@ -0,0 +1,82 @@ +/******************************************************************************* + * Copyright (c) 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import junit.framework.TestCase; + +import org.eclipse.jpt.common.utility.internal.Bag; +import org.eclipse.jpt.common.utility.internal.HashBag; + +@SuppressWarnings("nls") +public class BagTests extends TestCase { + + public BagTests(String name) { + super(name); + } + + public void testEmptyBag_iterator() throws Exception { + assertFalse(Bag.Empty.instance().iterator().hasNext()); + } + + public void testEmptyBag_size() throws Exception { + assertEquals(0, Bag.Empty.instance().size()); + } + + public void testEmptyBag_uniqueIterator() throws Exception { + assertFalse(Bag.Empty.instance().uniqueIterator().hasNext()); + } + + public void testEmptyBag_uniqueCount() throws Exception { + assertEquals(0, Bag.Empty.instance().uniqueCount()); + } + + public void testEmptyBag_count() throws Exception { + assertEquals(0, Bag.Empty.instance().count("foo")); + } + + public void testEmptyBag_entries() throws Exception { + assertFalse(Bag.Empty.instance().entries().hasNext()); + } + + public void testEmptyBag_remove() throws Exception { + assertFalse(Bag.Empty.instance().remove("foo", 3)); + } + + public void testEmptyBag_add() throws Exception { + boolean exCaught = false; + try { + Bag.Empty.instance().add("foo", 3); + fail(); + } catch (UnsupportedOperationException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEmptyBag_equals() throws Exception { + assertTrue(Bag.Empty.instance().equals(Bag.Empty.instance())); + assertFalse(Bag.Empty.instance().equals("foo")); + + Bag<Object> bag = new HashBag<Object>(); + assertTrue(Bag.Empty.instance().equals(bag)); + bag.add("foo"); + assertFalse(Bag.Empty.instance().equals(bag)); + } + + public void testEmptyBag_hashCode() throws Exception { + assertEquals(0, Bag.Empty.instance().hashCode()); + } + + public void testEmptyBag_serialization() throws Exception { + Bag<?> xxx = TestTools.serialize(Bag.Empty.instance()); + assertSame(Bag.Empty.instance(), xxx); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BidiFilterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BidiFilterTests.java new file mode 100644 index 0000000000..b2d1564479 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BidiFilterTests.java @@ -0,0 +1,88 @@ +/******************************************************************************* + * Copyright (c) 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import junit.framework.TestCase; + +import org.eclipse.jpt.common.utility.internal.BidiFilter; + +@SuppressWarnings("nls") +public class BidiFilterTests extends TestCase { + + public BidiFilterTests(String name) { + super(name); + } + + public void testNullBidiFilter_accept() throws Exception { + assertTrue(BidiFilter.Null.instance().accept("foo")); + } + + public void testNullBidiFilter_reverseAccept() throws Exception { + assertTrue(BidiFilter.Null.instance().reverseAccept("foo")); + } + + public void testNullBidiFilter_toString() throws Exception { + assertNotNull(BidiFilter.Null.instance().toString()); + } + + public void testNullBidiFilter_serialization() throws Exception { + BidiFilter<?> xxx = TestTools.serialize(BidiFilter.Null.instance()); + assertSame(BidiFilter.Null.instance(), xxx); + } + + public void testOpaqueBidiFilter_accept() throws Exception { + assertFalse(BidiFilter.Opaque.instance().accept("foo")); + } + + public void testOpaqueBidiFilter_reverseAccept() throws Exception { + assertFalse(BidiFilter.Opaque.instance().reverseAccept("foo")); + } + + public void testOpaqueBidiFilter_toString() throws Exception { + assertNotNull(BidiFilter.Opaque.instance().toString()); + } + + public void testOpaqueBidiFilter_serialization() throws Exception { + BidiFilter<?> xxx = TestTools.serialize(BidiFilter.Opaque.instance()); + assertSame(BidiFilter.Opaque.instance(), xxx); + } + + public void testDisabledBidiFilter_accept() throws Exception { + boolean exCaught = false; + try { + BidiFilter.Disabled.instance().accept("foo"); + fail(); + } catch (UnsupportedOperationException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testDisabledBidiFilter_reverseAccept() throws Exception { + boolean exCaught = false; + try { + BidiFilter.Disabled.instance().reverseAccept("foo"); + fail(); + } catch (UnsupportedOperationException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testDisabledBidiFilter_toString() throws Exception { + assertNotNull(BidiFilter.Disabled.instance().toString()); + } + + public void testDisabledBidiFilter_serialization() throws Exception { + BidiFilter<?> xxx = TestTools.serialize(BidiFilter.Disabled.instance()); + assertSame(BidiFilter.Disabled.instance(), xxx); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BidiStringConverterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BidiStringConverterTests.java new file mode 100644 index 0000000000..cf0400b104 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BidiStringConverterTests.java @@ -0,0 +1,115 @@ +/******************************************************************************* + * Copyright (c) 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import junit.framework.TestCase; + +import org.eclipse.jpt.common.utility.internal.BidiStringConverter; + +@SuppressWarnings("nls") +public class BidiStringConverterTests extends TestCase { + + public BidiStringConverterTests(String name) { + super(name); + } + + public void testDefaultBidiStringConverter_convertToString() throws Exception { + assertEquals("foo", BidiStringConverter.Default.instance().convertToString("foo")); + assertNull(BidiStringConverter.Default.instance().convertToString(null)); + } + + public void testDefaultBidiStringConverter_convertToObject() throws Exception { + assertEquals("foo", BidiStringConverter.Default.instance().convertToObject("foo")); + assertNull(BidiStringConverter.Default.instance().convertToString(null)); + } + + public void testDefaultBidiStringConverter_toString() throws Exception { + assertNotNull(BidiStringConverter.Default.instance().toString()); + } + + public void testDefaultBidiStringConverter_serialization() throws Exception { + BidiStringConverter<?> xxx = TestTools.serialize(BidiStringConverter.Default.instance()); + assertSame(BidiStringConverter.Default.instance(), xxx); + } + + public void testDisabledBidiStringConverter_convertToString() throws Exception { + boolean exCaught = false; + try { + BidiStringConverter.Disabled.instance().convertToString("foo"); + fail(); + } catch (UnsupportedOperationException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testDisabledBidiStringConverter_convertToObject() throws Exception { + boolean exCaught = false; + try { + BidiStringConverter.Disabled.instance().convertToObject("foo"); + fail(); + } catch (UnsupportedOperationException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testDisabledBidiStringConverter_toString() throws Exception { + assertNotNull(BidiStringConverter.Disabled.instance().toString()); + } + + public void testDisabledBidiStringConverter_serialization() throws Exception { + BidiStringConverter<?> xxx = TestTools.serialize(BidiStringConverter.Disabled.instance()); + assertSame(BidiStringConverter.Disabled.instance(), xxx); + } + + public void testBooleanBidiStringConverter_convertToString() throws Exception { + assertEquals("true", BidiStringConverter.BooleanConverter.instance().convertToString(Boolean.TRUE)); + assertEquals("false", BidiStringConverter.BooleanConverter.instance().convertToString(Boolean.FALSE)); + assertNull(BidiStringConverter.BooleanConverter.instance().convertToString(null)); + } + + public void testBooleanBidiStringConverter_convertToObject() throws Exception { + assertEquals(Boolean.TRUE, BidiStringConverter.BooleanConverter.instance().convertToObject("true")); + assertEquals(Boolean.TRUE, BidiStringConverter.BooleanConverter.instance().convertToObject("TRUE")); + assertEquals(Boolean.FALSE, BidiStringConverter.BooleanConverter.instance().convertToObject("false")); + assertEquals(Boolean.FALSE, BidiStringConverter.BooleanConverter.instance().convertToObject("xxxx")); + assertNull(BidiStringConverter.BooleanConverter.instance().convertToObject(null)); + } + + public void testBooleanBidiStringConverter_toString() throws Exception { + assertNotNull(BidiStringConverter.BooleanConverter.instance().toString()); + } + + public void testBooleanBidiStringConverter_serialization() throws Exception { + BidiStringConverter<?> xxx = TestTools.serialize(BidiStringConverter.BooleanConverter.instance()); + assertSame(BidiStringConverter.BooleanConverter.instance(), xxx); + } + + public void testIntegerBidiStringConverter_convertToString() throws Exception { + assertEquals("7", BidiStringConverter.IntegerConverter.instance().convertToString(Integer.valueOf(7))); + assertNull(BidiStringConverter.IntegerConverter.instance().convertToString(null)); + } + + public void testIntegerBidiStringConverter_convertToObject() throws Exception { + assertEquals(Integer.valueOf(7), BidiStringConverter.IntegerConverter.instance().convertToObject("7")); + assertNull(BidiStringConverter.IntegerConverter.instance().convertToObject(null)); + } + + public void testIntegerBidiStringConverter_toString() throws Exception { + assertNotNull(BidiStringConverter.IntegerConverter.instance().toString()); + } + + public void testIntegerBidiStringConverter_serialization() throws Exception { + BidiStringConverter<?> xxx = TestTools.serialize(BidiStringConverter.IntegerConverter.instance()); + assertSame(BidiStringConverter.IntegerConverter.instance(), xxx); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BidiTransformerTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BidiTransformerTests.java new file mode 100644 index 0000000000..973f153f45 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BidiTransformerTests.java @@ -0,0 +1,73 @@ +/******************************************************************************* + * Copyright (c) 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import junit.framework.TestCase; + +import org.eclipse.jpt.common.utility.internal.BidiTransformer; + +@SuppressWarnings("nls") +public class BidiTransformerTests extends TestCase { + + public BidiTransformerTests(String name) { + super(name); + } + + public void testNullBidiTransformer_transform() throws Exception { + assertEquals("foo", BidiTransformer.Null.instance().transform("foo")); + assertNull(BidiTransformer.Null.instance().transform(null)); + } + + public void testNullBidiTransformer_reverseTransform() throws Exception { + assertEquals("foo", BidiTransformer.Null.instance().reverseTransform("foo")); + assertNull(BidiTransformer.Null.instance().transform(null)); + } + + public void testNullBidiTransformer_toString() throws Exception { + assertNotNull(BidiTransformer.Null.instance().toString()); + } + + public void testNullBidiTransformer_serialization() throws Exception { + BidiTransformer<?, ?> xxx = TestTools.serialize(BidiTransformer.Null.instance()); + assertSame(BidiTransformer.Null.instance(), xxx); + } + + public void testDisabledBidiTransformer_transform() throws Exception { + boolean exCaught = false; + try { + BidiTransformer.Disabled.instance().transform("foo"); + fail(); + } catch (UnsupportedOperationException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testDisabledBidiTransformer_reverseTransform() throws Exception { + boolean exCaught = false; + try { + BidiTransformer.Disabled.instance().reverseTransform("foo"); + fail(); + } catch (UnsupportedOperationException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testDisabledBidiTransformer_toString() throws Exception { + assertNotNull(BidiTransformer.Disabled.instance().toString()); + } + + public void testDisabledBidiTransformer_serialization() throws Exception { + BidiTransformer<?, ?> xxx = TestTools.serialize(BidiTransformer.Disabled.instance()); + assertSame(BidiTransformer.Disabled.instance(), xxx); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BitToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BitToolsTests.java new file mode 100644 index 0000000000..dd1941237b --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BitToolsTests.java @@ -0,0 +1,262 @@ +/******************************************************************************* + * Copyright (c) 2006, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import java.lang.reflect.InvocationTargetException; + +import junit.framework.TestCase; + +import org.eclipse.jpt.common.utility.internal.BitTools; +import org.eclipse.jpt.common.utility.internal.ReflectionTools; + +public class BitToolsTests extends TestCase { + + public BitToolsTests(String name) { + super(name); + } + + public void testFlagIsSetIntInt() { + assertTrue(BitTools.flagIsSet(0x0003, 0x0001)); + assertTrue(BitTools.flagIsSet(0x0303, 0x0001)); + assertTrue(BitTools.flagIsSet(0x0303, 0x0101)); + assertTrue(BitTools.flagIsSet(0x0303, 0x0103)); + + assertFalse(BitTools.flagIsSet(0x0303, 0x1103)); + assertFalse(BitTools.flagIsSet(0x0000, 0x1103)); + } + + public void testFlagIsOffIntInt() { + assertFalse(BitTools.flagIsOff(0x0003, 0x0001)); + assertFalse(BitTools.flagIsOff(0x0303, 0x0001)); + assertFalse(BitTools.flagIsOff(0x0303, 0x0101)); + assertFalse(BitTools.flagIsOff(0x0303, 0x0103)); + + assertTrue(BitTools.flagIsOff(0x2204, 0x1103)); + assertTrue(BitTools.flagIsOff(0x0000, 0x1103)); + } + + public void testOnlyFlagIsSetIntInt() { + assertFalse(BitTools.onlyFlagIsSet(0x0003, 0x0001)); + assertTrue(BitTools.onlyFlagIsSet(0x0001, 0x0001)); + + assertFalse(BitTools.onlyFlagIsSet(0x0303, 0x0001)); + assertTrue(BitTools.onlyFlagIsSet(0x0001, 0x0001)); + + assertFalse(BitTools.onlyFlagIsSet(0x0303, 0x0101)); + assertTrue(BitTools.onlyFlagIsSet(0x0101, 0x0101)); + + assertFalse(BitTools.onlyFlagIsSet(0x0303, 0x0103)); + assertTrue(BitTools.onlyFlagIsSet(0x0103, 0x0103)); + + assertFalse(BitTools.onlyFlagIsSet(0x0303, 0x1103)); + assertTrue(BitTools.onlyFlagIsSet(0x1103, 0x1103)); + + assertFalse(BitTools.onlyFlagIsSet(0x0000, 0x1103)); + assertTrue(BitTools.onlyFlagIsSet(0x0103, 0x0103)); + } + + public void testOnlyFlagIsOffIntInt() { + assertFalse(BitTools.onlyFlagIsOff(0x0003, 0x0001)); + assertFalse(BitTools.onlyFlagIsOff(0x0303, 0x0001)); + assertTrue(BitTools.onlyFlagIsOff(0xFFFFFFFE, 0x0001)); + + assertFalse(BitTools.onlyFlagIsOff(0x0303, 0x0101)); + assertTrue(BitTools.onlyFlagIsOff(0xFFFFFEFE, 0x0101)); + + assertFalse(BitTools.onlyFlagIsOff(0x0303, 0x0103)); + assertTrue(BitTools.onlyFlagIsOff(0xFFFFFEFC, 0x0103)); + + assertFalse(BitTools.onlyFlagIsOff(0x0303, 0x1103)); + assertTrue(BitTools.onlyFlagIsOff(0xFFFFEEFC, 0x1103)); + } + + public void testAllFlagsAreSetIntInt() { + assertTrue(BitTools.allFlagsAreSet(0x0003, 0x0001)); + assertTrue(BitTools.allFlagsAreSet(0x0303, 0x0001)); + assertTrue(BitTools.allFlagsAreSet(0x0303, 0x0101)); + assertTrue(BitTools.allFlagsAreSet(0x0303, 0x0103)); + + assertFalse(BitTools.allFlagsAreSet(0x0303, 0x1103)); + assertFalse(BitTools.allFlagsAreSet(0x0000, 0x1103)); + } + + public void testAllFlagsAreOffIntInt() { + assertFalse(BitTools.allFlagsAreOff(0x0003, 0x0001)); + assertFalse(BitTools.allFlagsAreOff(0x0303, 0x0001)); + assertFalse(BitTools.allFlagsAreOff(0x0303, 0x0101)); + assertFalse(BitTools.allFlagsAreOff(0x0303, 0x0103)); + + assertTrue(BitTools.allFlagsAreOff(0x2204, 0x1103)); + assertTrue(BitTools.allFlagsAreOff(0x0000, 0x1103)); + } + + public void testOnlyFlagsAreSetIntInt() { + assertFalse(BitTools.onlyFlagsAreSet(0x0003, 0x0001)); + assertTrue(BitTools.onlyFlagsAreSet(0x0001, 0x0001)); + + assertFalse(BitTools.onlyFlagsAreSet(0x0303, 0x0001)); + assertTrue(BitTools.onlyFlagsAreSet(0x0001, 0x0001)); + + assertFalse(BitTools.onlyFlagsAreSet(0x0303, 0x0101)); + assertTrue(BitTools.onlyFlagsAreSet(0x0101, 0x0101)); + + assertFalse(BitTools.onlyFlagsAreSet(0x0303, 0x0103)); + assertTrue(BitTools.onlyFlagsAreSet(0x0103, 0x0103)); + + assertFalse(BitTools.onlyFlagsAreSet(0x0303, 0x1103)); + assertTrue(BitTools.onlyFlagsAreSet(0x1103, 0x1103)); + + assertFalse(BitTools.onlyFlagsAreSet(0x0000, 0x1103)); + assertTrue(BitTools.onlyFlagsAreSet(0x0103, 0x0103)); + } + + public void testOnlyFlagsAreOffIntInt() { + assertFalse(BitTools.onlyFlagsAreOff(0x0003, 0x0001)); + assertFalse(BitTools.onlyFlagsAreOff(0x0303, 0x0001)); + assertTrue(BitTools.onlyFlagsAreOff(0xFFFFFFFE, 0x0001)); + + assertFalse(BitTools.onlyFlagsAreOff(0x0303, 0x0101)); + assertTrue(BitTools.onlyFlagsAreOff(0xFFFFFEFE, 0x0101)); + + assertFalse(BitTools.onlyFlagsAreOff(0x0303, 0x0103)); + assertTrue(BitTools.onlyFlagsAreOff(0xFFFFFEFC, 0x0103)); + + assertFalse(BitTools.onlyFlagsAreOff(0x0303, 0x1103)); + assertTrue(BitTools.onlyFlagsAreOff(0xFFFFEEFC, 0x1103)); + } + + public void testAnyFlagsAreSetIntInt() { + assertTrue(BitTools.anyFlagsAreSet(0x0003, 0x0001)); + assertTrue(BitTools.anyFlagsAreSet(0xFFFF, 0x0001)); + assertTrue(BitTools.anyFlagsAreSet(0x0003, 0xFFFF)); + + assertFalse(BitTools.anyFlagsAreSet(0x0303, 0x1010)); + assertFalse(BitTools.anyFlagsAreSet(0x0000, 0xFFFF)); + } + + public void testAnyFlagsAreOffIntInt() { + assertTrue(BitTools.anyFlagsAreOff(0x333E, 0x0001)); + assertTrue(BitTools.anyFlagsAreOff(0xFFFE, 0x0001)); + assertTrue(BitTools.anyFlagsAreOff(0x0003, 0xFFFF)); + + assertFalse(BitTools.anyFlagsAreOff(0x7373, 0x1010)); + assertFalse(BitTools.anyFlagsAreOff(0xFFFF, 0xFFFF)); + } + + public void testAllFlagsAreSetIntIntArray() { + assertTrue(BitTools.allFlagsAreSet(0x0003, new int[] { 0x0001 })); + assertTrue(BitTools.allFlagsAreSet(0x0303, new int[] { 0x0001 })); + assertTrue(BitTools.allFlagsAreSet(0x0303, new int[] { 0x0100, 0x0001 })); + assertTrue(BitTools.allFlagsAreSet(0x0303, new int[] { 0x0100, 0x0002, 0x0001 })); + + assertFalse(BitTools.allFlagsAreSet(0x0303, new int[] { 0x1000, 0x0100, 0x0002, 0x0001 })); + assertFalse(BitTools.allFlagsAreSet(0x0000, new int[] { 0x1000, 0x0100, 0x0002, 0x0001 })); + } + + public void testAllFlagsAreOffIntIntArray() { + assertFalse(BitTools.allFlagsAreOff(0x0003, new int[] { 0x0001 })); + assertFalse(BitTools.allFlagsAreOff(0x0303, new int[] { 0x0001 })); + assertFalse(BitTools.allFlagsAreOff(0x0303, new int[] { 0x0100, 0x0001 })); + assertFalse(BitTools.allFlagsAreOff(0x0303, new int[] { 0x0100, 0x0002, 0x0001 })); + + assertTrue(BitTools.allFlagsAreOff(0x0303, new int[] { 0x1000, 0x0400, 0x0020, 0x0000 })); + assertTrue(BitTools.allFlagsAreOff(0x0000, new int[] { 0x1000, 0x0100, 0x0002, 0x0001 })); + } + + public void testOnlyFlagsAreSetIntIntArray() { + assertFalse(BitTools.onlyFlagsAreSet(0x0003, new int[] { 0x001, 0x0000, 0x0000, 0x0001 })); + assertTrue(BitTools.onlyFlagsAreSet(0x0001, new int[] { 0x001, 0x0000, 0x0000, 0x0001 })); + + assertFalse(BitTools.onlyFlagsAreSet(0x0303, new int[] { 0x001, 0x0000, 0x0000, 0x0001 })); + assertTrue(BitTools.onlyFlagsAreSet(0x0001, new int[] { 0x001, 0x0000, 0x0000, 0x0001 })); + + assertFalse(BitTools.onlyFlagsAreSet(0x0303, new int[] { 0x001, 0x0100, 0x0000, 0x0001 })); + assertTrue(BitTools.onlyFlagsAreSet(0x0101, new int[] { 0x001, 0x0100, 0x0000, 0x0001 })); + + assertFalse(BitTools.onlyFlagsAreSet(0x0303, new int[] { 0x001, 0x0100, 0x0002, 0x0001 })); + assertTrue(BitTools.onlyFlagsAreSet(0x0103, new int[] { 0x001, 0x0100, 0x0002, 0x0001 })); + + assertFalse(BitTools.onlyFlagsAreSet(0x0303, new int[] { 0x011, 0x0100, 0x0002, 0x0001 })); + assertTrue(BitTools.onlyFlagsAreSet(0x1103, new int[] { 0x1100, 0x0100, 0x0002, 0x0001 })); + + assertFalse(BitTools.onlyFlagsAreSet(0x0000, new int[] { 0x011, 0x0100, 0x0002, 0x0001 })); + assertTrue(BitTools.onlyFlagsAreSet(0x0103, new int[] { 0x0101, 0x0100, 0x0002, 0x0001 })); + } + + public void testOnlyFlagsAreOffIntIntArray() { + assertFalse(BitTools.onlyFlagsAreOff(0x0003, new int[] { 0x001, 0x0000, 0x0000, 0x0001 })); + assertFalse(BitTools.onlyFlagsAreOff(0x0303, new int[] { 0x001, 0x0000, 0x0000, 0x0001 })); + assertTrue(BitTools.onlyFlagsAreOff(0xFFFFFFFE, new int[] { 0x001, 0x0000, 0x0000, 0x0001 })); + + assertFalse(BitTools.onlyFlagsAreOff(0x0303, new int[] { 0x001, 0x0100, 0x0000, 0x0001 })); + assertTrue(BitTools.onlyFlagsAreOff(0xFFFFFEFE, new int[] { 0x001, 0x0100, 0x0000, 0x0001 })); + + assertFalse(BitTools.onlyFlagsAreOff(0x0303, new int[] { 0x001, 0x0100, 0x0002, 0x0001 })); + assertTrue(BitTools.onlyFlagsAreOff(0xFFFFFEFC, new int[] { 0x001, 0x0100, 0x0002, 0x0001 })); + + assertFalse(BitTools.onlyFlagsAreOff(0x0303, new int[] { 0x1100, 0x0100, 0x0002, 0x0001 })); + assertTrue(BitTools.onlyFlagsAreOff(0xFFFFEEFC, new int[] { 0x1100, 0x0100, 0x0002, 0x0001 })); + } + + public void testAnyFlagsAreSetIntIntArray() { + assertTrue(BitTools.anyFlagsAreSet(0x0003, new int[] { 0x0001 })); + assertTrue(BitTools.anyFlagsAreSet(0xFFFF, new int[] { 0x0001 })); + assertTrue(BitTools.anyFlagsAreSet(0x0303, new int[] { 0xF000, 0x0F00, 0x00F0, 0x000F })); + + assertFalse(BitTools.anyFlagsAreSet(0x0303, new int[] { 0x1000, 0x0010 })); + assertFalse(BitTools.anyFlagsAreSet(0x0000, new int[] { 0xF000, 0x0F00, 0x00F0, 0x000F })); + } + + public void testAnyFlagsAreOffIntIntArray() { + assertFalse(BitTools.anyFlagsAreOff(0x0003, new int[] { 0x0001 })); + assertFalse(BitTools.anyFlagsAreOff(0xFFFF, new int[] { 0x0001 })); + assertFalse(BitTools.anyFlagsAreOff(0x0303, new int[] { 0x0100, 0x0200, 0x0003, 0x0002 })); + + assertTrue(BitTools.anyFlagsAreOff(0x0303, new int[] { 0x0100, 0x0010 })); + assertTrue(BitTools.anyFlagsAreOff(0x0000, new int[] { 0xF000, 0x0F00, 0x00F0, 0x000F })); + } + + public void testOrFlags() { + assertEquals(0x0001, BitTools.orFlags(new int[] { 0x0001, 0x0000 })); + assertEquals(0x0011, BitTools.orFlags(new int[] { 0x0001, 0x0011 })); + assertEquals(0xF011, BitTools.orFlags(new int[] { 0x0001, 0x0011, 0xF000 })); + } + + public void testAndFlags() { + assertEquals(0x0001, BitTools.andFlags(new int[] { 0x0001, 0x0001 })); + assertEquals(0x0001, BitTools.andFlags(new int[] { 0x0001, 0x0011 })); + assertEquals(0x0000, BitTools.andFlags(new int[] { 0x0001, 0x0011, 0xF000 })); + assertEquals(0x0001, BitTools.andFlags(new int[] { 0x0001, 0x0011, 0xF001 })); + } + + public void testXorFlags() { + assertEquals(0x0001, BitTools.xorFlags(new int[] { 0x0001, 0x0000 })); + assertEquals(0x0010, BitTools.xorFlags(new int[] { 0x0001, 0x0011 })); + assertEquals(0xF010, BitTools.xorFlags(new int[] { 0x0001, 0x0011, 0xF000 })); + assertEquals(0xFF11, BitTools.xorFlags(new int[] { 0x0001, 0x0011, 0xF000, 0x0F01 })); + assertEquals(0xF010, BitTools.xorFlags(new int[] { 0x0001, 0x0011, 0xF000, 0x0F01, 0x0F01 })); + } + + public void testConstructor() { + boolean exCaught = false; + try { + Object at = ReflectionTools.newInstance(BitTools.class); + fail("bogus: " + at); //$NON-NLS-1$ + } catch (RuntimeException ex) { + if (ex.getCause() instanceof InvocationTargetException) { + if (ex.getCause().getCause() instanceof UnsupportedOperationException) { + exCaught = true; + } + } + } + assertTrue(exCaught); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BooleanToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BooleanToolsTests.java new file mode 100644 index 0000000000..f134a70e87 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BooleanToolsTests.java @@ -0,0 +1,89 @@ +/******************************************************************************* + * Copyright (c) 2009, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import java.lang.reflect.InvocationTargetException; + +import junit.framework.TestCase; + +import org.eclipse.jpt.common.utility.internal.BooleanTools; +import org.eclipse.jpt.common.utility.internal.ReflectionTools; + +public class BooleanToolsTests extends TestCase { + private static final Boolean TRUE = Boolean.TRUE; + private static final Boolean FALSE = Boolean.FALSE; + + public BooleanToolsTests(String name) { + super(name); + } + + public void testNOT() { + assertEquals(FALSE, BooleanTools.not(TRUE)); + assertEquals(TRUE, BooleanTools.not(FALSE)); + } + + public void testAND() { + assertEquals(TRUE, BooleanTools.and(TRUE, TRUE)); + assertEquals(FALSE, BooleanTools.and(TRUE, FALSE)); + assertEquals(FALSE, BooleanTools.and(FALSE, TRUE)); + assertEquals(FALSE, BooleanTools.and(FALSE, FALSE)); + } + + public void testOR() { + assertEquals(TRUE, BooleanTools.or(TRUE, TRUE)); + assertEquals(TRUE, BooleanTools.or(TRUE, FALSE)); + assertEquals(TRUE, BooleanTools.or(FALSE, TRUE)); + assertEquals(FALSE, BooleanTools.or(FALSE, FALSE)); + } + + public void testXOR() { + assertEquals(FALSE, BooleanTools.xor(TRUE, TRUE)); + assertEquals(TRUE, BooleanTools.xor(TRUE, FALSE)); + assertEquals(TRUE, BooleanTools.xor(FALSE, TRUE)); + assertEquals(FALSE, BooleanTools.xor(FALSE, FALSE)); + } + + public void testNAND() { + assertEquals(FALSE, BooleanTools.nand(TRUE, TRUE)); + assertEquals(TRUE, BooleanTools.nand(TRUE, FALSE)); + assertEquals(TRUE, BooleanTools.nand(FALSE, TRUE)); + assertEquals(TRUE, BooleanTools.nand(FALSE, FALSE)); + } + + public void testNOR() { + assertEquals(FALSE, BooleanTools.nor(TRUE, TRUE)); + assertEquals(FALSE, BooleanTools.nor(TRUE, FALSE)); + assertEquals(FALSE, BooleanTools.nor(FALSE, TRUE)); + assertEquals(TRUE, BooleanTools.nor(FALSE, FALSE)); + } + + public void testXNOR() { + assertEquals(TRUE, BooleanTools.xnor(TRUE, TRUE)); + assertEquals(FALSE, BooleanTools.xnor(TRUE, FALSE)); + assertEquals(FALSE, BooleanTools.xnor(FALSE, TRUE)); + assertEquals(TRUE, BooleanTools.xnor(FALSE, FALSE)); + } + + public void testConstructor() { + boolean exCaught = false; + try { + Object at = ReflectionTools.newInstance(BooleanTools.class); + fail("bogus: " + at); //$NON-NLS-1$ + } catch (RuntimeException ex) { + if (ex.getCause() instanceof InvocationTargetException) { + if (ex.getCause().getCause() instanceof UnsupportedOperationException) { + exCaught = true; + } + } + } + assertTrue(exCaught); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ClassNameTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ClassNameTests.java new file mode 100644 index 0000000000..8e070b6d18 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ClassNameTests.java @@ -0,0 +1,368 @@ +/******************************************************************************* + * Copyright (c) 2005, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import junit.framework.TestCase; +import org.eclipse.jpt.common.utility.internal.ClassName; +import org.eclipse.jpt.common.utility.internal.ReflectionTools; + +@SuppressWarnings("nls") +public class ClassNameTests extends TestCase { + + public ClassNameTests(String name) { + super(name); + } + + public void testIsArray() { + assertFalse(ClassName.isArray(int.class.getName())); + assertTrue(ClassName.isArray(int[].class.getName())); + assertTrue(ClassName.isArray(int[][].class.getName())); + + assertFalse(ClassName.isArray(java.lang.String.class.getName())); + assertTrue(ClassName.isArray(java.lang.String[].class.getName())); + assertTrue(ClassName.isArray(java.lang.String[][].class.getName())); + } + + public void testGetElementTypeName() { + assertEquals(java.util.Vector.class.getName(), ClassName.getElementTypeName(java.util.Vector.class.getName())); + assertEquals(int.class.getName(), ClassName.getElementTypeName(int.class.getName())); + assertEquals(void.class.getName(), ClassName.getElementTypeName(void.class.getName())); + assertEquals(java.util.Vector.class.getName(), ClassName.getElementTypeName(java.util.Vector[].class.getName())); + assertEquals(int.class.getName(), ClassName.getElementTypeName(int[].class.getName())); + assertEquals(java.util.Vector.class.getName(), ClassName.getElementTypeName(java.util.Vector[][][].class.getName())); + assertEquals(int.class.getName(), ClassName.getElementTypeName(int[][][].class.getName())); + } + + public void testGetArrayDepth() { + assertEquals(0, ClassName.getArrayDepth(java.util.Vector.class.getName())); + assertEquals(0, ClassName.getArrayDepth(int.class.getName())); + assertEquals(0, ClassName.getArrayDepth(void.class.getName())); + assertEquals(1, ClassName.getArrayDepth(java.util.Vector[].class.getName())); + assertEquals(1, ClassName.getArrayDepth(int[].class.getName())); + assertEquals(3, ClassName.getArrayDepth(java.util.Vector[][][].class.getName())); + assertEquals(3, ClassName.getArrayDepth(int[][][].class.getName())); + } + + public void testGetComponentTypeName() { + assertEquals(null, ClassName.getComponentTypeName(java.lang.Object.class.getName())); + assertEquals(java.lang.Object.class.getName(), ClassName.getComponentTypeName(java.lang.Object[].class.getName())); + assertEquals(java.lang.Object[].class.getName(), ClassName.getComponentTypeName(java.lang.Object[][].class.getName())); + + assertEquals(null, ClassName.getComponentTypeName(int.class.getName())); + assertEquals(int.class.getName(), ClassName.getComponentTypeName(int[].class.getName())); + assertEquals(int[].class.getName(), ClassName.getComponentTypeName(int[][].class.getName())); + } + + public void testGetSimpleName() throws Exception { + assertEquals("Object", ClassName.getSimpleName(java.lang.Object.class.getName())); + assertEquals("Object[]", ClassName.getSimpleName(java.lang.Object[].class.getName())); + assertEquals("Object[][]", ClassName.getSimpleName(java.lang.Object[][].class.getName())); + + assertEquals(java.util.Map.class.getSimpleName(), ClassName.getSimpleName(java.util.Map.class.getName())); + assertEquals(java.util.Map.Entry.class.getSimpleName(), ClassName.getSimpleName(java.util.Map.Entry.class.getName())); + + assertEquals("int", ClassName.getSimpleName(int.class.getName())); + assertEquals("int[]", ClassName.getSimpleName(int[].class.getName())); + assertEquals("int[][]", ClassName.getSimpleName(int[][].class.getName())); + + Object anonObject = new Object() { + // anonymous class + }; + assertEquals("", ClassName.getSimpleName(anonObject.getClass().getName())); + + class Local { + // anonymous class + } + Local localObject = new Local(); + assertEquals("Local", ClassName.getSimpleName(localObject.getClass().getName())); + } + + public void testGetPackageName() throws Exception { + assertEquals(java.lang.Object.class.getPackage().getName(), ClassName.getPackageName(java.lang.Object.class.getName())); + assertEquals("", ClassName.getPackageName(java.lang.Object[].class.getName())); + assertEquals("", ClassName.getPackageName(java.lang.Object[][].class.getName())); + + assertEquals(java.util.Map.class.getPackage().getName(), ClassName.getPackageName(java.util.Map.class.getName())); + assertEquals(java.util.Map.Entry.class.getPackage().getName(), ClassName.getPackageName(java.util.Map.Entry.class.getName())); + + assertEquals("", ClassName.getPackageName(int.class.getName())); + assertEquals("", ClassName.getPackageName(int[].class.getName())); + assertEquals("", ClassName.getPackageName(int[][].class.getName())); + + assertEquals("", ClassName.getPackageName(void.class.getName())); + + Object anonObject = new Object() { + // anonymous class + }; + assertEquals(anonObject.getClass().getPackage().getName(), ClassName.getPackageName(anonObject.getClass().getName())); + } + + public void testIsTopLevel() throws Exception { + assertTrue(ClassName.isTopLevel(java.util.Map.class.getName())); // top-level + assertFalse(ClassName.isTopLevel(java.util.Map.Entry.class.getName())); // member + assertFalse(ClassName.isTopLevel(Class.forName(this.getClass().getName() + "$1LocalClass").getName())); // local + assertFalse(ClassName.isTopLevel(Class.forName("java.util.Vector$1").getName())); // anonymous + + Object[] array = new java.util.Map[0]; // top-level + assertFalse(ClassName.isTopLevel(array.getClass().getName())); + array = new java.util.Map.Entry[0]; // member + assertFalse(ClassName.isTopLevel(array.getClass().getName())); + Class<?> localClass = Class.forName(this.getClass().getName() + "$1LocalClass"); // local + array = (Object[]) Array.newInstance(localClass, 0); + assertFalse(ClassName.isTopLevel(array.getClass().getName())); + Class<?> anonClass = Class.forName("java.util.Vector$1"); // local + array = (Object[]) Array.newInstance(anonClass, 0); + assertFalse(ClassName.isTopLevel(array.getClass().getName())); + } + + public void testIsMember() throws Exception { + assertFalse(ClassName.isMember(java.util.Map.class.getName())); // top-level + assertTrue(ClassName.isMember(java.util.Map.Entry.class.getName())); // member + assertFalse(ClassName.isMember(Class.forName(this.getClass().getName() + "$1LocalClass").getName())); // local + assertFalse(ClassName.isMember(Class.forName("java.util.Vector$1").getName())); // anonymous + + Object[] array = new java.util.Map[0]; // top-level + assertFalse(ClassName.isMember(array.getClass().getName())); + array = new java.util.Map.Entry[0]; // member + assertFalse(ClassName.isMember(array.getClass().getName())); + Class<?> localClass = Class.forName(this.getClass().getName() + "$1LocalClass"); // local + array = (Object[]) Array.newInstance(localClass, 0); + assertFalse(ClassName.isMember(array.getClass().getName())); + Class<?> anonClass = Class.forName("java.util.Vector$1"); // local + array = (Object[]) Array.newInstance(anonClass, 0); + assertFalse(ClassName.isMember(array.getClass().getName())); + + // test a few edge cases + assertTrue(ClassName.isMember("java.util.Map$a1")); + assertTrue(ClassName.isMember("java.util.Map$1aa$aaa")); // member inside local + assertTrue(ClassName.isMember("java.util.Map$1$aaa")); // member inside anonymous + assertTrue(ClassName.isMember("java.util.Map$a1$aaa$bbb")); + assertTrue(ClassName.isMember("java.util.Map$1a1$aaa")); // member inside local + assertFalse(ClassName.isMember("java.util.Map$1a")); + assertTrue(ClassName.isMember("java.util.Map$a12345$b12345")); + assertFalse(ClassName.isMember("java.util.Map$12345a")); + assertFalse(ClassName.isMember("java.util.Map$333")); + assertFalse(ClassName.isMember("java.util.Map3$333")); + } + + public void testIsLocal() throws Exception { + class LocalClass { + void foo() { + System.getProperty("foo"); + } + } + new LocalClass().foo(); + assertFalse(ClassName.isLocal(java.util.Map.class.getName())); // top-level + assertFalse(ClassName.isLocal(java.util.Map.Entry.class.getName())); // member + assertTrue(ClassName.isLocal(Class.forName(this.getClass().getName() + "$1LocalClass").getName())); // local + assertFalse(ClassName.isLocal(Class.forName("java.util.Vector$1").getName())); // anonymous + + Object[] array = new java.util.Map[0]; // top-level + assertFalse(ClassName.isLocal(array.getClass().getName())); + array = new java.util.Map.Entry[0]; // member + assertFalse(ClassName.isLocal(array.getClass().getName())); + Class<?> localClass = Class.forName(this.getClass().getName() + "$1LocalClass"); // local + array = (Object[]) Array.newInstance(localClass, 0); + assertFalse(ClassName.isLocal(array.getClass().getName())); + Class<?> anonClass = Class.forName("java.util.Vector$1"); // local + array = (Object[]) Array.newInstance(anonClass, 0); + assertFalse(ClassName.isLocal(array.getClass().getName())); + + // test a few edge cases + assertFalse(ClassName.isLocal("java.util.Map$a1")); + assertFalse(ClassName.isLocal("java.util.Map$a1$aaa$bbb")); + assertFalse(ClassName.isLocal("java.util.Map$11$aaa")); + assertTrue(ClassName.isLocal("java.util.Map$1a")); + assertTrue(ClassName.isLocal("java.util.Map$2abc")); + assertTrue(ClassName.isLocal("java.util.Map$2abc1")); + assertFalse(ClassName.isLocal("java.util.Map$a12345$b12345")); + assertTrue(ClassName.isLocal("java.util.Map$12345$1234a")); + assertFalse(ClassName.isLocal("java.util.Map$333")); + assertFalse(ClassName.isLocal("java.util.Map3$333")); + } + + public void testIsAnonymous() throws Exception { + assertFalse(ClassName.isAnonymous(java.util.Map.class.getName())); // top-level + assertFalse(ClassName.isAnonymous(java.util.Map.Entry.class.getName())); // member + assertFalse(ClassName.isAnonymous(Class.forName(this.getClass().getName() + "$1LocalClass").getName())); // local + assertTrue(ClassName.isAnonymous(Class.forName("java.util.Vector$1").getName())); // anonymous + + Object[] array = new java.util.Map[0]; // top-level + assertFalse(ClassName.isAnonymous(array.getClass().getName())); + array = new java.util.Map.Entry[0]; // member + assertFalse(ClassName.isAnonymous(array.getClass().getName())); + Class<?> localClass = Class.forName(this.getClass().getName() + "$1LocalClass"); // local + array = (Object[]) Array.newInstance(localClass, 0); + assertFalse(ClassName.isAnonymous(array.getClass().getName())); + Class<?> anonClass = Class.forName("java.util.Vector$1"); // local + array = (Object[]) Array.newInstance(anonClass, 0); + assertFalse(ClassName.isAnonymous(array.getClass().getName())); + + // test a few edge cases + assertFalse(ClassName.isAnonymous("java.util.Map$a1")); + assertFalse(ClassName.isAnonymous("java.util.Map$a1$aaa$bbb")); + assertFalse(ClassName.isAnonymous("java.util.Map$1a1$aaa")); + assertFalse(ClassName.isAnonymous("java.util.Map$1$a")); + assertFalse(ClassName.isAnonymous("java.util.Map$1a")); + assertFalse(ClassName.isAnonymous("java.util.Map$a12345$b12345")); + assertFalse(ClassName.isAnonymous("java.util.Map$12345$a1234")); + assertTrue(ClassName.isAnonymous("java.util.Map$333")); + assertTrue(ClassName.isAnonymous("java.util.Map3$333")); + } + + public void testIsReference() throws Exception { + assertFalse(ClassName.isReference(int.class.getName())); // top-level + + assertTrue(ClassName.isReference(java.util.Map.class.getName())); // top-level + assertTrue(ClassName.isReference(java.util.Map.Entry.class.getName())); // member + assertTrue(ClassName.isReference(Class.forName(this.getClass().getName() + "$1LocalClass").getName())); // local + assertTrue(ClassName.isReference(Class.forName("java.util.Vector$1").getName())); // anonymous + + Object[] array = new java.util.Map[0]; // top-level + assertTrue(ClassName.isReference(array.getClass().getName())); + array = new java.util.Map.Entry[0]; // member + assertTrue(ClassName.isReference(array.getClass().getName())); + Class<?> localClass = Class.forName(this.getClass().getName() + "$1LocalClass"); // local + array = (Object[]) Array.newInstance(localClass, 0); + assertTrue(ClassName.isReference(array.getClass().getName())); + Class<?> anonClass = Class.forName("java.util.Vector$1"); // local + array = (Object[]) Array.newInstance(anonClass, 0); + assertTrue(ClassName.isReference(array.getClass().getName())); + } + + public void testIsPrimitive() { + assertTrue(void.class.isPrimitive()); + + assertTrue(ClassName.isPrimitive(void.class.getName())); + assertTrue(ClassName.isPrimitive(int.class.getName())); + assertTrue(ClassName.isPrimitive(float.class.getName())); + assertTrue(ClassName.isPrimitive(boolean.class.getName())); + + assertFalse(ClassName.isPrimitive(java.lang.Number.class.getName())); + assertFalse(ClassName.isPrimitive(java.lang.String.class.getName())); + assertFalse(ClassName.isPrimitive(java.lang.Boolean.class.getName())); + assertFalse(ClassName.isPrimitive(java.lang.Integer.class.getName())); + } + + public void testIsPrimitiveWrapper() { + assertFalse(ClassName.isPrimitiveWrapper(void.class.getName())); + assertFalse(ClassName.isPrimitiveWrapper(int.class.getName())); + assertFalse(ClassName.isPrimitiveWrapper(float.class.getName())); + assertFalse(ClassName.isPrimitiveWrapper(boolean.class.getName())); + + assertFalse(ClassName.isPrimitiveWrapper(java.lang.reflect.Field.class.getName())); + assertFalse(ClassName.isPrimitiveWrapper(java.lang.String.class.getName())); + assertTrue(ClassName.isPrimitiveWrapper(java.lang.Boolean.class.getName())); + assertTrue(ClassName.isPrimitiveWrapper(java.lang.Integer.class.getName())); + } + + public void testIsVariablePrimitive() { + assertFalse(ClassName.isVariablePrimitive(void.class.getName())); + + assertTrue(ClassName.isVariablePrimitive(int.class.getName())); + assertTrue(ClassName.isVariablePrimitive(float.class.getName())); + assertTrue(ClassName.isVariablePrimitive(boolean.class.getName())); + + assertFalse(ClassName.isVariablePrimitive(java.lang.Number.class.getName())); + assertFalse(ClassName.isVariablePrimitive(java.lang.String.class.getName())); + assertFalse(ClassName.isVariablePrimitive(java.lang.Boolean.class.getName())); + } + + public void testIsVariablePrimitiveWrapper() { + assertFalse(ClassName.isVariablePrimitiveWrapper(java.lang.Void.class.getName())); + + assertTrue(ClassName.isVariablePrimitiveWrapper(java.lang.Integer.class.getName())); + assertTrue(ClassName.isVariablePrimitiveWrapper(java.lang.Float.class.getName())); + assertTrue(ClassName.isVariablePrimitiveWrapper(java.lang.Boolean.class.getName())); + + assertFalse(ClassName.isVariablePrimitiveWrapper(java.lang.Number.class.getName())); + assertFalse(ClassName.isVariablePrimitiveWrapper(java.lang.String.class.getName())); + assertFalse(ClassName.isVariablePrimitiveWrapper(java.lang.Object.class.getName())); + } + + public void testGetWrapperClassName() { + assertEquals(java.lang.Void.class.getName(), ClassName.getWrapperClassName(void.class.getName())); + assertEquals(java.lang.Integer.class.getName(), ClassName.getWrapperClassName(int.class.getName())); + assertEquals(java.lang.Float.class.getName(), ClassName.getWrapperClassName(float.class.getName())); + assertEquals(java.lang.Boolean.class.getName(), ClassName.getWrapperClassName(boolean.class.getName())); + + assertNull(ClassName.getWrapperClassName(java.lang.String.class.getName())); + } + + public void testGetPrimitiveClassName() { + assertEquals(void.class.getName(), ClassName.getPrimitiveClassName(java.lang.Void.class.getName())); + assertEquals(int.class.getName(), ClassName.getPrimitiveClassName(java.lang.Integer.class.getName())); + assertEquals(float.class.getName(), ClassName.getPrimitiveClassName(java.lang.Float.class.getName())); + assertEquals(boolean.class.getName(), ClassName.getPrimitiveClassName(java.lang.Boolean.class.getName())); + + assertNull(ClassName.getPrimitiveClassName(java.lang.String.class.getName())); + } + + public void testAreAutoboxEquivalents() { + assertTrue(ClassName.areAutoboxEquivalents(Integer.class.getName(), Integer.class.getName())); + assertTrue(ClassName.areAutoboxEquivalents(int.class.getName(), Integer.class.getName())); + assertTrue(ClassName.areAutoboxEquivalents(Integer.class.getName(), int.class.getName())); + assertFalse(ClassName.areAutoboxEquivalents(int.class.getName(), Boolean.class.getName())); + assertTrue(ClassName.areAutoboxEquivalents(String.class.getName(), String.class.getName())); + } + + public void testForCode() { + assertEquals("byte", ClassName.forCode('B')); + assertEquals("char", ClassName.forCode('C')); + assertEquals("double", ClassName.forCode('D')); + assertEquals("float", ClassName.forCode('F')); + assertEquals("int", ClassName.forCode('I')); + assertEquals("long", ClassName.forCode('J')); + assertEquals("short", ClassName.forCode('S')); + assertEquals("boolean", ClassName.forCode('Z')); + assertEquals("void", ClassName.forCode('V')); + + assertNull(ClassName.forCode('X')); + + assertEquals("byte", ClassName.forCode((int) 'B')); + assertEquals("char", ClassName.forCode((int) 'C')); + assertEquals("double", ClassName.forCode((int) 'D')); + assertEquals("float", ClassName.forCode((int) 'F')); + assertEquals("int", ClassName.forCode((int) 'I')); + assertEquals("long", ClassName.forCode((int) 'J')); + assertEquals("short", ClassName.forCode((int) 'S')); + assertEquals("boolean", ClassName.forCode((int) 'Z')); + assertEquals("void", ClassName.forCode((int) 'V')); + + assertNull(ClassName.forCode((int) 'X')); + } + + public void testGetCodeForClassName() { + assertEquals('I', ClassName.getCodeForClassName(int.class.getName())); + assertEquals('I', ClassName.getCodeForClassName("int")); + assertEquals('B', ClassName.getCodeForClassName(byte.class.getName())); + assertEquals('B', ClassName.getCodeForClassName("byte")); + + assertEquals((char) 0, ClassName.getCodeForClassName(java.lang.Object.class.getName())); + } + + public void testConstructor() { + boolean exCaught = false; + try { + Object at = ReflectionTools.newInstance(ClassName.class); + fail("bogus: " + at); //$NON-NLS-1$ + } catch (RuntimeException ex) { + if (ex.getCause() instanceof InvocationTargetException) { + if (ex.getCause().getCause() instanceof UnsupportedOperationException) { + exCaught = true; + } + } + } + assertTrue(exCaught); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ClasspathTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ClasspathTests.java new file mode 100644 index 0000000000..6542662416 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ClasspathTests.java @@ -0,0 +1,402 @@ +/******************************************************************************* + * Copyright (c) 2005, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +import junit.framework.TestCase; + +import org.eclipse.jpt.common.utility.internal.ArrayTools; +import org.eclipse.jpt.common.utility.internal.Classpath; +import org.eclipse.jpt.common.utility.internal.CollectionTools; +import org.eclipse.jpt.common.utility.internal.Tools; + +@SuppressWarnings("nls") +public class ClasspathTests extends TestCase { + private static final String JAVA_HOME = System.getProperty("java.home"); + + public ClasspathTests(String name) { + super(name); + } + + public void testCompressed() { + String path = ""; + + // no changes + path = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar")).compressed().getPath(); + assertEquals(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar"), path); + + path = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar")).compressed().getPath(); + assertEquals(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar"), path); + + path = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\i18n.jar;C:\\jdk\\jaws.jar")).compressed().getPath(); + assertEquals(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar"), path); + + path = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar;C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar")).compressed().getPath(); + assertEquals(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar"), path); + + path = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\i18n.jar;C:\\jdk\\i18n.jar;C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar")).compressed().getPath(); + assertEquals(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar"), path); + + path = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar;C:\\jdk\\rt.jar;;;;C:\\jdk\\jaws.jar;C:\\jdk\\jaws.jar;C:\\jdk\\rt.jar;;;")).compressed().getPath(); + assertEquals(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar"), path); + + // no changes + path = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar")).compressed().getPath(); + assertEquals(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar"), path); + + path = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar")).compressed().getPath(); + assertEquals(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar"), path); + + path = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\..\\jdk\\i18n.jar;C:\\jdk\\jaws.jar")).compressed().getPath(); + assertEquals(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar"), path); + + path = new Classpath(this.morph("C:\\jdk1\\jdk2\\jdk3\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk1\\jdk2\\jdk3\\..\\..\\..\\jdk1\\jdk2\\jdk3\\i18n.jar;C:\\jdk\\jaws.jar")).compressed().getPath(); + assertEquals(this.morph("C:\\jdk1\\jdk2\\jdk3\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar"), path); + + } + + public void testConvertToClassName() { + String fileName = "java/lang/String.class"; + File file = new File(fileName); + String className = Classpath.convertToClassName(file); + assertEquals(java.lang.String.class.getName(), className); + } + + public void testConvertToClass() throws ClassNotFoundException { + String fileName = "java/lang/String.class"; + File file = new File(fileName); + Class<?> javaClass = Classpath.convertToClass(file); + assertEquals(java.lang.String.class, javaClass); + } + + public void testConvertToArchiveClassFileEntryName() { + String fileName = Classpath.convertToArchiveClassFileEntryName(java.lang.String.class); + assertEquals("java/lang/String.class", fileName); + } + + public void testConvertToArchiveEntryNameBase() { + String fileName = Classpath.convertToArchiveEntryNameBase(java.lang.String.class); + assertEquals("java/lang/String", fileName); + } + + public void testConvertToClassFileName() { + char sc = File.separatorChar; + String fileName = Classpath.convertToClassFileName(java.lang.String.class); + assertEquals("java" + sc + "lang" + sc + "String.class", fileName); + } + + public void testConvertToClassFileString() { + char sc = File.separatorChar; + File file = Classpath.convertToClassFile(java.lang.String.class.getName()); + assertEquals("java" + sc + "lang" + sc + "String.class", file.getPath()); + } + + public void testConvertToClassFileClass() { + char sc = File.separatorChar; + File file = Classpath.convertToClassFile(java.lang.String.class); + assertEquals("java" + sc + "lang" + sc + "String.class", file.getPath()); + } + + public void testConvertToJavaFileName() { + char sc = File.separatorChar; + String fileName = Classpath.convertToJavaFileName(java.lang.String.class); + assertEquals("java" + sc + "lang" + sc + "String.java", fileName); + } + + public void testConvertToJavaFileString() { + char sc = File.separatorChar; + File file = Classpath.convertToJavaFile(java.lang.String.class.getName()); + assertEquals("java" + sc + "lang" + sc + "String.java", file.getPath()); + } + + public void testConvertToJavaFileClass() { + char sc = File.separatorChar; + File file = Classpath.convertToJavaFile(java.lang.String.class); + assertEquals("java" + sc + "lang" + sc + "String.java", file.getPath()); + } + + public void testConvertToFileNameBase() { + char sc = File.separatorChar; + String fileName = Classpath.convertToFileNameBase(java.lang.String.class); + assertEquals("java" + sc + "lang" + sc + "String", fileName); + } + + public void testConvertToURLs() { + Iterator<URL> entries = new Classpath(this.morph("C:\\jdk\\rt.jar;C:\\jdk\\i18n.jar;C:\\jdk\\jaws.jar;C:\\foo\\classes;C:\\bar\\bar.jar")).getURLs().iterator(); + assertEquals(this.morphURL("/C:/jdk/rt.jar"), entries.next().getPath()); + assertEquals(this.morphURL("/C:/jdk/i18n.jar"), entries.next().getPath()); + assertEquals(this.morphURL("/C:/jdk/jaws.jar"), entries.next().getPath()); + assertEquals(this.morphURL("/C:/foo/classes"), entries.next().getPath()); + assertEquals(this.morphURL("/C:/bar/bar.jar"), entries.next().getPath()); + assertFalse(entries.hasNext()); + } + + public void testGetEntries() { + Classpath cp = new Classpath(this.morph("C:\\jdk\\rt.jar;;.;C:\\jdk\\i18n.jar;;;C:\\jdk\\jaws.jar;;C:\\foo\\classes;C:\\bar\\bar.jar;C:\\bar\\bar.jar;")); + Iterator<Classpath.Entry> entries = cp.getEntries().iterator(); + assertEquals(this.morph("C:\\jdk\\rt.jar"), entries.next().getFileName()); + assertEquals(this.morph("."), entries.next().getFileName()); + assertEquals(this.morph("C:\\jdk\\i18n.jar"), entries.next().getFileName()); + assertEquals(this.morph("C:\\jdk\\jaws.jar"), entries.next().getFileName()); + assertEquals(this.morph("C:\\foo\\classes"), entries.next().getFileName()); + assertEquals(this.morph("C:\\bar\\bar.jar"), entries.next().getFileName()); + assertEquals(this.morph("C:\\bar\\bar.jar"), entries.next().getFileName()); + assertFalse(entries.hasNext()); + + cp = cp.compressed(); + entries = cp.getEntries().iterator(); + assertEquals(this.morph("C:\\jdk\\rt.jar"), entries.next().getFileName()); + assertEquals(this.morph("."), entries.next().getFileName()); + assertEquals(this.morph("C:\\jdk\\i18n.jar"), entries.next().getFileName()); + assertEquals(this.morph("C:\\jdk\\jaws.jar"), entries.next().getFileName()); + assertEquals(this.morph("C:\\foo\\classes"), entries.next().getFileName()); + assertEquals(this.morph("C:\\bar\\bar.jar"), entries.next().getFileName()); + assertFalse(entries.hasNext()); + } + + public void testGetEntryForFileNamed() { + Classpath.Entry entry = null; + + // in the middle - qualified + entry = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar;C:\\foo\\classes;C:\\bar\\bar.jar")).getEntryForFileNamed("rt.jar"); + assertEquals(this.morph("C:\\jdk\\rt.jar"), entry.getFileName()); + + // in the middle - unqualified + entry = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\jaws.jar;rt.jar;C:\\foo\\classes;C:\\bar\\bar.jar")).getEntryForFileNamed("rt.jar"); + assertEquals("rt.jar", entry.getFileName()); + + // at the beginning - qualified + entry = new Classpath(this.morph("C:\\jdk\\rt.jar;C:\\jdk\\i18n.jar;C:\\jdk\\jaws.jar;C:\\foo\\classes;C:\\bar\\bar.jar")).getEntryForFileNamed("rt.jar"); + assertEquals(this.morph("C:\\jdk\\rt.jar"), entry.getFileName()); + + // at the beginning - unqualified + entry = new Classpath(this.morph("rt.jar;C:\\jdk\\i18n.jar;C:\\jdk\\jaws.jar;C:\\foo\\classes;C:\\bar\\bar.jar")).getEntryForFileNamed("rt.jar"); + assertEquals("rt.jar", entry.getFileName()); + + // at the end - qualified + entry = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\jaws.jar;C:\\foo\\classes;C:\\bar\\bar.jar;C:\\jdk\\rt.jar")).getEntryForFileNamed("rt.jar"); + assertEquals(this.morph("C:\\jdk\\rt.jar"), entry.getFileName()); + + // at the end - unqualified + entry = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\jaws.jar;C:\\foo\\classes;C:\\bar\\bar.jar;rt.jar")).getEntryForFileNamed("rt.jar"); + assertEquals("rt.jar", entry.getFileName()); + + // alone - qualified + entry = new Classpath(this.morph("C:\\jdk\\rt.jar")).getEntryForFileNamed("rt.jar"); + assertEquals(this.morph("C:\\jdk\\rt.jar"), entry.getFileName()); + + // alone - unqualified + entry = new Classpath("rt.jar").getEntryForFileNamed("rt.jar"); + assertEquals("rt.jar", entry.getFileName()); + + // trick entry at the beginning + entry = new Classpath(this.morph("rt.jar.new;C:\\jdk\\rt.jar;C:\\jdk\\i18n.jar;C:\\jdk\\jaws.jar;C:\\foo\\classes;C:\\bar\\bar.jar")).getEntryForFileNamed("rt.jar"); + assertEquals(this.morph("C:\\jdk\\rt.jar"), entry.getFileName()); + + // trick entry in the middle + entry = new Classpath(this.morph("rt.jar.new;C:\\jdk\\rtrtrt.jar;C:\\jdk\\rt.jar;C:\\jdk\\i18n.jar;C:\\jdk\\jaws.jar;C:\\foo\\classes;C:\\bar\\bar.jar")).getEntryForFileNamed("rt.jar"); + assertEquals(this.morph("C:\\jdk\\rt.jar"), entry.getFileName()); + + // trick entry at the end + entry = new Classpath(this.morph("rt.jar.new;C:\\jdk\\rtrtrt.jar;C:\\jdk\\rt.jar;C:\\jdk\\i18n.jar;C:\\jdk\\jaws.jar;C:\\foo\\classes;C:\\bar\\bar.jar;C:\\jdk\\rtrtrt.jar")).getEntryForFileNamed("rt.jar"); + assertEquals(this.morph("C:\\jdk\\rt.jar"), entry.getFileName()); + + // missing + entry = new Classpath(this.morph("rt.jar.new;C:\\jdk\\rtrtrt.jar;C:\\jdk\\i18n.jar;C:\\jdk\\jaws.jar;C:\\foo\\classes;C:\\bar\\bar.jar;C:\\jdk\\rtrtrt.jar")).getEntryForFileNamed("rt.jar"); + assertEquals("path entry should not be found", null, entry); + + } + + public void testGetEntryForClassNamed() { + assertNotNull(Classpath.completeClasspath().getEntryForClassNamed(java.lang.String.class.getName())); + assertNull(Classpath.completeClasspath().getEntryForClassNamed("foo.bar.Baz")); + } + + public void testLocationForClass() { + Class<?> javaClass = Classpath.class; + File entry = new File(Classpath.locationFor(javaClass)); + if (entry.isFile() || entry.isDirectory()) { + assertTrue(entry.exists()); + } + if (entry.isDirectory()) { + assertTrue(new File(entry, Classpath.convertToClassFileName(javaClass)).exists()); + } + } + + public void testRtJarName() throws IOException { + File rtFile = new File(Classpath.rtJarName()); + assertTrue("rt.jar does not exist", rtFile.exists()); + + JarFile rtJarFile = new JarFile(rtFile); + JarEntry entry = rtJarFile.getJarEntry("java/lang/Object.class"); + rtJarFile.close(); + assertTrue("bogus rt.jar", entry != null); + } + + public void testJREClassNames() { + assertTrue("Vector is missing from JRE class names", CollectionTools.contains(Classpath.bootClasspath().getClassNames(), java.util.Vector.class.getName())); + assertTrue("File is missing from JRE class names", CollectionTools.contains(Classpath.bootClasspath().getClassNames(), java.io.File.class.getName())); + } + + public void testJavaExtensionDirectoryNames() { + char sep = File.separatorChar; + String stdExtDirName = JAVA_HOME + sep + "lib" + sep + "ext"; + assertTrue("standard extension dir name missing: " + stdExtDirName, ArrayTools.contains(Classpath.javaExtensionDirectoryNames(), stdExtDirName)); + } + + public void testJavaExtensionDirectories() { + char sep = File.separatorChar; + File stdExtDir = new File(JAVA_HOME + sep + "lib" + sep + "ext"); + assertTrue("standard extension dir missing: " + stdExtDir.getParent(), ArrayTools.contains(Classpath.javaExtensionDirectories(), stdExtDir)); + } + + public void testJavaExtensionClasspathEntries() { + char sep = File.separatorChar; + String jdk = System.getProperty("java.version"); + if (jdk.startsWith("1.4") || jdk.startsWith("1.5") || jdk.startsWith("1.6")) { + Collection<String> jarNames = new ArrayList<String>(); + Iterable<Classpath.Entry> entries = Classpath.javaExtensionClasspath().getEntries(); + for (Classpath.Entry entry : entries) { + jarNames.add(entry.getFileName()); + } + String stdExtJarName = JAVA_HOME + sep + "lib" + sep + "ext" + sep + "dnsns.jar"; + String msg = "jdk 1.4.x standard extension jar missing: " + stdExtJarName; + boolean jarPresent = jarNames.contains(stdExtJarName); + if (Tools.jvmIsSun() || (Tools.jvmIsIBM() && jdk.startsWith("1.6"))) { + assertTrue(msg, jarPresent); + } + } else { + fail("we need to update this test for the current jdk"); + } + } + + public void testJavaExtensionClassNames() { + String jdk = System.getProperty("java.version"); + if (jdk.startsWith("1.4") || jdk.startsWith("1.5") || jdk.startsWith("1.6")) { + String className = "sun.net.spi.nameservice.dns.DNSNameService"; + String msg = "jdk 1.4.x standard extension class missing: " + className; + boolean classPresent = CollectionTools.contains(Classpath.javaExtensionClasspath().classNames(), className); + if (Tools.jvmIsSun() || (Tools.jvmIsIBM() && jdk.startsWith("1.6"))) { + assertTrue(msg, classPresent); + } + } else { + fail("we need to update this test for the current jdk"); + } + } + + public void testJavaClasspathClassNames() { + String className = this.getClass().getName(); + ClassLoader cl = this.getClass().getClassLoader(); + // make sure we are running under the "normal" class loader; + // when the tests are executed as an ANT task, they are run under + // an ANT class loader and the "Java" classpath does not include this class + if (cl.getClass().getName().startsWith("sun.misc")) { + assertTrue("class missing: " + className, CollectionTools.contains(Classpath.javaClasspath().getClassNames(), className)); + } + } + + public void testCompleteClasspathClassNames() { + String className = this.getClass().getName(); + ClassLoader cl = this.getClass().getClassLoader(); + // make sure we are running under the "normal" class loader; + // when the tests are executed as an ANT task, they are run under + // an ANT class loader and the "Java" classpath does not include this class + if (cl.getClass().getName().startsWith("sun.misc")) { + assertTrue("class missing: " + className, CollectionTools.contains(Classpath.completeClasspath().getClassNames(), className)); + } + } + + public void testClasspathForClass() { + assertNotNull(Classpath.classpathFor(java.lang.String.class)); + } + + public void testAddClassNamesTo() { + Collection<String> classNames = new ArrayList<String>(1000); + Classpath.bootClasspath().addClassNamesTo(classNames); + assertTrue(classNames.contains(java.util.Vector.class.getName())); + } + + public void testToString() { + assertNotNull(Classpath.bootClasspath().toString()); + } + + public void testEntry_getCanonicalFile() { + Classpath.Entry entry = Classpath.bootClasspath().getEntryForClassNamed(java.lang.String.class.getName()); + assertTrue(entry.getCanonicalFile().getPath().endsWith(".jar")); + } + + public void testEntry_getCanonicalFileName() { + Classpath.Entry entry = Classpath.bootClasspath().getEntryForClassNamed(java.lang.String.class.getName()); + String name = entry.getCanonicalFileName(); + if (Tools.jvmIsSun()) { + assertTrue(name.endsWith("rt.jar")); + } else if (Tools.jvmIsIBM()) { + assertTrue(name.endsWith("vm.jar")); + } + } + + public void testEntry_equals() { + Classpath.Entry entry = Classpath.bootClasspath().getEntryForClassNamed(java.lang.String.class.getName()); + assertFalse(entry.equals("foo")); + } + + public void testEntry_containsClass() { + Classpath.Entry entry = Classpath.bootClasspath().getEntryForClassNamed(java.lang.String.class.getName()); + assertTrue(entry.contains(java.lang.String.class)); + } + + public void testEntry_containsString() { + Classpath.Entry entry = Classpath.bootClasspath().getEntryForClassNamed(java.lang.String.class.getName()); + assertTrue(entry.contains(java.lang.String.class.getName())); + } + + public void testEntry_getClassNames() { + Classpath.Entry entry = Classpath.bootClasspath().getEntryForClassNamed(java.lang.String.class.getName()); + assertTrue(CollectionTools.contains(entry.getClassNames(), java.lang.String.class.getName())); + } + + public void testEntry_classNames() { + Classpath.Entry entry = Classpath.bootClasspath().getEntryForClassNamed(java.lang.String.class.getName()); + assertTrue(CollectionTools.contains(entry.classNames(), java.lang.String.class.getName())); + } + + /** + * morph the specified path to a platform-independent path + */ + private String morph(String path) { + String result = path; + result = result.replace('\\', File.separatorChar); + result = result.replace(';', File.pathSeparatorChar); + if (!ArrayTools.contains(File.listRoots(), new File("C:\\"))) { + result = result.replaceAll("C:", ""); + } + return result; + } + + /** + * morph the specified URL to a platform-independent path + */ + private String morphURL(String url) { + String result = url; + if (!ArrayTools.contains(File.listRoots(), new File("C:\\"))) { + result = result.replaceAll("/C:", ""); + } + return result; + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/CollectionToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/CollectionToolsTests.java new file mode 100644 index 0000000000..a397d85f30 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/CollectionToolsTests.java @@ -0,0 +1,2354 @@ +/******************************************************************************* + * Copyright (c) 2005, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.ListIterator; +import java.util.NoSuchElementException; +import java.util.Random; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; +import java.util.Vector; +import junit.framework.TestCase; +import org.eclipse.jpt.common.utility.internal.Bag; +import org.eclipse.jpt.common.utility.internal.CollectionTools; +import org.eclipse.jpt.common.utility.internal.HashBag; +import org.eclipse.jpt.common.utility.internal.Range; +import org.eclipse.jpt.common.utility.internal.ReflectionTools; +import org.eclipse.jpt.common.utility.internal.ReverseComparator; +import org.eclipse.jpt.common.utility.internal.enumerations.EmptyEnumeration; +import org.eclipse.jpt.common.utility.internal.iterables.EmptyIterable; +import org.eclipse.jpt.common.utility.internal.iterators.ArrayIterator; +import org.eclipse.jpt.common.utility.internal.iterators.EmptyIterator; + +@SuppressWarnings("nls") +public class CollectionToolsTests extends TestCase { + + public CollectionToolsTests(String name) { + super(name); + } + + + // ********** add all ********** + + public void testAddAllCollectionIterable_StringModified() { + List<String> list1 = this.buildStringList1(); + Iterable<String> iterable2 = this.buildStringList2(); + assertTrue(CollectionTools.addAll(list1, iterable2.iterator())); + assertEquals(6, list1.size()); + assertTrue(list1.containsAll(this.buildStringList2())); + } + + public void testAddAllCollectionIterable_StringUnmodified() { + Set<String> set1 = this.buildStringSet1(); + Iterable<String> iterable3 = this.buildStringList1(); // same elements as set1 + assertFalse(CollectionTools.addAll(set1, iterable3.iterator())); + assertEquals(3, set1.size()); + assertTrue(set1.containsAll(this.buildStringList1())); + } + + public void testAddAllCollectionIterable_ObjectModified() { + List<Object> list1 = this.buildObjectList1(); + Iterable<String> iterable2 = this.buildStringList2(); + assertTrue(CollectionTools.addAll(list1, iterable2)); + assertEquals(6, list1.size()); + assertTrue(list1.containsAll((List<String>) iterable2)); + } + + public void testAddAllCollectionIterable_ObjectUnmodified() { + Set<Object> set1 = this.buildObjectSet1(); + Iterable<String> iterable3 = this.buildStringList1(); // same elements as set1 + assertFalse(CollectionTools.addAll(set1, iterable3)); + assertEquals(3, set1.size()); + assertTrue(set1.containsAll((List<String>) iterable3)); + } + + public void testAddAllCollectionIterable_EmptyIterable() { + Set<Object> set1 = this.buildObjectSet1(); + assertFalse(CollectionTools.addAll(set1, EmptyIterable.instance())); + assertEquals(3, set1.size()); + } + + public void testAddAllCollectionIterableInt_Modified() { + List<String> list1 = this.buildStringList1(); + List<String> list2 = this.buildStringList2(); + Iterable<String> iterable2 = list2; + assertTrue(CollectionTools.addAll(list1, iterable2, list2.size())); + assertEquals(6, list1.size()); + assertTrue(list1.containsAll(this.buildStringList2())); + } + + public void testAddAllCollectionIterableInt_Unmodified() { + Set<String> set1 = this.buildStringSet1(); + List<String> list1 = this.buildStringList1(); // same elements as set1 + Iterable<String> iterable3 = list1; + assertFalse(CollectionTools.addAll(set1, iterable3, list1.size())); + assertEquals(3, set1.size()); + assertTrue(set1.containsAll(this.buildStringList1())); + } + + public void testAddAllCollectionIterator_StringModified() { + List<String> list1 = this.buildStringList1(); + List<String> list2 = this.buildStringList2(); + assertTrue(CollectionTools.addAll(list1, list2.iterator())); + assertEquals(6, list1.size()); + assertTrue(list1.containsAll(list2)); + } + + public void testAddAllCollectionIterator_StringUnmodified() { + Set<String> set1 = this.buildStringSet1(); + List<String> list3 = this.buildStringList1(); // same elements as s1 + assertFalse(CollectionTools.addAll(set1, list3.iterator())); + assertEquals(3, set1.size()); + assertTrue(set1.containsAll(list3)); + } + + public void testAddAllCollectionIterator_ObjectModified() { + List<Object> list1 = this.buildObjectList1(); + List<String> list2 = this.buildStringList2(); + assertTrue(CollectionTools.addAll(list1, list2.iterator())); + assertEquals(6, list1.size()); + assertTrue(list1.containsAll(list2)); + } + + public void testAddAllCollectionIterator_ObjectUnmodified() { + Set<Object> set1 = this.buildObjectSet1(); + List<String> list3 = this.buildStringList1(); // same elements as s1 + assertFalse(CollectionTools.addAll(set1, list3.iterator())); + assertEquals(3, set1.size()); + assertTrue(set1.containsAll(list3)); + } + + public void testAddAllCollectionIterator_EmptyIterator() { + List<String> list1 = this.buildStringList1(); + assertFalse(CollectionTools.addAll(list1, EmptyIterator.<String>instance())); + assertEquals(3, list1.size()); + } + + public void testAddAllCollectionIteratorInt_Modified() { + List<String> list1 = this.buildStringList1(); + List<String> list2 = this.buildStringList2(); + assertTrue(CollectionTools.addAll(list1, list2.iterator(), 3)); + assertEquals(6, list1.size()); + assertTrue(list1.containsAll(list2)); + } + + public void testAddAllCollectionIteratorInt_Unmodified() { + Set<String> set1 = this.buildStringSet1(); + List<String> list3 = this.buildStringList1(); // same elements as s1 + assertFalse(CollectionTools.addAll(set1, list3.iterator(), 3)); + assertEquals(3, set1.size()); + assertTrue(set1.containsAll(list3)); + } + + public void testAddAllCollectionIteratorInt_EmptyIterator() { + List<String> list1 = this.buildStringList1(); + assertFalse(CollectionTools.addAll(list1, EmptyIterator.<String>instance(), 0)); + assertEquals(3, list1.size()); + } + + public void testAddAllCollectionObjectArray_StringModified() { + List<String> list = this.buildStringList1(); + String[] a = this.buildStringArray1(); + assertTrue(CollectionTools.addAll(list, a)); + assertEquals(6, list.size()); + assertTrue(list.containsAll(CollectionTools.collection(a))); + } + + public void testAddAllCollectionObjectArray_StringListEmptyArray() { + List<String> list = this.buildStringList1(); + assertFalse(CollectionTools.addAll(list, new String[0])); + } + + public void testAddAllCollectionObjectArray_StringUnmodified() { + Set<String> set = this.buildStringSet1(); + String[] a = this.buildStringArray1(); + assertFalse(CollectionTools.addAll(set, a)); + assertEquals(3, set.size()); + assertTrue(set.containsAll(CollectionTools.collection(a))); + + assertFalse(CollectionTools.addAll(set, new String[0])); + } + + public void testAddAllCollectionObjectArray_StringSetEmptyArray() { + Set<String> set = this.buildStringSet1(); + assertFalse(CollectionTools.addAll(set, new String[0])); + } + + public void testAddAllCollectionObjectArray_ObjectModified() { + List<Object> list = this.buildObjectList1(); + String[] a = this.buildStringArray1(); + + assertTrue(CollectionTools.addAll(list, a)); + assertEquals(6, list.size()); + assertTrue(list.containsAll(CollectionTools.collection(a))); + } + + public void testAddAllCollectionObjectArray_ObjectUnmodified() { + String[] a = this.buildStringArray1(); + Set<Object> set = this.buildObjectSet1(); + assertFalse(CollectionTools.addAll(set, a)); + assertEquals(3, set.size()); + assertTrue(set.containsAll(CollectionTools.collection(a))); + } + + public void testAddAllListIntObjectArray() { + List<String> list = this.buildStringList1(); + CollectionTools.addAll(list, 2, new String[] { "X", "X", "X" }); + assertEquals(6, list.size()); + assertTrue(list.contains("X")); + assertTrue(Arrays.equals(new Object[] { "zero", "one", "X", "X", "X", "two" }, list.toArray())); + } + + public void testAddAllListIntObjectArray_Zero() { + List<String> list = new ArrayList<String>(); + CollectionTools.addAll(list, 0, new String[] { "X", "X", "X" }); + assertEquals(3, list.size()); + assertTrue(list.contains("X")); + assertTrue(Arrays.equals(new Object[] { "X", "X", "X" }, list.toArray())); + } + + public void testAddAllListIntObjectArray_EmptyArray() { + List<String> list = this.buildStringList1(); + CollectionTools.addAll(list, 2, new String[0]); + assertEquals(3, list.size()); + assertTrue(Arrays.equals(new Object[] { "zero", "one", "two" }, list.toArray())); + } + + public void testAddAllListIntIterable() { + List<String> list = this.buildStringList1(); + Iterable<String> iterable = Arrays.asList(new String[] { "X", "X", "X" }); + CollectionTools.addAll(list, 2, iterable); + assertEquals(6, list.size()); + assertTrue(list.contains("X")); + assertTrue(Arrays.equals(new Object[] { "zero", "one", "X", "X", "X", "two" }, list.toArray())); + } + + public void testAddAllListIntIterable_Zero() { + List<String> list = new ArrayList<String>(); + Iterable<String> iterable = Arrays.asList(new String[] { "X", "X", "X" }); + CollectionTools.addAll(list, 0, iterable); + assertEquals(3, list.size()); + assertTrue(list.contains("X")); + assertTrue(Arrays.equals(new Object[] { "X", "X", "X" }, list.toArray())); + } + + public void testAddAllListIntIterable_EmptyIterable() { + List<String> list = this.buildStringList1(); + Iterable<String> iterable = EmptyIterable.instance(); + CollectionTools.addAll(list, 2, iterable); + assertEquals(3, list.size()); + assertTrue(Arrays.equals(new Object[] { "zero", "one", "two" }, list.toArray())); + } + + public void testAddAllListIntIterableInt() { + List<String> list = this.buildStringList1(); + Iterable<String> iterable = Arrays.asList(new String[] { "X", "X", "X" }); + CollectionTools.addAll(list, 2, iterable, 3); + assertEquals(6, list.size()); + assertTrue(list.contains("X")); + assertTrue(Arrays.equals(new Object[] { "zero", "one", "X", "X", "X", "two" }, list.toArray())); + } + + public void testAddAllListIntIterableInt_Zero() { + List<String> list = new ArrayList<String>(); + Iterable<String> iterable = Arrays.asList(new String[] { "X", "X", "X" }); + CollectionTools.addAll(list, 0, iterable, 3); + assertEquals(3, list.size()); + assertTrue(list.contains("X")); + assertTrue(Arrays.equals(new Object[] { "X", "X", "X" }, list.toArray())); + } + + public void testAddAllListIntIterableInt_EmptyIterable() { + List<String> list = this.buildStringList1(); + Iterable<String> iterable = EmptyIterable.instance(); + CollectionTools.addAll(list, 2, iterable, 0); + assertEquals(3, list.size()); + assertTrue(Arrays.equals(new Object[] { "zero", "one", "two" }, list.toArray())); + } + + public void testAddAllListIntIterator() { + List<String> list = this.buildStringList1(); + Iterator<String> iterator = Arrays.asList(new String[] { "X", "X", "X" }).iterator(); + CollectionTools.addAll(list, 2, iterator); + assertEquals(6, list.size()); + assertTrue(list.contains("X")); + assertTrue(Arrays.equals(new Object[] { "zero", "one", "X", "X", "X", "two" }, list.toArray())); + } + + public void testAddAllListIntIterator_Zero() { + List<String> list = new ArrayList<String>(); + Iterator<String> iterator = Arrays.asList(new String[] { "X", "X", "X" }).iterator(); + CollectionTools.addAll(list, 0, iterator); + assertEquals(3, list.size()); + assertTrue(list.contains("X")); + assertTrue(Arrays.equals(new Object[] { "X", "X", "X" }, list.toArray())); + } + + public void testAddAllListIntIterator_EmptyIterator() { + List<String> list = this.buildStringList1(); + Iterator<String> iterator = EmptyIterator.instance(); + CollectionTools.addAll(list, 2, iterator); + assertEquals(3, list.size()); + assertTrue(Arrays.equals(new Object[] { "zero", "one", "two" }, list.toArray())); + } + + public void testAddAllListIntIteratorInt() { + List<String> list = this.buildStringList1(); + Iterator<String> iterator = Arrays.asList(new String[] { "X", "X", "X" }).iterator(); + CollectionTools.addAll(list, 2, iterator, 3); + assertEquals(6, list.size()); + assertTrue(list.contains("X")); + assertTrue(Arrays.equals(new Object[] { "zero", "one", "X", "X", "X", "two" }, list.toArray())); + } + + public void testAddAllListIntIteratorInt_Zero() { + List<String> list = new ArrayList<String>(); + Iterator<String> iterator = Arrays.asList(new String[] { "X", "X", "X" }).iterator(); + CollectionTools.addAll(list, 0, iterator, 3); + assertEquals(3, list.size()); + assertTrue(list.contains("X")); + assertTrue(Arrays.equals(new Object[] { "X", "X", "X" }, list.toArray())); + } + + public void testAddAllListIntIteratorInt_EmptyIterator() { + List<String> list = this.buildStringList1(); + Iterator<String> iterator = EmptyIterator.instance(); + CollectionTools.addAll(list, 2, iterator, 0); + assertEquals(3, list.size()); + assertTrue(Arrays.equals(new Object[] { "zero", "one", "two" }, list.toArray())); + } + + + // ********** bag ********** + + public void testBagEnumeration_String() { + Bag<String> b = CollectionTools.bag(this.buildStringVector1().elements()); + assertEquals(3, b.size()); + assertTrue(b.containsAll(this.buildStringVector1())); + } + + public void testBagEnumeration_Object() { + Bag<Object> b = CollectionTools.<Object>bag(this.buildStringVector1().elements()); + assertEquals(3, b.size()); + assertTrue(b.containsAll(this.buildStringVector1())); + } + + public void testBagEnumeration_Empty() { + Bag<Object> b = CollectionTools.<Object>bag(EmptyEnumeration.instance()); + assertEquals(0, b.size()); + } + + public void testBagEnumerationInt() { + Bag<String> b = CollectionTools.bag(this.buildStringVector1().elements(), 3); + assertEquals(3, b.size()); + assertTrue(b.containsAll(this.buildStringVector1())); + } + + public void testBagEnumerationInt_Empty() { + Bag<String> b = CollectionTools.bag(EmptyEnumeration.<String>instance(), 3); + assertEquals(0, b.size()); + } + + public void testBagIterable() { + Iterable<String> iterable = this.buildStringList1(); + Bag<String> b = CollectionTools.bag(iterable); + assertEquals(3, b.size()); + assertTrue(b.containsAll(this.buildStringList1())); + } + + public void testBagIterableInt() { + Iterable<String> iterable = this.buildStringList1(); + Bag<String> b = CollectionTools.bag(iterable, 3); + assertEquals(3, b.size()); + assertTrue(b.containsAll(this.buildStringList1())); + } + + public void testBagIterator_String() { + Bag<String> b = CollectionTools.bag(this.buildStringList1().iterator()); + assertEquals(3, b.size()); + assertTrue(b.containsAll(this.buildStringList1())); + } + + public void testBagIterator_StringObject() { + Collection<String> c = new ArrayList<String>(); + c.add("zero"); + c.add("one"); + c.add("two"); + c.add("three"); + Bag<Object> b = CollectionTools.<Object>bag(c.iterator()); + assertEquals(4, b.size()); + assertTrue(b.containsAll(c)); + } + + public void testBagIterator_Empty() { + Bag<String> b = CollectionTools.bag(EmptyIterator.<String>instance()); + assertEquals(0, b.size()); + } + + public void testBagIteratorInt() { + Bag<String> b = CollectionTools.bag(this.buildStringList1().iterator(), 3); + assertEquals(3, b.size()); + assertTrue(b.containsAll(this.buildStringList1())); + } + + public void testBagIteratorInt_Empty() { + Bag<String> b = CollectionTools.bag(EmptyIterator.<String>instance(), 3); + assertEquals(0, b.size()); + } + + public void testBagObjectArray() { + Bag<String> b = CollectionTools.bag(this.buildStringArray1()); + assertEquals(3, b.size()); + assertTrue(CollectionTools.containsAll(b, (Object[]) this.buildStringArray1())); + } + + public void testBagObjectArray_Vararg() { + Bag<String> b = CollectionTools.bag("foo", "bar", "baz"); + assertEquals(3, b.size()); + assertTrue(CollectionTools.containsAll(b, new Object[]{"foo", "bar", "baz"})); + } + + public void testBagObjectArray_Empty() { + Bag<String> b = CollectionTools.bag(Bag.Empty.<String>instance()); + assertEquals(0, b.size()); + } + + + // ********** collection ********** + + public void testCollectionEnumeration() { + Collection<String> c = CollectionTools.collection(this.buildStringVector1().elements()); + assertEquals(3, c.size()); + assertTrue(c.containsAll(this.buildStringVector1())); + } + + public void testCollectionEnumeration_ObjectString() { + Collection<Object> c = CollectionTools.<Object>collection(this.buildStringVector1().elements()); + assertEquals(3, c.size()); + assertTrue(c.containsAll(this.buildStringVector1())); + } + + public void testCollectionEnumerationInt() { + Collection<String> c = CollectionTools.collection(this.buildStringVector1().elements(), 3); + assertEquals(3, c.size()); + assertTrue(c.containsAll(this.buildStringVector1())); + } + + public void testCollectionIterable() { + Iterable<String> iterable = this.buildStringList1(); + Collection<String> c = CollectionTools.collection(iterable); + assertEquals(3, c.size()); + assertTrue(c.containsAll(this.buildStringList1())); + } + + public void testCollectionIterableInt() { + Iterable<String> iterable = this.buildStringList1(); + Collection<String> c = CollectionTools.collection(iterable, 3); + assertEquals(3, c.size()); + assertTrue(c.containsAll(this.buildStringList1())); + } + + public void testCollectionIterator() { + Collection<String> c = CollectionTools.collection(this.buildStringList1().iterator()); + assertEquals(3, c.size()); + assertTrue(c.containsAll(this.buildStringList1())); + } + + public void testCollectionIterator_ObjectString() { + Collection<Object> c = CollectionTools.<Object>collection(this.buildStringList1().iterator()); + assertEquals(3, c.size()); + assertTrue(c.containsAll(this.buildStringList1())); + } + + public void testCollectionIteratorInt() { + Collection<String> c = CollectionTools.collection(this.buildStringList1().iterator(), 3); + assertEquals(3, c.size()); + assertTrue(c.containsAll(this.buildStringList1())); + } + + public void testCollectionObjectArray() { + Collection<String> c = CollectionTools.collection(this.buildStringArray1()); + assertEquals(3, c.size()); + assertTrue(CollectionTools.containsAll(c, (Object[]) this.buildStringArray1())); + } + + + // ********** contains ********** + + public void testContainsEnumerationObject_String() { + Vector<String> v = this.buildStringVector1(); + assertTrue(CollectionTools.contains(v.elements(), "one")); + assertFalse(CollectionTools.contains(v.elements(), null)); + v.add(null); + assertTrue(CollectionTools.contains(v.elements(), null)); + } + + public void testContainsEnumerationObject_Object() { + Vector<Object> c = new Vector<Object>(); + c.add("zero"); + c.add("one"); + c.add("two"); + c.add("three"); + String one = "one"; + assertTrue(CollectionTools.contains(c.elements(), one)); + assertFalse(CollectionTools.contains(c.elements(), null)); + c.add(null); + assertTrue(CollectionTools.contains(c.elements(), null)); + } + + public void testContainsIterableObject() { + Collection<String> c = this.buildStringList1(); + Iterable<String> iterable = c; + assertTrue(CollectionTools.contains(iterable, "one")); + assertFalse(CollectionTools.contains(iterable, null)); + c.add(null); + assertTrue(CollectionTools.contains(iterable, null)); + } + + public void testContainsIteratorObject_String() { + Collection<String> c = this.buildStringList1(); + assertTrue(CollectionTools.contains(c.iterator(), "one")); + assertFalse(CollectionTools.contains(c.iterator(), null)); + c.add(null); + assertTrue(CollectionTools.contains(c.iterator(), null)); + } + + public void testContainsIteratorObject_Object() { + Collection<Object> c = new HashBag<Object>(); + c.add("zero"); + c.add("one"); + c.add("two"); + c.add("three"); + String one = "one"; + assertTrue(CollectionTools.contains(c.iterator(), one)); + assertFalse(CollectionTools.contains(c.iterator(), null)); + c.add(null); + assertTrue(CollectionTools.contains(c.iterator(), null)); + } + + + // ********** contains all ********** + + public void testContainsAllCollectionIterable() { + Iterable<String> iterable = this.buildStringList1(); + assertTrue(CollectionTools.containsAll(this.buildStringList1(), iterable)); + } + + public void testContainsAllCollectionIterator_String() { + assertTrue(CollectionTools.containsAll(this.buildStringList1(), this.buildStringList1().iterator())); + } + + public void testContainsAllCollectionIterator_Object() { + Collection<Object> c1 = new ArrayList<Object>(); + c1.add("zero"); + c1.add("one"); + c1.add("two"); + Collection<String> c2 = new ArrayList<String>(); + c2.add("two"); + c2.add("zero"); + c2.add("one"); + assertTrue(CollectionTools.containsAll(c1, c2.iterator())); + } + + public void testContainsAllCollectionObjectArray_StringObject() { + assertTrue(CollectionTools.containsAll(this.buildStringList1(), this.buildObjectArray1())); + } + + public void testContainsAllCollectionObjectArray() { + Object[] a = new Object[] { "zero", "one", "two" }; + assertTrue(CollectionTools.containsAll(this.buildStringList1(), a)); + } + + public void testContainsAllIterableCollection() { + Iterable<String> iterable = this.buildStringList1(); + assertTrue(CollectionTools.containsAll(iterable, this.buildStringList1())); + } + + public void testContainsAllIterableIntCollection() { + Iterable<String> iterable = this.buildStringList1(); + assertTrue(CollectionTools.containsAll(iterable, 3, this.buildStringList1())); + } + + public void testContainsAllIterableIterable() { + Iterable<String> iterable1 = this.buildStringList1(); + Iterable<String> iterable2 = this.buildStringList1(); + assertTrue(CollectionTools.containsAll(iterable1, iterable2)); + } + + public void testContainsAllIterableIntIterable() { + Iterable<String> iterable1 = this.buildStringList1(); + Iterable<String> iterable2 = this.buildStringList1(); + assertTrue(CollectionTools.containsAll(iterable1, 3, iterable2)); + } + + public void testContainsAllIterableIterator() { + Iterable<String> iterable = this.buildStringList1(); + assertTrue(CollectionTools.containsAll(iterable, this.buildStringList1().iterator())); + } + + public void testContainsAllIterableIntIterator() { + Iterable<String> iterable = this.buildStringList1(); + assertTrue(CollectionTools.containsAll(iterable, 3, this.buildStringList1().iterator())); + } + + public void testContainsAllIterableObjectArray() { + Iterable<String> iterable = this.buildStringList1(); + assertTrue(CollectionTools.containsAll(iterable, this.buildObjectArray1())); + iterable = this.buildStringList2(); + assertFalse(CollectionTools.containsAll(iterable, this.buildObjectArray1())); + } + + public void testContainsAllIterableIntObjectArray() { + Iterable<String> iterable = this.buildStringList1(); + assertTrue(CollectionTools.containsAll(iterable, 3, this.buildObjectArray1())); + iterable = this.buildStringList2(); + assertFalse(CollectionTools.containsAll(iterable, 3, this.buildObjectArray1())); + } + + public void testContainsAllIteratorCollection_StringString() { + assertTrue(CollectionTools.containsAll(this.buildStringList1().iterator(), this.buildStringList1())); + assertFalse(CollectionTools.containsAll(this.buildStringList1().iterator(), this.buildStringList2())); + } + + public void testContainsAllIteratorCollection_ObjectString() { + Collection<Object> c1 = new ArrayList<Object>(); + c1.add("zero"); + c1.add("one"); + c1.add("two"); + Collection<String> c2 = new ArrayList<String>(); + c2.add("zero"); + c2.add("one"); + c2.add("two"); + assertTrue(CollectionTools.containsAll(c1.iterator(), c2)); + } + + public void testContainsAllIteratorIntCollection() { + assertTrue(CollectionTools.containsAll(this.buildStringList1().iterator(), 5, this.buildStringList1())); + assertFalse(CollectionTools.containsAll(this.buildStringList1().iterator(), 5, this.buildStringList2())); + } + + public void testContainsAllIteratorIterable() { + Iterable<String> iterable = this.buildStringList1(); + assertTrue(CollectionTools.containsAll(this.buildStringList1().iterator(), iterable)); + iterable = this.buildStringList2(); + assertFalse(CollectionTools.containsAll(this.buildStringList1().iterator(), iterable)); + } + + public void testContainsAllIteratorIntIterable() { + Iterable<String> iterable = this.buildStringList1(); + assertTrue(CollectionTools.containsAll(this.buildStringList1().iterator(), 3, iterable)); + iterable = this.buildStringList2(); + assertFalse(CollectionTools.containsAll(this.buildStringList1().iterator(), 3, iterable)); + } + + public void testContainsAllIteratorIterator_StringString() { + assertTrue(CollectionTools.containsAll(this.buildStringList1().iterator(), this.buildStringList1().iterator())); + assertFalse(CollectionTools.containsAll(this.buildStringList1().iterator(), this.buildStringList2().iterator())); + } + + public void testContainsAllIteratorIterator_ObjectString() { + Collection<Object> c1 = new ArrayList<Object>(); + c1.add("zero"); + c1.add("one"); + c1.add("two"); + Collection<String> c2 = new ArrayList<String>(); + c2.add("zero"); + c2.add("one"); + c2.add("two"); + assertTrue(CollectionTools.containsAll(c1.iterator(), c2.iterator())); + } + + public void testContainsAllIteratorIntIterator() { + assertTrue(CollectionTools.containsAll(this.buildStringList1().iterator(), 3, this.buildStringList1().iterator())); + assertFalse(CollectionTools.containsAll(this.buildStringList1().iterator(), 3, this.buildStringList2().iterator())); + } + + public void testContainsAllIteratorObjectArray() { + assertTrue(CollectionTools.containsAll(this.buildStringList1().iterator(), this.buildObjectArray1())); + assertFalse(CollectionTools.containsAll(this.buildStringList1().iterator(), this.buildObjectArray2())); + } + + public void testContainsAllIteratorIntObjectArray() { + assertTrue(CollectionTools.containsAll(this.buildStringList1().iterator(), 3, this.buildObjectArray1())); + assertFalse(CollectionTools.containsAll(this.buildStringList1().iterator(), 3, this.buildObjectArray2())); + } + + + // ********** diff ********** + + public void testDiffEndListList() { + List<String> list1 = new ArrayList<String>(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List<String> list2 = new ArrayList<String>(); + list2.add(new String("a")); + list2.add(new String("b")); + list2.add(new String("c")); + assertEquals(-1, CollectionTools.diffEnd(list1, list2)); + } + + public void testDiffRangeListList() { + List<String> list1 = new ArrayList<String>(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List<String> list2 = new ArrayList<String>(); + list2.add(new String("a")); + list2.add(new String("b")); + list2.add(new String("c")); + assertEquals(new Range(3, -1), CollectionTools.diffRange(list1, list2)); + } + + public void testDiffStartListList() { + List<String> list1 = new ArrayList<String>(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List<String> list2 = new ArrayList<String>(); + list2.add(new String("a")); + list2.add(new String("b")); + list2.add(new String("c")); + assertEquals(3, CollectionTools.diffStart(list1, list2)); + } + + + // ********** identity diff ********** + + public void testIdentityDiffEndListList() { + List<String> list1 = new ArrayList<String>(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List<String> list2 = new ArrayList<String>(); + list2.add("a"); + list2.add("b"); + list2.add("c"); + assertEquals(-1, CollectionTools.identityDiffEnd(list1, list2)); + } + + public void testIdentityDiffRangeListList() { + List<String> list1 = new ArrayList<String>(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List<String> list2 = new ArrayList<String>(); + list2.add("a"); + list2.add("b"); + list2.add("c"); + assertEquals(new Range(3, -1), CollectionTools.identityDiffRange(list1, list2)); + } + + public void testIdentityDiffStartListList() { + List<String> list1 = new ArrayList<String>(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List<String> list2 = new ArrayList<String>(); + list2.add("a"); + list2.add("b"); + list2.add("c"); + assertEquals(3, CollectionTools.identityDiffStart(list1, list2)); + } + + + // ********** elements are equal ********** + + public void testElementsAreDifferentIterableIterable() { + List<String> list1 = new ArrayList<String>(); + list1.add("1000"); + list1.add("2000"); + list1.add("3000"); + list1.add("4000"); + + List<String> list2 = new ArrayList<String>(); + + assertTrue(CollectionTools.elementsAreDifferent(list1, list2)); + assertFalse(CollectionTools.elementsAreEqual(list1, list2)); + } + + public void testElementsAreDifferentIteratorIterator() { + List<String> list1 = new ArrayList<String>(); + list1.add("1000"); + list1.add("2000"); + list1.add("3000"); + list1.add("4000"); + + List<String> list2 = new ArrayList<String>(); + + assertTrue(CollectionTools.elementsAreDifferent(list1.iterator(), list2.iterator())); + assertFalse(CollectionTools.elementsAreEqual(list1, list2)); + } + + public void testElementsAreEqualIterableIterable() { + List<String> list1 = new ArrayList<String>(); + list1.add("1000"); + list1.add("2000"); + list1.add("3000"); + list1.add("4000"); + + List<String> list2 = new ArrayList<String>(); + for (int i = 0; i < list1.size(); i++) { + list2.add(String.valueOf((i + 1) * 1000)); + } + assertFalse(CollectionTools.elementsAreIdentical(list1, list2)); + assertFalse(CollectionTools.elementsAreDifferent(list1, list2)); + assertTrue(CollectionTools.elementsAreEqual(list1, list2)); + } + + public void testElementsAreEqualIteratorIterator() { + List<String> list1 = new ArrayList<String>(); + list1.add("1000"); + list1.add("2000"); + list1.add("3000"); + list1.add("4000"); + + List<String> list2 = new ArrayList<String>(); + for (int i = 0; i < list1.size(); i++) { + list2.add(String.valueOf((i + 1) * 1000)); + } + assertFalse(CollectionTools.elementsAreIdentical(list1.iterator(), list2.iterator())); + assertFalse(CollectionTools.elementsAreDifferent(list1.iterator(), list2.iterator())); + assertTrue(CollectionTools.elementsAreEqual(list1.iterator(), list2.iterator())); + } + + + // ********** elements are identical ********** + + public void testElementsAreIdenticalIterableIterable() { + List<String> list1 = new ArrayList<String>(); + list1.add("0"); + list1.add("1"); + list1.add("2"); + list1.add("3"); + Iterable<String> iterable1 = list1; + + List<String> list2 = new ArrayList<String>(); + for (String s : list1) { + list2.add(s); + } + Iterable<String> iterable2 = list2; + assertTrue(CollectionTools.elementsAreIdentical(iterable1, iterable2)); + assertTrue(CollectionTools.elementsAreEqual(iterable1, iterable2)); + } + + public void testElementsAreIdenticalIteratorIterator() { + List<String> list1 = new ArrayList<String>(); + list1.add("0"); + list1.add("1"); + list1.add("2"); + list1.add("3"); + + List<String> list2 = new ArrayList<String>(); + for (String s : list1) { + list2.add(s); + } + assertTrue(CollectionTools.elementsAreIdentical(list1.iterator(), list2.iterator())); + assertTrue(CollectionTools.elementsAreEqual(list1.iterator(), list2.iterator())); + } + + public void testElementsAreIdenticalIteratorIterator_Not() { + List<String> list1 = new ArrayList<String>(); + list1.add("0"); + list1.add("1"); + list1.add("2"); + list1.add("3"); + + List<String> list2 = new ArrayList<String>(); + for (String s : list1) { + list2.add(s); + } + list2.remove(0); + assertFalse(CollectionTools.elementsAreIdentical(list1.iterator(), list2.iterator())); + assertFalse(CollectionTools.elementsAreEqual(list1.iterator(), list2.iterator())); + } + + public void testElementsAreIdenticalIteratorIterator_DifferentSizes() { + List<String> list1 = new ArrayList<String>(); + list1.add("0"); + list1.add("1"); + list1.add("2"); + list1.add("3"); + + List<String> list2 = new ArrayList<String>(); + for (String s : list1) { + list2.add(s); + } + list2.remove(3); + assertFalse(CollectionTools.elementsAreIdentical(list1.iterator(), list2.iterator())); + assertFalse(CollectionTools.elementsAreEqual(list1.iterator(), list2.iterator())); + } + + + // ********** get ********** + + public void testGetIterableInt() { + List<String> list = this.buildStringList1(); + Iterable<String> iterable = list; + String o = CollectionTools.get(iterable, 1); + assertEquals("one", o); + list.add(null); + o = CollectionTools.get(iterable, 3); + assertNull(o); + } + + public void testGetIteratorInt1() { + List<String> list = this.buildStringList1(); + String o = CollectionTools.get(list.iterator(), 1); + assertEquals("one", o); + list.add(null); + o = CollectionTools.get(list.iterator(), list.size() - 1); + assertNull(o); + } + + public void testGetIteratorInt2() { + List<String> list = this.buildStringList1(); + boolean exCaught = false; + try { + CollectionTools.get(list.iterator(), list.size()); + fail(); + } catch (IndexOutOfBoundsException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + + // ********** hash code ********** + + public void testHashCodeIterable1() { + Iterable<String> iterable = null; + assertEquals(0, CollectionTools.hashCode(iterable)); + } + + public void testHashCodeIterable2() { + List<String> list = this.buildStringList1(); + Iterable<String> iterable = list; + int hashCode = CollectionTools.hashCode(iterable); + assertEquals(list.hashCode(), hashCode); + + list.add(null); + hashCode = CollectionTools.hashCode(iterable); + assertEquals(list.hashCode(), hashCode); + } + + + // ********** index of ********** + + public void testIndexOfIterableObject_String() { + Iterable<String> iterable = this.buildStringList1(); + assertEquals(1, CollectionTools.indexOf(iterable, "one")); + } + + public void testIndexOfIteratorObject_String() { + List<String> list = this.buildStringList1(); + assertEquals(1, CollectionTools.indexOf(list.iterator(), "one")); + } + + public void testIndexOfIteratorObject_String_Not() { + List<String> list = this.buildStringList1(); + assertEquals(-1, CollectionTools.indexOf(list.iterator(), null)); + assertEquals(-1, CollectionTools.indexOf(list.iterator(), "shazam")); + } + + public void testIndexOfIteratorObject_Null() { + List<String> list = this.buildStringList1(); + list.add(null); + assertEquals(list.size() - 1, CollectionTools.indexOf(list.iterator(), null)); + } + + public void testIndexOfIteratorObject_Object() { + List<Object> list = new ArrayList<Object>(); + list.add("0"); + list.add("1"); + list.add("2"); + list.add("3"); + + String one = "1"; + assertEquals(1, CollectionTools.indexOf(list.iterator(), one)); + list.add(null); + assertEquals(list.size() - 1, CollectionTools.indexOf(list.iterator(), null)); + } + + + // ********** insertion index of ********** + + public void testInsertionIndexOfListComparableRandomAccess() { + List<String> list = Arrays.asList(new String[] { "A", "C", "D" }); + assertEquals(1, CollectionTools.insertionIndexOf(list, "B")); + + list = Arrays.asList(new String[] { "A", "B", "C", "D" }); + assertEquals(2, CollectionTools.insertionIndexOf(list, "B")); + + list = Arrays.asList(new String[] { "A", "B", "B", "B", "C", "D" }); + assertEquals(4, CollectionTools.insertionIndexOf(list, "B")); + + list = Arrays.asList(new String[] { "A", "B", "B", "B", "C", "D" }); + assertEquals(6, CollectionTools.insertionIndexOf(list, "E")); + + list = Arrays.asList(new String[] { "B", "B", "B", "C", "D" }); + assertEquals(0, CollectionTools.insertionIndexOf(list, "A")); + + list = Arrays.asList(new String[] { "A", "A", "B", "B", "C", "D" }); + assertEquals(2, CollectionTools.insertionIndexOf(list, "A")); + } + + public void testInsertionIndexOfListComparableNonRandomAccess() { + List<String> list = new LinkedList<String>(Arrays.asList(new String[] { "A", "C", "D" })); + assertEquals(1, CollectionTools.insertionIndexOf(list, "B")); + + list = new LinkedList<String>(Arrays.asList(new String[] { "A", "B", "C", "D" })); + assertEquals(1, CollectionTools.insertionIndexOf(list, "B")); + + list = new LinkedList<String>(Arrays.asList(new String[] { "A", "B", "B", "B", "C", "D" })); + assertEquals(1, CollectionTools.insertionIndexOf(list, "B")); + + list = new LinkedList<String>(Arrays.asList(new String[] { "A", "B", "B", "B", "C", "D" })); + assertEquals(6, CollectionTools.insertionIndexOf(list, "E")); + + list = new LinkedList<String>(Arrays.asList(new String[] { "B", "B", "B", "C", "D" })); + assertEquals(0, CollectionTools.insertionIndexOf(list, "A")); + + list = new LinkedList<String>(Arrays.asList(new String[] { "A", "A", "B", "B", "C", "D" })); + assertEquals(0, CollectionTools.insertionIndexOf(list, "A")); + } + + public void testInsertionIndexOfListObjectComparatorRandomAccess() { + Comparator<String> c = new ReverseComparator<String>(); + List<String> list = Arrays.asList(new String[] { "D", "C", "A" }); + assertEquals(2, CollectionTools.insertionIndexOf(list, "B", c)); + + list = Arrays.asList(new String[] { "D", "C", "B", "A" }); + assertEquals(3, CollectionTools.insertionIndexOf(list, "B", c)); + + list = Arrays.asList(new String[] { "D", "C", "B", "B", "B", "A" }); + assertEquals(5, CollectionTools.insertionIndexOf(list, "B", c)); + + list = Arrays.asList(new String[] { "D", "C", "B", "B", "B", "A" }); + assertEquals(0, CollectionTools.insertionIndexOf(list, "E", c)); + + list = Arrays.asList(new String[] { "D", "C", "B", "B", "B" }); + assertEquals(5, CollectionTools.insertionIndexOf(list, "A", c)); + + list = Arrays.asList(new String[] { "D", "C", "B", "B", "A", "A" }); + assertEquals(6, CollectionTools.insertionIndexOf(list, "A", c)); + } + + public void testInsertionIndexOfListObjectComparatorNonRandomAccess() { + Comparator<String> c = new ReverseComparator<String>(); + List<String> list = new LinkedList<String>(Arrays.asList(new String[] { "D", "C", "A" })); + assertEquals(2, CollectionTools.insertionIndexOf(list, "B", c)); + + list = new LinkedList<String>(Arrays.asList(new String[] { "D", "C", "B", "A" })); + assertEquals(2, CollectionTools.insertionIndexOf(list, "B", c)); + + list = new LinkedList<String>(Arrays.asList(new String[] { "D", "C", "B", "B", "B", "A" })); + assertEquals(2, CollectionTools.insertionIndexOf(list, "B", c)); + + list = new LinkedList<String>(Arrays.asList(new String[] { "D", "C", "B", "B", "B", "A" })); + assertEquals(0, CollectionTools.insertionIndexOf(list, "E", c)); + + list = new LinkedList<String>(Arrays.asList(new String[] { "D", "C", "B", "B", "B" })); + assertEquals(5, CollectionTools.insertionIndexOf(list, "A", c)); + + list = new LinkedList<String>(Arrays.asList(new String[] { "D", "C", "B", "B", "A", "A" })); + assertEquals(4, CollectionTools.insertionIndexOf(list, "A", c)); + } + + + // ********** is empty ********** + + public void testIsEmptyIterable() { + assertFalse(CollectionTools.isEmpty(buildObjectList1())); + assertTrue(CollectionTools.isEmpty(EmptyIterable.instance())); + } + + public void testIsEmptyIterator() { + assertFalse(CollectionTools.isEmpty(buildObjectList1().iterator())); + assertTrue(CollectionTools.isEmpty(EmptyIterator.instance())); + } + + + // ********** iterable/iterator ********** + + public void testIterableObjectArray() { + String[] strings = this.buildStringArray1(); + int i = 0; + for (String string : CollectionTools.iterable(strings)) { + assertEquals(strings[i++], string); + } + } + + public void testIteratorObjectArray() { + String[] a = this.buildStringArray1(); + int i = 0; + for (Iterator<String> stream = CollectionTools.iterator(a); stream.hasNext(); i++) { + assertEquals(a[i], stream.next()); + } + } + + + // ********** last ********** + + public void testLastIterable1() { + List<String> list = this.buildStringList1(); + Iterable<String> iterable = list; + assertEquals("two", CollectionTools.last(iterable)); + list.add(null); + assertEquals(null, CollectionTools.last(iterable)); + } + + public void testLastIterable2() { + Iterable<String> iterable = new ArrayList<String>(); + boolean exCaught = false; + try { + CollectionTools.last(iterable); + fail(); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testLastIterator1() { + List<String> list = this.buildStringList1(); + assertEquals("two", CollectionTools.last(list.iterator())); + list.add(null); + assertEquals(null, CollectionTools.last(list.iterator())); + } + + public void testLastIterator2() { + List<String> list = new ArrayList<String>(); + boolean exCaught = false; + try { + CollectionTools.last(list.iterator()); + fail(); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + + // ********** last index of ********** + + public void testLastIndexOfIterableObject() { + List<String> list = this.buildStringList1(); + Iterable<String> iterable = list; + assertEquals(1, CollectionTools.lastIndexOf(iterable, "one")); + list.add(null); + assertEquals(list.size() - 1, CollectionTools.lastIndexOf(iterable, null)); + } + + public void testLastIndexOfIterableIntObject() { + List<String> list = this.buildStringList1(); + Iterable<String> iterable = list; + assertEquals(1, CollectionTools.lastIndexOf(iterable, 23, "one")); + list.add(null); + assertEquals(list.size() - 1, CollectionTools.lastIndexOf(iterable, 42, null)); + } + + public void testLastIndexOfIteratorObject() { + List<String> list = this.buildStringList1(); + assertEquals(1, CollectionTools.lastIndexOf(list.iterator(), "one")); + list.add(null); + assertEquals(list.size() - 1, CollectionTools.lastIndexOf(list.iterator(), null)); + } + + public void testLastIndexOfIteratorObject_Empty() { + assertEquals(-1, CollectionTools.lastIndexOf(EmptyIterator.instance(), "foo")); + } + + public void testLastIndexOfIteratorIntObject() { + List<String> list = this.buildStringList1(); + assertEquals(1, CollectionTools.lastIndexOf(list.iterator(), 3, "one")); + list.add(null); + assertEquals(list.size() - 1, CollectionTools.lastIndexOf(list.iterator(), 4, null)); + } + + public void testLastIndexOfIteratorIntObject_Empty() { + assertEquals(-1, CollectionTools.lastIndexOf(EmptyIterator.instance(), 42, "foo")); + } + + + // ********** list ********** + + public void testListIterable() { + Iterable<String> iterable = this.buildStringList1(); + assertEquals(this.buildStringList1(), CollectionTools.list(iterable)); + } + + public void testListIterableInt() { + Iterable<String> iterable = this.buildStringList1(); + assertEquals(this.buildStringList1(), CollectionTools.list(iterable, 3)); + } + + public void testListIterator_String() { + List<String> list = CollectionTools.list(this.buildStringList1().iterator()); + assertEquals(this.buildStringList1(), list); + } + + public void testListIterator_StringObject() { + List<String> list1 = new ArrayList<String>(); + list1.add("0"); + list1.add("1"); + list1.add("2"); + list1.add("3"); + + List<Object> list2 = CollectionTools.<Object>list(list1.iterator()); + assertEquals(list1, list2); + } + + public void testListIterator_Empty() { + assertEquals(0, CollectionTools.list(EmptyIterator.instance()).size()); + } + + public void testListIteratorInt() { + List<String> list = CollectionTools.list(this.buildStringList1().iterator(), 3); + assertEquals(this.buildStringList1(), list); + } + + public void testListIteratorInt_Empty() { + assertEquals(0, CollectionTools.list(EmptyIterator.instance(), 5).size()); + } + + public void testListObjectArray() { + List<String> list = CollectionTools.list(this.buildStringArray1()); + assertEquals(this.buildStringList1(), list); + } + + public void testListIteratorObjectArray() { + String[] a = this.buildStringArray1(); + int i = 0; + for (ListIterator<String> stream = CollectionTools.listIterator(a); stream.hasNext(); i++) { + assertEquals(a[i], stream.next()); + } + } + + public void testListIteratorObjectArrayInt() { + String[] a = this.buildStringArray1(); + int i = 1; + for (ListIterator<String> stream = CollectionTools.listIterator(a, 1); stream.hasNext(); i++) { + assertEquals(a[i], stream.next()); + } + } + + + // ********** move ********** + + public void testMoveListIntIntRandomAccess() { + List<String> list = new ArrayList<String>(); + CollectionTools.addAll(list, new String[] { "0", "1", "2", "3", "4", "5" }); + + List<String> result = CollectionTools.move(list, 4, 2); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "0", "1", "3", "4", "2", "5" }, result.toArray())); + + result = CollectionTools.move(list, 0, 5); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "1", "3", "4", "2" }, result.toArray())); + + result = CollectionTools.move(list, 2, 4); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "4", "1", "3", "2" }, result.toArray())); + + result = CollectionTools.move(list, 2, 2); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "4", "1", "3", "2" }, result.toArray())); + } + + public void testMoveListIntIntSequentialAccess() { + List<String> list = new LinkedList<String>(); + CollectionTools.addAll(list, new String[] { "0", "1", "2", "3", "4", "5" }); + + List<String> result = CollectionTools.move(list, 4, 2); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "0", "1", "3", "4", "2", "5" }, result.toArray())); + + result = CollectionTools.move(list, 0, 5); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "1", "3", "4", "2" }, result.toArray())); + + result = CollectionTools.move(list, 2, 4); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "4", "1", "3", "2" }, result.toArray())); + + result = CollectionTools.move(list, 2, 2); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "4", "1", "3", "2" }, result.toArray())); + } + + public void testMoveListIntIntIntRandomAccess() { + List<String> list = new ArrayList<String>(Arrays.asList(new String[] { "0", "1", "2", "3", "4", "5" })); + + List<String> result = CollectionTools.move(list, 4, 2, 1); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "0", "1", "3", "4", "2", "5" }, result.toArray())); + + result = CollectionTools.move(list, 0, 5, 1); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "1", "3", "4", "2" }, result.toArray())); + + result = CollectionTools.move(list, 2, 4, 1); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "4", "1", "3", "2" }, result.toArray())); + + result = CollectionTools.move(list, 2, 4, 2); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result.toArray())); + + result = CollectionTools.move(list, 0, 1, 4); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "0", "3", "2", "4", "5", "1" }, result.toArray())); + + result = CollectionTools.move(list, 1, 0, 4); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result.toArray())); + + result = CollectionTools.move(list, 1, 1, 4); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result.toArray())); + + result = CollectionTools.move(list, 1, 0, 0); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result.toArray())); + } + + public void testMoveListIntIntIntSequentialAccess() { + List<String> list = new LinkedList<String>(Arrays.asList(new String[] { "0", "1", "2", "3", "4", "5" })); + + List<String> result = CollectionTools.move(list, 4, 2, 1); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "0", "1", "3", "4", "2", "5" }, result.toArray())); + + result = CollectionTools.move(list, 0, 5, 1); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "1", "3", "4", "2" }, result.toArray())); + + result = CollectionTools.move(list, 2, 4, 1); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "4", "1", "3", "2" }, result.toArray())); + + result = CollectionTools.move(list, 2, 4, 2); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result.toArray())); + + result = CollectionTools.move(list, 0, 1, 4); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "0", "3", "2", "4", "5", "1" }, result.toArray())); + + result = CollectionTools.move(list, 1, 0, 4); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result.toArray())); + + result = CollectionTools.move(list, 1, 1, 4); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result.toArray())); + + result = CollectionTools.move(list, 1, 0, 0); + assertSame(list, result); // the array is modified in place and returned + assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result.toArray())); + } + + + // ********** remove all ********** + + public void testRemoveAllCollectionIterable() { + Collection<String> c = this.buildStringList1(); + Iterable<String> iterable = this.buildStringList1(); + assertTrue(CollectionTools.removeAll(c, iterable)); + assertEquals(0, c.size()); + assertFalse(c.contains("one")); + assertFalse(c.contains("two")); + assertFalse(c.contains("three")); + + c = this.buildStringList1(); + iterable = this.buildStringList2(); + assertFalse(CollectionTools.removeAll(c, iterable)); + assertEquals(this.buildStringList1().size(), c.size()); + assertEquals(this.buildStringList1(), c); + } + + public void testRemoveAllCollectionIterableInt() { + Collection<String> c = this.buildStringList1(); + Iterable<String> iterable = this.buildStringList1(); + assertTrue(CollectionTools.removeAll(c, iterable, 4)); + assertEquals(0, c.size()); + assertFalse(c.contains("one")); + assertFalse(c.contains("two")); + assertFalse(c.contains("three")); + + c = this.buildStringList1(); + iterable = this.buildStringList2(); + assertFalse(CollectionTools.removeAll(c, iterable, 55)); + assertEquals(this.buildStringList1().size(), c.size()); + assertEquals(this.buildStringList1(), c); + } + + public void testRemoveAllCollectionIterator_Empty() { + Collection<String> c = this.buildStringList1(); + assertTrue(CollectionTools.removeAll(c, this.buildStringList1().iterator())); + assertEquals(0, c.size()); + assertFalse(c.contains("one")); + assertFalse(c.contains("two")); + assertFalse(c.contains("three")); + + c = this.buildStringList1(); + assertFalse(CollectionTools.removeAll(c, this.buildStringList2().iterator())); + assertEquals(this.buildStringList1().size(), c.size()); + assertEquals(this.buildStringList1(), c); + + c = this.buildStringList1(); + assertFalse(CollectionTools.removeAll(c, EmptyIterator.instance())); + assertEquals(this.buildStringList1().size(), c.size()); + assertEquals(this.buildStringList1(), c); + } + + public void testRemoveAllCollectionIteratorInt_Empty() { + Collection<String> c = this.buildStringList1(); + assertTrue(CollectionTools.removeAll(c, this.buildStringList1().iterator(), 5)); + assertEquals(0, c.size()); + assertFalse(c.contains("one")); + assertFalse(c.contains("two")); + assertFalse(c.contains("three")); + + c = this.buildStringList1(); + assertFalse(CollectionTools.removeAll(c, this.buildStringList2().iterator(), 5)); + assertEquals(this.buildStringList1().size(), c.size()); + assertEquals(this.buildStringList1(), c); + + c = this.buildStringList1(); + assertFalse(CollectionTools.removeAll(c, EmptyIterator.instance(), 0)); + assertEquals(this.buildStringList1().size(), c.size()); + assertEquals(this.buildStringList1(), c); + } + + public void testRemoveAllCollectionIterator_Duplicates() { + Collection<String> c = new ArrayList<String>(); + c.add("a"); + c.add("a"); + c.add("b"); + c.add("c"); + c.add("d"); + c.add("d"); + String[] a = new String[] { "a", "d" }; + Iterator<String> iterator = new ArrayIterator<String>(a); + assertTrue(CollectionTools.removeAll(c, iterator)); + assertEquals(2, c.size()); + assertFalse(c.contains("a")); + assertTrue(c.contains("b")); + assertTrue(c.contains("c")); + assertFalse(c.contains("d")); + + iterator = new ArrayIterator<String>(a); + assertFalse(CollectionTools.removeAll(c, iterator)); + } + + public void testRemoveAllCollectionIterator_ObjectString() { + Collection<Object> c = new ArrayList<Object>(); + c.add("a"); + c.add("a"); + c.add("b"); + c.add("c"); + c.add("d"); + c.add("d"); + String[] a = new String[] { "a", "d" }; + Iterator<String> iterator = new ArrayIterator<String>(a); + assertTrue(CollectionTools.removeAll(c, iterator)); + assertEquals(2, c.size()); + assertFalse(c.contains("a")); + assertTrue(c.contains("b")); + assertTrue(c.contains("c")); + assertFalse(c.contains("d")); + + iterator = new ArrayIterator<String>(a); + assertFalse(CollectionTools.removeAll(c, iterator)); + } + + public void testRemoveAllCollectionObjectArray_Empty() { + Collection<String> c = this.buildStringList1(); + assertTrue(CollectionTools.removeAll(c, this.buildObjectArray1())); + assertEquals(0, c.size()); + assertFalse(c.contains("one")); + assertFalse(c.contains("two")); + assertFalse(c.contains("three")); + + c = this.buildStringList1(); + assertFalse(CollectionTools.removeAll(c, this.buildObjectArray2())); + assertEquals(this.buildStringList1().size(), c.size()); + assertEquals(this.buildStringList1(), c); + + c = this.buildStringList1(); + assertFalse(CollectionTools.removeAll(c, new Object[0])); + assertEquals(this.buildStringList1().size(), c.size()); + assertEquals(this.buildStringList1(), c); + } + + public void testRemoveAllCollectionObjectArray_Duplicates() { + Collection<String> c = new ArrayList<String>(); + c.add("a"); + c.add("a"); + c.add("b"); + c.add("c"); + c.add("d"); + c.add("d"); + String[] a = new String[] { "a", "d" }; + assertTrue(CollectionTools.removeAll(c, (Object[]) a)); + assertEquals(2, c.size()); + assertFalse(c.contains("a")); + assertTrue(c.contains("b")); + assertTrue(c.contains("c")); + assertFalse(c.contains("d")); + + assertFalse(CollectionTools.removeAll(c,(Object[]) a)); + } + + public void testRemoveAllCollectionObjectArray_MoreDuplicates() { + Collection<String> c = new ArrayList<String>(); + c.add("a"); + c.add("b"); + c.add("c"); + c.add("d"); + c.add("a"); + c.add("d"); + c.add("d"); + c.add("a"); + c.add("c"); + String[] a = new String[] { "a", "d" }; + assertTrue(CollectionTools.removeAll(c, (Object[]) a)); + assertEquals(3, c.size()); + assertFalse(c.contains("a")); + assertTrue(c.contains("b")); + assertTrue(c.contains("c")); + assertFalse(c.contains("d")); + + assertFalse(CollectionTools.removeAll(c, (Object[]) a)); + } + + + // ********** remove all occurrences ********** + + public void testRemoveAllOccurrencesCollectionObject() { + Collection<String> c = this.buildStringList1(); + assertEquals(3, c.size()); + assertFalse(CollectionTools.removeAllOccurrences(c, "three")); + assertTrue(CollectionTools.removeAllOccurrences(c, "two")); + assertFalse(CollectionTools.removeAllOccurrences(c, "two")); + assertEquals(2, c.size()); + + c.add("five"); + c.add("five"); + c.add("five"); + assertEquals(5, c.size()); + assertTrue(CollectionTools.removeAllOccurrences(c, "five")); + assertFalse(CollectionTools.removeAllOccurrences(c, "five")); + assertEquals(2, c.size()); + + c.add(null); + c.add(null); + c.add(null); + assertEquals(5, c.size()); + assertTrue(CollectionTools.removeAllOccurrences(c, null)); + assertFalse(CollectionTools.removeAllOccurrences(c, null)); + assertEquals(2, c.size()); + } + + + // ********** remove elements at index ********** + + public void testRemoveElementsAtIndexListIntInt() { + List<String> list = new ArrayList<String>(Arrays.asList(new String[] { "A", "B", "A", "C", "A", "D" })); + List<String> removed = CollectionTools.removeElementsAtIndex(list, 3, 2); + assertTrue(Arrays.equals(new String[] { "A", "B", "A", "D" }, list.toArray())); + assertTrue(Arrays.equals(new String[] { "C", "A" }, removed.toArray())); + + list = new ArrayList<String>(Arrays.asList(new String[] { "A", "B", "C", "D", "E", "F" })); + removed = CollectionTools.removeElementsAtIndex(list, 3, 3); + assertTrue(Arrays.equals(new String[] { "A", "B", "C" }, list.toArray())); + assertTrue(Arrays.equals(new String[] { "D", "E", "F" }, removed.toArray())); + + list = new ArrayList<String>(Arrays.asList(new String[] { "A", "B", "C", "D", "E", "F" })); + removed = CollectionTools.removeElementsAtIndex(list, 0, 3); + assertTrue(Arrays.equals(new String[] { "D", "E", "F" }, list.toArray())); + assertTrue(Arrays.equals(new String[] { "A", "B", "C" }, removed.toArray())); + } + + + // ********** remove duplicate elements ********** + + public void testRemoveDuplicateElementsList1() { + List<String> list = this.buildStringVector1(); + list.add("zero"); + list.add("zero"); + list.add("two"); + list.add("zero"); + assertTrue(CollectionTools.removeDuplicateElements(list)); + int i = 0; + assertEquals("zero", list.get(i++)); + assertEquals("one", list.get(i++)); + assertEquals("two", list.get(i++)); + assertEquals(i, list.size()); + } + + public void testRemoveDuplicateElementsList2() { + List<String> list = this.buildStringVector1(); + assertFalse(CollectionTools.removeDuplicateElements(list)); + int i = 0; + assertEquals("zero", list.get(i++)); + assertEquals("one", list.get(i++)); + assertEquals("two", list.get(i++)); + assertEquals(i, list.size()); + } + + public void testRemoveDuplicateElementsList_Empty() { + List<String> list = new ArrayList<String>(); + assertFalse(CollectionTools.removeDuplicateElements(list)); + assertEquals(0, list.size()); + } + + public void testRemoveDuplicateElementsList_SingleElement() { + List<String> list = new ArrayList<String>(); + list.add("zero"); + assertFalse(CollectionTools.removeDuplicateElements(list)); + assertEquals(1, list.size()); + } + + + // ********** retain all ********** + + public void testRetainAllCollectionIterable() { + Collection<String> c = this.buildStringList1(); + Iterable<String> iterable = this.buildStringList1(); + assertFalse(CollectionTools.retainAll(c, iterable)); + assertEquals(this.buildStringList1().size(), c.size()); + assertEquals(this.buildStringList1(), c); + + iterable = this.buildStringList2(); + assertTrue(CollectionTools.retainAll(c, iterable)); + assertEquals(0, c.size()); + assertFalse(c.contains("one")); + assertFalse(c.contains("two")); + assertFalse(c.contains("three")); + } + + public void testRetainAllCollectionIterableInt() { + Collection<String> c = this.buildStringList1(); + Iterable<String> iterable = this.buildStringList1(); + assertFalse(CollectionTools.retainAll(c, iterable)); + assertEquals(this.buildStringList1().size(), c.size()); + assertEquals(this.buildStringList1(), c); + + iterable = this.buildStringList2(); + assertTrue(CollectionTools.retainAll(c, iterable, 7)); + assertEquals(0, c.size()); + assertFalse(c.contains("one")); + assertFalse(c.contains("two")); + assertFalse(c.contains("three")); + } + + public void testRetainAllCollectionIterator() { + Collection<String> c = this.buildStringList1(); + assertFalse(CollectionTools.retainAll(c, this.buildStringList1().iterator())); + assertEquals(this.buildStringList1().size(), c.size()); + assertEquals(this.buildStringList1(), c); + + assertTrue(CollectionTools.retainAll(c, this.buildStringList2().iterator())); + assertEquals(0, c.size()); + assertFalse(c.contains("one")); + assertFalse(c.contains("two")); + assertFalse(c.contains("three")); + } + + public void testRetainAllCollectionIterator_ObjectString() { + Collection<Object> c1 = new ArrayList<Object>(); + c1.add("zero"); + c1.add("one"); + c1.add("two"); + + Collection<String> c2 = new ArrayList<String>(); + c2.add("zero"); + c2.add("one"); + c2.add("two"); + + assertFalse(CollectionTools.retainAll(c1, c2.iterator())); + assertEquals(c2.size(), c1.size()); + assertEquals(c2, c1); + + Collection<String> c3 = new ArrayList<String>(); + c3.add("three"); + c3.add("four"); + c3.add("five"); + } + + public void testRetainAllCollectionIterator_EmptyIterator() { + Collection<String> c = this.buildStringList1(); + assertTrue(CollectionTools.retainAll(c, EmptyIterator.instance())); + assertEquals(0, c.size()); + } + + public void testRetainAllCollectionIterator_EmptyCollection() { + Collection<String> c = new ArrayList<String>(); + assertFalse(CollectionTools.retainAll(c, this.buildStringList1().iterator())); + assertEquals(0, c.size()); + } + + public void testRetainAllCollectionIterator_EmptyCollectionEmptyIterator() { + Collection<String> c = new ArrayList<String>(); + assertFalse(CollectionTools.retainAll(c, EmptyIterator.instance())); + assertEquals(0, c.size()); + } + + public void testRetainAllCollectionIteratorInt() { + Collection<String> c = this.buildStringList1(); + assertFalse(CollectionTools.retainAll(c, this.buildStringList1().iterator(), 8)); + assertEquals(this.buildStringList1().size(), c.size()); + assertEquals(this.buildStringList1(), c); + + assertTrue(CollectionTools.retainAll(c, this.buildStringList2().iterator(), 9)); + assertEquals(0, c.size()); + assertFalse(c.contains("one")); + assertFalse(c.contains("two")); + assertFalse(c.contains("three")); + } + + public void testRetainAllCollectionIteratorInt_EmptyIterator() { + Collection<String> c = this.buildStringList1(); + assertTrue(CollectionTools.retainAll(c, EmptyIterator.instance(), 0)); + assertEquals(0, c.size()); + } + + public void testRetainAllCollectionIteratorInt_EmptyCollection() { + Collection<String> c = new ArrayList<String>(); + assertFalse(CollectionTools.retainAll(c, this.buildStringList1().iterator(), 3)); + assertEquals(0, c.size()); + } + + public void testRetainAllCollectionIteratorInt_EmptyCollectionEmptyIterator() { + Collection<String> c = new ArrayList<String>(); + assertFalse(CollectionTools.retainAll(c, EmptyIterator.instance(), 0)); + assertEquals(0, c.size()); + } + + public void testRetainAllCollectionObjectArray() { + Collection<String> c = this.buildStringList1(); + assertFalse(CollectionTools.retainAll(c, this.buildObjectArray1())); + assertEquals(this.buildStringList1().size(), c.size()); + assertEquals(this.buildStringList1(), c); + + assertTrue(CollectionTools.retainAll(c, this.buildObjectArray2())); + assertEquals(0, c.size()); + assertFalse(c.contains("one")); + assertFalse(c.contains("two")); + assertFalse(c.contains("three")); + } + + public void testRetainAllCollectionObjectArray_EmptyObjectArray() { + Collection<String> c = this.buildStringList1(); + assertTrue(CollectionTools.retainAll(c, new Object[0])); + assertEquals(0, c.size()); + } + + public void testRetainAllCollectionObjectArray_EmptyCollection() { + Collection<String> c = new ArrayList<String>(); + assertFalse(CollectionTools.retainAll(c, (Object[]) new String[] { "foo" })); + assertEquals(0, c.size()); + } + + public void testRetainAllCollectionObjectArray_EmptyCollectionEmptyObjectArray() { + Collection<String> c = new ArrayList<String>(); + assertFalse(CollectionTools.retainAll(c, (Object[]) new String[0])); + assertEquals(0, c.size()); + } + + + // ********** reverse list ********** + + public void testReverseListIterable() { + Iterable<String> iterable = this.buildStringList1(); + List<String> actual = CollectionTools.reverseList(iterable); + List<String> expected = this.buildStringList1(); + Collections.reverse(expected); + assertEquals(expected, actual); + } + + public void testReverseListIterableInt() { + Iterable<String> iterable = this.buildStringList1(); + List<String> actual = CollectionTools.reverseList(iterable, 10); + List<String> expected = this.buildStringList1(); + Collections.reverse(expected); + assertEquals(expected, actual); + } + + public void testReverseListIterator_String() { + List<String> actual = CollectionTools.reverseList(this.buildStringList1().iterator()); + List<String> expected = this.buildStringList1(); + Collections.reverse(expected); + assertEquals(expected, actual); + } + + public void testReverseListIterator_Object() { + List<Object> actual = CollectionTools.<Object>reverseList(this.buildStringList1().iterator()); + List<Object> expected = this.buildObjectList1(); + Collections.reverse(expected); + assertEquals(expected, actual); + } + + public void testReverseListIteratorInt() { + List<String> actual = CollectionTools.reverseList(this.buildStringList1().iterator(), 33); + List<String> expected = this.buildStringList1(); + Collections.reverse(expected); + assertEquals(expected, actual); + } + + + // ********** rotate ********** + + public void testRotateList() { + List<String> actual = CollectionTools.rotate(this.buildStringList1()); + List<String> expected = this.buildStringList1(); + Collections.rotate(expected, 1); + assertEquals(expected, actual); + } + + + // ********** set ********** + + public void testSetIterable() { + Iterable<String> iterable = this.buildStringSet1(); + assertEquals(this.buildStringSet1(), CollectionTools.set(iterable)); + } + + public void testSetIterableInt() { + Iterable<String> iterable = this.buildStringSet1(); + assertEquals(this.buildStringSet1(), CollectionTools.set(iterable, 22)); + } + + public void testSetIterator_String() { + assertEquals(this.buildStringSet1(), CollectionTools.set(this.buildStringSet1().iterator())); + } + + public void testSetIterator_Object() { + List<String> list = new ArrayList<String>(); + list.add("0"); + list.add("1"); + list.add("2"); + list.add("3"); + list.add("0"); + list.add("1"); + list.add("2"); + list.add("3"); + Set<String> set = new HashSet<String>(); + set.addAll(list); + + assertEquals(set, CollectionTools.<Object>set(list.iterator())); + } + + public void testSetIteratorInt() { + assertEquals(this.buildStringSet1(), CollectionTools.set(this.buildStringSet1().iterator(), 3)); + } + + public void testSetObjectArray() { + assertEquals(this.buildStringSet1(), CollectionTools.set(this.buildStringSet1().toArray())); + } + + + // ********** singleton iterator ********** + + public void testSingletonIterator_String() { + Iterator<String> stream = CollectionTools.singletonIterator("foo"); + assertTrue(stream.hasNext()); + assertEquals("foo", stream.next()); + } + + public void testSingletonIterator_Object() { + Iterator<Object> stream = CollectionTools.<Object>singletonIterator("foo"); + assertTrue(stream.hasNext()); + assertEquals("foo", stream.next()); + } + + public void testSingletonIterator_Cast() { + Iterator<Object> stream = CollectionTools.singletonIterator((Object) "foo"); + assertTrue(stream.hasNext()); + assertEquals("foo", stream.next()); + } + + public void testSingletonListIterator_String() { + ListIterator<String> stream = CollectionTools.singletonListIterator("foo"); + assertTrue(stream.hasNext()); + assertEquals("foo", stream.next()); + assertFalse(stream.hasNext()); + assertTrue(stream.hasPrevious()); + assertEquals("foo", stream.previous()); + } + + + // ********** size ********** + + public void testSizeIterable() { + Iterable<Object> iterable = this.buildObjectList1(); + assertEquals(3, CollectionTools.size(iterable)); + } + + public void testSizeIterator() { + assertEquals(3, CollectionTools.size(this.buildObjectList1().iterator())); + } + + + // ********** sort ********** + + public void testSortIterable() { + ArrayList<String> list = new ArrayList<String>(); + list.add("0"); + list.add("2"); + list.add("3"); + list.add("1"); + + SortedSet<String> ss = new TreeSet<String>(); + ss.addAll(list); + + Iterable<String> iterable1 = list; + Iterable<String> iterable2 = CollectionTools.<String>sort(iterable1); + assertTrue(CollectionTools.elementsAreEqual(ss, iterable2)); + } + + public void testSortIterableInt() { + ArrayList<String> list = new ArrayList<String>(); + list.add("0"); + list.add("2"); + list.add("3"); + list.add("1"); + + SortedSet<String> ss = new TreeSet<String>(); + ss.addAll(list); + + Iterable<String> iterable1 = list; + Iterable<String> iterable2 = CollectionTools.<String>sort(iterable1, 77); + assertTrue(CollectionTools.elementsAreEqual(ss, iterable2)); + } + + public void testSortIterableComparator() { + ArrayList<String> list = new ArrayList<String>(); + list.add("0"); + list.add("2"); + list.add("3"); + list.add("1"); + + SortedSet<String> ss = new TreeSet<String>(new ReverseComparator<String>()); + ss.addAll(list); + + Iterable<String> iterable1 = list; + Iterable<String> iterable2 = CollectionTools.<String>sort(iterable1, new ReverseComparator<String>()); + assertTrue(CollectionTools.elementsAreEqual(ss, iterable2)); + } + + public void testSortIterableComparatorInt() { + ArrayList<String> list = new ArrayList<String>(); + list.add("0"); + list.add("2"); + list.add("3"); + list.add("1"); + + SortedSet<String> ss = new TreeSet<String>(new ReverseComparator<String>()); + ss.addAll(list); + + Iterable<String> iterable1 = list; + Iterable<String> iterable2 = CollectionTools.<String>sort(iterable1, new ReverseComparator<String>(), 77); + assertTrue(CollectionTools.elementsAreEqual(ss, iterable2)); + } + + public void testSortIterator() { + ArrayList<String> list = new ArrayList<String>(); + list.add("0"); + list.add("2"); + list.add("3"); + list.add("1"); + + SortedSet<String> ss = new TreeSet<String>(); + ss.addAll(list); + + Iterator<String> iterator1 = list.iterator(); + Iterator<String> iterator2 = CollectionTools.<String>sort(iterator1); + assertTrue(CollectionTools.elementsAreEqual(ss.iterator(), iterator2)); + } + + public void testSortIteratorInt() { + ArrayList<String> list = new ArrayList<String>(); + list.add("0"); + list.add("2"); + list.add("3"); + list.add("1"); + + SortedSet<String> ss = new TreeSet<String>(); + ss.addAll(list); + + Iterator<String> iterator1 = list.iterator(); + Iterator<String> iterator2 = CollectionTools.<String>sort(iterator1, 77); + assertTrue(CollectionTools.elementsAreEqual(ss.iterator(), iterator2)); + } + + public void testSortIteratorComparator() { + ArrayList<String> list = new ArrayList<String>(); + list.add("0"); + list.add("2"); + list.add("3"); + list.add("1"); + + SortedSet<String> ss = new TreeSet<String>(new ReverseComparator<String>()); + ss.addAll(list); + + Iterator<String> iterator1 = list.iterator(); + Iterator<String> iterator2 = CollectionTools.<String>sort(iterator1, new ReverseComparator<String>()); + assertTrue(CollectionTools.elementsAreEqual(ss.iterator(), iterator2)); + } + + public void testSortIteratorComparatorInt() { + ArrayList<String> list = new ArrayList<String>(); + list.add("0"); + list.add("2"); + list.add("3"); + list.add("1"); + + SortedSet<String> ss = new TreeSet<String>(new ReverseComparator<String>()); + ss.addAll(list); + + Iterator<String> iterator1 = list.iterator(); + Iterator<String> iterator2 = CollectionTools.<String>sort(iterator1, new ReverseComparator<String>(), 77); + assertTrue(CollectionTools.elementsAreEqual(ss.iterator(), iterator2)); + } + + + // ********** sorted set ********** + + public void testSortedSetIterable() { + ArrayList<String> list = new ArrayList<String>(); + list.add("0"); + list.add("2"); + list.add("3"); + list.add("1"); + + SortedSet<String> ss1 = new TreeSet<String>(); + ss1.addAll(list); + + Iterable<String> iterable = list; + SortedSet<String> ss2 = CollectionTools.<String>sortedSet(iterable); + assertEquals(ss1, ss2); + } + + public void testSortedSetIterableInt() { + ArrayList<String> list = new ArrayList<String>(); + list.add("0"); + list.add("2"); + list.add("3"); + list.add("1"); + + SortedSet<String> ss1 = new TreeSet<String>(); + ss1.addAll(list); + + Iterable<String> iterable = list; + SortedSet<String> ss2 = CollectionTools.<String>sortedSet(iterable, 5); + assertEquals(ss1, ss2); + } + + public void testSortedSetIterableComparator() { + ArrayList<String> list = new ArrayList<String>(); + list.add("0"); + list.add("2"); + list.add("3"); + list.add("1"); + + SortedSet<String> ss1 = new TreeSet<String>(new ReverseComparator<String>()); + ss1.addAll(list); + + Iterable<String> iterable = list; + SortedSet<String> ss2 = CollectionTools.<String>sortedSet(iterable, new ReverseComparator<String>()); + assertEquals(ss1, ss2); + } + + public void testSortedSetIterableComparatorInt() { + ArrayList<String> list = new ArrayList<String>(); + list.add("0"); + list.add("2"); + list.add("3"); + list.add("1"); + + SortedSet<String> ss1 = new TreeSet<String>(new ReverseComparator<String>()); + ss1.addAll(list); + + Iterable<String> iterable = list; + SortedSet<String> ss2 = CollectionTools.<String>sortedSet(iterable, new ReverseComparator<String>(), 5); + assertEquals(ss1, ss2); + } + + public void testSortedSetIterator() { + assertEquals(this.buildSortedStringSet1(), CollectionTools.sortedSet(this.buildSortedStringSet1().iterator())); + } + + public void testSortedSetIterator_TreeSet() { + SortedSet<String> ss1 = new TreeSet<String>(); + ss1.add("0"); + ss1.add("2"); + ss1.add("3"); + ss1.add("1"); + + SortedSet<String> set2 = CollectionTools.<String>sortedSet(ss1.iterator()); + assertEquals(ss1, set2); + } + + public void testSortedSetIteratorInt() { + assertEquals(this.buildSortedStringSet1(), CollectionTools.sortedSet(this.buildSortedStringSet1().iterator(), 8)); + } + + public void testSortedSetObjectArray() { + assertEquals(this.buildSortedStringSet1(), CollectionTools.sortedSet(this.buildStringSet1().toArray(new String[0]))); + } + + public void testSortedSetObjectArrayComparator() { + ArrayList<String> list = new ArrayList<String>(); + list.add("0"); + list.add("2"); + list.add("3"); + list.add("1"); + + SortedSet<String> ss1 = new TreeSet<String>(new ReverseComparator<String>()); + ss1.addAll(list); + + String[] array = list.toArray(new String[list.size()]); + SortedSet<String> ss2 = CollectionTools.<String>sortedSet(array, new ReverseComparator<String>()); + assertEquals(ss1, ss2); + } + + + // ********** Old School Vector ********** + + public void testVectorIterable() { + Iterable<String> iterable = this.buildStringList1(); + Vector<String> v = CollectionTools.vector(iterable); + assertEquals(3, v.size()); + assertTrue(v.containsAll(this.buildStringList1())); + } + + public void testVectorIterableInt() { + Iterable<String> iterable = this.buildStringList1(); + Vector<String> v = CollectionTools.vector(iterable, 8); + assertEquals(3, v.size()); + assertTrue(v.containsAll(this.buildStringList1())); + } + + public void testVectorIterator_String() { + Vector<String> v = CollectionTools.vector(this.buildStringList1().iterator()); + assertEquals(3, v.size()); + assertTrue(v.containsAll(this.buildStringList1())); + } + + public void testVectorIterator_Object() { + Vector<Object> v = CollectionTools.<Object>vector(this.buildStringList1().iterator()); + assertEquals(3, v.size()); + assertTrue(v.containsAll(this.buildStringList1())); + } + + public void testVectorIteratorInt() { + Vector<String> v = CollectionTools.vector(this.buildStringList1().iterator(), 7); + assertEquals(3, v.size()); + assertTrue(v.containsAll(this.buildStringList1())); + } + + public void testVectorObjectArray() { + Vector<String> v = CollectionTools.vector(this.buildStringArray1()); + assertEquals(3, v.size()); + assertTrue(v.containsAll(this.buildStringList1())); + } + + + // ********** single-use iterable ********** + + public void testIterableIterator() { + Iterator<Object> emptyIterator = EmptyIterator.instance(); + Iterable<Object> emptyIterable = CollectionTools.iterable(emptyIterator); + + assertFalse(emptyIterable.iterator().hasNext()); + + boolean exceptionThrown = false; + try { + emptyIterator = emptyIterable.iterator(); + fail("invalid iterator: " + emptyIterator); + } catch (IllegalStateException ise) { + exceptionThrown = true; + } + assertTrue("IllegalStateException not thrown.", exceptionThrown); + } + + public void testIterableIterator_NPE() { + Iterator<Object> nullIterator = null; + boolean exceptionThrown = false; + try { + Iterable<Object> emptyIterable = CollectionTools.iterable(nullIterator); + fail("invalid iterable: " + emptyIterable); + } catch (NullPointerException ise) { + exceptionThrown = true; + } + assertTrue(exceptionThrown); + } + + public void testIterableIterator_ToString() { + Iterator<Object> emptyIterator = EmptyIterator.instance(); + Iterable<Object> emptyIterable = CollectionTools.iterable(emptyIterator); + assertNotNull(emptyIterable.toString()); + } + + + // ********** java.util.Collections enhancements ********** + + public void testCopyListList() { + List<String> src = this.buildStringList1(); + List<String> dest = new ArrayList<String>(); + for (String s : src) { + dest.add(s.toUpperCase()); + } + List<String> result = CollectionTools.copy(dest, src); + assertSame(dest, result); + assertTrue(CollectionTools.elementsAreIdentical(src, dest)); + } + + public void testFillListObject() { + List<String> list = this.buildStringList1(); + List<String> result = CollectionTools.fill(list, "foo"); + assertSame(list, result); + for (String string : result) { + assertEquals("foo", string); + } + } + + public void testShuffleList() { + List<String> list = this.buildStringList1(); + List<String> result = CollectionTools.shuffle(list); + assertSame(list, result); + } + + public void testShuffleListRandom() { + List<String> list = this.buildStringList1(); + List<String> result = CollectionTools.shuffle(list, new Random()); + assertSame(list, result); + } + + public void testSortList() { + List<String> list = this.buildStringList1(); + SortedSet<String> ss = new TreeSet<String>(); + ss.addAll(list); + List<String> result = CollectionTools.sort(list); + assertSame(list, result); + assertTrue(CollectionTools.elementsAreEqual(ss, result)); + } + + public void testSwapListIntInt() { + List<String> list = this.buildStringList1(); + List<String> result = CollectionTools.swap(list, 0, 1); + assertSame(list, result); + List<String> original = this.buildStringList1(); + assertEquals(original.get(0), result.get(1)); + assertEquals(original.get(1), result.get(0)); + assertEquals(original.get(2), result.get(2)); + } + + public void testConstructor() { + boolean exCaught = false; + try { + Object at = ReflectionTools.newInstance(CollectionTools.class); + fail("bogus: " + at); //$NON-NLS-1$ + } catch (RuntimeException ex) { + if (ex.getCause() instanceof InvocationTargetException) { + if (ex.getCause().getCause() instanceof UnsupportedOperationException) { + exCaught = true; + } + } + } + assertTrue(exCaught); + } + + + // ********** test harness ********** + + private Object[] buildObjectArray1() { + return new Object[] { "zero", "one", "two" }; + } + + private String[] buildStringArray1() { + return new String[] { "zero", "one", "two" }; + } + + private Object[] buildObjectArray2() { + return new Object[] { "three", "four", "five" }; + } + + private Vector<String> buildStringVector1() { + Vector<String> v = new Vector<String>(); + this.addToCollection1(v); + return v; + } + + private List<String> buildStringList1() { + List<String> l = new ArrayList<String>(); + this.addToCollection1(l); + return l; + } + + private List<Object> buildObjectList1() { + List<Object> l = new ArrayList<Object>(); + this.addToCollection1(l); + return l; + } + + private void addToCollection1(Collection<? super String> c) { + c.add("zero"); + c.add("one"); + c.add("two"); + } + + private List<String> buildStringList2() { + List<String> l = new ArrayList<String>(); + this.addToCollection2(l); + return l; + } + + private void addToCollection2(Collection<? super String> c) { + c.add("three"); + c.add("four"); + c.add("five"); + } + + private Set<String> buildStringSet1() { + Set<String> s = new HashSet<String>(); + this.addToCollection1(s); + return s; + } + + private Set<Object> buildObjectSet1() { + Set<Object> s = new HashSet<Object>(); + this.addToCollection1(s); + return s; + } + + private SortedSet<String> buildSortedStringSet1() { + SortedSet<String> s = new TreeSet<String>(); + this.addToCollection1(s); + return s; + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/CommandExecutorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/CommandExecutorTests.java new file mode 100644 index 0000000000..693b9c91b4 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/CommandExecutorTests.java @@ -0,0 +1,113 @@ +/******************************************************************************* + * Copyright (c) 2008, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import org.eclipse.jpt.common.utility.Command; +import org.eclipse.jpt.common.utility.CommandExecutor; +import org.eclipse.jpt.common.utility.internal.ThreadLocalCommandExecutor; + +public class CommandExecutorTests + extends MultiThreadedTestCase +{ + + public CommandExecutorTests(String name) { + super(name); + } + + public void testDefaultCommandExecutor_toString() throws Exception { + CommandExecutor commandExecutor = CommandExecutor.Default.instance(); + assertNotNull(commandExecutor.toString()); + } + + public void testDefaultCommandExecutor_serialization() throws Exception { + CommandExecutor commandExecutor1 = CommandExecutor.Default.instance(); + CommandExecutor commandExecutor2 = TestTools.serialize(commandExecutor1); + assertSame(commandExecutor1, commandExecutor2); + } + + public void testDefaultCommandExecutor() { + TestCommand testCommand = new TestCommand(); + assertEquals(0, testCommand.count); + CommandExecutor commandExecutor = CommandExecutor.Default.instance(); + commandExecutor.execute(testCommand); + assertEquals(1, testCommand.count); + } + + static class TestCommand implements Command { + int count = 0; + public void execute() { + this.count++; + } + } + + public void testThreadLocalCommandExecutor_toString() throws Exception { + CommandExecutor commandExecutor = new ThreadLocalCommandExecutor(); + assertNotNull(commandExecutor.toString()); + } + + public void testThreadLocalCommandExecutor() throws Exception { + ThreadLocalCommandExecutor threadLocalCommandExecutor = new ThreadLocalCommandExecutor(); + TestRunnable testRunnable1 = new TestRunnable(threadLocalCommandExecutor, 1); + Thread thread1 = this.buildThread(testRunnable1); + thread1.run(); + + TestRunnable testRunnable2 = new TestRunnable(threadLocalCommandExecutor, 2); + Thread thread2 = this.buildThread(testRunnable2); + thread2.run(); + + TestRunnable testRunnable3 = new TestRunnable(threadLocalCommandExecutor, 3, null); + Thread thread3 = this.buildThread(testRunnable3); + thread3.run(); + + thread1.join(); + thread2.join(); + thread3.join(); + + assertEquals(1, testRunnable1.testCommand.count); + assertEquals(1, testRunnable1.testCommandExecutor.count); + + assertEquals(2, testRunnable2.testCommand.count); + assertEquals(2, testRunnable2.testCommandExecutor.count); + + assertEquals(3, testRunnable3.testCommand.count); + assertNull(testRunnable3.testCommandExecutor); + } + + static class TestCommandExecutor implements CommandExecutor { + int count = 0; + public void execute(Command command) { + this.count++; + command.execute(); + } + } + + static class TestRunnable implements Runnable { + final ThreadLocalCommandExecutor threadLocalCommandExecutor; + final int executionCount; + final TestCommand testCommand = new TestCommand(); + final TestCommandExecutor testCommandExecutor; + TestRunnable(ThreadLocalCommandExecutor threadLocalCommandExecutor, int executionCount) { + this(threadLocalCommandExecutor, executionCount, new TestCommandExecutor()); + } + TestRunnable(ThreadLocalCommandExecutor threadLocalCommandExecutor, int executionCount, TestCommandExecutor testCommandExecutor) { + super(); + this.threadLocalCommandExecutor = threadLocalCommandExecutor; + this.executionCount = executionCount; + this.testCommandExecutor = testCommandExecutor; + } + public void run() { + this.threadLocalCommandExecutor.set(this.testCommandExecutor); + for (int i = 0; i < this.executionCount; i++) { + this.threadLocalCommandExecutor.execute(this.testCommand); + } + } + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/CommandRunnableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/CommandRunnableTests.java new file mode 100644 index 0000000000..623b2b2449 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/CommandRunnableTests.java @@ -0,0 +1,55 @@ +/******************************************************************************* + * Copyright (c) 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import junit.framework.TestCase; + +import org.eclipse.jpt.common.utility.Command; +import org.eclipse.jpt.common.utility.internal.CommandRunnable; + +@SuppressWarnings("nls") +public class CommandRunnableTests extends TestCase { + boolean commandExecuted = false; + + public CommandRunnableTests(String name) { + super(name); + } + + public void testNullCommand() { + boolean exCaught = false; + try { + Runnable runnable = new CommandRunnable(null); + fail("bogus: " + runnable); + } catch (NullPointerException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testRun() { + Runnable runnable = new CommandRunnable(this.buildCommand()); + runnable.run(); + assertTrue(this.commandExecuted); + } + + public void testToString() { + Runnable runnable = new CommandRunnable(this.buildCommand()); + assertNotNull(runnable.toString()); + } + + private Command buildCommand() { + return new Command() { + public void execute() { + CommandRunnableTests.this.commandExecuted = true; + } + }; + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/CommandTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/CommandTests.java new file mode 100644 index 0000000000..0eb8392e8b --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/CommandTests.java @@ -0,0 +1,137 @@ +/******************************************************************************* + * Copyright (c) 2008, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import org.eclipse.jpt.common.utility.Command; +import org.eclipse.jpt.common.utility.CommandExecutor; +import org.eclipse.jpt.common.utility.internal.CommandRunnable; +import org.eclipse.jpt.common.utility.internal.RunnableCommand; +import org.eclipse.jpt.common.utility.internal.ThreadLocalCommand; + +public class CommandTests + extends MultiThreadedTestCase +{ + public CommandTests(String name) { + super(name); + } + + public void testNullCommand() { + Command command = Command.Null.instance(); + command.execute(); // just make sure it doesn't blow up? + } + + public void testNullCommand_toString() { + Command command = Command.Null.instance(); + assertNotNull(command.toString()); + } + + public void testNullCommand_serialization() throws Exception { + Command command1 = Command.Null.instance(); + Command command2 = TestTools.serialize(command1); + assertSame(command1, command2); + } + + public void testDisabledCommand() { + Command command = Command.Disabled.instance(); + boolean exCaught = false; + try { + command.execute(); + fail(); + } catch (UnsupportedOperationException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testDisabledCommand_toString() { + Command command = Command.Disabled.instance(); + assertNotNull(command.toString()); + } + + public void testDisabledCommand_serialization() throws Exception { + Command command1 = Command.Disabled.instance(); + Command command2 = TestTools.serialize(command1); + assertSame(command1, command2); + } + + public void testRunnableCommand() { + SimpleTestRunnable testRunnable = new SimpleTestRunnable(); + assertFalse(testRunnable.ran); + Command command = new RunnableCommand(testRunnable); + command.execute(); + assertTrue(testRunnable.ran); + } + + static class SimpleTestRunnable implements Runnable { + boolean ran = false; + public void run() { + this.ran = true; + } + } + + public void testCommandRunnable() { + TestCommand testCommand = new TestCommand(); + assertEquals(0, testCommand.count); + Runnable runnable = new CommandRunnable(testCommand); + runnable.run(); + assertEquals(1, testCommand.count); + } + + static class TestCommand implements Command { + int count = 0; + public void execute() { + this.count++; + } + } + + public void testThreadLocalCommand() throws Exception { + ThreadLocalCommand threadLocalCommand = new ThreadLocalCommand(); + TestRunnable testRunnable1 = new TestRunnable(threadLocalCommand, 1); + Thread thread1 = this.buildThread(testRunnable1); + thread1.run(); + + TestRunnable testRunnable2 = new TestRunnable(threadLocalCommand, 2); + Thread thread2 = this.buildThread(testRunnable2); + thread2.run(); + + thread1.join(); + thread2.join(); + + assertEquals(1, testRunnable1.testCommand.count); + + assertEquals(2, testRunnable2.testCommand.count); + } + + static class TestCommandExecutor implements CommandExecutor { + int count = 0; + public void execute(Command command) { + this.count++; + command.execute(); + } + } + + static class TestRunnable implements Runnable { + final ThreadLocalCommand threadLocalCommand; + final int executionCount; + final TestCommand testCommand = new TestCommand(); + TestRunnable(ThreadLocalCommand threadLocalCommand, int executionCount) { + super(); + this.threadLocalCommand = threadLocalCommand; + this.executionCount = executionCount; + } + public void run() { + this.threadLocalCommand.set(this.testCommand); + for (int i = 0; i < this.executionCount; i++) { + this.threadLocalCommand.execute(); + } + } + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/CompositeCommandTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/CompositeCommandTests.java new file mode 100644 index 0000000000..cfabc54bef --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/CompositeCommandTests.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * Copyright (c) 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import junit.framework.TestCase; + +import org.eclipse.jpt.common.utility.Command; +import org.eclipse.jpt.common.utility.internal.CommandRunnable; +import org.eclipse.jpt.common.utility.internal.CompositeCommand; + +public class CompositeCommandTests extends TestCase { + boolean command1Executed = false; + boolean command2Executed = false; + + public CompositeCommandTests(String name) { + super(name); + } + + public void testRun() { + Runnable runnable = new CommandRunnable(this.buildCompositeCommand()); + runnable.run(); + assertTrue(this.command1Executed); + assertTrue(this.command2Executed); + } + + public void testToString() { + Runnable runnable = new CommandRunnable(this.buildCompositeCommand()); + assertNotNull(runnable.toString()); + } + + private Command buildCompositeCommand() { + return new CompositeCommand( + this.buildCommand1(), + this.buildCommand2() + ); + } + + private Command buildCommand1() { + return new Command() { + public void execute() { + CompositeCommandTests.this.command1Executed = true; + } + }; + } + + private Command buildCommand2() { + return new Command() { + public void execute() { + CompositeCommandTests.this.command2Executed = true; + } + }; + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ExceptionHandlerTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ExceptionHandlerTests.java new file mode 100644 index 0000000000..23097f3ab5 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ExceptionHandlerTests.java @@ -0,0 +1,51 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import junit.framework.TestCase; + +import org.eclipse.jpt.common.utility.internal.ExceptionHandler; + +public class ExceptionHandlerTests extends TestCase { + + public ExceptionHandlerTests(String name) { + super(name); + } + + public void testNullExceptionHandler() { + ExceptionHandler exceptionHandler = ExceptionHandler.Null.instance(); + exceptionHandler.handleException(new NullPointerException()); // just make sure it doesn't blow up? + } + + public void testNullExceptionHandlerToString() { + ExceptionHandler exceptionHandler = ExceptionHandler.Null.instance(); + assertNotNull(exceptionHandler.toString()); + } + + public void testRuntimeExceptionHandler() { + Exception npe = new NullPointerException(); + ExceptionHandler exceptionHandler = ExceptionHandler.Runtime.instance(); + boolean exCaught = false; + try { + exceptionHandler.handleException(npe); + fail(); + } catch (RuntimeException ex) { + assertSame(npe, ex.getCause()); + exCaught = true; + } + assertTrue(exCaught); + } + + public void testRuntimeExceptionHandlerToString() { + ExceptionHandler exceptionHandler = ExceptionHandler.Runtime.instance(); + assertNotNull(exceptionHandler.toString()); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/FileToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/FileToolsTests.java new file mode 100644 index 0000000000..5483b8588d --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/FileToolsTests.java @@ -0,0 +1,593 @@ +/******************************************************************************* + * Copyright (c) 2005, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import java.io.File; +import java.io.FileFilter; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.Reader; +import java.io.Writer; +import java.lang.reflect.InvocationTargetException; +import java.net.URL; +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; + +import junit.framework.TestCase; + +import org.eclipse.jpt.common.utility.internal.CollectionTools; +import org.eclipse.jpt.common.utility.internal.FileTools; +import org.eclipse.jpt.common.utility.internal.ReflectionTools; +import org.eclipse.jpt.common.utility.internal.Tools; + +@SuppressWarnings("nls") +public class FileToolsTests extends TestCase { + private File tempDir; + + public FileToolsTests(String name) { + super(name); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + this.tempDir = this.buildTempDir(); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + this.deleteDir(this.tempDir); + } + + public void testFilesIn() { + Collection<File> files = CollectionTools.collection(FileTools.filesIn(this.tempDir.getPath())); + assertEquals("invalid file count", 3, files.size()); + } + + public void testDirectoriesIn() { + Collection<File> files = CollectionTools.collection(FileTools.directoriesIn(this.tempDir.getPath())); + assertEquals("invalid directory count", 2, files.size()); + } + + public void testFilesInTree() { + Collection<File> files = CollectionTools.collection(FileTools.filesInTree(this.tempDir.getPath())); + assertEquals("invalid file count", 9, files.size()); + } + + public void testDirectoriesInTree() { + Collection<File> files = CollectionTools.collection(FileTools.directoriesInTree(this.tempDir.getPath())); + assertEquals("invalid directory count", 3, files.size()); + } + + public void testDeleteDirectory() throws IOException { + // build another temporary directory just for this test + File dir = this.buildTempDir(); + assertTrue("temporary directory not created", dir.exists()); + FileTools.deleteDirectory(dir.getPath()); + assertFalse("temporary directory not deleted", dir.exists()); + } + + public void testDeleteDirectoryContents() throws IOException { + // build another temporary directory just for this test + File dir = this.buildTempDir(); + assertTrue("temporary directory not created", dir.exists()); + FileTools.deleteDirectoryContents(dir.getPath()); + assertTrue("temporary directory should not have been deleted", dir.exists()); + assertTrue("temporary directory contents not deleted", dir.listFiles().length == 0); + dir.delete(); + } + + public void testCopyToFile() throws IOException { + File destFile = new File(this.tempDir, "destfile.txt"); + this.copyToFile(destFile, "testCopyToFile"); + } + + public void testCopyToPreExistingFile() throws IOException { + File destFile = new File(this.tempDir, "destfile.txt"); + Writer writer = new OutputStreamWriter(new FileOutputStream(destFile)); + writer.write("this text should be replaced..."); + writer.close(); + this.copyToFile(destFile, "testCopyToPreExistingFile"); + } + + private void copyToFile(File destFile, String writeString) throws IOException { + File sourceFile = new File(this.tempDir, "sourcefile.txt"); + char[] readBuffer = new char[writeString.length()]; + + Writer writer = new OutputStreamWriter(new FileOutputStream(sourceFile)); + writer.write(writeString); + writer.close(); + + FileTools.copyToFile(sourceFile, destFile); + + Reader reader = new InputStreamReader(new FileInputStream(destFile)); + reader.read(readBuffer); + reader.close(); + String readString = new String(readBuffer); + assertEquals(writeString, readString); + } + + public void testCopyToDirectory() throws IOException { + File sourceFile = new File(this.tempDir, "sourcefile.txt"); + String writeString = "testCopyToDirectory"; + + File destDir = new File(this.tempDir, "destdir"); + destDir.mkdir(); + File destFile = new File(destDir, "sourcefile.txt"); + char[] readBuffer = new char[writeString.length()]; + + Writer writer = new OutputStreamWriter(new FileOutputStream(sourceFile)); + writer.write(writeString); + writer.close(); + + FileTools.copyToDirectory(sourceFile, destDir); + + Reader reader = new InputStreamReader(new FileInputStream(destFile)); + reader.read(readBuffer); + reader.close(); + String readString = new String(readBuffer); + assertEquals(writeString, readString); + + FileTools.copyToDirectory(sourceFile, destDir); //Try again with the directory is already created + reader = new InputStreamReader(new FileInputStream(destFile)); + reader.read(readBuffer); + reader.close(); + readString = new String(readBuffer); + assertEquals(writeString, readString); + } + + public void testFilter() throws IOException { + String prefix = "XXXtestFileXXX"; + File testFile1 = new File(this.tempDir, prefix + "1"); + testFile1.createNewFile(); + File testFile2 = new File(this.tempDir, prefix + "2"); + testFile2.createNewFile(); + + FileFilter filter = this.buildFileFilter(prefix); + Iterator<File> filteredFilesIterator = FileTools.filter(FileTools.filesIn(this.tempDir), filter); + Collection<File> filteredFiles = CollectionTools.collection(filteredFilesIterator); + assertEquals(2, filteredFiles.size()); + assertTrue(filteredFiles.contains(testFile1)); + assertTrue(filteredFiles.contains(testFile2)); + } + + private FileFilter buildFileFilter(final String prefix) { + return new FileFilter() { + public boolean accept(File file) { + return file.getName().startsWith(prefix); + } + }; + } + + public void testStripExtension() { + assertEquals("foo", FileTools.stripExtension("foo.xml")); + assertEquals("foo.bar", FileTools.stripExtension("foo.bar.xml")); + assertEquals("foo", FileTools.stripExtension("foo")); + assertEquals("foo", FileTools.stripExtension("foo.")); + } + + public void testExtension() { + assertEquals(".xml", FileTools.extension("foo.xml")); + assertEquals(".xml", FileTools.extension("foo.bar.xml")); + assertEquals("", FileTools.extension("foo")); + assertEquals("", FileTools.extension("foo,xml")); + assertEquals(".", FileTools.extension("foo.")); + } + + public void testEmptyTemporaryDirectory() throws IOException { + File tempDir1 = FileTools.temporaryDirectory(); + File testFile1 = new File(tempDir1, "junk"); + testFile1.createNewFile(); + + File tempDir2 = FileTools.emptyTemporaryDirectory(); + assertEquals(tempDir1, tempDir2); + assertTrue(tempDir2.isDirectory()); + assertEquals(0, tempDir2.listFiles().length); + tempDir2.delete(); + } + + public void testCanonicalFileName() { + File file1 = new File("foo"); + file1 = new File(file1, "bar"); + file1 = new File(file1, "baz"); + file1 = new File(file1, ".."); + file1 = new File(file1, ".."); + file1 = new File(file1, "bar"); + file1 = new File(file1, "baz"); + File file2 = new File(System.getProperty("user.dir")); + file2 = new File(file2, "foo"); + file2 = new File(file2, "bar"); + file2 = new File(file2, "baz"); + File file3 = FileTools.canonicalFile(file1); + assertEquals(file2, file3); + } + + public void testPathFiles() { + File[] expected; + File[] actual; + + if (Tools.osIsWindows()) { + expected = new File[] { new File("C:/"), new File("C:/foo"), new File("C:/foo/bar"), new File("C:/foo/bar/baz.txt") }; + actual = this.pathFiles(new File("C:/foo/bar/baz.txt")); + assertTrue(Arrays.equals(expected, actual)); + } + + expected = new File[] { new File("/"), new File("/foo"), new File("/foo/bar"), new File("/foo/bar/baz.txt") }; + actual = this.pathFiles(new File("/foo/bar/baz.txt")); + assertTrue(Arrays.equals(expected, actual)); + + expected = new File[] { new File("foo"), new File("foo/bar"), new File("foo/bar/baz.txt") }; + actual = this.pathFiles(new File("foo/bar/baz.txt")); + assertTrue(Arrays.equals(expected, actual)); + + expected = new File[] { new File(".."), new File("../foo"), new File("../foo/bar"), new File("../foo/bar/baz.txt") }; + actual = this.pathFiles(new File("../foo/bar/baz.txt")); + assertTrue(Arrays.equals(expected, actual)); + + expected = new File[] { new File("."), new File("./foo"), new File("./foo/bar"), new File("./foo/bar/baz.txt") }; + actual = this.pathFiles(new File("./foo/bar/baz.txt")); + assertTrue(Arrays.equals(expected, actual)); + } + + private File[] pathFiles(File file) { + return (File[]) ReflectionTools.executeStaticMethod(FileTools.class, "pathFiles", File.class, file); + } + + public void testRelativeParentFile() { + assertEquals(new File(".."), this.relativeParentFile(1)); + assertEquals(new File("../.."), this.relativeParentFile(2)); + assertEquals(new File("../../.."), this.relativeParentFile(3)); + + boolean exCaught = false; + try { + File file = this.relativeParentFile(0); + fail("invalid return: " + file); + } catch (RuntimeException ex) { + if (ex.getCause() instanceof InvocationTargetException) { + InvocationTargetException ite = (InvocationTargetException) ex.getCause(); + if (ite.getTargetException() instanceof IllegalArgumentException) { + exCaught = true; + } + } + } + assertTrue(exCaught); + } + + private File relativeParentFile(int len) { + return (File) ReflectionTools.executeStaticMethod(FileTools.class, "relativeParentFile", int.class, new Integer(len)); + } + + public void testConvertToRelativeFile() { + String prefix = Tools.osIsWindows() ? "C:" : ""; + File file; + File dir; + File relativeFile; + + if (Tools.osIsWindows()) { + // on Windows, a drive must be specified for a file to be absolute (i.e. not relative) + this.verifyUnchangedRelativeFile("/dir1/dir2/file.txt", "C:/dir1/dir2"); + // different drives + this.verifyUnchangedRelativeFile("D:/dir1/dir2/file.txt", "C:/dir1/dir2"); + } + this.verifyUnchangedRelativeFile("dir1/dir2/file.txt", prefix + "/dir1/dir2"); + this.verifyUnchangedRelativeFile("./dir1/dir2/file.txt", prefix + "/dir1/dir2"); + this.verifyUnchangedRelativeFile("../../dir1/dir2/file.txt", prefix + "/dir1/dir2"); + + file = new File(prefix + "/dir1/dir2"); + dir = new File(prefix + "/dir1/dir2"); + relativeFile = FileTools.convertToRelativeFile(file, dir); + assertEquals(new File("."), relativeFile); + + file = new File(prefix + "/dir1/dir2/file.txt"); + dir = new File(prefix + "/dir1/dir2"); + relativeFile = FileTools.convertToRelativeFile(file, dir); + assertEquals(new File("file.txt"), relativeFile); + + file = new File(prefix + "/dir1/dir2/../dir2/file.txt"); + dir = new File(prefix + "/dir1/dir2"); + relativeFile = FileTools.convertToRelativeFile(file, dir); + assertEquals(new File("file.txt"), relativeFile); + + file = new File(prefix + "/dir1/dir2/dir3/dir4/dir5/file.txt"); + dir = new File(prefix + "/dir1/dir2"); + relativeFile = FileTools.convertToRelativeFile(file, dir); + assertEquals(new File("dir3/dir4/dir5/file.txt"), relativeFile); + + file = new File(prefix + "/dir1/dir2/file.txt"); + dir = new File(prefix + "/dir1/dir2/dir3/dir4/dir5"); + relativeFile = FileTools.convertToRelativeFile(file, dir); + assertEquals(new File("../../../file.txt"), relativeFile); + + file = new File(prefix + "/dir1/dir2/file.txt"); + dir = new File(prefix + "/dir1/dir2/dir3"); + relativeFile = FileTools.convertToRelativeFile(file, dir); + assertEquals(new File("../file.txt"), relativeFile); + + file = new File(prefix + "/dir1/dir2/dirA/dirB/dirC/file.txt"); + dir = new File(prefix + "/dir1/dir2/dir3/dir4/dir5"); + relativeFile = FileTools.convertToRelativeFile(file, dir); + assertEquals(new File("../../../dirA/dirB/dirC/file.txt"), relativeFile); + + file = new File(prefix + "/dir1/dir2"); + dir = new File(prefix + "/dir1/dir2/dir3/dir4/dir5"); + relativeFile = FileTools.convertToRelativeFile(file, dir); + assertEquals(new File("../../.."), relativeFile); + + file = new File(prefix + "/My Documents/My Workspace/Project 1/lib/toplink.jar"); + dir = new File(prefix + "/My Documents/My Workspace/Project 1"); + relativeFile = FileTools.convertToRelativeFile(file, dir); + assertEquals(new File("lib/toplink.jar"), relativeFile); + } + + private void verifyUnchangedRelativeFile(String fileName, String dirName) { + File file = new File(fileName); + File dir = new File(dirName); + File relativeFile = FileTools.convertToRelativeFile(file, dir); + assertEquals(file, relativeFile); + } + + public void testConvertToAbsoluteFile() { + String prefix = Tools.osIsWindows() ? "C:" : ""; + File file; + File dir; + File absoluteFile; + + if (Tools.osIsWindows()) { + // on Windows, a drive must be specified for a file to be absolute (i.e. not relative) + this.verifyUnchangedAbsoluteFile("C:/dir1/dir2/file.txt", "C:/dir1/dir2"); + // different drives + this.verifyUnchangedAbsoluteFile("D:/dir1/dir2/file.txt", "C:/dir1/dir2"); + } + this.verifyUnchangedAbsoluteFile(prefix + "/dir1/dir2/file.txt", prefix + "/dir1/dir2"); + this.verifyUnchangedAbsoluteFile(prefix + "/./dir1/dir2/file.txt", prefix + "/dir1/dir2"); + this.verifyUnchangedAbsoluteFile(prefix + "/dir1/dir2/../../dir1/dir2/file.txt", prefix + "/dir1/dir2"); + + file = new File("."); + dir = new File(prefix + "/dir1/dir2"); + absoluteFile = FileTools.convertToAbsoluteFile(file, dir); + assertEquals(new File(prefix + "/dir1/dir2"), absoluteFile); + + file = new File("./file.txt"); + dir = new File(prefix + "/dir1/dir2"); + absoluteFile = FileTools.convertToAbsoluteFile(file, dir); + assertEquals(new File(prefix + "/dir1/dir2/file.txt"), absoluteFile); + + file = new File("file.txt"); + dir = new File(prefix + "/dir1/dir2"); + absoluteFile = FileTools.convertToAbsoluteFile(file, dir); + assertEquals(new File(prefix + "/dir1/dir2/file.txt"), absoluteFile); + + file = new File("../dir2/file.txt"); + dir = new File(prefix + "/dir1/dir2"); + absoluteFile = FileTools.convertToAbsoluteFile(file, dir); + assertEquals(new File(prefix + "/dir1/dir2/file.txt"), absoluteFile); + + file = new File("dir3/dir4/dir5/file.txt"); + dir = new File(prefix + "/dir1/dir2"); + absoluteFile = FileTools.convertToAbsoluteFile(file, dir); + assertEquals(new File(prefix + "/dir1/dir2/dir3/dir4/dir5/file.txt"), absoluteFile); + + file = new File("../../../file.txt"); + dir = new File(prefix + "/dir1/dir2/dir3/dir4/dir5"); + absoluteFile = FileTools.convertToAbsoluteFile(file, dir); + assertEquals(new File(prefix + "/dir1/dir2/file.txt"), absoluteFile); + + // too many ".." directories will resolve to the root; + // this is consistent with Windows and Linux command shells + file = new File("../../../../../../../../file.txt"); + dir = new File(prefix + "/dir1/dir2"); + absoluteFile = FileTools.convertToAbsoluteFile(file, dir); + assertEquals(new File(prefix + "/file.txt"), absoluteFile); + + file = new File("../file.txt"); + dir = new File(prefix + "/dir1/dir2/dir3"); + absoluteFile = FileTools.convertToAbsoluteFile(file, dir); + assertEquals(new File(prefix + "/dir1/dir2/file.txt"), absoluteFile); + + file = new File("../../../dirA/dirB/dirC/file.txt"); + dir = new File(prefix + "/dir1/dir2/dir3/dir4/dir5"); + absoluteFile = FileTools.convertToAbsoluteFile(file, dir); + assertEquals(new File(prefix + "/dir1/dir2/dirA/dirB/dirC/file.txt"), absoluteFile); + + file = new File("../../.."); + dir = new File(prefix + "/dir1/dir2/dir3/dir4/dir5"); + absoluteFile = FileTools.convertToAbsoluteFile(file, dir); + assertEquals(new File(prefix + "/dir1/dir2"), absoluteFile); + + file = new File("lib/toplink.jar"); + dir = new File(prefix + "/My Documents/My Workspace/Project 1"); + absoluteFile = FileTools.convertToAbsoluteFile(file, dir); + assertEquals(new File(prefix + "/My Documents/My Workspace/Project 1/lib/toplink.jar"), absoluteFile); + } + + public void testFileNameIsReserved() { + boolean expected = Tools.osIsWindows(); + assertEquals(expected, FileTools.fileNameIsReserved("CON")); + assertEquals(expected, FileTools.fileNameIsReserved("con")); + assertEquals(expected, FileTools.fileNameIsReserved("cON")); + assertEquals(expected, FileTools.fileNameIsReserved("AUX")); + assertEquals(expected, FileTools.fileNameIsReserved("COM3")); + assertEquals(expected, FileTools.fileNameIsReserved("LPT3")); + assertEquals(expected, FileTools.fileNameIsReserved("nUL")); + assertEquals(expected, FileTools.fileNameIsReserved("Prn")); + } + + public void testFileHasAnyReservedComponents() { + boolean expected = Tools.osIsWindows(); + assertEquals(expected, FileTools.fileHasAnyReservedComponents(new File("C:/CON"))); + assertEquals(expected, FileTools.fileHasAnyReservedComponents(new File("/con/foo"))); + assertEquals(expected, FileTools.fileHasAnyReservedComponents(new File("c:/temp/cON"))); + assertEquals(expected, FileTools.fileHasAnyReservedComponents(new File("bar//baz//AUX"))); + assertEquals(expected, FileTools.fileHasAnyReservedComponents(new File("COM3//ttt"))); + assertEquals(expected, FileTools.fileHasAnyReservedComponents(new File("d:/LPT3/xxx"))); + assertEquals(expected, FileTools.fileHasAnyReservedComponents(new File("c:/my docs and stuff/tuesday/nUL"))); + assertEquals(expected, FileTools.fileHasAnyReservedComponents(new File("Prn"))); + } + + public void testShortenFileNameFile() { + if (Tools.osIsWindows()) { + this.verifyShortenFileNameFileWin(); + } else { + this.verifyShortenFileNameFileNonWin(); + } + } + + private void verifyShortenFileNameFileWin() { + File file = new File("C:\\Documents and Settings\\Administrator\\Desktop\\Project\\Text.txt"); + String fileName = FileTools.shortenFileName(file); + assertEquals("C:\\Documents and Settings\\...\\Desktop\\Project\\Text.txt", fileName); + assertTrue(fileName.length() <= FileTools.MAXIMUM_SHORTENED_FILE_NAME_LENGTH); + + file = new File("C:/"); + fileName = FileTools.shortenFileName(file); + assertEquals("C:\\", fileName); + assertTrue(fileName.length() <= FileTools.MAXIMUM_SHORTENED_FILE_NAME_LENGTH); + } + + private void verifyShortenFileNameFileNonWin() { + File file = new File("/home/administrator/documents and settings/desktop/Project/Text.txt"); + String fileName = FileTools.shortenFileName(file); + assertEquals("/home/administrator/.../desktop/Project/Text.txt", fileName); + assertTrue(fileName.length() <= FileTools.MAXIMUM_SHORTENED_FILE_NAME_LENGTH); + + file = new File("/home"); + fileName = FileTools.shortenFileName(file); + assertEquals("/home", fileName); + assertTrue(fileName.length() <= FileTools.MAXIMUM_SHORTENED_FILE_NAME_LENGTH); + } + + public void testShortenFileNameFileInt() { + if (Tools.osIsWindows()) { + this.verifyShortenFileNameFileIntWin(); + } else { + this.verifyShortenFileNameFileIntNonWin(); + } + } + + private void verifyShortenFileNameFileIntWin() { + File file = new File("C:\\Documents and Settings\\Administrator\\Desktop\\Project\\Text.txt"); + String fileName = FileTools.shortenFileName(file, 31); + assertEquals("C:\\...\\Desktop\\Project\\Text.txt", fileName); + assertEquals(31, fileName.length()); + + file = new File("C:/This is the file name.txt"); + fileName = FileTools.shortenFileName(file, 10); + assertEquals("C:\\This is the file name.txt", fileName); + assertEquals(28, fileName.length()); + } + + private void verifyShortenFileNameFileIntNonWin() { + File file = new File("/home/administrator/documents and settings/desktop/Project/Text.txt"); + String fileName = FileTools.shortenFileName(file, 31); + assertEquals("/home/.../desktop/Project/Text.txt", fileName); + assertEquals(34, fileName.length()); + + file = new File("/This is the file name.txt"); + fileName = FileTools.shortenFileName(file, 10); + assertEquals("/This is the file name.txt", fileName); + assertEquals(26, fileName.length()); + } + + public void testShortenFileNameURL() throws Exception { + if (Tools.osIsWindows()) { + this.verifyShortenFileNameURLWin(); + } else { + this.verifyShortenFileNameURLNonWin(); + } + } + + private void verifyShortenFileNameURLWin() throws Exception { + URL url = new URL("file", "", "C:/Documents and Settings/Administrator/Desktop/Project/Text.txt"); + String fileName = FileTools.shortenFileName(url); + assertEquals("C:\\Documents and Settings\\...\\Desktop\\Project\\Text.txt", fileName); + assertTrue(fileName.length() <= FileTools.MAXIMUM_SHORTENED_FILE_NAME_LENGTH); + } + + private void verifyShortenFileNameURLNonWin() throws Exception { + URL url = new URL("file", "", "/home/administrator/documents and settings/desktop/Project/Text.txt"); + String fileName = FileTools.shortenFileName(url); + assertEquals("/home/administrator/.../desktop/Project/Text.txt", fileName); + assertTrue(fileName.length() <= FileTools.MAXIMUM_SHORTENED_FILE_NAME_LENGTH); + } + + public void testShortenFileNameURLInt() throws Exception { + if (Tools.osIsWindows()) { + this.verifyShortenFileNameURLIntWin(); + } else { + this.verifyShortenFileNameURLIntNonWin(); + } + } + + private void verifyShortenFileNameURLIntWin() throws Exception { + URL url = new URL("file", "", "/C:/Documents and Settings/Administrator/Desktop/Project/Text.txt"); + String fileName = FileTools.shortenFileName(url, 31); + assertEquals("C:\\...\\Desktop\\Project\\Text.txt", fileName); + assertEquals(31, fileName.length()); + } + + private void verifyShortenFileNameURLIntNonWin() throws Exception { + URL url = new URL("file", "", "/home/administrator/documents and settings/desktop/Project/Text.txt"); + String fileName = FileTools.shortenFileName(url, 31); + assertEquals("/home/.../desktop/Project/Text.txt", fileName); + assertEquals(34, fileName.length()); + } + + private void verifyUnchangedAbsoluteFile(String fileName, String dirName) { + File file = new File(fileName); + File dir = new File(dirName); + File absoluteFile = FileTools.convertToAbsoluteFile(file, dir); + assertEquals(file, absoluteFile); + } + + private File buildTempDir() throws IOException { + // build a new directory for each test, to prevent any cross-test effects + File dir = FileTools.newTemporaryDirectory(this.getClass().getSimpleName() + "." + this.getName()); + + File file0a = new File(dir, "file0a"); + file0a.createNewFile(); + File file0b = new File(dir, "file0b"); + file0b.createNewFile(); + File file0c = new File(dir, "file0c"); + file0c.createNewFile(); + + File subdir1 = new File(dir, "subdir1"); + subdir1.mkdir(); + File file1a = new File(subdir1, "file1a"); + file1a.createNewFile(); + File file1b = new File(subdir1, "file1b"); + file1b.createNewFile(); + + File subdir2 = new File(dir, "subdir2"); + subdir2.mkdir(); + File file2a = new File(subdir2, "file2a"); + file2a.createNewFile(); + File file2b = new File(subdir2, "file2b"); + file2b.createNewFile(); + + File subdir3 = new File(subdir2, "subdir3"); + subdir3.mkdir(); + File file3a = new File(subdir3, "file3a"); + file3a.createNewFile(); + File file3b = new File(subdir3, "file3b"); + file3b.createNewFile(); + + return dir; + } + + private void deleteDir(File dir) { + FileTools.deleteDirectory(dir); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/FilterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/FilterTests.java new file mode 100644 index 0000000000..b27a0a3543 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/FilterTests.java @@ -0,0 +1,79 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import junit.framework.TestCase; + +import org.eclipse.jpt.common.utility.Filter; + +@SuppressWarnings("nls") +public class FilterTests extends TestCase { + + public FilterTests(String name) { + super(name); + } + + public void testNullFilter() { + Filter<String> filter = Filter.Null.instance(); + assertTrue(filter.accept("")); + assertTrue(filter.accept("foo")); + assertTrue(filter.accept("bar")); + } + + public void testNullFilter_toString() { + Filter<String> filter = Filter.Null.instance(); + assertNotNull(filter.toString()); + } + + public void testNullFilter_serialization() throws Exception { + Filter<String> filter = Filter.Null.instance(); + assertSame(filter, TestTools.serialize(filter)); + } + + public void testOpaqueFilter() { + Filter<String> filter = Filter.Opaque.instance(); + assertFalse(filter.accept("")); + assertFalse(filter.accept("foo")); + assertFalse(filter.accept("bar")); + } + + public void testOpaqueFilter_toString() { + Filter<String> filter = Filter.Opaque.instance(); + assertNotNull(filter.toString()); + } + + public void testOpaqueFilter_serialization() throws Exception { + Filter<String> filter = Filter.Opaque.instance(); + assertSame(filter, TestTools.serialize(filter)); + } + + public void testDisabledFilter() { + Filter<String> filter = Filter.Disabled.instance(); + boolean exCaught = false; + try { + assertFalse(filter.accept("foo")); + fail(); + } catch (UnsupportedOperationException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testDisabledFilter_toString() { + Filter<String> filter = Filter.Disabled.instance(); + assertNotNull(filter.toString()); + } + + public void testDisabledFilter_serialization() throws Exception { + Filter<String> filter = Filter.Disabled.instance(); + assertSame(filter, TestTools.serialize(filter)); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/HashBagTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/HashBagTests.java new file mode 100644 index 0000000000..df2a10bd28 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/HashBagTests.java @@ -0,0 +1,555 @@ +/******************************************************************************* + * Copyright (c) 2005, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.ConcurrentModificationException; +import java.util.Iterator; +import java.util.NoSuchElementException; + +import junit.framework.TestCase; + +import org.eclipse.jpt.common.utility.internal.ArrayTools; +import org.eclipse.jpt.common.utility.internal.Bag; +import org.eclipse.jpt.common.utility.internal.HashBag; +import org.eclipse.jpt.common.utility.internal.Tools; + +@SuppressWarnings("nls") +public class HashBagTests extends TestCase { + private HashBag<String> bag; + + public HashBagTests(String name) { + super(name); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + this.bag = this.buildBag(); + } + + private HashBag<String> buildBag() { + HashBag<String> b = new HashBag<String>(); + b.add(null); + b.add(new String("one")); + b.add(new String("two")); + b.add(new String("two")); + b.add(new String("three")); + b.add(new String("three")); + b.add(new String("three")); + b.add(new String("four")); + b.add(new String("four")); + b.add(new String("four")); + b.add(new String("four")); + return b; + } + + @Override + protected void tearDown() throws Exception { + TestTools.clear(this); + super.tearDown(); + } + + private Collection<String> buildCollection() { + Collection<String> c = new ArrayList<String>(); + c.add(new String("foo")); + c.add(new String("foo")); + c.add(new String("bar")); + c.add(new String("bar")); + c.add(new String("bar")); + return c; + } + + public void testCtorCollection() { + Collection<String> c = this.buildCollection(); + Bag<String> b = new HashBag<String>(c); + for (String s : c) { + assertTrue(b.contains(s)); + } + } + + public void testCtorIntFloat() { + boolean exCaught; + + exCaught = false; + try { + this.bag = new HashBag<String>(-20, 0.66f); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + + exCaught = false; + try { + this.bag = new HashBag<String>(20, -0.66f); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testAdd() { + // the other adds took place in setUp + assertTrue(this.bag.add("five")); + + assertTrue(this.bag.contains("one")); + assertTrue(this.bag.contains("two")); + assertTrue(this.bag.contains("three")); + assertTrue(this.bag.contains("four")); + assertTrue(this.bag.contains("five")); + } + + public void testAddCount() { + // the other adds took place in setUp + this.bag.add("minus3", -3); + this.bag.add("zero", 0); + this.bag.add("five", 5); + + assertFalse(this.bag.contains("minus3")); + assertFalse(this.bag.contains("zero")); + assertEquals(1, this.bag.count("one")); + assertEquals(2, this.bag.count("two")); + assertEquals(3, this.bag.count("three")); + assertEquals(4, this.bag.count("four")); + assertEquals(5, this.bag.count("five")); + + this.bag.add("three", 2); + assertEquals(5, this.bag.count("three")); + } + + public void testAddAll() { + Collection<String> c = this.buildCollection(); + assertTrue(this.bag.addAll(c)); + for (String s : c) { + assertTrue(this.bag.contains(s)); + } + } + + public void testClear() { + assertTrue(this.bag.contains("one")); + assertTrue(this.bag.contains("two")); + assertTrue(this.bag.contains("three")); + assertTrue(this.bag.contains("four")); + assertTrue(this.bag.contains(null)); + assertEquals(11, this.bag.size()); + this.bag.clear(); + assertFalse(this.bag.contains("one")); + assertFalse(this.bag.contains("two")); + assertFalse(this.bag.contains("three")); + assertFalse(this.bag.contains("four")); + assertFalse(this.bag.contains(null)); + assertEquals(0, this.bag.size()); + } + + public void testClone() { + Bag<String> bag2 = this.bag.clone(); + assertTrue(this.bag != bag2); + assertEquals(this.bag, bag2); + assertTrue(this.bag.hashCode() == bag2.hashCode()); + } + + public void testContains() { + assertTrue(this.bag.contains(null)); + assertTrue(this.bag.contains("one")); + assertTrue(this.bag.contains("two")); + assertTrue(this.bag.contains("three")); + assertTrue(this.bag.contains("four")); + assertTrue(this.bag.contains(new String("four"))); + assertTrue(this.bag.contains("fo" + "ur")); + assertFalse(this.bag.contains("five")); + } + + public void testContainsAll() { + Collection<String> c = new ArrayList<String>(); + c.add(null); + c.add(new String("one")); + c.add(new String("two")); + c.add(new String("three")); + c.add(new String("four")); + assertTrue(this.bag.containsAll(c)); + } + + public void testCount() { + assertEquals(0, this.bag.count("zero")); + assertEquals(1, this.bag.count("one")); + assertEquals(2, this.bag.count("two")); + assertEquals(3, this.bag.count("three")); + assertEquals(4, this.bag.count("four")); + assertEquals(0, this.bag.count("five")); + } + + public void testEquals() { + Bag<String> bag2 = this.buildBag(); + assertEquals(this.bag, bag2); + bag2.add("five"); + assertFalse(this.bag.equals(bag2)); + Collection<String> c = new ArrayList<String>(this.bag); + assertFalse(this.bag.equals(c)); + } + + public void testHashCode() { + Bag<String> bag2 = this.buildBag(); + assertEquals(this.bag.hashCode(), bag2.hashCode()); + } + + public void testIsEmpty() { + assertFalse(this.bag.isEmpty()); + this.bag.clear(); + assertTrue(this.bag.isEmpty()); + this.bag.add("foo"); + assertFalse(this.bag.isEmpty()); + } + + public void testEmptyIterator() { + this.bag.clear(); + Iterator<String> iterator = this.bag.iterator(); + assertFalse(iterator.hasNext()); + + boolean exCaught = false; + Object element = null; + try { + element = iterator.next(); + fail(element.toString()); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + + exCaught = false; + try { + iterator.remove(); + } catch (IllegalStateException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testIterator() { + int i = 0; + Iterator<String> iterator = this.bag.iterator(); + assertTrue(iterator.hasNext()); + while (iterator.hasNext()) { + iterator.next(); + i++; + } + assertEquals(11, i); + assertFalse(iterator.hasNext()); + + boolean exCaught = false; + Object element = null; + try { + element = iterator.next(); + fail(element.toString()); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + + iterator.remove(); + assertEquals(10, this.bag.size()); + + exCaught = false; + try { + iterator.remove(); + } catch (IllegalStateException ex) { + exCaught = true; + } + assertTrue(exCaught); + + // start over + iterator = this.bag.iterator(); + this.bag.add("five"); + exCaught = false; + try { + iterator.next(); + } catch (ConcurrentModificationException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testUniqueIterator() { + int i = 0; + Iterator<String> iterator = this.bag.uniqueIterator(); + assertTrue(iterator.hasNext()); + while (iterator.hasNext()) { + iterator.next(); + i++; + } + assertEquals(5, i); + assertFalse(iterator.hasNext()); + + boolean exCaught = false; + Object element = null; + try { + element = iterator.next(); + fail(element.toString()); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + + // start over + iterator = this.bag.uniqueIterator(); + Object next = null; + while (iterator.hasNext() && !"four".equals(next)) { + next = iterator.next(); + } + iterator.remove(); + assertEquals(7, this.bag.size()); + + exCaught = false; + try { + iterator.remove(); + } catch (IllegalStateException ex) { + exCaught = true; + } + assertTrue(exCaught); + + // start over + iterator = this.bag.uniqueIterator(); + this.bag.add("five"); + exCaught = false; + try { + iterator.next(); + } catch (ConcurrentModificationException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEntries() { + int i = 0; + Iterator<Bag.Entry<String>> iterator = this.bag.entries(); + assertTrue(iterator.hasNext()); + while (iterator.hasNext()) { + iterator.next(); + i++; + } + assertEquals(5, i); + assertFalse(iterator.hasNext()); + + boolean exCaught = false; + Object element = null; + try { + element = iterator.next(); + fail(element.toString()); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + + // start over + iterator = this.bag.entries(); + Bag.Entry<String> next = null; + while (iterator.hasNext()) { + next = iterator.next(); + if (next.getElement().equals("four")) { + iterator.remove(); + break; + } + } + assertEquals(7, this.bag.size()); + + exCaught = false; + try { + iterator.remove(); + } catch (IllegalStateException ex) { + exCaught = true; + } + assertTrue(exCaught); + + // start over + iterator = this.bag.entries(); + this.bag.add("five"); + exCaught = false; + try { + iterator.next(); + } catch (ConcurrentModificationException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testHashingDistribution() throws Exception { + Bag<String> bigBag = new HashBag<String>(); + for (int i = 0; i < 10000; i++) { + bigBag.add("object" + i); + } + + java.lang.reflect.Field field = bigBag.getClass().getDeclaredField("table"); + field.setAccessible(true); + Object[] table = (Object[]) field.get(bigBag); + int bucketCount = table.length; + int filledBucketCount = 0; + for (Object o : table) { + if (o != null) { + filledBucketCount++; + } + } + float loadFactor = ((float) filledBucketCount) / ((float) bucketCount); + if ((loadFactor < 0.20) || (loadFactor > 0.80)) { + String msg = "poor load factor: " + loadFactor; + if (Tools.jvmIsSun()) { + fail(msg); + } else { + // poor load factor is seen in the Eclipse build environment for some reason... + System.out.println(this.getClass().getName() + '.' + this.getName() + " - " + msg); + TestTools.printSystemProperties(); + } + } + } + + public void testRemove() { + assertTrue(this.bag.remove("one")); + assertFalse(this.bag.contains("one")); + assertFalse(this.bag.remove("one")); + + assertTrue(this.bag.remove("two")); + assertTrue(this.bag.remove("two")); + assertFalse(this.bag.contains("two")); + assertFalse(this.bag.remove("two")); + } + + public void testRemoveCount() { + assertFalse(this.bag.remove("one", 0)); + assertTrue(this.bag.contains("one")); + + assertTrue(this.bag.remove("one", 1)); + assertFalse(this.bag.contains("one")); + assertFalse(this.bag.remove("one")); + + assertFalse(this.bag.remove("two", -3)); + assertTrue(this.bag.remove("two", 1)); + assertTrue(this.bag.contains("two")); + + assertTrue(this.bag.remove("two", 1)); + assertFalse(this.bag.contains("two")); + assertFalse(this.bag.remove("two")); + + assertTrue(this.bag.remove("three", 3)); + assertFalse(this.bag.contains("three")); + assertFalse(this.bag.remove("three")); + } + + public void testRemoveAll() { + Collection<String> c = new ArrayList<String>(); + c.add("one"); + c.add("three"); + assertTrue(this.bag.removeAll(c)); + assertFalse(this.bag.contains("one")); + assertFalse(this.bag.contains("three")); + assertFalse(this.bag.remove("one")); + assertFalse(this.bag.remove("three")); + assertFalse(this.bag.removeAll(c)); + } + + public void testRetainAll() { + Collection<String> c = new ArrayList<String>(); + c.add("one"); + c.add("three"); + assertTrue(this.bag.retainAll(c)); + assertTrue(this.bag.contains("one")); + assertTrue(this.bag.contains("three")); + assertFalse(this.bag.contains("two")); + assertFalse(this.bag.contains("four")); + assertFalse(this.bag.remove("two")); + assertFalse(this.bag.remove("four")); + assertFalse(this.bag.retainAll(c)); + } + + public void testSize() { + assertTrue(this.bag.size() == 11); + this.bag.add("five"); + this.bag.add("five"); + this.bag.add("five"); + this.bag.add("five"); + this.bag.add("five"); + assertEquals(16, this.bag.size()); + } + + public void testSerialization() throws Exception { + Bag<String> bag2 = TestTools.serialize(this.bag); + + assertTrue("same object?", this.bag != bag2); + assertEquals(11, bag2.size()); + assertEquals(this.bag, bag2); + // look for similar elements + assertTrue(bag2.contains(null)); + assertTrue(bag2.contains("one")); + assertTrue(bag2.contains("two")); + assertTrue(bag2.contains("three")); + assertTrue(bag2.contains("four")); + + int nullCount = 0, oneCount = 0, twoCount = 0, threeCount = 0, fourCount = 0; + for (String s : bag2) { + if (s == null) { + nullCount++; + } else if (s.equals("one")) { + oneCount++; + } else if (s.equals("two")) { + twoCount++; + } else if (s.equals("three")) { + threeCount++; + } else if (s.equals("four")) { + fourCount++; + } + } + assertEquals(1, nullCount); + assertEquals(1, oneCount); + assertEquals(2, twoCount); + assertEquals(3, threeCount); + assertEquals(4, fourCount); + } + + public void testToArray() { + Object[] a = this.bag.toArray(); + assertEquals(11, a.length); + assertTrue(ArrayTools.contains(a, null)); + assertTrue(ArrayTools.contains(a, "one")); + assertTrue(ArrayTools.contains(a, "two")); + assertTrue(ArrayTools.contains(a, "three")); + assertTrue(ArrayTools.contains(a, "four")); + } + + public void testToArrayObjectArray() { + String[] a = new String[12]; + a[11] = "not null"; + String[] b = this.bag.toArray(a); + assertEquals(a, b); + assertEquals(12, a.length); + assertTrue(ArrayTools.contains(a, null)); + assertTrue(ArrayTools.contains(a, "one")); + assertTrue(ArrayTools.contains(a, "two")); + assertTrue(ArrayTools.contains(a, "three")); + assertTrue(ArrayTools.contains(a, "four")); + assertTrue(a[11] == null); + } + + public void testToString() { + String s = this.bag.toString(); + assertTrue(s.startsWith("[")); + assertTrue(s.endsWith("]")); + int commaCount = 0; + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == ',') { + commaCount++; + } + } + assertEquals(10, commaCount); + assertTrue(s.indexOf("one") != -1); + assertTrue(s.indexOf("two") != -1); + assertTrue(s.indexOf("three") != -1); + assertTrue(s.indexOf("four") != -1); + assertTrue(s.indexOf("null") != -1); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/IdentityHashBagTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/IdentityHashBagTests.java new file mode 100644 index 0000000000..f1738bdeb5 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/IdentityHashBagTests.java @@ -0,0 +1,573 @@ +/******************************************************************************* + * Copyright (c) 2007, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.ConcurrentModificationException; +import java.util.Iterator; +import java.util.NoSuchElementException; + +import junit.framework.TestCase; + +import org.eclipse.jpt.common.utility.internal.ArrayTools; +import org.eclipse.jpt.common.utility.internal.CollectionTools; +import org.eclipse.jpt.common.utility.internal.IdentityHashBag; +import org.eclipse.jpt.common.utility.internal.Tools; + +@SuppressWarnings("nls") +public class IdentityHashBagTests extends TestCase { + private IdentityHashBag<String> bag; + private String one = "one"; + private String two = "two"; + private String three = "three"; + private String four = "four"; + private String foo = "foo"; + private String bar = "bar"; + + public IdentityHashBagTests(String name) { + super(name); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + this.bag = this.buildBag(); + } + + protected IdentityHashBag<String> buildBag() { + IdentityHashBag<String> result = new IdentityHashBag<String>(); + result.add(null); + result.add(this.one); + result.add(this.two); + result.add(this.two); + result.add(this.three); + result.add(this.three); + result.add(this.three); + result.add(this.four); + result.add(this.four); + result.add(this.four); + result.add(this.four); + return result; + } + + @Override + protected void tearDown() throws Exception { + TestTools.clear(this); + super.tearDown(); + } + + private Collection<String> buildCollection() { + Collection<String> c = new ArrayList<String>(); + c.add(this.foo); + c.add(this.foo); + c.add(this.bar); + c.add(this.bar); + c.add(this.bar); + return c; + } + + public void testCtorCollection() { + Collection<String> c = this.buildCollection(); + IdentityHashBag<String> localBag = new IdentityHashBag<String>(c); + for (String s : c) { + assertTrue(localBag.contains(s)); + } + } + + public void testCtorIntFloat() { + boolean exCaught; + + exCaught = false; + try { + this.bag = new IdentityHashBag<String>(-20, 0.66f); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue("IllegalArgumentException not thrown", exCaught); + + exCaught = false; + try { + this.bag = new IdentityHashBag<String>(20, -0.66f); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue("IllegalArgumentException not thrown", exCaught); + } + + public void testAdd() { + // the other adds took place in setUp + String five = "five"; + assertTrue(this.bag.add(five)); + + assertTrue(this.bag.contains(this.one)); + assertTrue(this.bag.contains(this.two)); + assertTrue(this.bag.contains(this.three)); + assertTrue(this.bag.contains(this.four)); + assertTrue(this.bag.contains(five)); + } + + public void testAddCount() { + String minus3 = "minus3"; + String zero = "zero"; + String five = "five"; + // the other adds took place in setUp + this.bag.add(minus3, -3); + this.bag.add(zero, 0); + this.bag.add(five, 5); + + assertFalse(this.bag.contains(minus3)); + assertFalse(this.bag.contains(zero)); + assertEquals(1, this.bag.count(this.one)); + assertEquals(2, this.bag.count(this.two)); + assertEquals(3, this.bag.count(this.three)); + assertEquals(4, this.bag.count(this.four)); + assertEquals(5, this.bag.count(five)); + + this.bag.add(this.three, 2); + assertEquals(5, this.bag.count(this.three)); + } + + public void testAddAll() { + Collection<String> c = this.buildCollection(); + assertTrue(this.bag.addAll(c)); + for (String s : c) { + assertTrue(this.bag.contains(s)); + } + } + + public void testClear() { + assertTrue(this.bag.contains(this.one)); + assertTrue(this.bag.contains(this.two)); + assertTrue(this.bag.contains(this.three)); + assertTrue(this.bag.contains(this.four)); + assertTrue(this.bag.contains(null)); + assertEquals(11, this.bag.size()); + this.bag.clear(); + assertFalse(this.bag.contains(this.one)); + assertFalse(this.bag.contains(this.two)); + assertFalse(this.bag.contains(this.three)); + assertFalse(this.bag.contains(this.four)); + assertFalse(this.bag.contains(null)); + assertEquals(0, this.bag.size()); + } + + public void testClone() { + IdentityHashBag<String> bag2 = this.bag.clone(); + assertTrue("bad clone", this.bag != bag2); + assertEquals("bad clone", this.bag, bag2); + assertTrue("bad clone", this.bag.hashCode() == bag2.hashCode()); + } + + public void testContains() { + assertTrue(this.bag.contains(null)); + assertTrue(this.bag.contains(this.one)); + assertTrue(this.bag.contains(this.two)); + assertTrue(this.bag.contains(this.three)); + assertTrue(this.bag.contains(this.four)); + + assertFalse(this.bag.contains(new String("four"))); + assertFalse(this.bag.contains("five")); + } + + public void testContainsAll() { + Collection<String> c = new ArrayList<String>(); + c.add(null); + c.add(this.one); + c.add(this.two); + c.add(this.three); + c.add(this.four); + assertTrue(this.bag.containsAll(c)); + c.add(new String(this.four)); + assertFalse(this.bag.containsAll(c)); + } + + public void testCount() { + assertEquals(0, this.bag.count("zero")); + assertEquals(1, this.bag.count("one")); + assertEquals(2, this.bag.count("two")); + assertEquals(3, this.bag.count("three")); + assertEquals(4, this.bag.count("four")); + assertEquals(0, this.bag.count("five")); + } + + public void testEquals() { + IdentityHashBag<String> bag2 = this.buildBag(); + assertEquals(this.bag, bag2); + bag2.add("five"); + assertFalse(this.bag.equals(bag2)); + Collection<String> c = new ArrayList<String>(this.bag); + assertFalse(this.bag.equals(c)); + } + + public void testHashCode() { + IdentityHashBag<String> bag2 = this.buildBag(); + assertEquals(this.bag.hashCode(), bag2.hashCode()); + } + + public void testIsEmpty() { + assertFalse(this.bag.isEmpty()); + this.bag.clear(); + assertTrue(this.bag.isEmpty()); + this.bag.add("foo"); + assertFalse(this.bag.isEmpty()); + } + + public void testEmptyIterator() { + this.bag.clear(); + Iterator<String> iterator = this.bag.iterator(); + assertFalse(iterator.hasNext()); + + boolean exCaught = false; + Object element = null; + try { + element = iterator.next(); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue("NoSuchElementException not thrown: " + element, exCaught); + + exCaught = false; + try { + iterator.remove(); + } catch (IllegalStateException ex) { + exCaught = true; + } + assertTrue("IllegalStateException not thrown", exCaught); + } + + public void testIterator() { + int i = 0; + Iterator<String> iterator = this.bag.iterator(); + assertTrue(iterator.hasNext()); + while (iterator.hasNext()) { + iterator.next(); + i++; + } + assertEquals(11, i); + assertFalse(iterator.hasNext()); + + boolean exCaught = false; + Object element = null; + try { + element = iterator.next(); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue("NoSuchElementException not thrown: " + element, exCaught); + + iterator.remove(); + assertEquals(10, this.bag.size()); + + exCaught = false; + try { + iterator.remove(); + } catch (IllegalStateException ex) { + exCaught = true; + } + assertTrue("IllegalStateException not thrown", exCaught); + + // start over + iterator = this.bag.iterator(); + this.bag.add("five"); + exCaught = false; + try { + iterator.next(); + } catch (ConcurrentModificationException ex) { + exCaught = true; + } + assertTrue("ConcurrentModificationException not thrown", exCaught); + } + + public void testUniqueIterator() { + int i = 0; + Iterator<String> iterator = this.bag.uniqueIterator(); + assertTrue(iterator.hasNext()); + while (iterator.hasNext()) { + iterator.next(); + i++; + } + assertEquals(5, i); + assertFalse(iterator.hasNext()); + + boolean exCaught = false; + Object element = null; + try { + element = iterator.next(); + fail(element.toString()); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + + // start over + iterator = this.bag.uniqueIterator(); + Object next = null; + while (iterator.hasNext() && !this.four.equals(next)) { + next = iterator.next(); + } + iterator.remove(); + assertEquals(7, this.bag.size()); + + exCaught = false; + try { + iterator.remove(); + } catch (IllegalStateException ex) { + exCaught = true; + } + assertTrue(exCaught); + + // start over + iterator = this.bag.uniqueIterator(); + String five = "five"; + this.bag.add(five); + exCaught = false; + try { + iterator.next(); + } catch (ConcurrentModificationException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEntries() { + int i = 0; + Iterator<org.eclipse.jpt.common.utility.internal.Bag.Entry<String>> iterator = this.bag.entries(); + assertTrue(iterator.hasNext()); + while (iterator.hasNext()) { + iterator.next(); + i++; + } + assertEquals(5, i); + assertFalse(iterator.hasNext()); + + boolean exCaught = false; + Object element = null; + try { + element = iterator.next(); + fail(element.toString()); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + + // start over + iterator = this.bag.entries(); + org.eclipse.jpt.common.utility.internal.Bag.Entry<String> next = null; + while (iterator.hasNext()) { + next = iterator.next(); + if (next.getElement().equals(this.four)) { + iterator.remove(); + break; + } + } + assertEquals(7, this.bag.size()); + + exCaught = false; + try { + iterator.remove(); + } catch (IllegalStateException ex) { + exCaught = true; + } + assertTrue(exCaught); + + // start over + iterator = this.bag.entries(); + String five = "five"; + this.bag.add(five); + exCaught = false; + try { + iterator.next(); + } catch (ConcurrentModificationException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testHashingDistribution() throws Exception { + IdentityHashBag<String> bigBag = new IdentityHashBag<String>(); + for (int i = 0; i < 10000; i++) { + bigBag.add("object" + i); + } + + java.lang.reflect.Field field = bigBag.getClass().getDeclaredField("table"); + field.setAccessible(true); + Object[] table = (Object[]) field.get(bigBag); + int bucketCount = table.length; + int filledBucketCount = 0; + for (int i = 0; i < bucketCount; i++) { + if (table[i] != null) { + filledBucketCount++; + } + } + float loadFactor = ((float) filledBucketCount) / ((float) bucketCount); + if ((loadFactor < 0.20) || (loadFactor > 0.80)) { + String msg = "poor load factor: " + loadFactor; + if (Tools.jvmIsSun()) { + fail(msg); + } else { + // poor load factor is seen in the Eclipse build environment for some reason... + System.out.println(this.getClass().getName() + '.' + this.getName() + " - " + msg); + TestTools.printSystemProperties(); + } + } + } + + public void testRemove() { + assertTrue(this.bag.remove(this.one)); + assertFalse(this.bag.contains(this.one)); + assertFalse(this.bag.remove(this.one)); + + assertTrue(this.bag.remove(this.two)); + assertTrue(this.bag.remove(this.two)); + assertFalse(this.bag.contains(this.two)); + assertFalse(this.bag.remove(this.two)); + + assertFalse(this.bag.remove(new String(this.three))); + } + + public void testRemoveCount() { + assertFalse(this.bag.remove(this.one, 0)); + assertTrue(this.bag.contains(this.one)); + + assertTrue(this.bag.remove(this.one, 1)); + assertFalse(this.bag.contains(this.one)); + assertFalse(this.bag.remove(this.one)); + + assertFalse(this.bag.remove(this.two, -3)); + assertTrue(this.bag.remove(this.two, 1)); + assertTrue(this.bag.contains(this.two)); + + assertTrue(this.bag.remove(this.two, 1)); + assertFalse(this.bag.contains(this.two)); + assertFalse(this.bag.remove(this.two)); + + assertTrue(this.bag.remove(this.three, 3)); + assertFalse(this.bag.contains(this.three)); + assertFalse(this.bag.remove(this.three)); + } + + public void testRemoveAll() { + Collection<String> c = new ArrayList<String>(); + c.add(this.one); + c.add(new String(this.two)); + c.add(this.three); + assertTrue(this.bag.removeAll(c)); + assertFalse(this.bag.contains(this.one)); + assertTrue(this.bag.contains(this.two)); + assertFalse(this.bag.contains(this.three)); + assertFalse(this.bag.remove(this.one)); + assertTrue(this.bag.remove(this.two)); + assertFalse(this.bag.remove(this.three)); + assertFalse(this.bag.removeAll(c)); + } + + public void testRetainAll() { + Collection<String> c = new ArrayList<String>(); + c.add(this.one); + c.add(new String(this.two)); + c.add(this.three); + assertTrue(this.bag.retainAll(c)); + assertTrue(this.bag.contains(this.one)); + assertFalse(this.bag.contains(this.two)); + assertTrue(this.bag.contains(this.three)); + assertFalse(this.bag.contains(this.four)); + assertFalse(this.bag.remove(this.two)); + assertFalse(this.bag.remove(this.four)); + assertFalse(this.bag.retainAll(c)); + } + + public void testSize() { + assertTrue(this.bag.size() == 11); + String five = "five"; + this.bag.add(five); + this.bag.add(five); + this.bag.add(five); + this.bag.add(five); + this.bag.add(new String(five)); + assertEquals(16, this.bag.size()); + } + + public void testSerialization() throws Exception { + IdentityHashBag<String> bag2 = TestTools.serialize(this.bag); + + assertTrue("same object?", this.bag != bag2); + assertEquals(11, bag2.size()); + assertEquals(CollectionTools.bag(this.bag.iterator()), CollectionTools.bag(bag2.iterator())); + // look for similar elements + assertTrue(CollectionTools.bag(bag2.iterator()).contains(null)); + assertTrue(CollectionTools.bag(bag2.iterator()).contains("one")); + assertTrue(CollectionTools.bag(bag2.iterator()).contains("two")); + assertTrue(CollectionTools.bag(bag2.iterator()).contains("three")); + assertTrue(CollectionTools.bag(bag2.iterator()).contains("four")); + + int nullCount = 0, oneCount = 0, twoCount = 0, threeCount = 0, fourCount = 0; + for (String next : bag2) { + if (next == null) + nullCount++; + else if (next.equals("one")) + oneCount++; + else if (next.equals("two")) + twoCount++; + else if (next.equals("three")) + threeCount++; + else if (next.equals("four")) + fourCount++; + } + assertEquals(1, nullCount); + assertEquals(1, oneCount); + assertEquals(2, twoCount); + assertEquals(3, threeCount); + assertEquals(4, fourCount); + } + + public void testToArray() { + Object[] a = this.bag.toArray(); + assertEquals(11, a.length); + assertTrue(ArrayTools.contains(a, null)); + assertTrue(ArrayTools.contains(a, this.one)); + assertTrue(ArrayTools.contains(a, this.two)); + assertTrue(ArrayTools.contains(a, this.three)); + assertTrue(ArrayTools.contains(a, this.four)); + } + + public void testToArrayObjectArray() { + String[] a = new String[12]; + a[11] = "not null"; + String[] b = this.bag.toArray(a); + assertEquals(a, b); + assertEquals(12, a.length); + assertTrue(ArrayTools.contains(a, null)); + assertTrue(ArrayTools.contains(a, this.one)); + assertTrue(ArrayTools.contains(a, this.two)); + assertTrue(ArrayTools.contains(a, this.three)); + assertTrue(ArrayTools.contains(a, this.four)); + assertTrue(a[11] == null); + } + + public void testToString() { + String s = this.bag.toString(); + assertTrue(s.startsWith("[")); + assertTrue(s.endsWith("]")); + int commaCount = 0; + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == ',') { + commaCount++; + } + } + assertEquals("invalid number of commas", 10, commaCount); + assertTrue(s.indexOf("one") != -1); + assertTrue(s.indexOf("two") != -1); + assertTrue(s.indexOf("three") != -1); + assertTrue(s.indexOf("four") != -1); + assertTrue(s.indexOf("null") != -1); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/IndentingPrintWriterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/IndentingPrintWriterTests.java new file mode 100644 index 0000000000..33d331b5f6 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/IndentingPrintWriterTests.java @@ -0,0 +1,109 @@ +/******************************************************************************* + * Copyright (c) 2005, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import java.io.StringWriter; +import junit.framework.TestCase; + +import org.eclipse.jpt.common.utility.IndentingPrintWriter; + +@SuppressWarnings("nls") +public class IndentingPrintWriterTests extends TestCase { + StringWriter sw1; + StringWriter sw2; + IndentingPrintWriter ipw1; + IndentingPrintWriter ipw2; + + static final String CR = System.getProperty("line.separator"); + + public IndentingPrintWriterTests(String name) { + super(name); + } + + @Override + public void setUp() throws Exception { + super.setUp(); + this.sw1 = new StringWriter(); + this.ipw1 = new IndentingPrintWriter(this.sw1); + this.sw2 = new StringWriter(); + this.ipw2 = new IndentingPrintWriter(this.sw2, " "); // indent with 4 spaces instead of a tab + } + + @Override + protected void tearDown() throws Exception { + TestTools.clear(this); + super.tearDown(); + } + + public void testIndent() { + assertEquals("wrong indent level", 0, this.ipw1.getIndentLevel()); + this.ipw1.indent(); + assertEquals("wrong indent level", 1, this.ipw1.getIndentLevel()); + } + + public void testUndent() { + assertEquals("wrong indent level", 0, this.ipw1.getIndentLevel()); + this.ipw1.indent(); + assertEquals("wrong indent level", 1, this.ipw1.getIndentLevel()); + this.ipw1.undent(); + assertEquals("wrong indent level", 0, this.ipw1.getIndentLevel()); + } + + public void testIncrementIndentLevel() { + assertEquals("wrong indent level", 0, this.ipw1.getIndentLevel()); + this.ipw1.incrementIndentLevel(); + assertEquals("wrong indent level", 1, this.ipw1.getIndentLevel()); + } + + public void testDecrementIndentLevel() { + assertEquals("wrong indent level", 0, this.ipw1.getIndentLevel()); + this.ipw1.incrementIndentLevel(); + assertEquals("wrong indent level", 1, this.ipw1.getIndentLevel()); + this.ipw1.decrementIndentLevel(); + assertEquals("wrong indent level", 0, this.ipw1.getIndentLevel()); + } + + public void testPrintTab() { + String expected = "foo0" + CR + "\tfoo1" + CR + "\tfoo1" + CR + "\t\tfoo2" + CR + "\tfoo1" + CR + "\tfoo1" + CR + "foo0" + CR; + + this.ipw1.println("foo0"); + this.ipw1.indent(); + this.ipw1.println("foo1"); + this.ipw1.println("foo1"); + this.ipw1.indent(); + this.ipw1.println("foo2"); + this.ipw1.undent(); + this.ipw1.println("foo1"); + this.ipw1.println("foo1"); + this.ipw1.undent(); + this.ipw1.println("foo0"); + + assertEquals("bogus output", expected, this.sw1.toString()); + } + + public void testPrintSpaces() { + String expected = "foo0" + CR + " foo1" + CR + " foo1" + CR + " foo2" + CR + " foo1" + CR + " foo1" + CR + "foo0" + CR; + + this.ipw2.println("foo0"); + this.ipw2.indent(); + this.ipw2.println("foo1"); + this.ipw2.println("foo1"); + this.ipw2.indent(); + this.ipw2.println("foo2"); + this.ipw2.undent(); + this.ipw2.println("foo1"); + this.ipw2.println("foo1"); + this.ipw2.undent(); + this.ipw2.println("foo0"); + + assertEquals("bogus output", expected, this.sw2.toString()); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/JDBCTypeTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/JDBCTypeTests.java new file mode 100644 index 0000000000..7853463449 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/JDBCTypeTests.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * Copyright (c) 2005, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import java.sql.Types; +import junit.framework.TestCase; +import org.eclipse.jpt.common.utility.internal.JDBCType; + +@SuppressWarnings("nls") +public class JDBCTypeTests extends TestCase { + + public JDBCTypeTests(String name) { + super(name); + } + + public void testTypesSize() { + assertEquals(Types.class.getDeclaredFields().length, JDBCType.types().length); + } + + public void testName() { + JDBCType jdbcType; + jdbcType = JDBCType.type(Types.VARCHAR); + assertEquals("VARCHAR", jdbcType.name()); + + jdbcType = JDBCType.type(Types.INTEGER); + assertEquals("INTEGER", jdbcType.name()); + } + + public void testCode() { + JDBCType jdbcType; + jdbcType = JDBCType.type(Types.VARCHAR); + assertEquals(Types.VARCHAR, jdbcType.code()); + + jdbcType = JDBCType.type(Types.INTEGER); + assertEquals(Types.INTEGER, jdbcType.code()); + } + + public void testInvalidTypeCode() throws Exception { + boolean exCaught = false; + try { + JDBCType jdbcType = JDBCType.type(55); + fail("invalid JDBCType: " + jdbcType); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testInvalidTypeName() throws Exception { + boolean exCaught = false; + try { + JDBCType jdbcType = JDBCType.type("VARCHAR2"); + fail("invalid JDBCType: " + jdbcType); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/JavaTypeTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/JavaTypeTests.java new file mode 100644 index 0000000000..da07a02a38 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/JavaTypeTests.java @@ -0,0 +1,252 @@ +/******************************************************************************* + * Copyright (c) 2005, 2008 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import junit.framework.TestCase; +import org.eclipse.jpt.common.utility.JavaType; +import org.eclipse.jpt.common.utility.internal.SimpleJavaType; + +@SuppressWarnings("nls") +public class JavaTypeTests extends TestCase { + + public JavaTypeTests(String name) { + super(name); + } + + public void testInvalidElementTypeNull() throws Exception { + boolean exCaught = false; + try { + JavaType javaType = new SimpleJavaType(null, 0); + fail("invalid JavaType: " + javaType); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testInvalidElementTypeEmpty() throws Exception { + boolean exCaught = false; + try { + JavaType javaType = new SimpleJavaType("", 0); + fail("invalid JavaType: " + javaType); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testInvalidElementTypeArray() throws Exception { + boolean exCaught = false; + try { + JavaType javaType = new SimpleJavaType(java.lang.Object[].class.getName(), 0); + fail("invalid JavaType: " + javaType); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testInvalidArrayDepthNegative() throws Exception { + boolean exCaught = false; + try { + JavaType javaType = new SimpleJavaType(java.lang.Object.class.getName(), -2); + fail("invalid JavaType: " + javaType); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testInvalidVoidArray() throws Exception { + boolean exCaught = false; + try { + JavaType javaType = new SimpleJavaType(void.class.getName(), 2); + fail("invalid JavaType: " + javaType); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testElementTypeName() throws Exception { + JavaType javaType; + javaType = new SimpleJavaType(java.lang.Object.class); + assertEquals("java.lang.Object", javaType.getElementTypeName()); + + javaType = new SimpleJavaType(java.lang.Object[].class); + assertEquals("java.lang.Object", javaType.getElementTypeName()); + + javaType = new SimpleJavaType(int.class); + assertEquals("int", javaType.getElementTypeName()); + + javaType = new SimpleJavaType(int[].class); + assertEquals("int", javaType.getElementTypeName()); + + javaType = new SimpleJavaType(void.class); + assertEquals("void", javaType.getElementTypeName()); + + javaType = new SimpleJavaType(java.util.Map.Entry.class); + assertEquals("java.util.Map$Entry", javaType.getElementTypeName()); + + javaType = new SimpleJavaType(java.util.Map.Entry[][].class); + assertEquals("java.util.Map$Entry", javaType.getElementTypeName()); + } + + public void testArrayDepth() throws Exception { + JavaType javaType; + javaType = new SimpleJavaType(java.lang.Object.class); + assertEquals(0, javaType.getArrayDepth()); + + javaType = new SimpleJavaType(java.lang.Object[].class); + assertEquals(1, javaType.getArrayDepth()); + + javaType = new SimpleJavaType(int.class); + assertEquals(0, javaType.getArrayDepth()); + + javaType = new SimpleJavaType(int[].class); + assertEquals(1, javaType.getArrayDepth()); + + javaType = new SimpleJavaType(void.class); + assertEquals(0, javaType.getArrayDepth()); + + javaType = new SimpleJavaType(java.util.Map.Entry.class); + assertEquals(0, javaType.getArrayDepth()); + + javaType = new SimpleJavaType(java.util.Map.Entry[][].class); + assertEquals(2, javaType.getArrayDepth()); + } + + public void testIsArray() throws Exception { + JavaType javaType; + javaType = new SimpleJavaType(java.lang.Object.class); + assertFalse(javaType.isArray()); + + javaType = new SimpleJavaType(java.lang.Object[].class); + assertTrue(javaType.isArray()); + + javaType = new SimpleJavaType(int.class); + assertFalse(javaType.isArray()); + + javaType = new SimpleJavaType(int[].class); + assertTrue(javaType.isArray()); + + javaType = new SimpleJavaType(void.class); + assertFalse(javaType.isArray()); + + javaType = new SimpleJavaType(java.util.Map.Entry.class); + assertFalse(javaType.isArray()); + + javaType = new SimpleJavaType(java.util.Map.Entry[][].class); + assertTrue(javaType.isArray()); + } + + public void testJavaClass() throws Exception { + this.verifyJavaClass(java.lang.Object.class); + this.verifyJavaClass(java.lang.Object[].class); + this.verifyJavaClass(int.class); + this.verifyJavaClass(int[].class); + this.verifyJavaClass(void.class); + this.verifyJavaClass(java.util.Map.Entry.class); + this.verifyJavaClass(java.util.Map.Entry[][].class); + } + + private void verifyJavaClass(Class<?> javaClass) throws Exception { + JavaType javaType = new SimpleJavaType(javaClass); + assertEquals(javaClass, javaType.getJavaClass()); + } + + public void testJavaClassName() throws Exception { + JavaType javaType; + javaType = new SimpleJavaType(java.lang.Object.class); + assertEquals("java.lang.Object", javaType.getJavaClassName()); + + javaType = new SimpleJavaType(java.lang.Object[].class); + assertEquals("[Ljava.lang.Object;", javaType.getJavaClassName()); + + javaType = new SimpleJavaType(int.class); + assertEquals("int", javaType.getJavaClassName()); + + javaType = new SimpleJavaType(int[].class); + assertEquals("[I", javaType.getJavaClassName()); + + javaType = new SimpleJavaType(void.class); + assertEquals("void", javaType.getJavaClassName()); + + javaType = new SimpleJavaType(java.util.Map.Entry.class); + assertEquals("java.util.Map$Entry", javaType.getJavaClassName()); + + javaType = new SimpleJavaType(java.util.Map.Entry[][].class); + assertEquals("[[Ljava.util.Map$Entry;", javaType.getJavaClassName()); + } + + public void testDescribes() throws Exception { + this.verifyDescribes(java.lang.Object.class); + this.verifyDescribes(java.lang.Object[].class); + this.verifyDescribes(int.class); + this.verifyDescribes(int[].class); + this.verifyDescribes(void.class); + this.verifyDescribes(java.util.Map.Entry.class); + this.verifyDescribes(java.util.Map.Entry[][].class); + } + + private void verifyDescribes(Class<?> javaClass) throws Exception { + JavaType javaType = new SimpleJavaType(javaClass); + assertTrue(javaType.describes(javaClass)); + } + + public void testDeclaration() throws Exception { + JavaType javaType; + javaType = new SimpleJavaType(java.lang.Object.class); + assertEquals("java.lang.Object", javaType.declaration()); + + javaType = new SimpleJavaType(java.lang.Object[].class); + assertEquals("java.lang.Object[]", javaType.declaration()); + + javaType = new SimpleJavaType(int.class); + assertEquals("int", javaType.declaration()); + + javaType = new SimpleJavaType(int[].class); + assertEquals("int[]", javaType.declaration()); + + javaType = new SimpleJavaType(void.class); + assertEquals("void", javaType.declaration()); + + javaType = new SimpleJavaType(java.util.Map.Entry.class); + assertEquals("java.util.Map.Entry", javaType.declaration()); + + javaType = new SimpleJavaType(java.util.Map.Entry[][].class); + assertEquals("java.util.Map.Entry[][]", javaType.declaration()); + } + + public void testIsPrimitive() throws Exception { + JavaType javaType; + javaType = new SimpleJavaType(java.lang.Object.class); + assertFalse(javaType.isPrimitive()); + + javaType = new SimpleJavaType(java.lang.Object[].class); + assertFalse(javaType.isPrimitive()); + + javaType = new SimpleJavaType(int.class); + assertTrue(javaType.isPrimitive()); + + javaType = new SimpleJavaType(int[].class); + assertFalse(javaType.isPrimitive()); + + javaType = new SimpleJavaType(void.class); + assertTrue(javaType.isPrimitive()); + + javaType = new SimpleJavaType(java.util.Map.Entry.class); + assertFalse(javaType.isPrimitive()); + + javaType = new SimpleJavaType(java.util.Map.Entry[][].class); + assertFalse(javaType.isPrimitive()); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/JptUtilityTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/JptUtilityTests.java new file mode 100644 index 0000000000..71980e97d4 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/JptUtilityTests.java @@ -0,0 +1,90 @@ +/******************************************************************************* + * Copyright (c) 2005, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import junit.framework.Test; +import junit.framework.TestSuite; +import org.eclipse.jpt.common.utility.tests.internal.enumerations.JptUtilityEnumerationsTests; +import org.eclipse.jpt.common.utility.tests.internal.iterables.JptUtilityIterablesTests; +import org.eclipse.jpt.common.utility.tests.internal.iterators.JptUtilityIteratorsTests; +import org.eclipse.jpt.common.utility.tests.internal.model.JptUtilityModelTests; +import org.eclipse.jpt.common.utility.tests.internal.node.JptUtilityNodeTests; +import org.eclipse.jpt.common.utility.tests.internal.synchronizers.JptUtilitySynchronizersTests; + +/** + * decentralize test creation code + */ +public class JptUtilityTests { + + public static Test suite() { + TestSuite suite = new TestSuite(JptUtilityTests.class.getPackage().getName()); + + suite.addTest(JptUtilityEnumerationsTests.suite()); + suite.addTest(JptUtilityIterablesTests.suite()); + suite.addTest(JptUtilityIteratorsTests.suite()); + suite.addTest(JptUtilityModelTests.suite()); + suite.addTest(JptUtilityNodeTests.suite()); + suite.addTest(JptUtilitySynchronizersTests.suite()); + + suite.addTestSuite(ArrayToolsTests.class); + suite.addTestSuite(AsynchronousCommandExecutorTests.class); + suite.addTestSuite(BagTests.class); + suite.addTestSuite(BidiFilterTests.class); + suite.addTestSuite(BidiStringConverterTests.class); + suite.addTestSuite(BidiTransformerTests.class); + suite.addTestSuite(BitToolsTests.class); + suite.addTestSuite(SimpleBooleanReferenceTests.class); + suite.addTestSuite(BooleanToolsTests.class); + suite.addTestSuite(ClasspathTests.class); + suite.addTestSuite(ClassNameTests.class); + suite.addTestSuite(CollectionToolsTests.class); + suite.addTestSuite(CommandExecutorTests.class); + suite.addTestSuite(CommandRunnableTests.class); + suite.addTestSuite(CommandTests.class); + suite.addTestSuite(CompositeCommandTests.class); + suite.addTestSuite(ExceptionHandlerTests.class); + suite.addTestSuite(FileToolsTests.class); + suite.addTestSuite(FilterTests.class); + suite.addTestSuite(HashBagTests.class); + suite.addTestSuite(IdentityHashBagTests.class); + suite.addTestSuite(IndentingPrintWriterTests.class); + suite.addTestSuite(SimpleIntReferenceTests.class); + suite.addTestSuite(JavaTypeTests.class); + suite.addTestSuite(JDBCTypeTests.class); + suite.addTestSuite(KeyedSetTests.class); + suite.addTestSuite(ListenerListTests.class); + suite.addTestSuite(MethodSignatureTests.class); + suite.addTestSuite(NameToolsTests.class); + suite.addTestSuite(NotNullFilterTests.class); + suite.addTestSuite(RangeTests.class); + suite.addTestSuite(ReflectionToolsTests.class); + suite.addTestSuite(ReverseComparatorTests.class); + suite.addTestSuite(SimpleAssociationTests.class); + suite.addTestSuite(SimpleObjectReferenceTests.class); + suite.addTestSuite(SimpleQueueTests.class); + suite.addTestSuite(SimpleStackTests.class); + suite.addTestSuite(StringToolsTests.class); + suite.addTestSuite(SynchronizedBooleanTests.class); + suite.addTestSuite(SynchronizedIntTests.class); + suite.addTestSuite(SynchronizedObjectTests.class); + suite.addTestSuite(SynchronizedQueueTests.class); + suite.addTestSuite(SynchronizedStackTests.class); + suite.addTestSuite(ToolsTests.class); + suite.addTestSuite(XMLStringEncoderTests.class); + + return suite; + } + + private JptUtilityTests() { + super(); + throw new UnsupportedOperationException(); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/KeyedSetTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/KeyedSetTests.java new file mode 100644 index 0000000000..ac134669eb --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/KeyedSetTests.java @@ -0,0 +1,123 @@ +/******************************************************************************* + * Copyright (c) 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Oracle - initial API and implementation + *******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import junit.framework.TestCase; +import org.eclipse.jpt.common.utility.internal.KeyedSet; + +public class KeyedSetTests + extends TestCase { + + private KeyedSet<String, String> nicknames; + + + public KeyedSetTests(String name) { + super(name); + } + + + @Override + protected void setUp() throws Exception { + super.setUp(); + this.nicknames = this.buildNicknames(); + } + + private KeyedSet<String, String> buildNicknames() { + KeyedSet<String, String> ks = new KeyedSet<String, String>(); + ks.addItem("Jimmy", "James Sullivan"); + ks.addKey("Sully", "James Sullivan"); + ks.addItem("Bob", "Robert McKenna"); + ks.addKey("Mac", "Robert McKenna"); + return ks; + } + + @Override + protected void tearDown() throws Exception { + TestTools.clear(this); + super.tearDown(); + } + + public void testAddItem() { + // items added in setup + assertTrue(this.nicknames.containsItem("James Sullivan")); + assertTrue(this.nicknames.containsItem("Robert McKenna")); + + assertFalse(this.nicknames.containsItem("John Teasdale")); + this.nicknames.addItem("Jack", "John Teasdale"); + assertTrue(this.nicknames.containsItem("John Teasdale")); + + this.nicknames.addItem("Teaser", "John Teasdale"); + assertTrue(this.nicknames.containsItem("John Teasdale")); + assertTrue(this.nicknames.containsKey("Teaser")); + } + + public void testAddKey() { + // items added in setup + assertTrue(this.nicknames.containsKey("Jimmy")); + assertTrue(this.nicknames.containsKey("Sully")); + assertTrue(this.nicknames.containsKey("Bob")); + assertTrue(this.nicknames.containsKey("Mac")); + + assertFalse(this.nicknames.containsKey("Robbie")); + this.nicknames.addKey("Robbie", "Robert McKenna"); + assertTrue(this.nicknames.containsKey("Robbie")); + + boolean exceptionCaught = false; + try { + this.nicknames.addKey("Teaser", "John Teasdale"); + } + catch (IllegalArgumentException iae) { + exceptionCaught = true; + } + assertTrue(exceptionCaught); + } + + public void testGetItem() { + // items added in setup + assertEquals(this.nicknames.getItem("Jimmy"), "James Sullivan"); + assertEquals(this.nicknames.getItem("Sully"), "James Sullivan"); + assertEquals(this.nicknames.getItem("Bob"), "Robert McKenna"); + assertEquals(this.nicknames.getItem("Mac"), "Robert McKenna"); + assertNull(this.nicknames.getItem("Jack")); + } + + public void testRemoveItem() { + // items added in setup + assertTrue(this.nicknames.containsItem("James Sullivan")); + assertTrue(this.nicknames.containsKey("Jimmy")); + assertTrue(this.nicknames.containsKey("Sully")); + + assertTrue(this.nicknames.removeItem("James Sullivan")); + assertFalse(this.nicknames.containsItem("James Sullivan")); + assertFalse(this.nicknames.containsKey("Jimmy")); + assertFalse(this.nicknames.containsKey("Sully")); + + assertFalse(this.nicknames.removeItem("William Goldberg")); + } + + public void testRemoveKey() { + // items added in setup + assertTrue(this.nicknames.containsItem("James Sullivan")); + assertTrue(this.nicknames.containsKey("Jimmy")); + assertTrue(this.nicknames.containsKey("Sully")); + + assertTrue(this.nicknames.removeKey("Jimmy")); + assertTrue(this.nicknames.containsItem("James Sullivan")); + assertFalse(this.nicknames.containsKey("Jimmy")); + assertTrue(this.nicknames.containsKey("Sully")); + + assertTrue(this.nicknames.removeKey("Sully")); + assertFalse(this.nicknames.containsItem("James Sullivan")); + assertFalse(this.nicknames.containsKey("Jimmy")); + assertFalse(this.nicknames.containsKey("Sully")); + + assertFalse(this.nicknames.removeKey("Billy")); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ListenerListTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ListenerListTests.java new file mode 100644 index 0000000000..7dd0f52e9f --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ListenerListTests.java @@ -0,0 +1,194 @@ +/******************************************************************************* + * Copyright (c) 2008, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import java.io.Serializable; +import java.util.EventListener; + +import junit.framework.TestCase; + +import org.eclipse.jpt.common.utility.internal.CollectionTools; +import org.eclipse.jpt.common.utility.internal.ListenerList; +import org.eclipse.jpt.common.utility.internal.Tools; + +@SuppressWarnings("nls") +public class ListenerListTests extends TestCase { + + public ListenerListTests(String name) { + super(name); + } + + public void testGetListeners() throws Exception { + ListenerList<Listener> listenerList = new ListenerList<Listener>(Listener.class); + Listener listener1 = new LocalListener(); + Listener listener2 = new LocalListener(); + Iterable<Listener> listeners = listenerList.getListeners(); + assertEquals(0, CollectionTools.size(listeners)); + + listenerList.add(listener1); + listenerList.add(listener2); + listeners = listenerList.getListeners(); + assertEquals(2, CollectionTools.size(listeners)); + assertTrue(CollectionTools.contains(listeners, listener1)); + assertTrue(CollectionTools.contains(listeners, listener2)); + } + + public void testSize() throws Exception { + ListenerList<Listener> listenerList = new ListenerList<Listener>(Listener.class); + Listener listener1 = new LocalListener(); + Listener listener2 = new LocalListener(); + assertEquals(0, listenerList.size()); + + listenerList.add(listener1); + listenerList.add(listener2); + assertEquals(2, listenerList.size()); + } + + public void testIsEmpty() throws Exception { + ListenerList<Listener> listenerList = new ListenerList<Listener>(Listener.class); + Listener listener1 = new LocalListener(); + Listener listener2 = new LocalListener(); + assertTrue(listenerList.isEmpty()); + + listenerList.add(listener1); + listenerList.add(listener2); + assertFalse(listenerList.isEmpty()); + } + + public void testAdd_null() throws Exception { + ListenerList<Listener> listenerList = new ListenerList<Listener>(Listener.class); + boolean exCaught = false; + try { + listenerList.add(null); + fail("invalid listener list: " + listenerList); + } catch (NullPointerException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testAdd_duplicate() throws Exception { + ListenerList<Listener> listenerList = new ListenerList<Listener>(Listener.class); + Listener listener = new LocalListener(); + listenerList.add(listener); + + boolean exCaught = false; + try { + listenerList.add(listener); + fail("invalid listener list: " + listenerList); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testRemove() throws Exception { + ListenerList<Listener> listenerList = new ListenerList<Listener>(Listener.class); + Listener listener1 = new LocalListener(); + Listener listener2 = new LocalListener(); + listenerList.add(listener1); + listenerList.add(listener2); + assertTrue(CollectionTools.contains(listenerList.getListeners(), listener1)); + assertTrue(CollectionTools.contains(listenerList.getListeners(), listener2)); + + listenerList.remove(listener1); + assertFalse(CollectionTools.contains(listenerList.getListeners(), listener1)); + assertTrue(CollectionTools.contains(listenerList.getListeners(), listener2)); + + listenerList.remove(listener2); + assertFalse(CollectionTools.contains(listenerList.getListeners(), listener2)); + } + + public void testRemove_null() throws Exception { + ListenerList<Listener> listenerList = new ListenerList<Listener>(Listener.class); + boolean exCaught = false; + try { + listenerList.remove(null); + fail("invalid listener list: " + listenerList); + } catch (NullPointerException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testRemove_unregistered() throws Exception { + ListenerList<Listener> listenerList = new ListenerList<Listener>(Listener.class); + Listener listener = new LocalListener(); + listenerList.add(listener); + listenerList.remove(listener); + + boolean exCaught = false; + try { + listenerList.remove(listener); + fail("invalid listener list: " + listenerList); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testClear() throws Exception { + ListenerList<Listener> listenerList = new ListenerList<Listener>(Listener.class); + Listener listener1 = new LocalListener(); + Listener listener2 = new LocalListener(); + listenerList.add(listener1); + listenerList.add(listener2); + assertTrue(CollectionTools.contains(listenerList.getListeners(), listener1)); + assertTrue(CollectionTools.contains(listenerList.getListeners(), listener2)); + + listenerList.clear(); + assertFalse(CollectionTools.contains(listenerList.getListeners(), listener1)); + assertFalse(CollectionTools.contains(listenerList.getListeners(), listener2)); + } + + public void testSerialization() throws Exception { + // This test doesn't pass in the Eclipse build environment (Linux/IBM VM) for some reason + if (Tools.jvmIsSun()) { + this.verifySerialization(); + } + } + + private void verifySerialization() throws Exception { + ListenerList<Listener> listenerList = new ListenerList<Listener>(Listener.class); + Listener listener1 = new LocalListener(); + Listener listener2 = new LocalListener(); + listenerList.add(listener1); + listenerList.add(listener2); + + ListenerList<Listener> listenerList2 = TestTools.serialize(listenerList); + assertNotSame(listenerList, listenerList2); + assertEquals(2, listenerList2.size()); + + Listener listener3 = new NonSerializableListener(); + listenerList.add(listener3); + + listenerList2 = TestTools.serialize(listenerList); + assertNotSame(listenerList, listenerList2); + assertEquals(2, listenerList2.size()); + + } + + interface Listener extends EventListener { + void somethingHappened(); + } + + static class LocalListener implements Listener, Serializable { + public void somethingHappened() { + // do nothing + } + } + + static class NonSerializableListener implements Listener { + public void somethingHappened() { + // do nothing + } + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/MethodSignatureTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/MethodSignatureTests.java new file mode 100644 index 0000000000..6558e2f45f --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/MethodSignatureTests.java @@ -0,0 +1,208 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import java.lang.reflect.Method; +import java.util.Arrays; +import junit.framework.TestCase; +import org.eclipse.jpt.common.utility.JavaType; +import org.eclipse.jpt.common.utility.MethodSignature; +import org.eclipse.jpt.common.utility.internal.SimpleJavaType; +import org.eclipse.jpt.common.utility.internal.SimpleMethodSignature; + +@SuppressWarnings("nls") +public class MethodSignatureTests extends TestCase { + + public MethodSignatureTests(String name) { + super(name); + } + + public void testInvalidNameNull() throws Exception { + boolean exCaught = false; + try { + MethodSignature methodSignature = new SimpleMethodSignature((String) null); + fail("invalid MethodSignature: " + methodSignature); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testInvalidNameEmpty() throws Exception { + boolean exCaught = false; + try { + MethodSignature methodSignature = new SimpleMethodSignature(""); + fail("invalid MethodSignature: " + methodSignature); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testInvalidParameterTypesNull() throws Exception { + boolean exCaught = false; + try { + MethodSignature methodSignature = new SimpleMethodSignature("foo", (JavaType[]) null); + fail("invalid MethodSignature: " + methodSignature); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testInvalidParameterTypesNullItem() throws Exception { + boolean exCaught = false; + try { + MethodSignature methodSignature = new SimpleMethodSignature("foo", new JavaType[1]); + fail("invalid MethodSignature: " + methodSignature); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testInvalidParameterTypesVoidItem() throws Exception { + JavaType jt = new SimpleJavaType(void.class.getName()); + boolean exCaught = false; + try { + MethodSignature methodSignature = new SimpleMethodSignature("foo", new JavaType[] {jt}); + fail("invalid MethodSignature: " + methodSignature); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testInvalidParameterTypeNamesNull() throws Exception { + boolean exCaught = false; + try { + MethodSignature methodSignature = new SimpleMethodSignature("foo", (String[]) null); + fail("invalid MethodSignature: " + methodSignature); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testInvalidParameterTypeNamesNullItem() throws Exception { + boolean exCaught = false; + try { + MethodSignature methodSignature = new SimpleMethodSignature("foo", new String[1]); + fail("invalid MethodSignature: " + methodSignature); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testInvalidParameterJavaClassesNull() throws Exception { + boolean exCaught = false; + try { + MethodSignature methodSignature = new SimpleMethodSignature("foo", (Class<?>[]) null); + fail("invalid MethodSignature: " + methodSignature); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testInvalidParameterJavaClassesNullItem() throws Exception { + boolean exCaught = false; + try { + MethodSignature methodSignature = new SimpleMethodSignature("foo", new Class[1]); + fail("invalid MethodSignature: " + methodSignature); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testGetSignature0() throws Exception { + MethodSignature ms = new SimpleMethodSignature(this.getMethod("method0")); + assertEquals("method0()", ms.getSignature()); + } + + public void testGetSignature1() throws Exception { + MethodSignature ms = new SimpleMethodSignature(this.getMethod("method1")); + assertEquals("method1(int)", ms.getSignature()); + } + + public void testGetSignature2() throws Exception { + MethodSignature ms = new SimpleMethodSignature(this.getMethod("method2")); + assertEquals("method2(int, java.lang.String)", ms.getSignature()); + } + + public void testGetSignature3() throws Exception { + MethodSignature ms = new SimpleMethodSignature(this.getMethod("method3")); + assertEquals("method3(int, java.lang.String, java.lang.Object[][])", ms.getSignature()); + } + + public void testGetName() throws Exception { + MethodSignature ms = new SimpleMethodSignature(this.getMethod("method2")); + assertEquals("method2", ms.getName()); + } + + public void testGetParameterTypes() throws Exception { + MethodSignature ms = new SimpleMethodSignature(this.getMethod("method3")); + JavaType[] expected = new JavaType[3]; + expected[0] = new SimpleJavaType("int"); + expected[1] = new SimpleJavaType("java.lang.String"); + expected[2] = new SimpleJavaType("java.lang.Object", 2); + assertTrue(Arrays.equals(expected, ms.getParameterTypes())); + } + + public void testEquals() throws Exception { + Object ms1 = new SimpleMethodSignature(this.getMethod("method3")); + Object ms2 = new SimpleMethodSignature(this.getMethod("method3")); + assertNotSame(ms1, ms2); + assertEquals(ms1, ms1); + assertEquals(ms1, ms2); + assertEquals(ms1.hashCode(), ms2.hashCode()); + + Object ms3 = new SimpleMethodSignature(this.getMethod("method2")); + assertNotSame(ms1, ms3); + assertFalse(ms1.equals(ms3)); + } + + public void testClone() throws Exception { + SimpleMethodSignature ms1 = new SimpleMethodSignature(this.getMethod("method3")); + SimpleMethodSignature ms2 = (SimpleMethodSignature) ms1.clone(); + assertNotSame(ms1, ms2); + assertEquals(ms1, ms2); + } + + public void testSerialization() throws Exception { + SimpleMethodSignature ms1 = new SimpleMethodSignature(this.getMethod("method3")); + SimpleMethodSignature ms2 = TestTools.serialize(ms1); + assertNotSame(ms1, ms2); + assertEquals(ms1, ms2); + } + + private Method getMethod(String methodName) { + for (Method method : this.getClass().getMethods()) { + if (method.getName().equals(methodName)) { + return method; + } + } + throw new IllegalArgumentException("method not found: " + methodName); + } + + public void method0() { /* used by tests */ } + @SuppressWarnings("unused") public void method1(int foo) { /* used by tests */ } + @SuppressWarnings("unused") public void method2(int foo, String bar) { /* used by tests */ } + @SuppressWarnings("unused") public void method3(int foo, String bar, Object[][] baz) { /* used by tests */ } + + @SuppressWarnings("unused") public void methodA(int foo, String bar) { /* used by tests */ } + @SuppressWarnings("unused") public void methodA(int foo, String bar, String baz) { /* used by tests */ } + + @SuppressWarnings("unused") public void methodB(int foo, Object bar) { /* used by tests */ } + @SuppressWarnings("unused") public void methodB(int foo, String bar) { /* used by tests */ } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/MultiThreadedTestCase.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/MultiThreadedTestCase.java new file mode 100644 index 0000000000..10ac313cc0 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/MultiThreadedTestCase.java @@ -0,0 +1,141 @@ +/******************************************************************************* + * Copyright (c) 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import java.util.ArrayList; +import java.util.Vector; +import java.util.concurrent.ThreadFactory; + +import org.eclipse.jpt.common.utility.internal.CompositeException; + +import junit.framework.TestCase; + +/** + * This test case helps simplify the testing of multi-threaded code. + */ +@SuppressWarnings("nls") +public abstract class MultiThreadedTestCase + extends TestCase +{ + private final ArrayList<Thread> threads = new ArrayList<Thread>(); + /* private */ final Vector<Throwable> exceptions = new Vector<Throwable>(); + + /** + * The default "tick" is one second. + * Specify the appropriate system property to override. + */ + public static final String TICK_SYSTEM_PROPERTY_NAME = "org.eclipse.jpt.common.utility.tests.tick"; + public static final long TICK = Long.getLong(TICK_SYSTEM_PROPERTY_NAME, 1000).longValue(); + public static final long TWO_TICKS = 2 * TICK; + public static final long THREE_TICKS = 3 * TICK; + + /** + * Default constructor. + */ + public MultiThreadedTestCase() { + super(); + } + + /** + * Named constructor. + */ + public MultiThreadedTestCase(String name) { + super(name); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + /** + * Stop all the threads constructed during the test case. + * If any exceptions were thrown by the threads, re-throw them here. + */ + @Override + protected void tearDown() throws Exception { + for (Thread thread : this.threads) { + if (thread.isAlive()) { + throw new IllegalStateException("thread is still alive: " + thread); + } + } + if ( ! this.exceptions.isEmpty()) { + throw new CompositeException(this.exceptions); + } + TestTools.clear(this); + super.tearDown(); + } + + protected Thread buildThread(Runnable runnable) { + return this.buildThread(runnable, null); + } + + protected Thread buildThread(Runnable runnable, String name) { + Thread thread = new Thread(new RunnableWrapper(runnable)); + if (name != null) { + thread.setName(name); + } + this.threads.add(thread); + return thread; + } + + protected ThreadFactory buildThreadFactory() { + return new TestThreadFactory(); + } + + /** + * Convenience method that handles {@link InterruptedException}. + */ + public void sleep(long millis) { + TestTools.sleep(millis); + } + + + /** + * Wrap a runnable and log any exception it throws. + */ + public class TestThreadFactory implements ThreadFactory { + public Thread newThread(Runnable r) { + return MultiThreadedTestCase.this.buildThread(r); + } + } + + /** + * Simplify runnables that execute call that throws checked exceptions. + */ + public abstract class TestRunnable implements Runnable { + public final void run() { + try { + this.run_(); + } catch (Throwable ex) { + throw new RuntimeException(ex); + } + } + protected abstract void run_() throws Throwable; + } + + /** + * Wrap a runnable and log any exception it throws. + */ + private class RunnableWrapper implements Runnable { + private final Runnable runnable; + RunnableWrapper(Runnable runnable) { + super(); + this.runnable = runnable; + } + public void run() { + try { + this.runnable.run(); + } catch (Throwable ex) { + MultiThreadedTestCase.this.exceptions.add(ex); + } + } + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/NameToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/NameToolsTests.java new file mode 100644 index 0000000000..d486aab6b7 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/NameToolsTests.java @@ -0,0 +1,226 @@ +/******************************************************************************* + * Copyright (c) 2005, 2008 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import junit.framework.TestCase; +import org.eclipse.jpt.common.utility.internal.CollectionTools; +import org.eclipse.jpt.common.utility.internal.NameTools; + +@SuppressWarnings("nls") +public class NameToolsTests extends TestCase { + + public NameToolsTests(String name) { + super(name); + } + + public void testStringAbsentIgnoreCase() { + List<String> colorCollection = this.buildColorCollection(); + String returned = NameTools.uniqueNameForIgnoreCase("Taupe", colorCollection); + assertEquals("Taupe", returned); + } + + public void testStringPresentCaseDiffers() { + List<String> colorCollection = this.buildColorCollection(); + String returned = NameTools.uniqueNameFor("green", colorCollection); + assertEquals("green", returned); + } + + public void testStringPresentIgnoreCase() { + List<String> colorCollection = this.buildColorCollection(); + String returned = NameTools.uniqueNameForIgnoreCase("green", colorCollection); + assertEquals("green2", returned); + } + + public void testStringPresentWithAppendices() { + List<String> colorCollection = this.buildColorCollection(); + colorCollection.add("Red1"); + colorCollection.add("red2"); + String returned = NameTools.uniqueNameForIgnoreCase("red", colorCollection); + colorCollection.remove("Red1"); + colorCollection.remove("red2"); + assertEquals("red3", returned); + } + + private List<String> buildColorCollection() { + List<String> colorCollection = new ArrayList<String>(); + colorCollection.add("Red"); + colorCollection.add("Orange"); + colorCollection.add("Yellow"); + colorCollection.add("Green"); + colorCollection.add("Blue"); + colorCollection.add("Indigo"); + colorCollection.add("Violet"); + return colorCollection; + } + + public void testUniqueNameForCollection1() { + Collection<String> strings = new ArrayList<String>(); + strings.add("Oracle"); + strings.add("Oracle Corporation"); + strings.add("Oracle2"); + strings.add("oracle1"); + strings.add("Oracl"); + + assertEquals("Oracle3", NameTools.uniqueNameFor("Oracle", strings)); + assertEquals("Test", NameTools.uniqueNameFor("Test", strings)); + + assertEquals("Oracle3", NameTools.uniqueNameForIgnoreCase("Oracle", strings)); + assertEquals("oracle3", NameTools.uniqueNameForIgnoreCase("oracle", strings)); + assertEquals("Test", NameTools.uniqueNameForIgnoreCase("Test", strings)); + } + + public void testUniqueNameForCollection2() { + Collection<String> strings = new ArrayList<String>(); + strings.add("Oracle"); + strings.add("oracle"); + strings.add("Oracle2"); + strings.add("Oracle1"); + + assertEquals("Oracle3", NameTools.uniqueNameFor("Oracle", strings)); + assertEquals("Test", NameTools.uniqueNameFor("Test", strings)); + + strings.add("Oracle Corporation"); + assertEquals("Oracle3", NameTools.uniqueNameForIgnoreCase("Oracle", strings)); + assertEquals("oracle3", NameTools.uniqueNameForIgnoreCase("oracle", strings)); + assertEquals("Test", NameTools.uniqueNameForIgnoreCase("Test", strings)); + } + + public void testUniqueNameForCollection3() { + Collection<String> strings = new ArrayList<String>(); + strings.add("Oracle"); + strings.add("Oracle"); + strings.add("Oracle2"); + strings.add("Oracle1"); + + assertEquals("Oracle3", NameTools.uniqueNameFor("Oracle", strings)); + } + + public void testUniqueNameForIterator1() { + Collection<String> strings = new ArrayList<String>(); + strings.add("Oracle"); + strings.add("Oracle Corporation"); + strings.add("Oracle2"); + strings.add("oracle1"); + strings.add("Oracl"); + + assertEquals("Oracle3", NameTools.uniqueNameFor("Oracle", strings.iterator())); + assertEquals("Test", NameTools.uniqueNameFor("Test", strings.iterator())); + + assertEquals("Oracle3", NameTools.uniqueNameForIgnoreCase("Oracle", strings.iterator())); + assertEquals("oracle3", NameTools.uniqueNameForIgnoreCase("oracle", strings.iterator())); + assertEquals("Test", NameTools.uniqueNameForIgnoreCase("Test", strings.iterator())); + } + + public void testUniqueNameForIterator2() { + Collection<String> strings = new ArrayList<String>(); + strings.add("Oracle"); + strings.add("oracle"); + strings.add("Oracle2"); + strings.add("Oracle1"); + + assertEquals("Oracle3", NameTools.uniqueNameFor("Oracle", strings.iterator())); + assertEquals("Test", NameTools.uniqueNameFor("Test", strings.iterator())); + + strings.add("Oracle Corporation"); + assertEquals("Oracle3", NameTools.uniqueNameForIgnoreCase("Oracle", strings.iterator())); + assertEquals("oracle3", NameTools.uniqueNameForIgnoreCase("oracle", strings.iterator())); + assertEquals("Test", NameTools.uniqueNameForIgnoreCase("Test", strings.iterator())); + } + + public void testUniqueNameForIterator3() { + Collection<String> strings = new ArrayList<String>(); + strings.add("Oracle"); + strings.add("Oracle"); + strings.add("Oracle2"); + strings.add("Oracle1"); + + assertEquals("Oracle3", NameTools.uniqueNameFor("Oracle", strings.iterator())); + } + + public void testBuildQualifiedDatabaseObjectName() { + assertEquals("catalog.schema.name", NameTools.buildQualifiedDatabaseObjectName("catalog", "schema", "name")); + assertEquals("catalog..name", NameTools.buildQualifiedDatabaseObjectName("catalog", null, "name")); + assertEquals("schema.name", NameTools.buildQualifiedDatabaseObjectName(null, "schema", "name")); + assertEquals("name", NameTools.buildQualifiedDatabaseObjectName(null, null, "name")); + } + + public void testJavaReservedWords() { + assertTrue(CollectionTools.contains(NameTools.javaReservedWords(), "class")); + assertFalse(CollectionTools.contains(NameTools.javaReservedWords(), "Class")); + assertTrue(CollectionTools.contains(NameTools.javaReservedWords(), "private")); + } + + public void testconvertToJavaIdentifierString() { + assertEquals("foo", NameTools.convertToJavaIdentifier("foo")); + assertEquals("foo1", NameTools.convertToJavaIdentifier("foo1")); + assertEquals("private_", NameTools.convertToJavaIdentifier("private")); + assertEquals("throw_", NameTools.convertToJavaIdentifier("throw")); + assertEquals("_foo", NameTools.convertToJavaIdentifier("1foo")); + assertEquals("foo_", NameTools.convertToJavaIdentifier("foo%")); + assertEquals("foo__bar__", NameTools.convertToJavaIdentifier("foo bar ")); + } + + public void testconvertToJavaIdentifierStringChar() { + assertEquals("foo", NameTools.convertToJavaIdentifier("foo", '$')); + assertEquals("foo1", NameTools.convertToJavaIdentifier("foo1", '$')); + assertEquals("private$", NameTools.convertToJavaIdentifier("private", '$')); + assertEquals("throwss", NameTools.convertToJavaIdentifier("throw", 's')); + assertEquals("$foo", NameTools.convertToJavaIdentifier("1foo", '$')); + assertEquals("foo$", NameTools.convertToJavaIdentifier("foo%", '$')); + assertEquals("foo$$bar$$", NameTools.convertToJavaIdentifier("foo bar ", '$')); + + boolean exCaught = false; + try { + String s = NameTools.convertToJavaIdentifier("1foo", '7'); + fail("invalid string: \"" + s + "\""); + } catch (IllegalArgumentException ex) { + if (ex.getMessage().indexOf('7') != -1) { + exCaught = true; + } + } + assertTrue(exCaught); + + exCaught = false; + try { + String s = NameTools.convertToJavaIdentifier("foo%", '^'); + fail("invalid string: \"" + s + "\""); + } catch (IllegalArgumentException ex) { + if (ex.getMessage().indexOf('^') != -1) { + exCaught = true; + } + } + assertTrue(exCaught); + + exCaught = false; + try { + String s = NameTools.convertToJavaIdentifier("private", '^'); + fail("invalid string: \"" + s + "\""); + } catch (IllegalArgumentException ex) { + if (ex.getMessage().indexOf('^') != -1) { + exCaught = true; + } + } + assertTrue(exCaught); + + } + + public void testStringIsLegalJavaIdentifier() { + assertFalse(NameTools.stringIsLegalJavaIdentifier("class")); + assertTrue(NameTools.stringIsLegalJavaIdentifier("clasS")); + + assertFalse(NameTools.stringIsLegalJavaIdentifier("7foo")); + assertFalse(NameTools.stringIsLegalJavaIdentifier("foo@bar")); + assertTrue(NameTools.stringIsLegalJavaIdentifier("_foo")); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/NotNullFilterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/NotNullFilterTests.java new file mode 100644 index 0000000000..caf06708ae --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/NotNullFilterTests.java @@ -0,0 +1,37 @@ +/******************************************************************************* + * Copyright (c) 2009 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import junit.framework.TestCase; + +import org.eclipse.jpt.common.utility.Filter; +import org.eclipse.jpt.common.utility.internal.NotNullFilter; + +@SuppressWarnings("nls") +public class NotNullFilterTests extends TestCase { + + public NotNullFilterTests(String name) { + super(name); + } + + public void testNotNullFilter() { + Filter<String> filter = NotNullFilter.instance(); + assertTrue(filter.accept("")); + assertFalse(filter.accept(null)); + assertTrue(filter.accept("foo")); + assertTrue(filter.accept("bar")); + } + + public void testToString() { + Filter<String> filter = NotNullFilter.instance(); + assertNotNull(filter.toString()); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/RangeTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/RangeTests.java new file mode 100644 index 0000000000..dcd959295a --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/RangeTests.java @@ -0,0 +1,74 @@ +/******************************************************************************* + * Copyright (c) 2005, 2007 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import junit.framework.TestCase; +import org.eclipse.jpt.common.utility.internal.Range; + +public class RangeTests extends TestCase { + + public RangeTests(String name) { + super(name); + } + + public void testIncludes() { + Range range = new Range(5, 17); + assertFalse(range.includes(-55)); + assertFalse(range.includes(0)); + assertFalse(range.includes(4)); + assertTrue(range.includes(5)); + assertTrue(range.includes(6)); + assertTrue(range.includes(16)); + assertTrue(range.includes(17)); + assertFalse(range.includes(18)); + assertFalse(range.includes(200)); + } + + public void testEquals() { + Range range1 = new Range(5, 17); + Range range2 = new Range(5, 17); + assertNotSame(range1, range2); + assertEquals(range1, range1); + assertEquals(range1, range2); + assertEquals(range2, range1); + assertEquals(range1.hashCode(), range2.hashCode()); + + range2 = new Range(17, 5); + assertFalse(range1.equals(range2)); + assertFalse(range2.equals(range1)); + // although they are unequal, they can have the same hash code + assertEquals(range1.hashCode(), range2.hashCode()); + + range2 = new Range(5, 15); + assertFalse(range1.equals(range2)); + assertFalse(range2.equals(range1)); + } + + public void testClone() { + Range range1 = new Range(5, 17); + Range range2 = range1.clone(); + assertNotSame(range1, range2); + assertEquals(range1, range1); + assertEquals(range1, range2); + assertEquals(range2, range1); + assertEquals(range1.hashCode(), range2.hashCode()); + } + + public void testSerialization() throws Exception { + Range range1 = new Range(5, 17); + Range range2 = TestTools.serialize(range1); + assertNotSame(range1, range2); + assertEquals(range1, range1); + assertEquals(range1, range2); + assertEquals(range2, range1); + assertEquals(range1.hashCode(), range2.hashCode()); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ReflectionToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ReflectionToolsTests.java new file mode 100644 index 0000000000..d210cb0f5f --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ReflectionToolsTests.java @@ -0,0 +1,440 @@ +/******************************************************************************* + * Copyright (c) 2005, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Vector; + +import junit.framework.TestCase; + +import org.eclipse.jpt.common.utility.internal.CollectionTools; +import org.eclipse.jpt.common.utility.internal.ReflectionTools; +import org.eclipse.jpt.common.utility.internal.iterables.TransformationIterable; + +@SuppressWarnings("nls") +public class ReflectionToolsTests extends TestCase { + + private static String testStaticField; + + public ReflectionToolsTests(String name) { + super(name); + } + +// this is no longer true - it appears the JLS now defines the generated names... +// /** +// * Return the compiler-generated class name. The Eclipse compiler generates +// * "local" classes with names in the form "com.foo.Outer$1$Local"; while the +// * JDK compiler generates "com.foo.Outer$1Local". There might be other +// * differences.... ~bjv +// */ +// public static String compilerDependentClassNameFor(String className) { +// int index = className.indexOf("$1$"); +// if (index == -1) { +// return className; +// } +// try { +// Class.forName(className); +// } catch (ClassNotFoundException ex) { +// return className.substring(0, index + 2) + className.substring(index + 3); +// } +// return className; +// } +// +// private static String munge(String className) { +// return compilerDependentClassNameFor(className); +// } + + public void testAllFields() { + int fieldCount = 0; + fieldCount += java.util.Vector.class.getDeclaredFields().length; + fieldCount += java.util.AbstractList.class.getDeclaredFields().length; + fieldCount += java.util.AbstractCollection.class.getDeclaredFields().length; + fieldCount += java.lang.Object.class.getDeclaredFields().length; + Iterable<Field> fields = ReflectionTools.getAllFields(java.util.Vector.class); + assertEquals(fieldCount, CollectionTools.size(fields)); + assertTrue(CollectionTools.contains(this.fieldNames(fields), "modCount")); + assertTrue(CollectionTools.contains(this.fieldNames(fields), "serialVersionUID")); + assertTrue(CollectionTools.contains(this.fieldNames(fields), "capacityIncrement")); + assertTrue(CollectionTools.contains(this.fieldNames(fields), "elementCount")); + assertTrue(CollectionTools.contains(this.fieldNames(fields), "elementData")); + assertTrue(fields.iterator().next().isAccessible()); + } + + public void testAllMethods() { + int methodCount = 0; + methodCount += java.util.Vector.class.getDeclaredMethods().length; + methodCount += java.util.AbstractList.class.getDeclaredMethods().length; + methodCount += java.util.AbstractCollection.class.getDeclaredMethods().length; + methodCount += java.lang.Object.class.getDeclaredMethods().length; + Iterable<Method> methods = ReflectionTools.getAllMethods(java.util.Vector.class); + assertEquals(methodCount, CollectionTools.size(methods)); + assertTrue(CollectionTools.contains(this.methodNames(methods), "wait")); + assertTrue(CollectionTools.contains(this.methodNames(methods), "addElement")); + assertTrue(methods.iterator().next().isAccessible()); + } + + public void testNewInstanceClass() { + Vector<?> v = ReflectionTools.newInstance(java.util.Vector.class); + assertNotNull(v); + assertEquals(0, v.size()); + } + + public void testNewInstanceClassClassObject() { + int initialCapacity = 200; + Vector<?> v = ReflectionTools.newInstance(java.util.Vector.class, int.class, new Integer(initialCapacity)); + assertNotNull(v); + assertEquals(0, v.size()); + Object[] elementData = (Object[]) ReflectionTools.getFieldValue(v, "elementData"); + assertEquals(initialCapacity, elementData.length); + } + + public void testNewInstanceClassClassArrayObjectArray() { + int initialCapacity = 200; + Class<?>[] parmTypes = new Class[1]; + parmTypes[0] = int.class; + Object[] parms = new Object[1]; + parms[0] = new Integer(initialCapacity); + Vector<?> v = ReflectionTools.newInstance(java.util.Vector.class, parmTypes, parms); + assertNotNull(v); + assertEquals(0, v.size()); + Object[] elementData = (Object[]) ReflectionTools.getFieldValue(v, "elementData"); + assertEquals(initialCapacity, elementData.length); + + parms[0] = new Integer(-1); + boolean exCaught = false; + try { + v = ReflectionTools.newInstance(java.util.Vector.class, parmTypes, parms); + } catch (RuntimeException ex) { + exCaught = true; + } + assertTrue("RuntimeException not thrown", exCaught); + + parmTypes[0] = java.lang.String.class; + parms[0] = "foo"; + exCaught = false; + try { + v = ReflectionTools.newInstance(java.util.Vector.class, parmTypes, parms); + } catch (RuntimeException ex) { + if (ex.getCause() instanceof NoSuchMethodException) { + exCaught = true; + } + } + assertTrue("NoSuchMethodException not thrown", exCaught); + } + + public void testFieldValue() { + int initialCapacity = 200; + Vector<?> v = new Vector<Object>(initialCapacity); + Object[] elementData = (Object[]) ReflectionTools.getFieldValue(v, "elementData"); + assertEquals(initialCapacity, elementData.length); + + // test inherited field + Integer modCountInteger = (Integer) ReflectionTools.getFieldValue(v, "modCount"); + int modCount = modCountInteger.intValue(); + assertEquals(0, modCount); + + boolean exCaught = false; + Object bogusFieldValue = null; + try { + bogusFieldValue = ReflectionTools.getFieldValue(v, "bogusField"); + } catch (RuntimeException ex) { + if (ex.getCause() instanceof NoSuchFieldException) { + exCaught = true; + } + } + assertTrue("NoSuchFieldException not thrown: " + bogusFieldValue, exCaught); + } + + public void testExecuteMethodObjectString() { + Vector<String> v = new Vector<String>(); + int size = ((Integer) ReflectionTools.executeMethod(v, "size")).intValue(); + assertEquals(0, size); + + v.addElement("foo"); + size = ((Integer) ReflectionTools.executeMethod(v, "size")).intValue(); + assertEquals(1, size); + } + + public void testExecuteMethodObjectStringClassObject() { + Vector<String> v = new Vector<String>(); + boolean booleanResult = ((Boolean) ReflectionTools.executeMethod(v, "add", Object.class, "foo")).booleanValue(); + assertTrue(booleanResult); + assertTrue(v.contains("foo")); + Object voidResult = ReflectionTools.executeMethod(v, "addElement", Object.class, "bar"); + assertNull(voidResult); + } + + public void testExecuteMethodObjectStringClassArrayObjectArray() { + Vector<String> v = new Vector<String>(); + Class<?>[] parmTypes = new Class[1]; + parmTypes[0] = java.lang.Object.class; + Object[] parms = new Object[1]; + parms[0] = "foo"; + boolean booleanResult = ((Boolean) ReflectionTools.executeMethod(v, "add", parmTypes, parms)).booleanValue(); + assertTrue(booleanResult); + assertTrue(v.contains("foo")); + + boolean exCaught = false; + Object bogusMethodReturnValue = null; + try { + bogusMethodReturnValue = ReflectionTools.executeMethod(v, "bogusMethod", parmTypes, parms); + } catch (RuntimeException ex) { + if (ex.getCause() instanceof NoSuchMethodException) { + exCaught = true; + } + } + assertTrue("NoSuchMethodException not thrown: " + bogusMethodReturnValue, exCaught); + } + + public void testExecuteStaticMethodClassString() { + Double randomObject = (Double) ReflectionTools.executeStaticMethod(java.lang.Math.class, "random"); + assertNotNull(randomObject); + double random = randomObject.doubleValue(); + assertTrue(random >= 0); + assertTrue(random < 1); + } + + public void testExecuteStaticMethodClassStringClassObject() { + String s = (String) ReflectionTools.executeStaticMethod(java.lang.String.class, "valueOf", boolean.class, Boolean.TRUE); + assertNotNull(s); + assertEquals("true", s); + } + + public void testExecuteStaticMethodClassStringClassArrayObjectArray() { + Class<?>[] parmTypes = new Class[1]; + parmTypes[0] = boolean.class; + Object[] parms = new Object[1]; + parms[0] = Boolean.TRUE; + String s = (String) ReflectionTools.executeStaticMethod(java.lang.String.class, "valueOf", parmTypes, parms); + assertNotNull(s); + assertEquals("true", s); + + boolean exCaught = false; + Object bogusStaticMethodReturnValue = null; + try { + bogusStaticMethodReturnValue = ReflectionTools.executeStaticMethod(java.lang.String.class, "bogusStaticMethod", parmTypes, parms); + } catch (RuntimeException ex) { + if (ex.getCause() instanceof NoSuchMethodException) { + exCaught = true; + } + } + assertTrue("NoSuchMethodException not thrown: " + bogusStaticMethodReturnValue, exCaught); + + // test non-static method + exCaught = false; + try { + bogusStaticMethodReturnValue = ReflectionTools.executeStaticMethod(java.lang.String.class, "toString"); + } catch (RuntimeException ex) { + if (ex.getCause() instanceof NoSuchMethodException) { + exCaught = true; + } + } + assertTrue("NoSuchMethodException not thrown: " + bogusStaticMethodReturnValue, exCaught); + } + + public void testSetFieldValue() { + Vector<String> v = new Vector<String>(); + Object[] newElementData = new Object[5]; + newElementData[0] = "foo"; + ReflectionTools.setFieldValue(v, "elementData", newElementData); + ReflectionTools.setFieldValue(v, "elementCount", new Integer(1)); + // test inherited field + ReflectionTools.setFieldValue(v, "modCount", new Integer(1)); + assertTrue(v.contains("foo")); + + boolean exCaught = false; + try { + ReflectionTools.setFieldValue(v, "bogusField", "foo"); + } catch (RuntimeException ex) { + if (ex.getCause() instanceof NoSuchFieldException) { + exCaught = true; + } + } + assertTrue("NoSuchFieldException not thrown", exCaught); + } + + public void testSetStaticFieldValue() { + ReflectionTools.setStaticFieldValue(this.getClass(), "testStaticField", "new value"); + assertEquals(testStaticField, "new value"); + + boolean exCaught = false; + try { + ReflectionTools.setStaticFieldValue(this.getClass(), "bogusStaticField", "new value"); + } catch (RuntimeException ex) { + if (ex.getCause() instanceof NoSuchFieldException) { + exCaught = true; + } + } + assertTrue("NoSuchFieldException not thrown", exCaught); + } + + public void testSimpleName() { + assertEquals("Vector", java.util.Vector.class.getSimpleName()); + assertEquals("Entry", java.util.Map.Entry.class.getSimpleName()); + assertEquals("int", int.class.getSimpleName()); + assertEquals("int[]", int[].class.getSimpleName()); + assertEquals("int[][]", int[][].class.getSimpleName()); + assertEquals("void", void.class.getSimpleName()); + } + + public void testPackageName() { + assertEquals("java.util", java.util.Vector.class.getPackage().getName()); + assertEquals("java.util", java.util.Map.Entry.class.getPackage().getName()); + } + + public void testArrayDepthFor() { + assertEquals(0, ReflectionTools.getArrayDepth(java.util.Vector.class)); + assertEquals(0, ReflectionTools.getArrayDepth(int.class)); + assertEquals(0, ReflectionTools.getArrayDepth(void.class)); + assertEquals(1, ReflectionTools.getArrayDepth(java.util.Vector[].class)); + assertEquals(1, ReflectionTools.getArrayDepth(int[].class)); + assertEquals(3, ReflectionTools.getArrayDepth(java.util.Vector[][][].class)); + assertEquals(3, ReflectionTools.getArrayDepth(int[][][].class)); + } + + public void testElementTypeFor() { + assertEquals(java.util.Vector.class, ReflectionTools.getElementType(java.util.Vector.class)); + assertEquals(int.class, ReflectionTools.getElementType(int.class)); + assertEquals(void.class, ReflectionTools.getElementType(void.class)); + assertEquals(java.util.Vector.class, ReflectionTools.getElementType(java.util.Vector[].class)); + assertEquals(int.class, ReflectionTools.getElementType(int[].class)); + assertEquals(java.util.Vector.class, ReflectionTools.getElementType(java.util.Vector[][][].class)); + assertEquals(int.class, ReflectionTools.getElementType(int[][][].class)); + } + + public void testClassIsPrimitiveWrapperClass() { + assertTrue(ReflectionTools.classIsPrimitiveWrapper(java.lang.Void.class)); + assertTrue(ReflectionTools.classIsPrimitiveWrapper(java.lang.Boolean.class)); + assertTrue(ReflectionTools.classIsPrimitiveWrapper(java.lang.Integer.class)); + assertTrue(ReflectionTools.classIsPrimitiveWrapper(java.lang.Float.class)); + + assertFalse(ReflectionTools.classIsPrimitiveWrapper(java.lang.String.class)); + assertFalse(ReflectionTools.classIsPrimitiveWrapper(void.class)); + assertFalse(ReflectionTools.classIsPrimitiveWrapper(int.class)); + } + + public void testClassIsVariablePrimitiveWrapperClass() { + assertFalse(ReflectionTools.classIsVariablePrimitiveWrapper(java.lang.Void.class)); + + assertTrue(ReflectionTools.classIsVariablePrimitiveWrapper(java.lang.Boolean.class)); + assertTrue(ReflectionTools.classIsVariablePrimitiveWrapper(java.lang.Integer.class)); + assertTrue(ReflectionTools.classIsVariablePrimitiveWrapper(java.lang.Float.class)); + + assertFalse(ReflectionTools.classIsVariablePrimitiveWrapper(java.lang.String.class)); + assertFalse(ReflectionTools.classIsVariablePrimitiveWrapper(void.class)); + assertFalse(ReflectionTools.classIsVariablePrimitiveWrapper(int.class)); + } + + public void testWrapperClass() { + assertEquals(java.lang.Void.class, ReflectionTools.getWrapperClass(void.class)); + assertEquals(java.lang.Integer.class, ReflectionTools.getWrapperClass(int.class)); + assertEquals(java.lang.Float.class, ReflectionTools.getWrapperClass(float.class)); + assertEquals(java.lang.Boolean.class, ReflectionTools.getWrapperClass(boolean.class)); + + assertNull(ReflectionTools.getWrapperClass(java.lang.String.class)); + } + + public void testClassForTypeDeclarationStringInt() throws Exception { + assertEquals(int.class, ReflectionTools.getClassForTypeDeclaration("int", 0)); + assertEquals(int[].class, ReflectionTools.getClassForTypeDeclaration("int", 1)); + assertEquals(int[][][].class, ReflectionTools.getClassForTypeDeclaration("int", 3)); + + assertEquals(Object.class, ReflectionTools.getClassForTypeDeclaration("java.lang.Object", 0)); + assertEquals(Object[][][].class, ReflectionTools.getClassForTypeDeclaration("java.lang.Object", 3)); + + assertEquals(void.class, ReflectionTools.getClassForTypeDeclaration("void", 0)); + try { + ReflectionTools.getClassForTypeDeclaration(void.class.getName(), 1); + fail("should not get here..."); + } catch (RuntimeException ex) { + // expected + } + } + + public void testCodeForClass() { + assertEquals('I', ReflectionTools.getCodeForClass(int.class)); + assertEquals('B', ReflectionTools.getCodeForClass(byte.class)); + } + + public void testClassNameForTypeDeclarationString() throws Exception { + assertEquals("int", ReflectionTools.getClassNameForTypeDeclaration("int")); + assertEquals("[I", ReflectionTools.getClassNameForTypeDeclaration("int[]")); + assertEquals("[[I", ReflectionTools.getClassNameForTypeDeclaration("int [ ] [ ]")); + + assertEquals("java.lang.Object", ReflectionTools.getClassNameForTypeDeclaration("java.lang.Object")); + assertEquals("[Ljava.lang.Object;", ReflectionTools.getClassNameForTypeDeclaration("java.lang.Object\t[]")); + assertEquals("[[Ljava.lang.Object;", ReflectionTools.getClassNameForTypeDeclaration("java.lang.Object\t[]\t[]")); + } + + public void testArrayDepthForTypeDeclarationString() throws Exception { + assertEquals(0, ReflectionTools.getArrayDepthForTypeDeclaration("java.lang.Object")); + assertEquals(1, ReflectionTools.getArrayDepthForTypeDeclaration("java.lang.Object[]")); + assertEquals(3, ReflectionTools.getArrayDepthForTypeDeclaration("java.lang.Object[][][]")); + + assertEquals(0, ReflectionTools.getArrayDepthForTypeDeclaration("int")); + assertEquals(1, ReflectionTools.getArrayDepthForTypeDeclaration("int[]")); + assertEquals(3, ReflectionTools.getArrayDepthForTypeDeclaration("int[][][]")); + + assertEquals(0, ReflectionTools.getArrayDepthForTypeDeclaration("float")); + assertEquals(1, ReflectionTools.getArrayDepthForTypeDeclaration("float [ ]")); + assertEquals(3, ReflectionTools.getArrayDepthForTypeDeclaration("float[] [] []")); + } + + public void testElementTypeNameForTypeDeclarationString() throws Exception { + assertEquals("java.lang.Object", ReflectionTools.getElementTypeNameForTypeDeclaration("java.lang.Object")); + assertEquals("java.lang.Object", ReflectionTools.getElementTypeNameForTypeDeclaration("java.lang.Object[]")); + assertEquals("java.lang.Object", ReflectionTools.getElementTypeNameForTypeDeclaration("java.lang.Object[][][]")); + + assertEquals("int", ReflectionTools.getElementTypeNameForTypeDeclaration("int")); + assertEquals("int", ReflectionTools.getElementTypeNameForTypeDeclaration("int[]")); + assertEquals("int", ReflectionTools.getElementTypeNameForTypeDeclaration("int[][][]")); + + assertEquals("float", ReflectionTools.getElementTypeNameForTypeDeclaration("float")); + assertEquals("float", ReflectionTools.getElementTypeNameForTypeDeclaration("float [ ]")); + assertEquals("float", ReflectionTools.getElementTypeNameForTypeDeclaration("float[] [] []")); + } + + public void testClassNameForTypeDeclarationStringInt() throws Exception { + assertEquals(int.class.getName(), ReflectionTools.getClassNameForTypeDeclaration("int", 0)); + assertEquals(int[].class.getName(), ReflectionTools.getClassNameForTypeDeclaration("int", 1)); + assertEquals(int[][][].class.getName(), ReflectionTools.getClassNameForTypeDeclaration("int", 3)); + + assertEquals(Object.class.getName(), ReflectionTools.getClassNameForTypeDeclaration("java.lang.Object", 0)); + assertEquals(Object[][][].class.getName(), ReflectionTools.getClassNameForTypeDeclaration("java.lang.Object", 3)); + + assertEquals(void.class.getName(), ReflectionTools.getClassNameForTypeDeclaration("void", 0)); + try { + ReflectionTools.getClassNameForTypeDeclaration(void.class.getName(), 1); + fail("should not get here..."); + } catch (IllegalArgumentException ex) { + // expected + } + } + + private Iterable<String> fieldNames(Iterable<Field> fields) { + return new TransformationIterable<Field, String>(fields) { + @Override + protected String transform(Field field) { + return field.getName(); + } + }; + } + + private Iterable<String> methodNames(Iterable<Method> methods) { + return new TransformationIterable<Method, String>(methods) { + @Override + protected String transform(Method method) { + return method.getName(); + } + }; + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ReverseComparatorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ReverseComparatorTests.java new file mode 100644 index 0000000000..1287868a13 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ReverseComparatorTests.java @@ -0,0 +1,102 @@ +/******************************************************************************* + * Copyright (c) 2005, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import junit.framework.TestCase; +import org.eclipse.jpt.common.utility.internal.ReverseComparator; + +@SuppressWarnings("nls") +public class ReverseComparatorTests extends TestCase { + private Comparator<String> naturalReverseComparator; + private Comparator<String> customComparator; + private Comparator<String> customReverseComparator; + + public ReverseComparatorTests(String name) { + super(name); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + this.naturalReverseComparator = new ReverseComparator<String>(); + this.customComparator = this.buildCustomComparator(); + this.customReverseComparator = new ReverseComparator<String>(this.customComparator); + } + + private Comparator<String> buildCustomComparator() { + return new Comparator<String>() { + public int compare(String s1, String s2) { + String lower1 = s1.toLowerCase(); + String lower2 = s2.toLowerCase(); + int result = lower1.compareTo(lower2); + if (result == 0) { + return s1.compareTo(s2); // use case to differentiate "equal" strings + } + return result; + } + }; + } + + private List<String> buildUnsortedList() { + List<String> result = new ArrayList<String>(); + result.add("T"); + result.add("Z"); + result.add("Y"); + result.add("M"); + result.add("m"); + result.add("a"); + result.add("B"); + result.add("b"); + result.add("A"); + return result; + } + + private List<String> buildNaturallySortedList() { + List<String> result = new ArrayList<String>(this.buildUnsortedList()); + Collections.sort(result); + return result; + } + + private List<String> buildCustomSortedList() { + List<String> result = new ArrayList<String>(this.buildUnsortedList()); + Collections.sort(result, this.customComparator); + return result; + } + + @Override + protected void tearDown() throws Exception { + TestTools.clear(this); + super.tearDown(); + } + + public void testNatural() { + List<String> list = this.buildUnsortedList(); + Collections.sort(list, this.naturalReverseComparator); + this.verifyList(this.buildNaturallySortedList(), list); + } + + public void testCustom() { + List<String> list = this.buildUnsortedList(); + Collections.sort(list, this.customReverseComparator); + this.verifyList(this.buildCustomSortedList(), list); + } + + private void verifyList(List<String> normal, List<String> reverse) { + int size = normal.size(); + int max = size - 1; + for (int i = 0; i < size; i++) { + assertEquals(normal.get(i), reverse.get(max - i)); + } + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleAssociationTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleAssociationTests.java new file mode 100644 index 0000000000..96fe163217 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleAssociationTests.java @@ -0,0 +1,112 @@ +/******************************************************************************* + * Copyright (c) 2008, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; +import org.eclipse.jpt.common.utility.internal.Association; +import org.eclipse.jpt.common.utility.internal.SimpleAssociation; + +@SuppressWarnings("nls") +public class SimpleAssociationTests extends TestCase { + private SimpleAssociation<String, String> assoc; + + public static Test suite() { + return new TestSuite(SimpleAssociationTests.class); + } + + public SimpleAssociationTests(String name) { + super(name); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + this.assoc = new SimpleAssociation<String, String>("foo", "bar"); + } + + @Override + protected void tearDown() throws Exception { + TestTools.clear(this); + super.tearDown(); + } + + public void testGetKey() { + assertEquals("foo", this.assoc.getKey()); + } + + public void testGetValue() { + assertEquals("bar", this.assoc.getValue()); + } + + public void testSetValue() { + assertEquals("bar", this.assoc.getValue()); + this.assoc.setValue("baz"); + assertEquals("baz", this.assoc.getValue()); + } + + public void testEquals() { + assertFalse(this.assoc.equals("foo")); + + assertEquals(this.assoc, this.copy(this.assoc)); + + SimpleAssociation<String, String> assoc2 = new SimpleAssociation<String, String>("foo", "baz"); + assertFalse(this.assoc.equals(assoc2)); + + assoc2 = new SimpleAssociation<String, String>("fop", "bar"); + assertFalse(this.assoc.equals(assoc2)); + + SimpleAssociation<String, String> assoc3 = new SimpleAssociation<String, String>(null, null); + SimpleAssociation<String, String> assoc4 = new SimpleAssociation<String, String>(null, null); + assertEquals(assoc3, assoc4); + } + + public void testHashCode() { + assertEquals(this.assoc.hashCode(), this.copy(this.assoc).hashCode()); + + SimpleAssociation<String, String> assoc2 = new SimpleAssociation<String, String>(null, null); + assertEquals(assoc2.hashCode(), this.copy(assoc2).hashCode()); + } + + public void testToString() { + assertNotNull(this.assoc.toString()); + } + + public void testClone() { + this.verifyClone(this.assoc, this.assoc.clone()); + } + + private void verifyClone(Association<String, String> expected, Association<String, String> actual) { + assertEquals(expected, actual); + assertNotSame(expected, actual); + assertEquals(expected.getKey(), actual.getKey()); + assertSame(expected.getKey(), actual.getKey()); + assertEquals(expected.getValue(), actual.getValue()); + assertSame(expected.getValue(), actual.getValue()); + } + + public void testSerialization() throws Exception { + @SuppressWarnings("cast") + Association<String, String> assoc2 = (Association<String, String>) TestTools.serialize(this.assoc); + + assertEquals(this.assoc, assoc2); + assertNotSame(this.assoc, assoc2); + assertEquals(this.assoc.getKey(), assoc2.getKey()); + assertNotSame(this.assoc.getKey(), assoc2.getKey()); + assertEquals(this.assoc.getValue(), assoc2.getValue()); + assertNotSame(this.assoc.getValue(), assoc2.getValue()); + } + + private SimpleAssociation<String, String> copy(SimpleAssociation<String, String> sa) { + return new SimpleAssociation<String, String>(sa.getKey(), sa.getValue()); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleBooleanReferenceTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleBooleanReferenceTests.java new file mode 100644 index 0000000000..04c06ddde3 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleBooleanReferenceTests.java @@ -0,0 +1,110 @@ +/******************************************************************************* + * Copyright (c) 2008, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import junit.framework.TestCase; +import org.eclipse.jpt.common.utility.internal.SimpleBooleanReference; + +@SuppressWarnings("nls") +public class SimpleBooleanReferenceTests extends TestCase { + + public SimpleBooleanReferenceTests(String name) { + super(name); + } + + public void testGetValue() { + SimpleBooleanReference br = new SimpleBooleanReference(true); + assertTrue(br.getValue()); + } + + public void testGetValueDefault() { + SimpleBooleanReference br = new SimpleBooleanReference(); + assertFalse(br.getValue()); + } + + public void testIs() { + SimpleBooleanReference br = new SimpleBooleanReference(true); + assertTrue(br.is(true)); + assertFalse(br.is(false)); + } + + public void testIsNot() { + SimpleBooleanReference br = new SimpleBooleanReference(true); + assertFalse(br.isNot(true)); + assertTrue(br.isNot(false)); + } + + public void testIsTrue() { + SimpleBooleanReference br = new SimpleBooleanReference(true); + assertTrue(br.isTrue()); + } + + public void testIsFalse() { + SimpleBooleanReference br = new SimpleBooleanReference(true); + assertFalse(br.isFalse()); + br.setFalse(); + assertTrue(br.isFalse()); + } + + public void testSetValue() { + SimpleBooleanReference br = new SimpleBooleanReference(true); + assertTrue(br.getValue()); + br.setValue(false); + assertFalse(br.getValue()); + } + + public void testFlip() { + SimpleBooleanReference br = new SimpleBooleanReference(true); + assertTrue(br.getValue()); + assertFalse(br.flip()); + assertFalse(br.getValue()); + assertTrue(br.flip()); + assertTrue(br.getValue()); + } + + public void testSetNotBoolean() { + SimpleBooleanReference br = new SimpleBooleanReference(false); + assertFalse(br.getValue()); + br.setNot(true); + assertFalse(br.getValue()); + br.setNot(true); + assertFalse(br.getValue()); + br.setNot(false); + assertTrue(br.getValue()); + } + + public void testSetTrue() { + SimpleBooleanReference br = new SimpleBooleanReference(false); + assertFalse(br.getValue()); + br.setTrue(); + assertTrue(br.getValue()); + } + + public void testSetFalse() { + SimpleBooleanReference br = new SimpleBooleanReference(true); + assertTrue(br.getValue()); + br.setFalse(); + assertFalse(br.getValue()); + } + + public void testClone() { + SimpleBooleanReference br = new SimpleBooleanReference(true); + SimpleBooleanReference clone = br.clone(); + assertTrue(clone.getValue()); + } + + public void testToString() { + SimpleBooleanReference br1 = new SimpleBooleanReference(true); + assertEquals("[true]", br1.toString()); + br1.setFalse(); + assertEquals("[false]", br1.toString()); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleIntReferenceTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleIntReferenceTests.java new file mode 100644 index 0000000000..196570b6de --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleIntReferenceTests.java @@ -0,0 +1,314 @@ +/******************************************************************************* + * Copyright (c) 2007, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import junit.framework.TestCase; +import org.eclipse.jpt.common.utility.internal.SimpleIntReference; + +@SuppressWarnings("nls") +public class SimpleIntReferenceTests extends TestCase { + + public SimpleIntReferenceTests(String name) { + super(name); + } + + public void testCtors() { + SimpleIntReference ir; + ir = new SimpleIntReference(); + assertEquals(0, ir.getValue()); + ir = new SimpleIntReference(7); + assertEquals(7, ir.getValue()); + ir = new SimpleIntReference(-7); + assertEquals(-7, ir.getValue()); + } + + public void testEqualsInt() { + SimpleIntReference ir; + ir = new SimpleIntReference(); + assertTrue(ir.equals(0)); + assertFalse(ir.equals(7)); + + ir = new SimpleIntReference(7); + assertTrue(ir.equals(7)); + assertFalse(ir.equals(0)); + } + + public void testNotEqualInt() { + SimpleIntReference ir; + ir = new SimpleIntReference(); + assertFalse(ir.notEqual(0)); + assertTrue(ir.notEqual(7)); + + ir = new SimpleIntReference(7); + assertFalse(ir.notEqual(7)); + assertTrue(ir.notEqual(0)); + } + + public void testIsZero() { + SimpleIntReference ir; + ir = new SimpleIntReference(); + assertTrue(ir.isZero()); + + ir = new SimpleIntReference(7); + assertFalse(ir.isZero()); + } + + public void testIsNotZero() { + SimpleIntReference ir; + ir = new SimpleIntReference(); + assertFalse(ir.isNotZero()); + + ir = new SimpleIntReference(7); + assertTrue(ir.isNotZero()); + } + + public void testIsGreaterThanInt() { + SimpleIntReference ir; + ir = new SimpleIntReference(); + assertTrue(ir.isGreaterThan(-1)); + assertFalse(ir.isGreaterThan(0)); + assertFalse(ir.isGreaterThan(7)); + } + + public void testIsGreaterThanOrEqualInt() { + SimpleIntReference ir; + ir = new SimpleIntReference(); + assertTrue(ir.isGreaterThanOrEqual(-1)); + assertTrue(ir.isGreaterThanOrEqual(0)); + assertFalse(ir.isGreaterThanOrEqual(7)); + } + + public void testIsLessThanInt() { + SimpleIntReference ir; + ir = new SimpleIntReference(); + assertFalse(ir.isLessThan(-1)); + assertFalse(ir.isLessThan(0)); + assertTrue(ir.isLessThan(7)); + } + + public void testIsLessThanOrEqualInt() { + SimpleIntReference ir; + ir = new SimpleIntReference(); + assertFalse(ir.isLessThanOrEqual(-1)); + assertTrue(ir.isLessThanOrEqual(0)); + assertTrue(ir.isLessThanOrEqual(7)); + } + + public void testIsPositive() { + SimpleIntReference ir; + ir = new SimpleIntReference(-3); + assertFalse(ir.isPositive()); + + ir = new SimpleIntReference(); + assertFalse(ir.isPositive()); + + ir = new SimpleIntReference(7); + assertTrue(ir.isPositive()); + } + + public void testIsNotPositive() { + SimpleIntReference ir; + ir = new SimpleIntReference(-3); + assertTrue(ir.isNotPositive()); + + ir = new SimpleIntReference(); + assertTrue(ir.isNotPositive()); + + ir = new SimpleIntReference(7); + assertFalse(ir.isNotPositive()); + } + + public void testIsNegative() { + SimpleIntReference ir; + ir = new SimpleIntReference(-3); + assertTrue(ir.isNegative()); + + ir = new SimpleIntReference(); + assertFalse(ir.isNegative()); + + ir = new SimpleIntReference(7); + assertFalse(ir.isNegative()); + } + + public void testIsNotNegative() { + SimpleIntReference ir; + ir = new SimpleIntReference(-3); + assertFalse(ir.isNotNegative()); + + ir = new SimpleIntReference(); + assertTrue(ir.isNotNegative()); + + ir = new SimpleIntReference(7); + assertTrue(ir.isNotNegative()); + } + + public void testSetValueInt() { + SimpleIntReference ir; + ir = new SimpleIntReference(-3); + assertEquals(-3, ir.getValue()); + assertEquals(-3, ir.setValue(4)); + assertEquals(4, ir.getValue()); + } + + public void testAbs() { + SimpleIntReference ir; + ir = new SimpleIntReference(-3); + assertEquals(-3, ir.getValue()); + assertEquals(3, ir.abs()); + + ir.setValue(3); + assertEquals(3, ir.getValue()); + assertEquals(3, ir.abs()); + } + + public void testNeg() { + SimpleIntReference ir; + ir = new SimpleIntReference(-3); + assertEquals(-3, ir.getValue()); + assertEquals(3, ir.neg()); + + ir.setValue(3); + assertEquals(3, ir.getValue()); + assertEquals(-3, ir.neg()); + } + + public void testSetZero() { + SimpleIntReference ir; + ir = new SimpleIntReference(-3); + assertEquals(-3, ir.getValue()); + assertEquals(-3, ir.setZero()); + assertEquals(0, ir.getValue()); + } + + public void testAddInt() { + SimpleIntReference ir; + int value; + ir = new SimpleIntReference(); + assertEquals(0, ir.getValue()); + + value = ir.add(3); + assertEquals(3, value); + + ir.setValue(3); + value = ir.add(-7); + assertEquals(-4, value); + } + + public void testIncrement() { + SimpleIntReference ir; + int value; + ir = new SimpleIntReference(); + assertEquals(0, ir.getValue()); + + value = ir.increment(); + assertEquals(1, value); + assertEquals(1, ir.getValue()); + } + + public void testSubtractInt() { + SimpleIntReference ir; + int count; + ir = new SimpleIntReference(); + assertEquals(0, ir.getValue()); + + count = ir.subtract(3); + assertEquals(-3, count); + + ir.setValue(-3); + count = ir.subtract(-7); + assertEquals(4, count); + } + + public void testDecrement() { + SimpleIntReference ir; + int count; + ir = new SimpleIntReference(); + assertEquals(0, ir.getValue()); + + count = ir.decrement(); + assertEquals(-1, count); + assertEquals(-1, ir.getValue()); + } + + public void testMultiplyInt() { + SimpleIntReference ir; + ir = new SimpleIntReference(3); + assertEquals(3, ir.getValue()); + assertEquals(9, ir.multiply(3)); + } + + public void testDivideInt() { + SimpleIntReference ir; + ir = new SimpleIntReference(24); + assertEquals(24, ir.getValue()); + assertEquals(8, ir.divide(3)); + } + + public void testRemainderInt() { + SimpleIntReference ir; + ir = new SimpleIntReference(25); + assertEquals(25, ir.getValue()); + assertEquals(1, ir.remainder(3)); + } + + public void testMinInt() { + SimpleIntReference ir; + ir = new SimpleIntReference(25); + assertEquals(25, ir.getValue()); + assertEquals(3, ir.min(3)); + assertEquals(25, ir.min(33)); + } + + public void testMaxInt() { + SimpleIntReference ir; + ir = new SimpleIntReference(25); + assertEquals(25, ir.getValue()); + assertEquals(25, ir.max(3)); + assertEquals(30, ir.max(30)); + } + + public void testPowInt() { + SimpleIntReference ir; + ir = new SimpleIntReference(5); + assertEquals(5, ir.getValue()); + assertTrue(ir.pow(2) == 25L); + } + + public void testCompareToIntReference() { + SimpleIntReference ir1 = new SimpleIntReference(44); + SimpleIntReference ir2 = new SimpleIntReference(44); + assertTrue(ir1.compareTo(ir2) == 0); + ir2 = new SimpleIntReference(55); + assertTrue(ir1.compareTo(ir2) < 0); + ir2 = new SimpleIntReference(33); + assertTrue(ir1.compareTo(ir2) > 0); + } + + public void testClone() { + SimpleIntReference ir1 = new SimpleIntReference(44); + SimpleIntReference ir2 = ir1.clone(); + assertEquals(44, ir2.getValue()); + assertNotSame(ir1, ir2); + } + + public void testSerialization() throws Exception { + SimpleIntReference ir1 = new SimpleIntReference(44); + SimpleIntReference ir2 = TestTools.serialize(ir1); + assertEquals(44, ir2.getValue()); + assertNotSame(ir1, ir2); + } + + public void testToString() { + SimpleIntReference ir; + ir = new SimpleIntReference(5); + assertEquals("[5]", ir.toString()); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleObjectReferenceTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleObjectReferenceTests.java new file mode 100644 index 0000000000..ea91ac9f7c --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleObjectReferenceTests.java @@ -0,0 +1,88 @@ +/******************************************************************************* + * Copyright (c) 2008, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import junit.framework.TestCase; + +import org.eclipse.jpt.common.utility.internal.SimpleObjectReference; + +@SuppressWarnings("nls") +public class SimpleObjectReferenceTests extends TestCase { + + public SimpleObjectReferenceTests(String name) { + super(name); + } + + public void testGetValue() { + SimpleObjectReference<String> or = new SimpleObjectReference<String>(); + assertNull(or.getValue()); + or.setValue("foo"); + assertEquals("foo", or.getValue()); + } + + public void testValueEqualsObject() { + SimpleObjectReference<String> or = new SimpleObjectReference<String>(); + assertTrue(or.valueEquals(null)); + assertFalse(or.valueEquals("foo")); + + or.setValue("foo"); + assertFalse(or.valueEquals(null)); + assertTrue(or.valueEquals("foo")); + } + + public void testValueNotEqualObject() { + SimpleObjectReference<String> or = new SimpleObjectReference<String>(); + assertFalse(or.valueNotEqual(null)); + assertTrue(or.valueNotEqual("foo")); + + or.setValue("foo"); + assertTrue(or.valueNotEqual(null)); + assertFalse(or.valueNotEqual("foo")); + } + + public void testIsNull() { + SimpleObjectReference<String> or = new SimpleObjectReference<String>(); + assertTrue(or.isNull()); + or.setValue("foo"); + assertFalse(or.isNull()); + } + + public void testIsNotNull() { + SimpleObjectReference<String> or = new SimpleObjectReference<String>(); + assertFalse(or.isNotNull()); + or.setValue("foo"); + assertTrue(or.isNotNull()); + } + + public void testSetNull() { + SimpleObjectReference<String> or = new SimpleObjectReference<String>(); + assertNull(or.getValue()); + or.setValue("foo"); + assertEquals("foo", or.getValue()); + or.setNull(); + assertNull(or.getValue()); + } + + public void testClone() { + SimpleObjectReference<String> or = new SimpleObjectReference<String>("foo"); + @SuppressWarnings("cast") + SimpleObjectReference<String> clone = (SimpleObjectReference<String>) or.clone(); + assertEquals("foo", clone.getValue()); + assertNotSame(or, clone); + } + + public void testToString() { + SimpleObjectReference<String> or = new SimpleObjectReference<String>(); + assertEquals("[null]", or.toString()); + or.setValue("foo"); + assertEquals("[foo]", or.toString()); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleQueueTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleQueueTests.java new file mode 100644 index 0000000000..4fb99dbc5a --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleQueueTests.java @@ -0,0 +1,149 @@ +/******************************************************************************* + * Copyright (c) 2009, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import java.util.NoSuchElementException; + +import org.eclipse.jpt.common.utility.internal.Queue; +import org.eclipse.jpt.common.utility.internal.SimpleQueue; + +@SuppressWarnings("nls") +public class SimpleQueueTests + extends MultiThreadedTestCase +{ + + public SimpleQueueTests(String name) { + super(name); + } + + Queue<String> buildQueue() { + return new SimpleQueue<String>(); + } + + public void testIsEmpty() { + Queue<String> queue = this.buildQueue(); + assertTrue(queue.isEmpty()); + queue.enqueue("first"); + assertFalse(queue.isEmpty()); + queue.enqueue("second"); + assertFalse(queue.isEmpty()); + queue.dequeue(); + assertFalse(queue.isEmpty()); + queue.dequeue(); + assertTrue(queue.isEmpty()); + } + + public void testEnqueueAndDequeue() { + Queue<String> queue = this.buildQueue(); + String first = "first"; + String second = "second"; + + queue.enqueue(first); + queue.enqueue(second); + assertEquals(first, queue.dequeue()); + assertEquals(second, queue.dequeue()); + } + + public void testEnqueueAndPeek() { + Queue<String> queue = this.buildQueue(); + String first = "first"; + String second = "second"; + + queue.enqueue(first); + queue.enqueue(second); + assertEquals(first, queue.peek()); + assertEquals(first, queue.peek()); + assertEquals(first, queue.dequeue()); + assertEquals(second, queue.peek()); + assertEquals(second, queue.peek()); + assertEquals(second, queue.dequeue()); + } + + public void testEmptyQueueExceptionPeek() { + Queue<String> queue = this.buildQueue(); + String first = "first"; + String second = "second"; + + queue.enqueue(first); + queue.enqueue(second); + assertEquals(first, queue.peek()); + assertEquals(first, queue.dequeue()); + assertEquals(second, queue.peek()); + assertEquals(second, queue.dequeue()); + + boolean exCaught = false; + try { + queue.peek(); + fail(); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEmptyQueueExceptionDequeue() { + Queue<String> queue = this.buildQueue(); + String first = "first"; + String second = "second"; + + queue.enqueue(first); + queue.enqueue(second); + assertEquals(first, queue.peek()); + assertEquals(first, queue.dequeue()); + assertEquals(second, queue.peek()); + assertEquals(second, queue.dequeue()); + + boolean exCaught = false; + try { + queue.dequeue(); + fail(); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testClone() { + SimpleQueue<String> queue = (SimpleQueue<String>) this.buildQueue(); + queue.enqueue("first"); + queue.enqueue("second"); + queue.enqueue("third"); + + this.verifyClone(queue, queue.clone()); + } + + public void testSerialization() throws Exception { + Queue<String> queue = this.buildQueue(); + queue.enqueue("first"); + queue.enqueue("second"); + queue.enqueue("third"); + + this.verifyClone(queue, TestTools.serialize(queue)); + } + + private void verifyClone(Queue<String> original, Queue<String> clone) { + assertNotSame(original, clone); + assertEquals(original.peek(), clone.peek()); + assertEquals(original.dequeue(), clone.dequeue()); + assertEquals(original.peek(), clone.peek()); + assertEquals(original.dequeue(), clone.dequeue()); + assertEquals(original.isEmpty(), clone.isEmpty()); + assertEquals(original.peek(), clone.peek()); + assertEquals(original.dequeue(), clone.dequeue()); + assertTrue(original.isEmpty()); + assertEquals(original.isEmpty(), clone.isEmpty()); + + original.enqueue("fourth"); + assertFalse(original.isEmpty()); + // clone should still be empty + assertTrue(clone.isEmpty()); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleStackTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleStackTests.java new file mode 100644 index 0000000000..b73d8633e3 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleStackTests.java @@ -0,0 +1,148 @@ +/******************************************************************************* + * Copyright (c) 2007, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import java.util.EmptyStackException; + +import org.eclipse.jpt.common.utility.internal.SimpleStack; +import org.eclipse.jpt.common.utility.internal.Stack; + +@SuppressWarnings("nls") +public class SimpleStackTests + extends MultiThreadedTestCase +{ + public SimpleStackTests(String name) { + super(name); + } + + Stack<String> buildStack() { + return new SimpleStack<String>(); + } + + public void testIsEmpty() { + Stack<String> stack = this.buildStack(); + assertTrue(stack.isEmpty()); + stack.push("first"); + assertFalse(stack.isEmpty()); + stack.push("second"); + assertFalse(stack.isEmpty()); + stack.pop(); + assertFalse(stack.isEmpty()); + stack.pop(); + assertTrue(stack.isEmpty()); + } + + public void testPushAndPop() { + Stack<String> stack = this.buildStack(); + String first = "first"; + String second = "second"; + + stack.push(first); + stack.push(second); + assertEquals(second, stack.pop()); + assertEquals(first, stack.pop()); + } + + public void testPushAndPeek() { + Stack<String> stack = this.buildStack(); + String first = "first"; + String second = "second"; + + stack.push(first); + stack.push(second); + assertEquals(second, stack.peek()); + assertEquals(second, stack.peek()); + assertEquals(second, stack.pop()); + assertEquals(first, stack.peek()); + assertEquals(first, stack.peek()); + assertEquals(first, stack.pop()); + } + + public void testEmptyStackExceptionPeek() { + Stack<String> stack = this.buildStack(); + String first = "first"; + String second = "second"; + + stack.push(first); + stack.push(second); + assertEquals(second, stack.peek()); + assertEquals(second, stack.pop()); + assertEquals(first, stack.peek()); + assertEquals(first, stack.pop()); + + boolean exCaught = false; + try { + stack.peek(); + fail(); + } catch (EmptyStackException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEmptyStackExceptionPop() { + Stack<String> stack = this.buildStack(); + String first = "first"; + String second = "second"; + + stack.push(first); + stack.push(second); + assertEquals(second, stack.peek()); + assertEquals(second, stack.pop()); + assertEquals(first, stack.peek()); + assertEquals(first, stack.pop()); + + boolean exCaught = false; + try { + stack.pop(); + fail(); + } catch (EmptyStackException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testClone() { + SimpleStack<String> stack = (SimpleStack<String>) this.buildStack(); + stack.push("first"); + stack.push("second"); + stack.push("third"); + + this.verifyClone(stack, stack.clone()); + } + + public void testSerialization() throws Exception { + Stack<String> stack = this.buildStack(); + stack.push("first"); + stack.push("second"); + stack.push("third"); + + this.verifyClone(stack, TestTools.serialize(stack)); + } + + private void verifyClone(Stack<String> original, Stack<String> clone) { + assertNotSame(original, clone); + assertEquals(original.peek(), clone.peek()); + assertEquals(original.pop(), clone.pop()); + assertEquals(original.peek(), clone.peek()); + assertEquals(original.pop(), clone.pop()); + assertEquals(original.isEmpty(), clone.isEmpty()); + assertEquals(original.peek(), clone.peek()); + assertEquals(original.pop(), clone.pop()); + assertTrue(original.isEmpty()); + assertEquals(original.isEmpty(), clone.isEmpty()); + + original.push("fourth"); + assertFalse(original.isEmpty()); + // clone should still be empty + assertTrue(clone.isEmpty()); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/StringToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/StringToolsTests.java new file mode 100644 index 0000000000..137b55249a --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/StringToolsTests.java @@ -0,0 +1,1850 @@ +/******************************************************************************* + * Copyright (c) 2005, 2010 Oracle. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0, which accompanies this distribution + * and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Contributors: + * Oracle - initial API and implementation + ******************************************************************************/ +package org.eclipse.jpt.common.utility.tests.internal; + +import java.io.StringWriter; +import java.io.Writer; +import junit.framework.TestCase; +import org.eclipse.jpt.common.utility.internal.StringTools; + +@SuppressWarnings("nls") +public class StringToolsTests extends TestCase { + + public StringToolsTests(String name) { + super(name); + } + + private static void assertEquals(String expected, char[] actual) { + assertEquals(expected, new String(actual)); + } + + // ********** padding/truncating ********** + + public void testPad() { + assertEquals("fred", StringTools.pad("fred", 4)); + assertEquals("fred ", StringTools.pad("fred", 6)); + boolean exThrown = false; + try { + assertEquals("fr", StringTools.pad("fred", 2)); + } catch (IllegalArgumentException ex) { + exThrown = true; + } + assertTrue(exThrown); + } + + public void testPadCharArray() { + assertEquals("fred", StringTools.pad(new char[] { 'f', 'r', 'e', 'd' }, 4)); + assertEquals("fred ", StringTools.pad(new char[] { 'f', 'r', 'e', 'd' }, 6)); + boolean exThrown = false; + try { + assertEquals("fr", StringTools.pad(new char[] { 'f', 'r', 'e', 'd' }, 2)); + } catch (IllegalArgumentException ex) { + exThrown = true; + } + assertTrue(exThrown); + } + + public void testPadOnWriter() { + Writer writer; + writer = new StringWriter(); + StringTools.padOn("fred", 4, writer); + assertEquals("fred", writer.toString()); + + writer = new StringWriter(); + StringTools.padOn("fred", 6, writer); + assertEquals("fred ", writer.toString()); + + writer = new StringWriter(); + boolean exThrown = false; + try { + StringTools.padOn("fred", 2, writer); + fail(); + } catch (IllegalArgumentException ex) { + exThrown = true; + } + assertTrue(exThrown); + } + + public void testPadOnStringBuffer() { + StringBuffer sb; + sb = new StringBuffer(); + StringTools.padOn("fred", 4, sb); + assertEquals("fred", sb.toString()); + + sb = new StringBuffer(); + StringTools.padOn("fred", 6, sb); + assertEquals("fred ", sb.toString()); + + sb = new StringBuffer(); + boolean exThrown = false; + try { + StringTools.padOn("fred", 2, sb); + fail(); + } catch (IllegalArgumentException ex) { + exThrown = true; + } + assertTrue(exThrown); + } + + public void testPadOnStringBuilder() { + StringBuilder sb; + sb = new StringBuilder(); + StringTools.padOn("fred", 4, sb); + assertEquals("fred", sb.toString()); + + sb = new StringBuilder(); + StringTools.padOn("fred", 6, sb); + assertEquals("fred ", sb.toString()); + + sb = new StringBuilder(); + boolean exThrown = false; + try { + StringTools.padOn("fred", 2, sb); + fail(); + } catch (IllegalArgumentException ex) { + exThrown = true; + } + assertTrue(exThrown); + } + + public void testPadOrTruncate() { + assertEquals("fred", StringTools.padOrTruncate("fred", 4)); + assertEquals("fred ", StringTools.padOrTruncate("fred", 6)); + assertEquals("fr", StringTools.padOrTruncate("fred", 2)); + } + + public void testPadOrTruncateCharArray() { + assertEquals("fred", StringTools.padOrTruncate(new char[] { 'f', 'r', 'e', 'd' }, 4)); + assertEquals("fred ", StringTools.padOrTruncate(new char[] { 'f', 'r', 'e', 'd' }, 6)); + assertEquals("fr", StringTools.padOrTruncate(new char[] { 'f', 'r', 'e', 'd' }, 2)); + } + + public void testPadOrTruncateOnWriter() { + this.verifyPadOrTruncateOnWriter("fred", "fred", 4); + this.verifyPadOrTruncateOnWriter("fred ", "fred", 6); + this.verifyPadOrTruncateOnWriter("fr", "fred", 2); + } + + private void verifyPadOrTruncateOnWriter(String expected, String string, int length) { + Writer writer = new StringWriter(); + StringTools.padOrTruncateOn(string, length, writer); + assertEquals(expected, writer.toString()); + } + + public void testPadOrTruncateOnStringBuffer() { + this.verifyPadOrTruncateOnStringBuffer("fred", "fred", 4); + this.verifyPadOrTruncateOnStringBuffer("fred ", "fred", 6); + this.verifyPadOrTruncateOnStringBuffer("fr", "fred", 2); + } + + private void verifyPadOrTruncateOnStringBuffer(String expected, String string, int length) { + StringBuffer sb = new StringBuffer(); + StringTools.padOrTruncateOn(string, length, sb); + assertEquals(expected, sb.toString()); + } + + public void testPadOrTruncateOnStringBuilder() { + this.verifyPadOrTruncateOnStringBuilder("fred", "fred", 4); + this.verifyPadOrTruncateOnStringBuilder("fred ", "fred", 6); + this.verifyPadOrTruncateOnStringBuilder("fr", "fred", 2); + } + + private void verifyPadOrTruncateOnStringBuilder(String expected, String string, int length) { + StringBuilder sb = new StringBuilder(); + StringTools.padOrTruncateOn(string, length, sb); + assertEquals(expected, sb.toString()); + } + + public void testZeroPad() { + assertEquals("1234", StringTools.zeroPad("1234", 4)); + assertEquals("001234", StringTools.zeroPad("1234", 6)); + boolean exThrown = false; + try { + assertEquals("12", StringTools.zeroPad("1234", 2)); + } catch (IllegalArgumentException ex) { + exThrown = true; + } + assertTrue(exThrown); + } + + public void testZeroPadCharArray() { + assertEquals("1234", StringTools.zeroPad(new char[] { '1', '2', '3', '4' }, 4)); + assertEquals("001234", StringTools.zeroPad(new char[] { '1', '2', '3', '4' }, 6)); + boolean exThrown = false; + try { + assertEquals("12", StringTools.zeroPad(new char[] { '1', '2', '3', '4' }, 2)); + } catch (IllegalArgumentException ex) { + exThrown = true; + } + assertTrue(exThrown); + } + + public void testZeroPadOnWriter() { + Writer writer; + writer = new StringWriter(); + StringTools.zeroPadOn("1234", 4, writer); + assertEquals("1234", writer.toString()); + + writer = new StringWriter(); + StringTools.zeroPadOn("1234", 6, writer); + assertEquals("001234", writer.toString()); + + writer = new StringWriter(); + boolean exThrown = false; + try { + StringTools.zeroPadOn("1234", 2, writer); + fail(); + } catch (IllegalArgumentException ex) { + exThrown = true; + } + assertTrue(exThrown); + } + + public void testZeroPadOnStringBuffer() { + StringBuffer sb; + sb = new StringBuffer(); + StringTools.zeroPadOn("1234", 4, sb); + assertEquals("1234", sb.toString()); + + sb = new StringBuffer(); + StringTools.zeroPadOn("1234", 6, sb); + assertEquals("001234", sb.toString()); + + sb = new StringBuffer(); + boolean exThrown = false; + try { + StringTools.zeroPadOn("1234", 2, sb); + fail(); + } catch (IllegalArgumentException ex) { + exThrown = true; + } + assertTrue(exThrown); + } + + public void testZeroPadOnStringBuilder() { + StringBuilder sb; + sb = new StringBuilder(); + StringTools.zeroPadOn("1234", 4, sb); + assertEquals("1234", sb.toString()); + + sb = new StringBuilder(); + StringTools.zeroPadOn("1234", 6, sb); + assertEquals("001234", sb.toString()); + + sb = new StringBuilder(); + boolean exThrown = false; + try { + StringTools.zeroPadOn("1234", 2, sb); + fail(); + } catch (IllegalArgumentException ex) { + exThrown = true; + } + assertTrue(exThrown); + } + + public void testZeroPadOrTruncate() { + assertEquals("1234", StringTools.zeroPadOrTruncate("1234", 4)); + assertEquals("001234", StringTools.zeroPadOrTruncate("1234", 6)); + assertEquals("34", StringTools.zeroPadOrTruncate("1234", 2)); + } + + public void testZeroPadOrTruncateCharArray() { + assertEquals("1234", StringTools.zeroPadOrTruncate(new char[] { '1', '2', '3', '4' }, 4)); + assertEquals("001234", StringTools.zeroPadOrTruncate(new char[] { '1', '2', '3', '4' }, 6)); + assertEquals("34", StringTools.zeroPadOrTruncate(new char[] { '1', '2', '3', '4' }, 2)); + } + + public void testZeroPadOrTruncateOnWriter() { + this.verifyZeroPadOrTruncateOnWriter("1234", "1234", 4); + this.verifyZeroPadOrTruncateOnWriter("001234", "1234", 6); + this.verifyZeroPadOrTruncateOnWriter("34", "1234", 2); + } + + private void verifyZeroPadOrTruncateOnWriter(String expected, String string, int length) { + Writer writer = new StringWriter(); + StringTools.zeroPadOrTruncateOn(string, length, writer); + assertEquals(expected, writer.toString()); + } + + public void testZeroPadOrTruncateOnStringBuffer() { + this.verifyZeroPadOrTruncateOnStringBuffer("1234", "1234", 4); + this.verifyZeroPadOrTruncateOnStringBuffer("001234", "1234", 6); + this.verifyZeroPadOrTruncateOnStringBuffer("34", "1234", 2); + } + + private void verifyZeroPadOrTruncateOnStringBuffer(String expected, String string, int length) { + StringBuffer sb = new StringBuffer(); + StringTools.zeroPadOrTruncateOn(string, length, sb); + assertEquals(expected, sb.toString()); + } + + public void testZeroPadOrTruncateOnStringBuilder() { + this.verifyZeroPadOrTruncateOnStringBuilder("1234", "1234", 4); + this.verifyZeroPadOrTruncateOnStringBuilder("001234", "1234", 6); + this.verifyZeroPadOrTruncateOnStringBuilder("34", "1234", 2); + } + + private void verifyZeroPadOrTruncateOnStringBuilder(String expected, String string, int length) { + StringBuilder sb = new StringBuilder(); + StringTools.zeroPadOrTruncateOn(string, length, sb); + assertEquals(expected, sb.toString()); + } + + // ********** separating ********** + + public void testSeparateStringCharInt() { + this.verifySeparate("012345", '-', 22, "012345"); + this.verifySeparate("012345", '-', 6, "012345"); + this.verifySeparate("012345", '-', 5, "01234-5"); + this.verifySeparate("012345", '-', 4, "0123-45"); + this.verifySeparate("012345", '-', 3, "012-345"); + this.verifySeparate("012345", '-', 2, "01-23-45"); + this.verifySeparate("012345", '-', 1, "0-1-2-3-4-5"); + } + + private void verifySeparate(String string, char separator, int segmentLength, String expected) { + assertEquals(expected, StringTools.separate(string, separator, segmentLength)); + } + + public void testSeparateOnStringCharIntWriter() { + this.verifySeparateOnWriter("012345", '-', 22, "012345"); + this.verifySeparateOnWriter("012345", '-', 6, "012345"); + this.verifySeparateOnWriter("012345", '-', 5, "01234-5"); + this.verifySeparateOnWriter("012345", '-', 4, "0123-45"); + this.verifySeparateOnWriter("012345", '-', 3, "012-345"); + this.verifySeparateOnWriter("012345", '-', 2, "01-23-45"); + this.verifySeparateOnWriter("012345", '-', 1, "0-1-2-3-4-5"); + } + + private void verifySeparateOnWriter(String string, char separator, int segmentLength, String expected) { + Writer writer = new StringWriter(); + StringTools.separateOn(string, separator, segmentLength, writer); + assertEquals(expected, writer.toString()); + } + + public void testSeparateOnStringCharIntStringBuffer() { + this.verifySeparateOnStringBuffer("012345", '-', 22, "012345"); + this.verifySeparateOnStringBuffer("012345", '-', 6, "012345"); + this.verifySeparateOnStringBuffer("012345", '-', 5, "01234-5"); + this.verifySeparateOnStringBuffer("012345", '-', 4, "0123-45"); + this.verifySeparateOnStringBuffer("012345", '-', 3, "012-345"); + this.verifySeparateOnStringBuffer("012345", '-', 2, "01-23-45"); + this.verifySeparateOnStringBuffer("012345", '-', 1, "0-1-2-3-4-5"); + } + + private void verifySeparateOnStringBuffer(String string, char separator, int segmentLength, String expected) { + StringBuffer sb = new StringBuffer(); + StringTools.separateOn(string, separator, segmentLength, sb); + assertEquals(expected, sb.toString()); + } + + public void testSeparateOnStringCharIntStringBuilder() { + this.verifySeparateOnStringBuilder("012345", '-', 22, "012345"); + this.verifySeparateOnStringBuilder("012345", '-', 6, "012345"); + this.verifySeparateOnStringBuilder("012345", '-', 5, "01234-5"); + this.verifySeparateOnStringBuilder("012345", '-', 4, "0123-45"); + this.verifySeparateOnStringBuilder("012345", '-', 3, "012-345"); + this.verifySeparateOnStringBuilder("012345", '-', 2, "01-23-45"); + this.verifySeparateOnStringBuilder("012345", '-', 1, "0-1-2-3-4-5"); + } + + private void verifySeparateOnStringBuilder(String string, char separator, int segmentLength, String expected) { + StringBuilder sb = new StringBuilder(); + StringTools.separateOn(string, separator, segmentLength, sb); + assertEquals(expected, sb.toString()); + } + + public void testSeparateCharArrayCharInt() { + this.verifySeparateCharArray("012345", '-', 22, "012345"); + this.verifySeparateCharArray("012345", '-', 6, "012345"); + this.verifySeparateCharArray("012345", '-', 5, "01234-5"); + this.verifySeparateCharArray("012345", '-', 4, "0123-45"); + this.verifySeparateCharArray("012345", '-', 3, "012-345"); + this.verifySeparateCharArray("012345", '-', 2, "01-23-45"); + this.verifySeparateCharArray("012345", '-', 1, "0-1-2-3-4-5"); + } + + private void verifySeparateCharArray(String string, char separator, int segmentLength, String expected) { + assertEquals(expected, StringTools.separate(string.toCharArray(), separator, segmentLength)); + } + + public void testSeparateOnCharArrayCharIntWriter() { + this.verifySeparateCharArrayOnWriter("012345", '-', 22, "012345"); + this.verifySeparateCharArrayOnWriter("012345", '-', 6, "012345"); + this.verifySeparateCharArrayOnWriter("012345", '-', 5, "01234-5"); + this.verifySeparateCharArrayOnWriter("012345", '-', 4, "0123-45"); + this.verifySeparateCharArrayOnWriter("012345", '-', 3, "012-345"); + this.verifySeparateCharArrayOnWriter("012345", '-', 2, "01-23-45"); + this.verifySeparateCharArrayOnWriter("012345", '-', 1, "0-1-2-3-4-5"); + } + + private void verifySeparateCharArrayOnWriter(String string, char separator, int segmentLength, String expected) { + Writer writer = new StringWriter(); + StringTools.separateOn(string.toCharArray(), separator, segmentLength, writer); + assertEquals(expected, writer.toString()); + } + + public void testSeparateOnCharArrayCharIntStringBuffer() { + this.verifySeparateCharArrayOnStringBuffer("012345", '-', 22, "012345"); + this.verifySeparateCharArrayOnStringBuffer("012345", '-', 6, "012345"); + this.verifySeparateCharArrayOnStringBuffer("012345", '-', 5, "01234-5"); + this.verifySeparateCharArrayOnStringBuffer("012345", '-', 4, "0123-45"); + this.verifySeparateCharArrayOnStringBuffer("012345", '-', 3, "012-345"); + this.verifySeparateCharArrayOnStringBuffer("012345", '-', 2, "01-23-45"); + this.verifySeparateCharArrayOnStringBuffer("012345", '-', 1, "0-1-2-3-4-5"); + } + + private void verifySeparateCharArrayOnStringBuffer(String string, char separator, int segmentLength, String expected) { + StringBuffer sb = new StringBuffer(); + StringTools.separateOn(string.toCharArray(), separator, segmentLength, sb); + assertEquals(expected, sb.toString()); + } + + public void testSeparateOnCharArrayCharIntStringBuilder() { + this.verifySeparateCharArrayOnStringBuilder("012345", '-', 22, "012345"); + this.verifySeparateCharArrayOnStringBuilder("012345", '-', 6, "012345"); + this.verifySeparateCharArrayOnStringBuilder("012345", '-', 5, "01234-5"); + this.verifySeparateCharArrayOnStringBuilder("012345", '-', 4, "0123-45"); + this.verifySeparateCharArrayOnStringBuilder("012345", '-', 3, "012-345"); + this.verifySeparateCharArrayOnStringBuilder("012345", '-', 2, "01-23-45"); + this.verifySeparateCharArrayOnStringBuilder("012345", '-', 1, "0-1-2-3-4-5"); + } + + private void verifySeparateCharArrayOnStringBuilder(String string, char separator, int segmentLength, String expected) { + StringBuilder sb = new StringBuilder(); + StringTools.separateOn(string.toCharArray(), separator, segmentLength, sb); + assertEquals(expected, sb.toString()); + } + + // ********** delimiting ********** + + public void testDelimit() { + this.verifyDelimit("Employee", "123", "123Employee123"); + this.verifyDelimit("123", "123", "123123123"); + this.verifyDelimit("", "123", "123123"); + } + + private void verifyDelimit(String string, String delimiter, String expectedString) { + assertEquals(expectedString, StringTools.delimit(string, delimiter)); + } + + public void testDelimitOnWriter() { + this.verifyDelimitOnWriter("Employee", "123", "123Employee123"); + this.verifyDelimitOnWriter("123", "123", "123123123"); + this.verifyDelimitOnWriter("", "123", "123123"); + } + + private void verifyDelimitOnWriter(String string, String delimiter, String expectedString) { + Writer writer = new StringWriter(); + StringTools.delimitOn(string, delimiter, writer); + assertEquals(expectedString, writer.toString()); + } + + public void testDelimitOnStringBuffer() { + this.verifyDelimitOnStringBuffer("Employee", "123", "123Employee123"); + this.verifyDelimitOnStringBuffer("123", "123", "123123123"); + this.verifyDelimitOnStringBuffer("", "123", "123123"); + } + |