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.Collections;
7 import java.util.HashMap;
8 import java.util.Iterator;
12 import org.apache.commons.csv.CSVFormat;
13 import org.apache.commons.csv.CSVParser;
14 import org.apache.commons.csv.CSVRecord;
15 import org.simantics.db.ReadGraph;
16 import org.simantics.db.Resource;
17 import org.simantics.db.common.request.ResourceRead;
18 import org.simantics.db.exception.DatabaseException;
19 import org.simantics.district.network.ontology.DistrictNetworkResource;
20 import org.simantics.district.network.techtype.TechTypeUtils;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
24 public class TechTypeTableData extends ResourceRead<Map<String, Map<String, String>>> {
26 private final static Logger LOGGER = LoggerFactory.getLogger(TechTypeTableData.class);
28 public TechTypeTableData(Resource table) {
33 public Map<String, Map<String, String>> perform(ReadGraph graph) throws DatabaseException {
34 Resource table = this.resource;
36 String data = graph.getRelatedValue2(table,
37 DistrictNetworkResource.getInstance(graph).TechType_TechTypeTable_HasData);
39 return Collections.emptyMap();
41 String keyName = TechTypeUtils.getKeyPropertyName(graph, table);
42 if (keyName.startsWith("_"))
43 keyName = keyName.substring(1);
45 Map<String, Map<String, String>> map = new HashMap<>();
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 return Collections.emptyMap();
66 CSVRecord header = records.remove(0);
67 records.remove(0); // Eliminate units row
70 for (int i = 0; i < header.size(); i++) {
71 if (header.get(i).equals(keyName)) {
77 for (CSVRecord r : records) {
78 String key = r.get(keyIndex).trim().intern();
82 Map<String, String> valueMap = new HashMap<>();
83 map.put(key, valueMap);
85 Iterator<String> h = header.iterator();
86 Iterator<String> v = r.iterator();
88 while (h.hasNext() && v.hasNext()) {
89 String name = h.next().trim().intern();
90 String value = v.next().trim();
91 valueMap.put(name, value);