]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.issues.ui/src/org/simantics/issues/ui/handler/ExportIssuesAsCsv.java
Fixed all line endings of the repository
[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
19 import org.eclipse.core.commands.AbstractHandler;
20 import org.eclipse.core.commands.ExecutionEvent;
21 import org.eclipse.core.commands.ExecutionException;
22 import org.eclipse.core.runtime.IProgressMonitor;
23 import org.eclipse.core.runtime.SubMonitor;
24 import org.eclipse.core.runtime.preferences.InstanceScope;
25 import org.eclipse.jface.operation.IRunnableWithProgress;
26 import org.eclipse.swt.SWT;
27 import org.eclipse.swt.widgets.FileDialog;
28 import org.eclipse.swt.widgets.Shell;
29 import org.eclipse.ui.IWorkbenchWindow;
30 import org.eclipse.ui.handlers.HandlerUtil;
31 import org.osgi.service.prefs.BackingStoreException;
32 import org.osgi.service.prefs.Preferences;
33 import org.simantics.Simantics;
34 import org.simantics.browsing.ui.common.ErrorLogger;
35 import org.simantics.databoard.Bindings;
36 import org.simantics.db.ReadGraph;
37 import org.simantics.db.Resource;
38 import org.simantics.db.common.request.ObjectsWithType;
39 import org.simantics.db.common.request.ReadRequest;
40 import org.simantics.db.common.utils.NameUtils;
41 import org.simantics.db.exception.DatabaseException;
42 import org.simantics.db.layer0.variable.Variable;
43 import org.simantics.db.request.Read;
44 import org.simantics.issues.common.AllVisibleIssues;
45 import org.simantics.issues.ui.internal.Activator;
46 import org.simantics.operation.Layer0X;
47 import org.simantics.simulation.ontology.SimulationResource;
48 import org.simantics.utils.DataContainer;
49 import org.simantics.utils.FileUtils;
50 import org.simantics.utils.strings.StringUtils;
51 import org.simantics.utils.ui.ExceptionUtils;
52
53 /**
54  * @author Tuukka Lehtonen
55  */
56 public class ExportIssuesAsCsv extends AbstractHandler {
57
58     private static final String PROP_LAST_VALIDATION_REPORT_PATH= "validation.report.path";
59
60     @Override
61     public Object execute(ExecutionEvent event) throws ExecutionException {
62         IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
63
64         try {
65             String fileName = generateFileName();
66             validate(window, fileName);
67         } catch (DatabaseException e) {
68             ErrorLogger.defaultLogError(e);
69         }
70
71         return null;
72     }
73
74     private String generateFileName() throws DatabaseException {
75         String generatedName = Simantics.getSession().syncRequest(new Read<String>() {
76             @Override
77             public String perform(ReadGraph graph) throws DatabaseException {
78                 Layer0X L0X = Layer0X.getInstance(graph);
79                 SimulationResource SIMU = SimulationResource.getInstance(graph);
80                 for (Resource model : graph.syncRequest(new ObjectsWithType(Simantics.getProjectResource(), L0X.Activates, SIMU.Model))) {
81                     return NameUtils.getSafeName(graph, model) + ".txt";
82                 }
83                 return "issues.txt";
84             }
85         });
86
87         if (!FileUtils.isValidFileName(generatedName))
88             generatedName = (String) Bindings.STR_VARIANT.createUnchecked(Bindings.STRING, generatedName);
89
90         return generatedName;
91     }
92
93     public void validate(IWorkbenchWindow window, String fileName) {
94         Preferences prefs = InstanceScope.INSTANCE.getNode(Activator.PLUGIN_ID);
95         String lastReportPath = prefs.get(PROP_LAST_VALIDATION_REPORT_PATH, null);
96
97         // Query for output path
98         Shell parentShell = null;
99         if (window != null)
100             parentShell = window.getShell();
101
102         final DataContainer<PrintStream> externalOutput = new DataContainer<PrintStream>();
103
104         FileDialog fd = new FileDialog(parentShell, SWT.SAVE);
105         fd.setText("Select Validation Output");
106         fd.setFilterExtensions(new String[] { "*.txt", "*.*" });
107         fd.setFilterNames(new String[] { "Comma-Separated Values (*.txt)", "All Files (*.*)" });
108         if (lastReportPath != null)
109             fd.setFilterPath(lastReportPath);
110         fd.setFileName(fileName);
111         final String path = fd.open();
112         if (path != null) {
113             prefs.put(PROP_LAST_VALIDATION_REPORT_PATH, path);
114             try {
115                 prefs.flush();
116             } catch (BackingStoreException e) {
117                 ExceptionUtils.logError(e);
118             }
119         } else {
120 //            boolean result = MessageDialog.openQuestion(parentShell, "Print to stdout?", "Would you like to perform model validation and print the results into stdout?");
121 //            if (!result)
122 //                return;
123 //            externalOutput.set(System.out);
124             return;
125         }
126
127         try {
128             window.getWorkbench().getProgressService().busyCursorWhile(new IRunnableWithProgress() {
129                 @Override
130                 public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
131                     try {
132                         if (externalOutput.get() == null)
133                             externalOutput.set(new PrintStream(new File(path)));
134
135                         final SubMonitor progress = SubMonitor.convert(monitor, "Export issues", IProgressMonitor.UNKNOWN);
136                         Simantics.getSession().syncRequest(new ReadRequest() {
137                             @Override
138                             public void run(ReadGraph graph) throws DatabaseException {
139                                 PrintStream out = externalOutput.get();
140
141                                 Collection<Variable> activeIssues = graph.syncRequest(new AllVisibleIssues(Simantics.getProjectResource()));
142                                 out.println("# Exported issues (" + activeIssues.size() + ")");
143                                 for (Variable issue : activeIssues) {
144                                     String description = StringUtils.safeString( (String) issue.getPossiblePropertyValue(graph, "HasDescription") );
145                                     String severity = StringUtils.safeString( (String) issue.getPossiblePropertyValue(graph, "severity") );
146                                     String resource = StringUtils.safeString( (String) issue.getPossiblePropertyValue(graph, "resource") );
147                                     String path = StringUtils.safeString( (String) issue.getPossiblePropertyValue(graph, "path") );
148                                     out.println(description + ";" + severity + ";" + resource + ";" + path);
149                                     progress.worked(1);
150                                 }
151                             }
152                         });
153                     } catch (Exception e) {
154                         throw new InvocationTargetException(e);
155                     } finally {
156                         monitor.done();
157                         if (externalOutput.get() != System.out)
158                             FileUtils.uncheckedClose(externalOutput.get());
159                     }
160                 }
161             });
162         } catch (InvocationTargetException e) {
163             ExceptionUtils.logAndShowError(e.getTargetException());
164         } catch (InterruptedException e) {
165             // Operation cancelled, ignore.
166         }
167     }
168
169 }