commons-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From adri...@apache.org
Subject svn commit: r933044 - in /commons/sandbox/convert/trunk/src: main/java/org/apache/commons/convert/CollectionConverters.java test/java/org/apache/commons/convert/TestCollectionConverters.java
Date Mon, 12 Apr 2010 00:02:42 GMT
Author: adrianc
Date: Mon Apr 12 00:02:41 2010
New Revision: 933044

URL: http://svn.apache.org/viewvc?rev=933044&view=rev
Log:
Improved Collection converters, added unit tests.

Added:
    commons/sandbox/convert/trunk/src/test/java/org/apache/commons/convert/TestCollectionConverters.java
  (with props)
Modified:
    commons/sandbox/convert/trunk/src/main/java/org/apache/commons/convert/CollectionConverters.java

Modified: commons/sandbox/convert/trunk/src/main/java/org/apache/commons/convert/CollectionConverters.java
URL: http://svn.apache.org/viewvc/commons/sandbox/convert/trunk/src/main/java/org/apache/commons/convert/CollectionConverters.java?rev=933044&r1=933043&r2=933044&view=diff
==============================================================================
--- commons/sandbox/convert/trunk/src/main/java/org/apache/commons/convert/CollectionConverters.java
(original)
+++ commons/sandbox/convert/trunk/src/main/java/org/apache/commons/convert/CollectionConverters.java
Mon Apr 12 00:02:41 2010
@@ -19,32 +19,62 @@
 package org.apache.commons.convert;
 
 import java.lang.reflect.Array;
