+package org.simantics.district.network.techtype.requests;
+
+import java.io.IOException;
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.csv.CSVFormat;
+import org.apache.commons.csv.CSVParser;
+import org.apache.commons.csv.CSVRecord;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.request.ResourceRead;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.district.network.ontology.DistrictNetworkResource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Get a list of the tech type table records in the order of appearance.
+ *
+ * The query result value is list of records in the form of a map from property name
+ * to string value.
+ *
+ * @author Reino Ruusu
+ */
+public class TechTypeTableRecords extends ResourceRead<List<Map<String, String>>> {
+
+ final static Logger LOGGER = LoggerFactory.getLogger(TechTypeTableRecords.class);
+
+ public TechTypeTableRecords(Resource resource) {
+ super(resource);
+ }
+
+ @Override
+ public List<Map<String, String>> perform(ReadGraph graph) throws DatabaseException {
+ Resource table = this.resource;
+
+ String data = graph.getRelatedValue2(table,
+ DistrictNetworkResource.getInstance(graph).TechType_TechTypeTable_HasData);
+ if (data == null)
+ return null;
+
+ long ncommas = data.chars().filter(c -> c == ',').count();
+ long nsemis = data.chars().filter(c -> c == ';').count();
+ char delim = nsemis > ncommas ? ';' : ',';
+ StringReader reader = new StringReader(data);
+
+ List<CSVRecord> records = new ArrayList<>();
+ try {
+ CSVFormat format = CSVFormat.newFormat(delim).withQuote('"');
+ try (CSVParser parser = format.parse(reader)) {
+ Iterator<CSVRecord> it = parser.iterator();
+ while (it.hasNext()) {
+ records.add(it.next());
+ }
+ }
+ } catch (IOException e) {
+ LOGGER.error("Error reading CSV data", e);
+ throw new DatabaseException("Invalid CSV data in table " + table, e);
+ }
+
+ CSVRecord header = records.remove(0);
+ records.remove(0); // Eliminate units row
+
+ List<Map<String, String>> result = new ArrayList<>();
+ for (CSVRecord r : records) {
+ Map<String, String> valueMap = new HashMap<>();
+ result.add(valueMap);
+
+ Iterator<String> h = header.iterator();
+ Iterator<String> v = r.iterator();
+
+ while (h.hasNext() && v.hasNext()) {
+ String name = h.next().trim().intern();
+ String value = v.next().trim();
+ valueMap.put(name, value);
+ }
+ }
+
+ return result;
+ }
+}