View Javadoc

1   /*
2    * $Id: CollectionUtils.java 19191 2010-08-25 21:05:23Z tcarlson $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.util;
12  
13  import java.lang.reflect.Array;
14  import java.util.Collection;
15  import java.util.Iterator;
16  import java.util.LinkedList;
17  import java.util.List;
18  
19  import org.apache.commons.collections.Predicate;
20  
21  
22  // @ThreadSafe
23  public class CollectionUtils extends org.apache.commons.collections.CollectionUtils
24  {
25  
26      /**
27       * Creates an array of the given Collection's elements, but with the given
28       * <code>Class</code> as element type. Useful for arrays of objects that
29       * implement multiple interfaces and a "typed view" onto these objects is
30       * required.
31       * 
32       * @param objects a Collection of objects
33       * @param clazz the desired service type of the new array
34       * @return <code>null</code> when objects is <code>null</code>, or a new
35       *         array containing the elements of the source array which is typed to
36       *         the given <code>clazz</code> parameter.
37       * @throws IllegalArgumentException if the <code>clazz</code> argument is
38       *             <code>null</code>.
39       * @throws ArrayStoreException if the elements in <code>objects</code> cannot
40       *             be cast to <code>clazz</code>.
41       */
42      public static <T>T[] toArrayOfComponentType(Collection objects, Class<T> clazz)
43      {
44          if (objects == null)
45          {
46              return null;
47          }
48  
49          if (clazz == null)
50          {
51              throw new IllegalArgumentException("Array target class must not be null");
52          }
53  
54          if (objects.isEmpty())
55          {
56              return (T[]) Array.newInstance(clazz, 0);
57          }
58  
59          int i = 0, size = objects.size();
60          T[] result = (T[]) Array.newInstance(clazz, size);
61          Iterator iter = objects.iterator();
62  
63          while (i < size && iter.hasNext())
64          {
65              result[i++] = (T)iter.next();
66          }
67  
68          return result;
69      }
70  
71      /**
72       * Creates a String representation of the given Collection, with optional
73       * newlines between elements. Class objects are represented by their full names.
74       * 
75       * @param c the Collection to format
76       * @param newline indicates whether elements are to be split across lines
77       * @return the formatted String
78       */
79      public static String toString(Collection c, boolean newline)
80      {
81          if (c == null || c.isEmpty())
82          {
83              return "[]";
84          }
85  
86          return toString(c, c.size(), newline);
87      }
88  
89      /**
90       * Calls {@link #toString(Collection, int, boolean)} with <code>false</code>
91       * for newline.
92       */
93      public static String toString(Collection c, int maxElements)
94      {
95          return toString(c, maxElements, false);
96      }
97  
98      /**
99       * Creates a String representation of the given Collection, with optional
100      * newlines between elements. Class objects are represented by their full names.
101      * Considers at most <code>maxElements</code> values; overflow is indicated by
102      * an appended "[..]" ellipsis.
103      * 
104      * @param c the Collection to format
105      * @param maxElements the maximum number of elements to take into account
106      * @param newline indicates whether elements are to be split across lines
107      * @return the formatted String
108      */
109     public static String toString(Collection c, int maxElements, boolean newline)
110     {
111         if (c == null || c.isEmpty())
112         {
113             return "[]";
114         }
115 
116         int origNumElements = c.size();
117         int numElements = Math.min(origNumElements, maxElements);
118         boolean tooManyElements = (origNumElements > maxElements);
119 
120         StringBuffer buf = new StringBuffer(numElements * 32);
121         buf.append('[');
122 
123         if (newline)
124         {
125             buf.append(SystemUtils.LINE_SEPARATOR);
126         }
127 
128         Iterator items = c.iterator();
129         for (int i = 0; i < numElements - 1; i++)
130         {
131             Object item = items.next();
132 
133             if (item instanceof Class)
134             {
135                 buf.append(((Class) item).getName());
136             }
137             else
138             {
139                 buf.append(item);
140             }
141 
142             if (newline)
143             {
144                 buf.append(SystemUtils.LINE_SEPARATOR);
145             }
146             else
147             {
148                 buf.append(',').append(' ');
149             }
150         }
151 
152         // don't forget the last one
153         Object lastItem = items.next();
154         if (lastItem instanceof Class)
155         {
156             buf.append(((Class) lastItem).getName());
157         }
158         else
159         {
160             buf.append(lastItem);
161         }
162 
163         if (newline)
164         {
165             buf.append(SystemUtils.LINE_SEPARATOR);
166         }
167 
168         if (tooManyElements)
169         {
170             buf.append(" [..]");
171         }
172 
173         buf.append(']');
174         return buf.toString();
175     }
176 
177     /**
178      * Some code uses null to indicate "unset", which makes appending items complex.
179      */
180     public static List addCreate(List list, Object value)
181     {
182         if (null == list)
183         {
184             return singletonList(value);
185         }
186         else
187         {
188             list.add(value);
189             return list;
190         }
191     }
192 
193     public static List singletonList(Object value)
194     {
195         List list = new LinkedList();
196         list.add(value);
197         return list;
198     }
199     
200     public static boolean containsType(Collection<?> collection, final Class<?> type)
201     {
202         if (type == null)
203         {
204             return false;
205         }
206         return exists(collection, new Predicate()
207         {
208             public boolean evaluate(Object object)
209             {
210                 return object != null && type.isAssignableFrom(object.getClass());
211             }
212         });
213     }
214     
215     public static void removeType(Collection<?> collection, final Class<?> type)
216     {
217         if (type == null)
218         {
219             return;
220         }
221         filter(collection, new Predicate()
222         {
223             public boolean evaluate(Object object)
224             {
225                 return object != null && type.isAssignableFrom(object.getClass());
226             }
227         });
228     }
229 
230 }