1
2
3
4
5
6
7
8
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
20
21 public class CollectionUtils extends org.apache.commons.collections.CollectionUtils
22 {
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40 public static Object[] toArrayOfComponentType(Collection objects, Class clazz)
41 {
42 if (objects == null)
43 {
44 return null;
45 }
46
47 if (clazz == null)
48 {
49 throw new IllegalArgumentException("Array target class must not be null");
50 }
51
52 if (objects.isEmpty())
53 {
54 return (Object[]) Array.newInstance(clazz, 0);
55 }
56
57 int i = 0, size = objects.size();
58 Object[] result = (Object[]) Array.newInstance(clazz, size);
59 Iterator iter = objects.iterator();
60
61 while (i < size && iter.hasNext())
62 {
63 result[i++] = iter.next();
64 }
65
66 return result;
67 }
68
69
70
71
72
73
74
75
76
77 public static String toString(Collection c, boolean newline)
78 {
79 if (c == null || c.isEmpty())
80 {
81 return "[]";
82 }
83
84 return toString(c, c.size(), newline);
85 }
86
87
88
89
90
91 public static String toString(Collection c, int maxElements)
92 {
93 return toString(c, maxElements, false);
94 }
95
96
97
98
99
100
101
102
103
104
105
106
107 public static String toString(Collection c, int maxElements, boolean newline)
108 {
109 if (c == null || c.isEmpty())
110 {
111 return "[]";
112 }
113
114 int origNumElements = c.size();
115 int numElements = Math.min(origNumElements, maxElements);
116 boolean tooManyElements = (origNumElements > maxElements);
117
118 StringBuffer buf = new StringBuffer(numElements * 32);
119 buf.append('[');
120
121 if (newline)
122 {
123 buf.append(SystemUtils.LINE_SEPARATOR);
124 }
125
126 Iterator items = c.iterator();
127 for (int i = 0; i < numElements - 1; i++)
128 {
129 Object item = items.next();
130
131 if (item instanceof Class)
132 {
133 buf.append(((Class) item).getName());
134 }
135 else
136 {
137 buf.append(item);
138 }
139
140 if (newline)
141 {
142 buf.append(SystemUtils.LINE_SEPARATOR);
143 }
144 else
145 {
146 buf.append(',').append(' ');
147 }
148 }
149
150
151 Object lastItem = items.next();
152 if (lastItem instanceof Class)
153 {
154 buf.append(((Class) lastItem).getName());
155 }
156 else
157 {
158 buf.append(lastItem);
159 }
160
161 if (newline)
162 {
163 buf.append(SystemUtils.LINE_SEPARATOR);
164 }
165
166 if (tooManyElements)
167 {
168 buf.append(" [..]");
169 }
170
171 buf.append(']');
172 return buf.toString();
173 }
174
175
176
177
178 public static List addCreate(List list, Object value)
179 {
180 if (null == list)
181 {
182 return singletonList(value);
183 }
184 else
185 {
186 list.add(value);
187 return list;
188 }
189 }
190
191 public static List singletonList(Object value)
192 {
193 List list = new LinkedList();
194 list.add(value);
195 return list;
196 }
197
198 }