+import java.lang.reflect.Modifier;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
-import java.util.HashSet;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.HashSet;
 import java.util.Set;
 
 /** Collection Converter classes. */
 public class CollectionConverters implements ConverterLoader {
-    public static class ArrayCreator implements ConverterCreator, ConverterLoader {
-        public void loadConverters() {
-            Converters.registerCreator(this);
+
+    @SuppressWarnings("unchecked")
+    public void loadConverters() {
+        Converters.loadContainedConverters(CollectionConverters.class);
+        Converters.registerConverter(new GenericToStringConverter<Collection>(Collection.class));
+        Converters.registerConverter(new GenericSingletonToList<Map>(Map.class));
+        Converters.registerConverter(new GenericSingletonToSet<Map>(Map.class));
+    }
+
+    private static class ArrayClassToArrayList<S, T> extends AbstractConverter<S,
T> {
+        public ArrayClassToArrayList(Class<S> sourceClass, Class<T> targetClass)
{
+            super(sourceClass, targetClass);
         }
 
-        public <S, T> Converter<S, T> createConverter(Class<S> sourceClass,
Class<T> targetClass) {
-            if (!sourceClass.isArray()) {
-               return null;
-            }
-            if (targetClass != List.class) {
-               return null;
+        public boolean canConvert(Class<?> sourceClass, Class<?> targetClass)
{
+            return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
+        }
+
+        public T convert(S obj) throws ConversionException {
+            List<Object> list = new ArrayList<Object>();
+            int len = Array.getLength(obj);
+            for (int i = 0; i < len; i++) {
+                list.add(Array.get(obj, i));
             }
-            if (!(sourceClass.getComponentType() instanceof Object)) {
-                return null;
+            return Util.<T>cast(list);
+        }
+    }
+
+    private static class ArrayClassToHashSet<S, T> extends AbstractConverter<S,
T> {
+        public ArrayClassToHashSet(Class<S> sourceClass, Class<T> targetClass)
{
+            super(sourceClass, targetClass);
+        }
+
+        public boolean canConvert(Class<?> sourceClass, Class<?> targetClass)
{
+            return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
+        }
+
+        public T convert(S obj) throws ConversionException {
+            Set<Object> set = new HashSet<Object>();
+            int len = Array.getLength(obj);
+            for (int i = 0; i < len; i++) {
+                set.add(Array.get(obj, i));
             }
-            return Util.cast(new ArrayClassToList<S, T>(sourceClass, targetClass));
+            return Util.<T>cast(set);
         }
     }
 
@@ -57,8 +87,14 @@ public class CollectionConverters implem
             return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
         }
 
+        @SuppressWarnings("unchecked")
         public T convert(S obj) throws ConversionException {
-            List<Object> list = new ArrayList<Object>();
+            List<Object> list = null;
+            try {
+                list = (List<Object>) this.getTargetClass().newInstance();
+            } catch (Exception e) {
+                throw new ConversionException(e);
+            }
             int len = Array.getLength(obj);
             for (int i = 0; i < len; i++) {
                 list.add(Array.get(obj, i));
@@ -67,6 +103,72 @@ public class CollectionConverters implem
         }
     }
 
+    private static class ArrayClassToSet<S, T> extends AbstractConverter<S, T>
{
+        public ArrayClassToSet(Class<S> sourceClass, Class<T> targetClass) {
+            super(sourceClass, targetClass);
+        }
+
+        public boolean canConvert(Class<?> sourceClass, Class<?> targetClass)
{
+            return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
+        }
+
+        @SuppressWarnings("unchecked")
+        public T convert(S obj) throws ConversionException {
+            Set<Object> set = new HashSet<Object>();
+            try {
+                set = (Set<Object>) this.getTargetClass().newInstance();
+            } catch (Exception e) {
+                throw new ConversionException(e);
+            }
+            int len = Array.getLength(obj);
+            for (int i = 0; i < len; i++) {
+                set.add(Array.get(obj, i));
+            }
+            return Util.<T>cast(set);
+        }
+    }
+
+    public static class ArrayCreator implements ConverterCreator, ConverterLoader {
+        @SuppressWarnings("unchecked")
+        public <S, T> Converter<S, T> createConverter(Class<S> sourceClass,
Class<T> targetClass) {
+            if (!targetClass.isArray()) {
+               return null;
+            }
+            if (!Collection.class.isAssignableFrom(sourceClass)) {
+               return null;
+            }
+            if (targetClass.getComponentType() == Boolean.TYPE) {
+                return Util.cast(new CollectionToBooleanArray(sourceClass, targetClass));
+            }
+            if (targetClass.getComponentType() == Byte.TYPE) {
+                return Util.cast(new CollectionToByteArray(sourceClass, targetClass));
+            }
+            if (targetClass.getComponentType() == Character.TYPE) {
+                return Util.cast(new CollectionToCharArray(sourceClass, targetClass));
+            }
+            if (targetClass.getComponentType() == Double.TYPE) {
+                return Util.cast(new CollectionToDoubleArray(sourceClass, targetClass));
+            }
+            if (targetClass.getComponentType() == Float.TYPE) {
+                return Util.cast(new CollectionToFloatArray(sourceClass, targetClass));
+            }
+            if (targetClass.getComponentType() == Integer.TYPE) {
+                return Util.cast(new CollectionToIntArray(sourceClass, targetClass));
+            }
+            if (targetClass.getComponentType() == Long.TYPE) {
+                return Util.cast(new CollectionToLongArray(sourceClass, targetClass));
+            }
+            if (targetClass.getComponentType() == Short.TYPE) {
+                return Util.cast(new CollectionToShortArray(sourceClass, targetClass));
+            }
+            return Util.cast(new CollectionToObjectArray(sourceClass, targetClass));
+        }
+
+        public void loadConverters() {
+            Converters.registerCreator(this);
+        }
+    }
+
     public static class ArrayToList<T> extends AbstractConverter<T[], List<T>>
{
         public ArrayToList() {
             super(Object[].class, List.class);
@@ -91,33 +193,240 @@ public class CollectionConverters implem
         }
     }
 
-    public static class MapToList<K, V> extends AbstractConverter<Map<K, V>,
List<Map<K, V>>> {
-        public MapToList() {
-            super(Map.class, List.class);
+    @SuppressWarnings("unchecked")
+    private static class CollectionToBooleanArray<T> extends AbstractConverter<Collection,
T> {
+        public CollectionToBooleanArray(Class<Collection> sourceClass, Class<T>
targetClass) {
+            super(sourceClass, targetClass);
         }
 
-        public List<Map<K, V>> convert(Map<K, V> obj) throws ConversionException
{
-            List<Map<K, V>> tempList = new ArrayList<Map<K, V>>();
-            tempList.add(obj);
-            return tempList;
+        public boolean canConvert(Class<?> sourceClass, Class<?> targetClass)
{
+            return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
+        }
+
+        public T convert(Collection obj) throws ConversionException {
+            boolean[] array = new boolean[obj.size()];
+            int index = 0;
+            Iterator<Boolean> iterator = obj.iterator();
+            while (iterator.hasNext()) {
+                array[index] = iterator.next().booleanValue();
+                index++;
+            }
+            return Util.<T>cast(array);
         }
     }
 
-    public static class MapToSet<K, V> extends AbstractConverter<Map<K, V>,
Set<Map<K, V>>> {
-        public MapToSet() {
-            super(Map.class, Set.class);
+    @SuppressWarnings("unchecked")
+    private static class CollectionToByteArray<T> extends AbstractConverter<Collection,
T> {
+        public CollectionToByteArray(Class<Collection> sourceClass, Class<T>
targetClass) {
+            super(sourceClass, targetClass);
+        }
+
+        public boolean canConvert(Class<?> sourceClass, Class<?> targetClass)
{
+            return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
         }
 
-        public Set<Map<K, V>> convert(Map<K, V> obj) throws ConversionException
{
-            Set<Map<K, V>> tempSet = new HashSet<Map<K, V>>();
-            tempSet.add(obj);
-            return tempSet;
+        public T convert(Collection obj) throws ConversionException {
+            byte[] array = new byte[obj.size()];
+            int index = 0;
+            Iterator<Byte> iterator = obj.iterator();
+            while (iterator.hasNext()) {
+                array[index] = iterator.next().byteValue();
+                index++;
+            }
+            return Util.<T>cast(array);
         }
     }
 
     @SuppressWarnings("unchecked")
-    public void loadConverters() {
-        Converters.loadContainedConverters(CollectionConverters.class);
-        Converters.registerConverter(new GenericToStringConverter<Collection>(Collection.class));
+    private static class CollectionToCharArray<T> extends AbstractConverter<Collection,
T> {
+        public CollectionToCharArray(Class<Collection> sourceClass, Class<T>
targetClass) {
+            super(sourceClass, targetClass);
+        }
+
+        public boolean canConvert(Class<?> sourceClass, Class<?> targetClass)
{
+            return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
+        }
+
+        public T convert(Collection obj) throws ConversionException {
+            char[] array = new char[obj.size()];
+            int index = 0;
+            Iterator<Character> iterator = obj.iterator();
+            while (iterator.hasNext()) {
+                array[index] = iterator.next().charValue();
+                index++;
+            }
+            return Util.<T>cast(array);
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    private static class CollectionToDoubleArray<T> extends AbstractConverter<Collection,
T> {
+        public CollectionToDoubleArray(Class<Collection> sourceClass, Class<T>
targetClass) {
+            super(sourceClass, targetClass);
+        }
+
+        public boolean canConvert(Class<?> sourceClass, Class<?> targetClass)
{
+            return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
+        }
+
+        public T convert(Collection obj) throws ConversionException {
+            double[] array = new double[obj.size()];
+            int index = 0;
+            Iterator<Double> iterator = obj.iterator();
+            while (iterator.hasNext()) {
+                array[index] = iterator.next().doubleValue();
+                index++;
+            }
+            return Util.<T>cast(array);
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    private static class CollectionToFloatArray<T> extends AbstractConverter<Collection,
T> {
+        public CollectionToFloatArray(Class<Collection> sourceClass, Class<T>
targetClass) {
+            super(sourceClass, targetClass);
+        }
+
+        public boolean canConvert(Class<?> sourceClass, Class<?> targetClass)
{
+            return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
+        }
+
+        public T convert(Collection obj) throws ConversionException {
+            float[] array = new float[obj.size()];
+            int index = 0;
+            Iterator<Float> iterator = obj.iterator();
+            while (iterator.hasNext()) {
+                array[index] = iterator.next().floatValue();
+                index++;
+            }
+            return Util.<T>cast(array);
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    private static class CollectionToIntArray<T> extends AbstractConverter<Collection,
T> {
+        public CollectionToIntArray(Class<Collection> sourceClass, Class<T> targetClass)
{
+            super(sourceClass, targetClass);
+        }
+
+        public boolean canConvert(Class<?> sourceClass, Class<?> targetClass)
{
+            return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
+        }
+
+        public T convert(Collection obj) throws ConversionException {
+            int[] array = new int[obj.size()];
+            int index = 0;
+            Iterator<Integer> iterator = obj.iterator();
+            while (iterator.hasNext()) {
+                array[index] = iterator.next().intValue();
+                index++;
+            }
+            return Util.<T>cast(array);
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    private static class CollectionToLongArray<T> extends AbstractConverter<Collection,
T> {
+        public CollectionToLongArray(Class<Collection> sourceClass, Class<T>
targetClass) {
+            super(sourceClass, targetClass);
+        }
+
+        public boolean canConvert(Class<?> sourceClass, Class<?> targetClass)
{
+            return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
+        }
+
+        public T convert(Collection obj) throws ConversionException {
+            long[] array = new long[obj.size()];
+            int index = 0;
+            Iterator<Long> iterator = obj.iterator();
+            while (iterator.hasNext()) {
+                array[index] = iterator.next().longValue();
+                index++;
+            }
+            return Util.<T>cast(array);
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    private static class CollectionToObjectArray<T> extends AbstractConverter<Collection,
T> {
+        public CollectionToObjectArray(Class<Collection> sourceClass, Class<T>
targetClass) {
+            super(sourceClass, targetClass);
+        }
+
+        public boolean canConvert(Class<?> sourceClass, Class<?> targetClass)
{
+            return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
+        }
+
+        public T convert(Collection obj) throws ConversionException {
+            return Util.<T>cast(obj.toArray());
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    private static class CollectionToShortArray<T> extends AbstractConverter<Collection,
T> {
+        public CollectionToShortArray(Class<Collection> sourceClass, Class<T>
targetClass) {
+            super(sourceClass, targetClass);
+        }
+
+        public boolean canConvert(Class<?> sourceClass, Class<?> targetClass)
{
+            return sourceClass == this.getSourceClass() && targetClass == this.getTargetClass();
+        }
+
+        public T convert(Collection obj) throws ConversionException {
+            short[] array = new short[obj.size()];
+            int index = 0;
+            Iterator<Short> iterator = obj.iterator();
+            while (iterator.hasNext()) {
+                array[index] = iterator.next().shortValue();
+                index++;
+            }
+            return Util.<T>cast(array);
+        }
+    }
+
+    public static class ListCreator implements ConverterCreator, ConverterLoader {
+        public <S, T> Converter<S, T> createConverter(Class<S> sourceClass,
Class<T> targetClass) {
+            if (!sourceClass.isArray()) {
+               return null;
+            }
+            if (!List.class.isAssignableFrom(targetClass)) {
+               return null;
+            }
+            if (!(sourceClass.getComponentType() instanceof Object)) {
+                return null;
+            }
+            if ((targetClass.getModifiers() & Modifier.ABSTRACT) == 0) {
+                return Util.cast(new ArrayClassToList<S, T>(sourceClass, targetClass));
+            } else {
+                return Util.cast(new ArrayClassToArrayList<S, T>(sourceClass, targetClass));
+            }
+        }
+
+        public void loadConverters() {
+            Converters.registerCreator(this);
+        }
+    }
+
+    public static class SetCreator implements ConverterCreator, ConverterLoader {
+        public <S, T> Converter<S, T> createConverter(Class<S> sourceClass,
Class<T> targetClass) {
+            if (!sourceClass.isArray()) {
+               return null;
+            }
+            if (!Set.class.isAssignableFrom(targetClass)) {
+               return null;
+            }
+            if (!(sourceClass.getComponentType() instanceof Object)) {
+                return null;
+            }
+            if ((targetClass.getModifiers() & Modifier.ABSTRACT) == 0) {
+                return Util.cast(new ArrayClassToSet<S, T>(sourceClass, targetClass));
+            } else {
+                return Util.cast(new ArrayClassToHashSet<S, T>(sourceClass, targetClass));
+            }
+        }
+
+        public void loadConverters() {
+            Converters.registerCreator(this);
+        }
     }
 }

Added: commons/sandbox/convert/trunk/src/test/java/org/apache/commons/convert/TestCollectionConverters.java
URL: http://svn.apache.org/viewvc/commons/sandbox/convert/trunk/src/test/java/org/apache/commons/convert/TestCollectionConverters.java?rev=933044&view=auto
==============================================================================
--- commons/sandbox/convert/trunk/src/test/java/org/apache/commons/convert/TestCollectionConverters.java
(added)
+++ commons/sandbox/convert/trunk/src/test/java/org/apache/commons/convert/TestCollectionConverters.java
Mon Apr 12 00:02:41 2010
@@ -0,0 +1,77 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *******************************************************************************/
+package org.apache.commons.convert;
+
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+
+import junit.framework.TestCase;
+
+public class TestCollectionConverters extends TestCase {
+
+    @SuppressWarnings("unchecked")
+    public static <S> void assertArrayToCollection(String label, S source, Class<?
extends Collection> targetClass, int resultSize) throws Exception {
+        Class<?> sourceClass = source.getClass();
+        Converter<S, Collection<?>> converter = (Converter<S, Collection<?>>)
Converters.getConverter(sourceClass, targetClass);
+        assertTrue(label + " can convert", converter.canConvert(sourceClass, targetClass));
+        Collection<?> result = converter.convert(source);
+        assertTrue(label + " converted", targetClass.isAssignableFrom(result.getClass()));
+        assertEquals(label + " result size", resultSize, result.size());
+        try {
+            Converter<Collection<?>, S> reflectiveConverter = (Converter<Collection<?>,
S>) Converters.getConverter(targetClass, sourceClass);
+            assertEquals(label + " reflection converted", sourceClass, reflectiveConverter.convert(result).getClass());
+            assertTrue(label + " can convert", reflectiveConverter.canConvert(targetClass,
sourceClass));
+        } catch (ClassNotFoundException e) {
+            System.out.println(converter.getClass() + " not reflective");
+        }
+    }
+
+    public TestCollectionConverters(String name) {
+        super(name);
+    }
+
+    public void testCollectionConverters() throws Exception {
+        ConverterLoader loader = new CollectionConverters();
+        loader.loadConverters();
+        int[] intArray = {0, 1, 2, 3, 3};
+        assertArrayToCollection("int[] to List", intArray, List.class, intArray.length);
+        assertArrayToCollection("int[] to LinkedList", intArray, LinkedList.class, intArray.length);
+        assertArrayToCollection("int[] to Set", intArray, Set.class, intArray.length - 1);
+        assertArrayToCollection("int[] to TreeSet", intArray, TreeSet.class, intArray.length
- 1);
+        boolean[] booleanArray = {true, false};
+        assertArrayToCollection("boolean[] to List", booleanArray, List.class, booleanArray.length);
+        byte[] byteArray = {0, 1, 2, 3};
+        assertArrayToCollection("byte[] to List", byteArray, List.class, byteArray.length);
+        char[] charArray = {'a', 'b', 'c'};
+        assertArrayToCollection("char[] to List", charArray, List.class, charArray.length);
+        double[] doubleArray = {0, 1, 2, 3};
+        assertArrayToCollection("double[] to List", doubleArray, List.class, doubleArray.length);
+        float[] floatArray = {0, 1, 2, 3};
+        assertArrayToCollection("float[] to List", floatArray, List.class, floatArray.length);
+        long[] longArray = {0, 1, 2, 3};
+        assertArrayToCollection("long[] to List", longArray, List.class, longArray.length);
+        short[] shortArray = {0, 1, 2, 3};
+        assertArrayToCollection("short[] to List", shortArray, List.class, shortArray.length);
+        String[] stringArray = {"a", "b", "c"};
+        assertArrayToCollection("String[] to List", stringArray, List.class, stringArray.length);
+    }
+}

Propchange: commons/sandbox/convert/trunk/src/test/java/org/apache/commons/convert/TestCollectionConverters.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: commons/sandbox/convert/trunk/src/test/java/org/apache/commons/convert/TestCollectionConverters.java
------------------------------------------------------------------------------
    svn:keywords = Date Rev Author URL Id

Propchange: commons/sandbox/convert/trunk/src/test/java/org/apache/commons/convert/TestCollectionConverters.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain



Mime
View raw message