]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.event/src/org/simantics/event/view/handler/ExportEventsAsCsv.java
Migrated source code from Simantics SVN
[simantics/platform.git] / bundles / org.simantics.event / src / org / simantics / event / view / handler / ExportEventsAsCsv.java
1 /*******************************************************************************\r
2  * Copyright (c) 2014 Association for Decentralized Information Management\r
3  * in Industry THTH ry.\r
4  * All rights reserved. This program and the accompanying materials\r
5  * are made available under the terms of the Eclipse Public License v1.0\r
6  * which accompanies this distribution, and is available at\r
7  * http://www.eclipse.org/legal/epl-v10.html\r
8  *\r
9  * Contributors:\r
10  *     Semantum Oy - initial API and implementation\r
11  *******************************************************************************/\r
12 package org.simantics.event.view.handler;\r
13 \r
14 import java.io.File;\r
15 import java.io.FileNotFoundException;\r
16 import java.lang.reflect.InvocationTargetException;\r
17 import java.util.Calendar;\r
18 \r
19 import org.eclipse.core.commands.AbstractHandler;\r
20 import org.eclipse.core.commands.ExecutionEvent;\r
21 import org.eclipse.core.commands.ExecutionException;\r
22 import org.eclipse.core.runtime.IProgressMonitor;\r
23 import org.eclipse.core.runtime.preferences.InstanceScope;\r
24 import org.eclipse.jface.operation.IRunnableWithProgress;\r
25 import org.eclipse.swt.SWT;\r
26 import org.eclipse.swt.widgets.FileDialog;\r
27 import org.eclipse.swt.widgets.Shell;\r
28 import org.eclipse.ui.IWorkbenchWindow;\r
29 import org.eclipse.ui.handlers.HandlerUtil;\r
30 import org.osgi.service.prefs.BackingStoreException;\r
31 import org.osgi.service.prefs.Preferences;\r
32 import org.simantics.Simantics;\r
33 import org.simantics.browsing.ui.common.ErrorLogger;\r
34 import org.simantics.databoard.Bindings;\r
35 import org.simantics.db.ReadGraph;\r
36 import org.simantics.db.Resource;\r
37 import org.simantics.db.common.request.ObjectsWithType;\r
38 import org.simantics.db.common.utils.NameUtils;\r
39 import org.simantics.db.exception.DatabaseException;\r
40 import org.simantics.db.request.Read;\r
41 import org.simantics.event.Activator;\r
42 import org.simantics.event.util.EventExporter;\r
43 import org.simantics.operation.Layer0X;\r
44 import org.simantics.simulation.ontology.SimulationResource;\r
45 import org.simantics.utils.FileUtils;\r
46 import org.simantics.utils.ui.ExceptionUtils;\r
47 import org.simantics.utils.ui.dialogs.ShowError;\r
48 \r
49 /**\r
50  * @author Tuukka Lehtonen\r
51  */\r
52 public class ExportEventsAsCsv extends AbstractHandler {\r
53 \r
54     private static final String PROP_LAST_PATH= "event.csv.export.path";\r
55 \r
56     @Override\r
57     public Object execute(ExecutionEvent event) throws ExecutionException {\r
58         IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);\r
59 \r
60         try {\r
61             String fileName = generateFileName();\r
62             validate(window, fileName);\r
63         } catch (DatabaseException e) {\r
64             ErrorLogger.defaultLogError(e);\r
65         }\r
66 \r
67         return null;\r
68     }\r
69 \r
70     private String generateFileName() throws DatabaseException {\r
71         String generatedName = Simantics.getSession().syncRequest(new Read<String>() {\r
72             @Override\r
73             public String perform(ReadGraph graph) throws DatabaseException {\r
74                 Layer0X L0X = Layer0X.getInstance(graph);\r
75                 SimulationResource SIMU = SimulationResource.getInstance(graph);\r
76                 for (Resource model : graph.syncRequest(new ObjectsWithType(Simantics.getProjectResource(), L0X.Activates, SIMU.Model))) {\r
77                     return NameUtils.getSafeName(graph, model) + "-events-" + getTimestamp() + ".txt";\r
78                 }\r
79                 return "events-" + getTimestamp() + ".txt";\r
80             }\r
81 \r
82             private String getTimestamp() {\r
83                 Calendar c = Calendar.getInstance();\r
84                 return c.get(Calendar.YEAR) + "-" + (1 + c.get(Calendar.MONTH)) + "-" + c.get(Calendar.DAY_OF_MONTH)\r
85                         + "_" + c.get(Calendar.HOUR_OF_DAY) \r
86                         + "-" + c.get(Calendar.MINUTE) \r
87                         + "-" + c.get(Calendar.SECOND); \r
88             }\r
89         });\r
90 \r
91         if (!FileUtils.isValidFileName(generatedName))\r
92             generatedName = (String) Bindings.STR_VARIANT.createUnchecked(Bindings.STRING, generatedName);\r
93 \r
94         return generatedName;\r
95     }\r
96 \r
97     public void validate(IWorkbenchWindow window, String fileName) {\r
98         Preferences prefs = InstanceScope.INSTANCE.getNode(Activator.BUNDLE_ID);\r
99         String lastReportPath = prefs.get(PROP_LAST_PATH, null);\r
100 \r
101         // Query for output path\r
102         Shell parentShell = null;\r
103         if (window != null)\r
104             parentShell = window.getShell();\r
105 \r
106         FileDialog fd = new FileDialog(parentShell, SWT.SAVE);\r
107         fd.setText("Select Output");\r
108         fd.setFilterExtensions(new String[] { "*.txt", "*.csv", "*.*" });\r
109         fd.setFilterNames(new String[] { "Tab-Separated Values (*.txt)", "Comma-Separated Values (*.csv)", "All Files (*.*)" });\r
110         if (lastReportPath != null)\r
111             fd.setFilterPath(lastReportPath);\r
112         fd.setFileName(fileName);\r
113         String path = fd.open();\r
114         if (path != null) {\r
115             prefs.put(PROP_LAST_PATH, path);\r
116             try {\r
117                 prefs.flush();\r
118             } catch (BackingStoreException e) {\r
119                 ExceptionUtils.logError(e);\r
120             }\r
121         } else {\r
122             return;\r
123         }\r
124 \r
125         String _cs = null;\r
126         switch (fd.getFilterIndex()) {\r
127         case 1:\r
128             _cs = ";";\r
129             if (!path.endsWith(".csv"))\r
130                 path += ".csv";\r
131             break;\r
132         case 0:\r
133             if (!path.endsWith(".txt"))\r
134                 path += ".txt";\r
135             // Intentional fallthrough\r
136         default:\r
137             _cs = "\t";\r
138             break;\r
139         }\r
140         final String columnSeparator = _cs;\r
141         final File out = new File(path);\r
142         System.out.println("out: " + out);\r
143 \r
144         try {\r
145             window.getWorkbench().getProgressService().busyCursorWhile(new IRunnableWithProgress() {\r
146                 @Override\r
147                 public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {\r
148                     try {\r
149                         new EventExporter().exportCsv(monitor, out, columnSeparator);\r
150                     } catch (Exception e) {\r
151                         throw new InvocationTargetException(e);\r
152                     } finally {\r
153                         monitor.done();\r
154                     }\r
155                 }\r
156             });\r
157         } catch (InvocationTargetException e) {\r
158             Throwable t = e.getTargetException();\r
159             if (t instanceof FileNotFoundException) {\r
160                 ShowError.showError("Export Failed", "Failed to write " + t.getMessage(), (Exception) null);\r
161             } else {\r
162                 ExceptionUtils.logAndShowError(t);\r
163             }\r
164         } catch (InterruptedException e) {\r
165             // Operation cancelled, ignore.\r
166         }\r
167     }\r
168 \r
169 }