]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.issues.ui/src/org/simantics/issues/ui/handler/ExportIssuesAsCsv.java
6659a5227ccff3635b46ee173e2c5087f49c7c44
[simantics/platform.git] / bundles / org.simantics.issues.ui / src / org / simantics / issues / ui / handler / ExportIssuesAsCsv.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2011 Association for Decentralized Information Management
3  * in Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.issues.ui.handler;
13
14 import java.io.File;
15 import java.io.PrintStream;
16 import java.lang.reflect.InvocationTargetException;
17 import java.util.Collection;
18 import java.util.Map;
19 import java.util.Set;
20 import java.util.TreeMap;
21
22 import org.eclipse.core.commands.AbstractHandler;
23 import org.eclipse.core.commands.ExecutionEvent;
24 import org.eclipse.core.commands.ExecutionException;
25 import org.eclipse.core.runtime.IProgressMonitor;
26 import org.eclipse.core.runtime.SubMonitor;
27 import org.eclipse.core.runtime.preferences.InstanceScope;
28 import org.eclipse.swt.SWT;
29 import org.eclipse.swt.widgets.FileDialog;
30 import org.eclipse.swt.widgets.Shell;
31 import org.eclipse.ui.IWorkbenchWindow;
32 import org.eclipse.ui.handlers.HandlerUtil;
33 import org.osgi.service.prefs.BackingStoreException;
34 import org.osgi.service.prefs.Preferences;
35 import org.simantics.Simantics;
36 import org.simantics.browsing.ui.common.ErrorLogger;
37 import org.simantics.databoard.Bindings;
38 import org.simantics.db.ReadGraph;
39 import org.simantics.db.Resource;
40 import org.simantics.db.common.request.ObjectsWithType;
41 import org.simantics.db.common.request.ReadRequest;
42 import org.simantics.db.common.utils.NameUtils;
43 import org.simantics.db.exception.DatabaseException;
44 import org.simantics.db.layer0.variable.Variable;
45 import org.simantics.db.request.Read;
46 import org.simantics.issues.common.AllVisibleIssues;
47 import org.simantics.issues.common.DynamicIssueSources;
48 import org.simantics.issues.ui.internal.Activator;
49 import org.simantics.operation.Layer0X;
50 import org.simantics.simulation.ontology.SimulationResource;
51 import org.simantics.utils.DataContainer;
52 import org.simantics.utils.FileUtils;
53 import org.simantics.utils.strings.StringUtils;
54 import org.simantics.utils.ui.ExceptionUtils;
55
56 /**
57  * @author Tuukka Lehtonen
58  */
59 public class ExportIssuesAsCsv extends AbstractHandler {
60
61     private static final String PROP_LAST_VALIDATION_REPORT_PATH= "validation.report.path";
62
63     @Override
64     public Object execute(ExecutionEvent event) throws ExecutionException {
65         IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
66
67         try {
68             String fileName = generateFileName();
69             validate(window, fileName);
70         } catch (DatabaseException e) {
71             ErrorLogger.defaultLogError(e);
72         }
73
74         return null;
75     }
76
77     private String generateFileName() throws DatabaseException {
78         String generatedName = Simantics.getSession().syncRequest(new Read<String>() {
79             @Override
80             public String perform(ReadGraph graph) throws DatabaseException {
81                 Layer0X L0X = Layer0X.getInstance(graph);
82                 SimulationResource SIMU = SimulationResource.getInstance(graph);
83                 for (Resource model : graph.syncRequest(new ObjectsWithType(Simantics.getProjectResource(), L0X.Activates, SIMU.Model))) {
84                     return NameUtils.getSafeName(graph, model) + ".txt";
85                 }
86                 return "issues.txt";
87             }
88         });
89
90         if (!FileUtils.isValidFileName(generatedName))
91             generatedName = (String) Bindings.STR_VARIANT.createUnchecked(Bindings.STRING, generatedName);
92
93         return generatedName;
94     }
95
96     public void validate(IWorkbenchWindow window, String fileName) {
97         Preferences prefs = InstanceScope.INSTANCE.getNode(Activator.PLUGIN_ID);
98         String lastReportPath = prefs.get(PROP_LAST_VALIDATION_REPORT_PATH, null);
99
100         // Query for output path
101         Shell parentShell = null;
102         if (window != null)
103             parentShell = window.getShell();
104
105         final DataContainer<PrintStream> externalOutput = new DataContainer<PrintStream>();
106
107         FileDialog fd = new FileDialog(parentShell, SWT.SAVE);
108         fd.setText("Select Validation Output");
109         fd.setFilterExtensions(new String[] { "*.txt", "*.*" });
110         fd.setFilterNames(new String[] { "Comma-Separated Values (*.txt)", "All Files (*.*)" });
111         if (lastReportPath != null)
112             fd.setFilterPath(lastReportPath);
113         fd.setFileName(fileName);
114         final String path = fd.open();
115         if (path != null) {
116             prefs.put(PROP_LAST_VALIDATION_REPORT_PATH, path);
117             try {
118                 prefs.flush();
119             } catch (BackingStoreException e) {
120                 ExceptionUtils.logError(e);
121             }
122         } else {
123             return;
124         }
125
126         try {
127             window.getWorkbench().getProgressService().busyCursorWhile(monitor -> {
128                 try (PrintStream out = new PrintStream(new File(path))) {
129                     export(monitor, out);
130                 } catch (Exception e) {
131                     throw new InvocationTargetException(e);
132                 } finally {
133                     monitor.done();
134                 }
135             });
136         } catch (InvocationTargetException e) {
137             ExceptionUtils.logAndShowError(e.getTargetException());
138         } catch (InterruptedException e) {
139             // Operation cancelled, ignore.
140         }
141     }
142
143     private void export(IProgressMonitor monitor, PrintStream out) throws DatabaseException {
144         SubMonitor progress = SubMonitor.convert(monitor, "Export issues", IProgressMonitor.UNKNOWN);
145         Simantics.getSession().syncRequest(new ReadRequest() {
146             @Override
147             public void run(ReadGraph graph) throws DatabaseException {
148                 Collection<Variable> activeIssues = graph.syncRequest(new AllVisibleIssues(Simantics.getProjectResource()));
149                 out.println("# Exported issues (" + activeIssues.size() + ")");
150                 for (Variable issue : activeIssues) {
151                     exportIssue(graph, issue, out, 0);
152                     progress.worked(1);
153                 }
154
155                 Map<String, Variable> dynamicIssueSources = nameMap(graph,
156                         graph.syncRequest(new DynamicIssueSources(Simantics.getProjectResource())));
157                 if (!dynamicIssueSources.isEmpty()) {
158                     out.println();
159                     out.println("# Dynamic Issues");
160                     for (Variable source : dynamicIssueSources.values()) {
161                         exportDynamicIssueSource(progress, graph, source, out, 0);
162                     }
163                 }
164             }
165         });
166     }
167
168     private Map<String, Variable> nameMap(ReadGraph graph, Set<Variable> sources) throws DatabaseException {
169         TreeMap<String, Variable> sorted = new TreeMap<>();
170         for (Variable v : sources) {
171             String name = v.getPossiblePropertyValue(graph, "HasDescription", Bindings.STRING);
172             if (name == null)
173                 name = v.getName(graph);
174             sorted.put(name, v);
175         }
176         return sorted;
177     }
178
179     protected void exportDynamicIssueSource(IProgressMonitor monitor, ReadGraph graph, Variable issue, PrintStream out, int startColumn) throws DatabaseException {
180         exportIssue(graph, issue, out, startColumn);
181         for (Variable child : issue.getChildren(graph)) {
182             exportDynamicIssueSource(monitor, graph, child, out, startColumn+1);
183             monitor.worked(1);
184         }
185     }
186
187     private void exportIssue(ReadGraph graph, Variable issue, PrintStream out, int startColumn) throws DatabaseException {
188         String description = StringUtils.safeString( (String) issue.getPossiblePropertyValue(graph, "HasDescription") );
189         String severity = StringUtils.safeString( (String) issue.getPossiblePropertyValue(graph, "severity") );
190         String resource = StringUtils.safeString( (String) issue.getPossiblePropertyValue(graph, "resource") );
191         String path = StringUtils.safeString( (String) issue.getPossiblePropertyValue(graph, "path") );
192         for (int i = 0; i < startColumn; ++i)
193             out.print(";");
194         out.println(description + ";" + severity + ";" + resource + ";" + path);
195     }
196
197 }