1 package org.simantics.district.network.techtype.requests;
3 import java.io.IOException;
4 import java.io.StringReader;
5 import java.util.ArrayList;
6 import java.util.HashMap;
7 import java.util.Iterator;
11 import org.apache.commons.csv.CSVFormat;
12 import org.apache.commons.csv.CSVParser;
13 import org.apache.commons.csv.CSVRecord;
14 import org.simantics.db.ReadGraph;
15 import org.simantics.db.Resource;
16 import org.simantics.db.common.request.ResourceRead;
17 import org.simantics.db.exception.DatabaseException;
18 import org.simantics.district.network.ontology.DistrictNetworkResource;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
23 * Get a list of the tech type table records in the order of appearance.
25 * The query result value is list of records in the form of a map from property name
30 public class TechTypeTableRecords extends ResourceRead<List<Map<String, String>>> {
32 final static Logger LOGGER = LoggerFactory.getLogger(TechTypeTableRecords.class);
34 public TechTypeTableRecords(Resource resource) {
39 public List<Map<String, String>> perform(ReadGraph graph) throws DatabaseException {
40 Resource table = this.resource;
42 String data = graph.getRelatedValue2(table,
43 DistrictNetworkResource.getInstance(graph).TechType_TechTypeTable_HasData);
47 long ncommas = data.chars().filter(c -> c == ',').count();
48 long nsemis = data.chars().filter(c -> c == ';').count();
49 char delim = nsemis > ncommas ? ';' : ',';
50 StringReader reader = new StringReader(data);
52 List<CSVRecord> records = new ArrayList<>();
54 CSVFormat format = CSVFormat.newFormat(delim).withQuote('"');
55 try (CSVParser parser = format.parse(reader)) {
56 Iterator<CSVRecord> it = parser.iterator();
57 while (it.hasNext()) {
58 records.add(it.next());
61 } catch (IOException e) {
62 LOGGER.error("Error reading CSV data", e);
63 throw new DatabaseException("Invalid CSV data in table " + table, e);
66 CSVRecord header = records.remove(0);
67 records.remove(0); // Eliminate units row
69 List<Map<String, String>> result = new ArrayList<>();
70 for (CSVRecord r : records) {
71 Map<String, String> valueMap = new HashMap<>();
74 Iterator<String> h = header.iterator();
75 Iterator<String> v = r.iterator();
77 while (h.hasNext() && v.hasNext()) {
78 String name = h.next().trim().intern();
79 String value = v.next().trim();
80 valueMap.put(name, value);