1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package fulmine.util.collection;
17
18 import static fulmine.util.Utils.CLOSE_CURLY;
19 import static fulmine.util.Utils.OPEN_CURLY;
20 import static fulmine.util.Utils.SPACING_4_CHARS;
21 import static fulmine.util.Utils.safeToString;
22
23 import java.util.Collection;
24 import java.util.Map;
25 import java.util.Set;
26
27 import org.apache.commons.lang.SystemUtils;
28
29
30
31
32
33
34
35 public abstract class CollectionUtils
36 {
37
38
39
40 private final static ThreadLocal<Integer> indent =
41 new ThreadLocal<Integer>();
42
43
44
45
46
47
48
49
50
51
52 @SuppressWarnings("unchecked")
53 public static StringBuilder toFormattedString(Collection collection)
54 {
55 try
56 {
57 String indent = indent();
58 StringBuilder sb = new StringBuilder();
59 sb.append(SystemUtils.LINE_SEPARATOR).append(indent).append(
60 OPEN_CURLY);
61 for (Object element : collection)
62 {
63 sb.append(SystemUtils.LINE_SEPARATOR).append(indent).append(
64 SPACING_4_CHARS).append(safeToString(element));
65 }
66 sb.append(SystemUtils.LINE_SEPARATOR).append(indent).append(
67 CLOSE_CURLY);
68 return sb;
69 }
70 catch (RuntimeException e)
71 {
72 indent.remove();
73 throw e;
74 }
75 finally
76 {
77 unindent();
78 }
79 }
80
81
82
83
84
85
86
87 @SuppressWarnings("boxing")
88 private static String indent()
89 {
90 Integer level = indent.get();
91 if (level == null)
92 {
93 level = Integer.valueOf(-1);
94 }
95 indent.set(++level);
96 StringBuilder sb = new StringBuilder();
97 for (int i = 0; i < level; i++)
98 {
99 sb.append(SPACING_4_CHARS);
100 }
101 return sb.toString();
102 }
103
104
105
106
107 @SuppressWarnings("boxing")
108 private static void unindent()
109 {
110 Integer level = indent.get();
111 if (level != null)
112 {
113 indent.set(--level);
114 }
115 }
116
117
118
119
120
121
122
123
124
125
126 @SuppressWarnings("unchecked")
127 public static StringBuilder toFormattedString(Map map)
128 {
129 StringBuilder sb = new StringBuilder();
130 final Set entrySet = map.entrySet();
131 return sb.append(toFormattedString(entrySet));
132 }
133 }