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