]> gerrit.simantics Code Review - simantics/district.git/commitdiff
Read tech type table data from model 16/4416/4
authorReino Ruusu <reino.ruusu@semantum.fi>
Mon, 31 Aug 2020 13:06:06 +0000 (16:06 +0300)
committerTuukka Lehtonen <tuukka.lehtonen@semantum.fi>
Tue, 1 Sep 2020 06:36:35 +0000 (06:36 +0000)
gitlab #93

Change-Id: Iee2cae3751983d059216fea7ec11fd47a9e9dda4

org.simantics.district.network.ui/fragment.e4xmi
org.simantics.district.network.ui/src/org/simantics/district/network/ui/table/ImportTechTypeCSVHandler.java
org.simantics.district.network.ui/src/org/simantics/district/network/ui/techtype/requests/PossibleTechTypeTable.java [new file with mode: 0644]
org.simantics.district.network.ui/src/org/simantics/district/network/ui/techtype/requests/PossibleTechTypeTableData.java [new file with mode: 0644]
org.simantics.district.network.ui/src/org/simantics/district/network/ui/techtype/requests/WriteTechTypeTableRequest.java [new file with mode: 0644]
org.simantics.district.network.ui/src/org/simantics/district/network/ui/techtype/table/TechTypeTable.java
org.simantics.district.network.ui/src/org/simantics/district/network/ui/techtype/table/TechTypeTableDataProvider.java
org.simantics.district.network.ui/src/org/simantics/district/network/ui/techtype/table/TechTypeTableView.java

index c199a95928557e5b505a47ed9ed76bc79ca0e153..89afdc5d9435258dd03c497252f391a7527069c9 100644 (file)
@@ -16,7 +16,7 @@
     <elements xsi:type="commands:Command" xmi:id="_CLKOUHVvEemS_rRAHnCQSw" elementId="org.simantics.district.network.ui.command.changeroutepointtovertex" commandName="Change Route Point to Vertex"/>
     <elements xsi:type="commands:Command" xmi:id="_Ee0TAHVvEemS_rRAHnCQSw" elementId="org.simantics.district.network.ui.command.changevertextoroutepoint" commandName="Change Vertex to Route Point"/>
     <elements xsi:type="commands:Command" xmi:id="_QcEKQIAGEemKlokjSaREFQ" elementId="org.simantics.district.network.ui.command.importcsv" commandName="Import CSV"/>
-    <!--<elements xsi:type="commands:Command" xmi:id="_VWtY8LqWEemcscVaZzEyWw" elementId="org.simantics.district.network.ui.command.importtechtypecsv" commandName="Import Tech Type CSV"/>-->
+    <elements xsi:type="commands:Command" xmi:id="_VWtY8LqWEemcscVaZzEyWw" elementId="org.simantics.district.network.ui.command.importtechtypecsv" commandName="Import Tech Type CSV"/>
   </fragments>
   <fragments xsi:type="fragment:StringModelFragment" xmi:id="_Js7rUMMAEea1mdgpHNVHMA" featurename="menuContributions" parentElementId="xpath:/">
     <elements xsi:type="menu:MenuContribution" xmi:id="_T-jiEN8NEeaigNyzMJBOrg" elementId="org.simantics.district.network.ui.menucontribution.districtDiagramPopup" parentId="#DistrictDiagramPopup">
@@ -49,6 +49,6 @@
     <elements xsi:type="commands:Handler" xmi:id="_F9vvIHVvEemS_rRAHnCQSw" elementId="org.simantics.district.network.ui.handler.7" contributionURI="bundleclass://org.simantics.district.network.ui/org.simantics.district.network.ui.contributions.ChangeRoutePointToVertexHandler" command="_CLKOUHVvEemS_rRAHnCQSw"/>
     <elements xsi:type="commands:Handler" xmi:id="_H7TA8HVvEemS_rRAHnCQSw" elementId="org.simantics.district.network.ui.handler.8" contributionURI="bundleclass://org.simantics.district.network.ui/org.simantics.district.network.ui.contributions.ChangeVertexToRoutePointHandler" command="_Ee0TAHVvEemS_rRAHnCQSw"/>
     <elements xsi:type="commands:Handler" xmi:id="_akE8EIAGEemKlokjSaREFQ" elementId="org.simantics.district.network.ui.handler.9" contributionURI="bundleclass://org.simantics.district.network.ui/org.simantics.district.network.ui.table.ImportCSVHandler" command="_QcEKQIAGEemKlokjSaREFQ"/>
