1
2
3
4
5
6
7
8
9
10
11 package org.csveed.row;
12
13 import java.util.ArrayList;
14 import java.util.Iterator;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.TreeMap;
18
19 import org.csveed.common.Column;
20 import org.csveed.report.RowReport;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23
24
25
26
27 public class LineWithInfo implements Line {
28
29
30 private static final Logger LOG = LoggerFactory.getLogger(LineWithInfo.class);
31
32
33 private List<String> cells = new ArrayList<>();
34
35
36 private StringBuilder originalLine = new StringBuilder();
37
38
39 private Map<Column, CellPositionInRow> cellPositions = new TreeMap<>();
40
41
42 private int printLength;
43
44
45 private Column currentColumn = new Column();
46
47
48
49
50
51
52
53 public void addCell(String cell) {
54 this.cells.add(cell);
55 if (cell == null || "".equals(cell)) {
56 markStartOfColumn();
57 }
58 markEndOfColumn();
59 }
60
61 @Override
62 public Iterator<String> iterator() {
63 return cells.iterator();
64 }
65
66
67
68
69 public void markStartOfColumn() {
70 LOG.debug("Start of column: {}", printLength);
71 getCellPosition(currentColumn).setStart(printLength);
72 }
73
74
75
76
77 protected void markEndOfColumn() {
78 LOG.debug("End of column: {}", printLength);
79 getCellPosition(currentColumn).setEnd(printLength);
80 currentColumn = currentColumn.nextColumn();
81 }
82
83
84
85
86
87
88
89
90
91 protected CellPositionInRow getCellPosition(Column column) {
92 CellPositionInRow cellPosition = cellPositions.get(column);
93 if (cellPosition == null) {
94 cellPosition = new CellPositionInRow();
95 cellPositions.put(column, cellPosition);
96 }
97 return cellPosition;
98 }
99
100
101
102
103
104
105
106 public void addCharacter(int symbol) {
107 String printableChar = convertToPrintable(symbol);
108 originalLine.append(printableChar);
109 printLength += printableChar.length();
110 }
111
112
113
114
115
116
117
118
119
120 public String convertToPrintable(int symbol) {
121 switch (symbol) {
122 case -1:
123 return "[EOF]";
124 case '\b':
125 return "\\b";
126 case '\f':
127 return "\\f";
128 case '\n':
129 return "\\n";
130 case '\r':
131 return "\\r";
132 case '\t':
133 return "\\t";
134 default:
135 return Character.toString((char) symbol);
136 }
137 }
138
139 @Override
140 public int size() {
141 return this.cells.size();
142 }
143
144 @Override
145 public String get(int index) {
146 return this.cells.get(index);
147 }
148
149 @Override
150 public RowReport reportOnColumn(Column column) {
151 CellPositionInRow cellPosition = cellPositions.get(column);
152 if (cellPosition == null) {
153 return null;
154 }
155 return new RowReport(originalLine.toString(), cellPosition.getStart(), cellPosition.getEnd());
156 }
157
158 @Override
159 public RowReport reportOnEndOfLine() {
160 return new RowReport(originalLine.toString(), printLength, printLength);
161 }
162
163 }