1 package org.simantics.district.network.ui.techtype.table;
3 import java.io.IOException;
4 import java.io.StringReader;
5 import java.nio.file.Path;
6 import java.nio.file.Paths;
7 import java.util.ArrayList;
8 import java.util.Comparator;
9 import java.util.Iterator;
10 import java.util.List;
11 import java.util.stream.IntStream;
13 import org.apache.commons.csv.CSVRecord;
14 import org.eclipse.core.runtime.ListenerList;
15 import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
16 import org.eclipse.nebula.widgets.nattable.sort.SortDirectionEnum;
17 import org.simantics.district.imports.DistrictImportUtils;
18 import org.simantics.district.network.techtype.TechTypeUtils;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
22 public class TechTypeTableDataProvider implements IDataProvider {
24 private final static Logger LOGGER = LoggerFactory.getLogger(TechTypeTableDataProvider.class);
26 private List<CSVRecord> records = new ArrayList<>();
27 private boolean[] enabled;
28 private String filter = null;
29 private List<String> variables = null;
30 private List<String> headers = null;
31 private int[] filteredRows;
33 private ListenerList<EnableListener> enableListeners = new ListenerList<EnableListener>();
35 private int[] sortedRows;
37 private static final Comparator<? super String> VALUE_COMPARATOR = (a, b) -> {
39 double da = Double.valueOf(a.replace(",", "."));
40 double db = Double.valueOf(b.replace(",", "."));
41 return Double.compare(da, db);
42 } catch (NumberFormatException e) {
43 return TechTypeUtils.compareNatural(a, b);
47 public TechTypeTableDataProvider(String data, int[] enabledList) {
49 setEnabledFlags(enabledList);
52 public TechTypeTableDataProvider(String data) {
57 public void setEnabledFlags(int[] enabledList) {
58 this.enabled = new boolean[records.size()];
59 if (enabledList != null) {
60 for (int i : enabledList) {
61 if (i >= 0 && i < enabled.length)
67 public String getVariableName(int columnIndex) {
68 return variables != null && columnIndex > 0 && columnIndex <= variables.size() ? variables.get(columnIndex - 1) : null;
71 public int getVariableIndex(String variableName) {
72 return variables != null ? variables.indexOf(variableName) + 1 : -1;
75 public CSVRecord getRecord(int rowIndex) {
76 return records.get(recordIndex(rowIndex));
79 public boolean isEnabled(int rowIndex) {
80 return enabled[recordIndex(rowIndex)];
83 private int recordIndex(int rowIndex) {
84 return sortedRows[filteredRows[rowIndex]];
87 public String getHeaderValue(int columnIndex) {
88 if (headers == null) {
90 } else if (columnIndex == 0) {
93 return headers.get(columnIndex - 1);
98 public Object getDataValue(int columnIndex, int rowIndex) {
99 if (columnIndex == 0) {
100 return isEnabled(rowIndex);
102 return getRecord(rowIndex).get(columnIndex - 1);
106 public void setDataValue(int columnIndex, int rowIndex, Object newValue) {
107 if (columnIndex == 0) {
108 boolean value = Boolean.parseBoolean((String) newValue);
109 enabled[recordIndex(rowIndex)] = value;
110 fireEnableEvent(rowIndex, value);
114 public void addEnableListener(EnableListener listener) {
115 enableListeners.add(listener);
118 private void fireEnableEvent(int rowIndex, boolean newValue) {
119 enableListeners.forEach(l -> l.rowEnabled(rowIndex, newValue));
123 public int getColumnCount() {
124 if (records.isEmpty()) {
127 return records.get(0).size() + 1;
131 public int getRowCount() {
132 return filteredRows.length;
135 public boolean isEditable(int columnIndex, int rowIndex) {
136 return columnIndex == 0;
139 public void setFilter(String text) {
140 this.filter = text != null ? text.toLowerCase() : null;
142 filteredRows = IntStream.range(0, records.size())
143 .filter(k -> isMatch(records.get(sortedRows[k]), filter))
147 private static boolean isMatch(CSVRecord record, String filterString) {
148 if (filterString == null || filterString.isEmpty())
151 for (int i = 0; i < record.size(); i++) {
152 String columnContent = record.get(i);
153 if (columnContent.toLowerCase().contains(filterString)) {
162 * Read a CSV file into table contents.
164 * Set path to null to create an empty table.
166 * @param path The path of the CSV file to be read.
168 public void setPath(String path) {
172 Path techTypeCsv = Paths.get(path);
174 DistrictImportUtils.consumeCSV(techTypeCsv, ';', false, record -> {
178 } catch (IOException e) {
183 enabled = new boolean[records.size()];
184 sortedRows = IntStream.range(0, records.size()).toArray();
190 * Set table data contents to a given string of CSV data.
192 * Set 'data' to null to create an empty table.
194 * @param data The CSV data to be shown in the table.
196 public void setData(String data) {
200 long ncommas = data.chars().filter(c -> c == ',').count();
201 long nsemis = data.chars().filter(c -> c == ';').count();
202 char delim = nsemis > ncommas ? ';' : ',';
203 StringReader reader = new StringReader(data);
205 DistrictImportUtils.consumeCSV(reader, delim, false, record -> {
209 } catch (IOException e) {
210 LOGGER.error("Error reading CSV file", e);
214 CSVRecord header = records.remove(0);
215 CSVRecord units = records.remove(0);
217 variables = new ArrayList<>();
218 headers = new ArrayList<>();
220 Iterator<String> it = header.iterator();
221 Iterator<String> uit = units.iterator();
223 while (it.hasNext()) {
224 String variable = it.next().trim();
225 String unit = uit.hasNext() ? uit.next().trim() : null;
227 variables.add(variable);
228 headers.add(variable + (unit != null && !unit.isEmpty() && !(unit.startsWith("(") && unit.endsWith(")")) ? " [" + unit + "]" : ""));
232 enabled = new boolean[records.size()];
233 sortedRows = IntStream.range(0, records.size()).toArray();
238 public void sortBy(int columnIndex, SortDirectionEnum sortDirection) {
240 if (columnIndex >= 0 && !sortDirection.equals(SortDirectionEnum.NONE)) {
241 Comparator<Integer> comparator = columnIndex == 0 ?
242 Comparator.comparing(k -> enabled[sortedRows[(int) k]]) :
243 Comparator.comparing(k -> records.get(sortedRows[(int) k]).get(columnIndex-1), VALUE_COMPARATOR);
245 if (sortDirection.equals(SortDirectionEnum.DESC))
246 comparator = comparator.reversed();
248 sortedRows = IntStream.range(0, records.size())
251 .mapToInt(i -> sortedRows[i])
254 sortedRows = IntStream.range(0, records.size()).toArray();