-    <!--<elements xsi:type="commands:Handler" xmi:id="_XjbIILqWEemcscVaZzEyWw" elementId="org.simantics.district.network.ui.handler.10" contributionURI="bundleclass://org.simantics.district.network.ui/org.simantics.district.network.ui.table.ImportTechTypeCSVHandler" command="_VWtY8LqWEemcscVaZzEyWw"/>-->
+    <elements xsi:type="commands:Handler" xmi:id="_XjbIILqWEemcscVaZzEyWw" elementId="org.simantics.district.network.ui.handler.10" contributionURI="bundleclass://org.simantics.district.network.ui/org.simantics.district.network.ui.table.ImportTechTypeCSVHandler" command="_VWtY8LqWEemcscVaZzEyWw"/>
   </fragments>
 </fragment:ModelFragments>
index 7ee841b4186f023057d725f48bc4983ff4151fcd..4f833fca58cd3356c60b3d7eb4cc37fbacef055d 100644 (file)
@@ -34,9 +34,10 @@ public class ImportTechTypeCSVHandler {
         String path = dialog.open();
         try {
             if (path != null) {
-                
+
                 Path p = Paths.get(path);
                 if (Files.exists(p)) {
+                    @SuppressWarnings("unused")
                     Map<String, Integer> readCSVHeader = DistrictImportUtils.readCSVHeader(p, ';', true);
                     TechTypeTableView.table.setTechTypePath(path);
                 } else {
diff --git a/org.simantics.district.network.ui/src/org/simantics/district/network/ui/techtype/requests/PossibleTechTypeTable.java b/org.simantics.district.network.ui/src/org/simantics/district/network/ui/techtype/requests/PossibleTechTypeTable.java
new file mode 100644 (file)
index 0000000..c722dfc
--- /dev/null
@@ -0,0 +1,33 @@
+package org.simantics.district.network.ui.techtype.requests;
+
+import java.util.Collection;
+
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.request.ResourceRead2;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.district.network.ontology.DistrictNetworkResource;
+import org.simantics.layer0.Layer0;
+
+public class PossibleTechTypeTable extends ResourceRead2<Resource> {
+       public PossibleTechTypeTable(Resource model, Resource componentType) {
+               super(model, componentType);
+       }
+
+       @Override
+       public Resource perform(ReadGraph graph) throws DatabaseException {
+               Layer0 L0 = Layer0.getInstance(graph);
+               DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
+               
+               Collection<Resource> children = graph.getObjects(resource, L0.ConsistsOf);
+               for (Resource child : children) {
+                       if (!graph.isInstanceOf(child, DN.TechType_TechTypeTable))
+                               continue;
+                       
+                       if (graph.hasStatement(child, DN.TechType_TechTypeTable_HasComponentType, resource2))
+                               return child;
+               }
+               
+               return null;
+       }
+}
\ No newline at end of file
diff --git a/org.simantics.district.network.ui/src/org/simantics/district/network/ui/techtype/requests/PossibleTechTypeTableData.java b/org.simantics.district.network.ui/src/org/simantics/district/network/ui/techtype/requests/PossibleTechTypeTableData.java
new file mode 100644 (file)
index 0000000..b47bbc7
--- /dev/null
@@ -0,0 +1,23 @@
+package org.simantics.district.network.ui.techtype.requests;
+
+import org.simantics.databoard.Bindings;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.procedure.adapter.TransientCacheListener;
+import org.simantics.db.common.request.ResourceRead2;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.district.network.ontology.DistrictNetworkResource;
+
+public class PossibleTechTypeTableData extends ResourceRead2<String> {
+       public PossibleTechTypeTableData(Resource model, Resource componentType) {
+               super(model, componentType);
+       }
+
+       @Override
+       public String perform(ReadGraph graph) throws DatabaseException {
+               DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
+
+               Resource ttt = graph.syncRequest(new PossibleTechTypeTable(resource, resource2), TransientCacheListener.instance());
+               return ttt != null ? graph.getPossibleRelatedValue2(ttt, DN.TechType_TechTypeTable_HasData, Bindings.STRING) : null;
+       }
+}
diff --git a/org.simantics.district.network.ui/src/org/simantics/district/network/ui/techtype/requests/WriteTechTypeTableRequest.java b/org.simantics.district.network.ui/src/org/simantics/district/network/ui/techtype/requests/WriteTechTypeTableRequest.java
new file mode 100644 (file)
index 0000000..118c8a7
--- /dev/null
@@ -0,0 +1,45 @@
+package org.simantics.district.network.ui.techtype.requests;
+
+import java.util.UUID;
+
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.procedure.adapter.TransientCacheListener;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.request.PossibleActiveModel;
+import org.simantics.district.network.ontology.DistrictNetworkResource;
+import org.simantics.layer0.Layer0;
+
+public final class WriteTechTypeTableRequest extends WriteRequest {
+       private final String data;
+       private final Resource componentType;
+
+       public WriteTechTypeTableRequest(Resource componentType, String data) {
+               this.data = data;
+               this.componentType = componentType;
+       }
+
+       @Override
+       public void perform(WriteGraph graph) throws DatabaseException {
+               Layer0 L0 = Layer0.getInstance(graph);
+               DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
+
+               Resource model = graph.syncRequest(new PossibleActiveModel(Simantics.getProjectResource()));
+               if (model == null)
+                       throw new DatabaseException("No active model for storing tech type data");
+
+               Resource ttt = graph.syncRequest(new PossibleTechTypeTable(model, componentType), TransientCacheListener.instance());
+
+               if (ttt == null) {
+                       ttt = graph.newResource();
+                       graph.claim(ttt, L0.InstanceOf, DN.TechType_TechTypeTable);
+                       graph.claimLiteral(ttt, L0.HasName, UUID.randomUUID().toString());
+                       graph.claim(model, L0.ConsistsOf, ttt);
+                       graph.claim(ttt, DN.TechType_TechTypeTable_HasComponentType, componentType);
+               }
+
+               graph.claimLiteral(ttt, DN.TechType_TechTypeTable_HasData, data);
+       }
+}
\ No newline at end of file
index 725700f89c50b1c660d9b95418e65e479e91c223..eb83c902ddf535c9bcd8ae236de40913d33bf4a6 100644 (file)
@@ -1,6 +1,10 @@
 package org.simantics.district.network.ui.techtype.table;
 
-import java.io.Serializable;
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.stream.Collectors;
 
 import org.eclipse.jface.layout.GridDataFactory;
 import org.eclipse.jface.layout.GridLayoutFactory;
@@ -9,7 +13,6 @@ import org.eclipse.nebula.widgets.nattable.config.DefaultNatTableStyleConfigurat
 import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry;
 import org.eclipse.nebula.widgets.nattable.copy.command.CopyDataCommandHandler;
 import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
-import org.eclipse.nebula.widgets.nattable.data.IRowIdAccessor;
 import org.eclipse.nebula.widgets.nattable.freeze.CompositeFreezeLayer;
 import org.eclipse.nebula.widgets.nattable.freeze.FreezeLayer;
 import org.eclipse.nebula.widgets.nattable.grid.GridRegion;
@@ -29,7 +32,6 @@ import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
 import org.eclipse.nebula.widgets.nattable.layer.ILayer;
 import org.eclipse.nebula.widgets.nattable.layer.IUniqueIndexLayer;
 import org.eclipse.nebula.widgets.nattable.reorder.RowReorderLayer;
-import org.eclipse.nebula.widgets.nattable.selection.RowSelectionModel;
 import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
 import org.eclipse.nebula.widgets.nattable.sort.SortHeaderLayer;
 import org.eclipse.nebula.widgets.nattable.viewport.ViewportLayer;
@@ -39,9 +41,17 @@ import org.eclipse.swt.events.ModifyEvent;
 import org.eclipse.swt.events.ModifyListener;
 import org.eclipse.swt.widgets.Composite;
 import org.eclipse.swt.widgets.Text;
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.district.network.ui.techtype.requests.WriteTechTypeTableRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 public class TechTypeTable extends Composite {
 
+       private final static Logger LOGGER = LoggerFactory.getLogger(TechTypeTable.class);
+
        NatTable table;
        private TechTypeTableDataProvider bodyDataProvider;
        DataLayer bodyDataLayer;
@@ -50,63 +60,69 @@ public class TechTypeTable extends Composite {
        private ViewportLayer viewportLayer;
        private CompositeFreezeLayer compositeFreezeLayer;
        private FreezeLayer freezeLayer;
-       //private TableDataSortModel sortModel;
+       // private TableDataSortModel sortModel;
        private ColumnHideShowLayer columnHideShowLayer;
        private ColumnGroupModel columnGroupModel = new ColumnGroupModel();
        private TechTypeColumnHeaderTableDataProvider columnHeaderDataProvider;
        Clipboard cpb;
        public SelectionLayer selectionLayer;
-    private TechTypeTableSortModel sortModel;
+       private TechTypeTableSortModel sortModel;
+
+       private Resource componentType;
 
-       public TechTypeTable(Composite parent, int style) {
+       public TechTypeTable(Composite parent, int style, Resource componentType, String data) {
                super(parent, style);
-               defaultInitializeUI();
+               this.componentType = componentType;
+
+               defaultInitializeUI(data);
        }
 
-       private void defaultInitializeUI() {
+       private void defaultInitializeUI(String data) {
                GridDataFactory.fillDefaults().grab(true, true).applyTo(this);
                GridLayoutFactory.fillDefaults().numColumns(1).applyTo(this);
-               
+
                Composite filterComposite = new Composite(this, SWT.NONE);
                GridDataFactory.fillDefaults().grab(true, false).applyTo(filterComposite);
-        GridLayoutFactory.fillDefaults().numColumns(1).applyTo(filterComposite);
-        
+               GridLayoutFactory.fillDefaults().numColumns(1).applyTo(filterComposite);
+
+               createFilterBar(filterComposite);
 
-        createFilterBar(filterComposite);
-        
                Composite tableComposite = new Composite(this, SWT.NONE);
                GridDataFactory.fillDefaults().grab(true, true).applyTo(tableComposite);
-        GridLayoutFactory.fillDefaults().numColumns(1).applyTo(tableComposite);
-               createTable(tableComposite);
+               GridLayoutFactory.fillDefaults().numColumns(1).applyTo(tableComposite);
+
+               createTable(tableComposite, data);
        }
 
        private void createFilterBar(Composite filterComposite) {
-           
-        Text filterText = new Text(filterComposite, SWT.BORDER);
-        GridDataFactory.fillDefaults().grab(true, true).applyTo(filterText);
-        filterText.addModifyListener(new ModifyListener() {
-            
-            @Override
-            public void modifyText(ModifyEvent e) {
-                System.out.println("text modified");
-                bodyDataProvider.setFilter(filterText.getText());
-                table.refresh(true);
-            }
-        });
-        
-    }
-
-    private void createTable(Composite parent) {
-
-               // build the body layer stack 
-               // Usually you would create a new layer stack by extending AbstractIndexLayerTransform and
-               // setting the ViewportLayer as underlying layer. But in this case using the ViewportLayer
+
+               Text filterText = new Text(filterComposite, SWT.BORDER);
+               GridDataFactory.fillDefaults().grab(true, true).applyTo(filterText);
+               filterText.addModifyListener(new ModifyListener() {
+
+                       @Override
+                       public void modifyText(ModifyEvent e) {
+                               System.out.println("text modified");
+                               bodyDataProvider.setFilter(filterText.getText());
+                               table.refresh(true);
+                       }
+               });
+
+       }
+
+       private void createTable(Composite parent, String data) {
+
+               // build the body layer stack
+               // Usually you would create a new layer stack by extending
+               // AbstractIndexLayerTransform and
+               // setting the ViewportLayer as underlying layer. But in this case using the
+               // ViewportLayer
                // directly as body layer is also working.
-               bodyDataProvider = new TechTypeTableDataProvider();
+               bodyDataProvider = new TechTypeTableDataProvider(data);
                bodyDataLayer = new DataLayer(bodyDataProvider);
 
-               RowReorderLayer rowReorderLayer =
-                               new RowReorderLayer(columnHideShowLayer = new ColumnHideShowLayer(bodyDataLayer));
+               RowReorderLayer rowReorderLayer = new RowReorderLayer(
+                               columnHideShowLayer = new ColumnHideShowLayer(bodyDataLayer));
 
                HoverLayer hoverLayer = new HoverLayer(rowReorderLayer, false);
                // we need to ensure that the hover styling is removed when the mouse
@@ -114,7 +130,7 @@ public class TechTypeTable extends Composite {
                hoverLayer.addConfiguration(new BodyHoverStylingBindings(hoverLayer));
 
                selectionLayer = new SelectionLayer(hoverLayer);
-               
+
                viewportLayer = new ViewportLayer(selectionLayer);
                viewportLayer.setRegionName(GridRegion.BODY);
                freezeLayer = new FreezeLayer(selectionLayer);
@@ -125,10 +141,13 @@ public class TechTypeTable extends Composite {
                DataLayer columnHeaderDataLayer = new DefaultColumnHeaderDataLayer(columnHeaderDataProvider);
                columnHeaderDataLayer.setRowsResizableByDefault(false);
                columnHeaderDataLayer.setColumnsResizableByDefault(true);
-               ColumnHeaderLayer columnHeaderLayer = new ColumnHeaderLayer(columnHeaderDataLayer, compositeFreezeLayer, selectionLayer);
-               ColumnGroupHeaderLayer columnGroupHeaderLayer = new ColumnGroupHeaderLayer(columnHeaderLayer, selectionLayer, columnGroupModel);
+               ColumnHeaderLayer columnHeaderLayer = new ColumnHeaderLayer(columnHeaderDataLayer, compositeFreezeLayer,
+                               selectionLayer);
+               ColumnGroupHeaderLayer columnGroupHeaderLayer = new ColumnGroupHeaderLayer(columnHeaderLayer, selectionLayer,
+                               columnGroupModel);
                columnGroupHeaderLayer.setCalculateHeight(true);
-               SortHeaderLayer<String> columnSortHeaderLayer = new SortHeaderLayer<>(columnGroupHeaderLayer, sortModel = new TechTypeTableSortModel(bodyDataProvider));
+               SortHeaderLayer<String> columnSortHeaderLayer = new SortHeaderLayer<>(columnGroupHeaderLayer,
+                               sortModel = new TechTypeTableSortModel(bodyDataProvider));
 
                // build the row header layer
                IDataProvider rowHeaderDataProvider = new TechTypeRowHeaderTableDataProvider(bodyDataProvider);
@@ -138,44 +157,59 @@ public class TechTypeTable extends Composite {
                RowHeaderLayer rowHeaderLayer = new RowHeaderLayer(rowHeaderDataLayer, compositeFreezeLayer, selectionLayer);
 
                // build the corner layer
-               IDataProvider cornerDataProvider = new DefaultCornerDataProvider(columnHeaderDataProvider, rowHeaderDataProvider);
+               IDataProvider cornerDataProvider = new DefaultCornerDataProvider(columnHeaderDataProvider,
+                               rowHeaderDataProvider);
                DataLayer cornerDataLayer = new DataLayer(cornerDataProvider);
                ILayer cornerLayer = new CornerLayer(cornerDataLayer, rowHeaderLayer, columnSortHeaderLayer);
 
                // build the grid layer
                GridLayer gridLayer = new GridLayer(compositeFreezeLayer, columnSortHeaderLayer, rowHeaderLayer, cornerLayer);
-               
+
                table = new NatTable(parent, NatTable.DEFAULT_STYLE_OPTIONS | SWT.BORDER, gridLayer, false);
                GridDataFactory.fillDefaults().grab(true, true).applyTo(table);
-               
+
                // Register a CopyDataCommandHandler that also copies the headers and
                // uses the configured IDisplayConverters
-               CopyDataCommandHandler copyHandler = new CopyDataCommandHandler(
-                               selectionLayer,
-                               columnHeaderDataLayer,
+               CopyDataCommandHandler copyHandler = new CopyDataCommandHandler(selectionLayer, columnHeaderDataLayer,
                                rowHeaderDataLayer);
                copyHandler.setCopyFormattedText(true);
                gridLayer.registerCommandHandler(copyHandler);
-               
+
                // initialize paste handler with SWT clipboard
                cpb = new Clipboard(getDisplay());
-               //PasteDataCommandHandler pasteHandler = new PasteDataCommandHandler(bodyDataProvider, bodyDataLayer, selectionLayer, cpb);
-               //bodyDataLayer.registerCommandHandler(pasteHandler);
-               
+               // PasteDataCommandHandler pasteHandler = new
+               // PasteDataCommandHandler(bodyDataProvider, bodyDataLayer, selectionLayer,
+               // cpb);
+               // bodyDataLayer.registerCommandHandler(pasteHandler);
+
                table.addConfiguration(new DefaultNatTableStyleConfiguration());
-               //table.addConfiguration(new EditingSupportConfiguration(bodyDataProvider));
+               // table.addConfiguration(new EditingSupportConfiguration(bodyDataProvider));
                table.configure();
        }
-       
+
        @Override
        public void dispose() {
                cpb.dispose();
                super.dispose();
        }
 
-    public void setTechTypePath(String path) {
-        bodyDataProvider.setPath(path);
-        table.refresh(true);
-    }
+       public void setTechTypePath(String path) {
+               String data;
+               try {
+                       data = Files.lines(Paths.get(path)).collect(Collectors.joining("\n"));
+               } catch (IOException e) {
+                       LOGGER.error("Failed to read contents of file '{}' as {}", path, Charset.defaultCharset(), e);
+                       return;
+               }
+
+               try {
+                       Simantics.getSession().syncRequest(new WriteTechTypeTableRequest(componentType, data));
+               } catch (DatabaseException e) {
+                       LOGGER.error("Failed to write tech type table data to model", e);
+               }
+
+               bodyDataProvider.setData(data);
+               table.refresh(true);
+       }
 
 }
index 534be1dafe5a57d2dfef57884de4b6e676203017..850cc39f3c3d86190ac7f91d7b814cb871231417 100644 (file)
@@ -1,38 +1,54 @@
 package org.simantics.district.network.ui.techtype.table;
 
 import java.io.IOException;
+import java.io.StringReader;
 import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.util.ArrayList;
+import java.util.Iterator;
 import java.util.List;
 import java.util.stream.Collectors;
 
 import org.apache.commons.csv.CSVRecord;
 import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
 import org.simantics.district.imports.DistrictImportUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 public class TechTypeTableDataProvider implements IDataProvider {
 
+    @SuppressWarnings("unused")
+    private final static Logger LOGGER = LoggerFactory.getLogger(TechTypeTableDataProvider.class);
+
     private List<CSVRecord> records = new ArrayList<>();
     private List<CSVRecord> filteredRecords = new ArrayList<>();
     private String filter = "";
+    private List<String> variables = null;
+    private List<String> headers = null;
 
-    public TechTypeTableDataProvider() {
+    public TechTypeTableDataProvider(String data) {
         // load csv
+        setData(data);
+    }
 
-        setPath("C:\\projektit\\apros\\Semantum_VTT_Fortum portaali 2018-17-12\\järvenpää\\qgis\\TechTypeData.csv");
+    public String getVariableName(int columnIndex) {
+        return variables != null && columnIndex < variables.size() ? variables.get(columnIndex) : null;
     }
 
-    public Object getHeaderValue(int columnIndex) {
-        if (records.isEmpty()) {
+    public int getVariableIndex(String variableName) {
+        return variables != null ? variables.indexOf(variableName) : -1;
+    }
+
+    public String getHeaderValue(int columnIndex) {
+        if (headers == null) {
             return "<empty>";
         }
-        return records.get(0).get(columnIndex);
+        return headers.get(columnIndex);
     }
 
     @Override
     public Object getDataValue(int columnIndex, int rowIndex) {
-        return filteredRecords.get(rowIndex + 1).get(columnIndex);
+        return filteredRecords.get(rowIndex).get(columnIndex);
     }
 
     @Override
@@ -71,20 +87,75 @@ public class TechTypeTableDataProvider implements IDataProvider {
         }).collect(Collectors.toList());
     }
 
+    /**
+     * Read a CSV file into table contents.
+     * 
+     * Set path to null to create an empty table.
+     * 
+     * @param path  The path of the CSV file to be read.
+     */
     public void setPath(String path) {
         records.clear();
         filteredRecords.clear();
-        Path techTypeCsv = Paths.get(path);
-        try {
-            DistrictImportUtils.consumeCSV(techTypeCsv, ';', false, record -> {
-                records.add(record);
-                return true;
-            });
-        } catch (IOException e) {
-            e.printStackTrace();
+        if (path != null) {
+            Path techTypeCsv = Paths.get(path);
+            try {
+                DistrictImportUtils.consumeCSV(techTypeCsv, ';', false, record -> {
+                    records.add(record);
+                    return true;
+                });
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+
+        setFilter("");
+    }
+
+    /**
+     * Set table data contents to a given string of CSV data.
+     * 
+     * Set 'data' to null to create an empty table.
+     * 
+     * @param data  The CSV data to be shown in the table.
+     */
+    public void setData(String data) {
+        records.clear();
+        filteredRecords.clear();
+        if (data != 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);
+            try {
+                DistrictImportUtils.consumeCSV(reader, delim, false, record -> {
+                    records.add(record);
+                    return true;
+                });
+            } catch (IOException e) {
+                LOGGER.error("Error reading CSV file", e);
+                return;
+            }
+
+            CSVRecord header = records.remove(0);
+            CSVRecord units = records.remove(0);
+
+            variables = new ArrayList<>();
+            headers = new ArrayList<>();
+
+            Iterator<String> it = header.iterator();
+            Iterator<String> uit = units.iterator();
+
+            while (it.hasNext()) {
+                String variable = it.next().trim();
+                String unit = uit.hasNext() ? uit.next().trim() : null;
+
+                variables.add(variable);
+                headers.add(variable + (unit != null && !unit.isEmpty() && !(unit.startsWith("(") && unit.endsWith(")")) ? " [" + unit + "]" : ""));
+            }
         }
 
         setFilter("");
     }
 
-}
+}
\ No newline at end of file
index cdb502c3c5a870ddc887f240a8c6c185173d055d..42b88207c1881fe0b8b1735f7a10e843675a915c 100644 (file)
@@ -1,6 +1,8 @@
 package org.simantics.district.network.ui.techtype.table;
 
 
+import java.util.List;
+
 import javax.annotation.PostConstruct;
 import javax.annotation.PreDestroy;
 import javax.inject.Inject;
@@ -13,9 +15,22 @@ import org.eclipse.e4.ui.model.application.ui.menu.MMenuFactory;
 import org.eclipse.e4.ui.model.application.ui.menu.MToolBar;
 import org.eclipse.e4.ui.workbench.modeling.ESelectionService;
 import org.eclipse.swt.widgets.Composite;
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.common.NamedResource;
+import org.simantics.db.common.procedure.adapter.TransientCacheListener;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.request.PossibleActiveModel;
+import org.simantics.db.layer0.request.PossibleResource;
+import org.simantics.district.network.DistrictNetworkUtil;
+import org.simantics.district.network.ui.techtype.requests.PossibleTechTypeTableData;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 public class TechTypeTableView {
 
+       private final static Logger LOGGER = LoggerFactory.getLogger(TechTypeTableView.class);
+
        @Inject ESelectionService selectionService;
 
        public static TechTypeTable table;
@@ -40,10 +55,36 @@ public class TechTypeTableView {
 
        @PostConstruct
        public void postConstruct(Composite parent) {
-               table = new TechTypeTable(parent, 0);
-               
+               Resource pipe = null;
+               try {
+                       List<NamedResource> componentTypes = DistrictNetworkUtil.getDistrictComponents();
+
+                       pipe = componentTypes.stream()
+                                       .filter(r -> r.getName().toLowerCase().contains("pipe"))
+                                       .map(r -> r.getResource())
+                                       .findFirst().orElse(null);
+
+                       if (pipe == null) {
+                               pipe = Simantics.getSession().syncRequest(new PossibleResource("http://DistrictComponents@C/dh_pipe@1"));
+                       }
+               } catch (DatabaseException e) {
+                       LOGGER.error("Failed to read district component types for active model", e);
+               }
+
+               LOGGER.debug("Pipe component type is {}", pipe);
+
+               String data = null;
+               try {
+                       Resource model = Simantics.getSession().syncRequest(new PossibleActiveModel(Simantics.getProjectResource()));
+                       if (model != null)
+                               data = Simantics.getSession().syncRequest(new PossibleTechTypeTableData(model, pipe), TransientCacheListener.instance());
+               } catch (DatabaseException e) {
+                       LOGGER.error("Failed to read tech type table data for {}", pipe, e);
+               }
+
+               table = new TechTypeTable(parent, 0, pipe, data);
        }
-       
+
        @PreDestroy
        public void dispose() {
                table.dispose();