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