1 package org.kite9.framework.logging;
2
3 import java.lang.reflect.Array;
4 import java.util.ArrayList;
5 import java.util.Collection;
6 import java.util.List;
7
8 /***
9 * Tabular displayer
10 *
11 */
12 public class Table {
13
14 List<Integer> widths = new ArrayList<Integer>();
15
16 List<String[]> rows = new ArrayList<String[]>();
17
18 public void addRow(Object... items) {
19 List<String> longRow = new ArrayList<String>();
20
21 for (Object object : items) {
22 if (object==null) {
23 longRow.add("null");
24 } else if (object.getClass().isArray()) {
25 int length = Array.getLength(object);
26
27 for (int i = 0; i < length; i++) {
28 Object item = Array.get(object, i);
29 longRow.add(item.toString());
30 }
31 } else if (object instanceof Collection<?>) {
32 Collection<?> c = (Collection<?>) object;
33 for (Object object2 : c) {
34 longRow.add(object2.toString());
35 }
36 } else {
37 longRow.add(object.toString());
38 }
39 }
40
41 addArrayRow((String[]) longRow.toArray(new String[longRow.size()]));
42
43 }
44
45 public void removeLastRow() {
46 rows.remove(rows.size()-1);
47 }
48
49 public void addArrayRow(String[] row) {
50 rows.add(row);
51
52 int col = 0;
53 for (String string : row) {
54 if (widths.size() > col) {
55 widths.set(col, widths.get(col) > string.length() ? widths.get(col) : string.length());
56 } else {
57 widths.add(string.length());
58 }
59 col++;
60 }
61 }
62
63 public void display(StringBuffer sb) {
64 for (String[] row : rows) {
65 int colno = 0;
66 for (String col : row) {
67 int width = widths.get(colno) + 1;
68 sb.append(col);
69 for (int i = col.length(); i < width; i++) {
70 sb.append(" ");
71 }
72
73 colno++;
74 }
75 sb.append("\n");
76 }
77
78 }
79 }