1 /*******************************************************************************
2 * Copyright (c) 2012,2017 Association for Decentralized Information Management in
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
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.charts.ui;
14 import java.io.BufferedOutputStream;
16 import java.io.FileOutputStream;
17 import java.io.IOException;
18 import java.io.PrintStream;
19 import java.io.RandomAccessFile;
20 import java.lang.reflect.InvocationTargetException;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.HashSet;
26 import org.eclipse.core.commands.ExecutionException;
27 import org.eclipse.core.runtime.IProgressMonitor;
28 import org.eclipse.core.runtime.IStatus;
29 import org.eclipse.core.runtime.Status;
30 import org.eclipse.core.runtime.SubMonitor;
31 import org.eclipse.core.runtime.preferences.IScopeContext;
32 import org.eclipse.core.runtime.preferences.InstanceScope;
33 import org.eclipse.jface.operation.IRunnableWithProgress;
34 import org.osgi.service.prefs.BackingStoreException;
35 import org.osgi.service.prefs.Preferences;
36 import org.simantics.Simantics;
37 import org.simantics.charts.Activator;
38 import org.simantics.charts.editor.ChartData;
39 import org.simantics.charts.editor.ChartKeys;
40 import org.simantics.databoard.binding.error.BindingException;
41 import org.simantics.databoard.serialization.SerializationException;
42 import org.simantics.db.ReadGraph;
43 import org.simantics.db.Resource;
44 import org.simantics.db.common.request.UniqueRead;
45 import org.simantics.db.common.utils.Logger;
46 import org.simantics.db.exception.DatabaseException;
47 import org.simantics.db.layer0.request.PossibleModel;
48 import org.simantics.history.HistoryException;
49 import org.simantics.history.csv.CSVFormatter;
50 import org.simantics.modeling.preferences.CSVPreferences;
51 import org.simantics.utils.datastructures.hints.IHintContext.Key;
52 import org.simantics.utils.format.FormattingUtils;
53 import org.simantics.utils.ui.dialogs.ShowMessage;
56 * @author Antti Villberg
58 public class CSVExporter implements IRunnableWithProgress {
60 CSVExportPlan exportModel;
62 public CSVExporter(CSVExportPlan exportModel) {
63 this.exportModel = exportModel;
67 public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
68 SubMonitor progress = SubMonitor.convert(monitor, 50);
70 exportModel(progress.newChild(50, SubMonitor.SUPPRESS_NONE));
71 } catch (IOException e) {
72 throw new InvocationTargetException(e);
73 } catch (DatabaseException e) {
74 throw new InvocationTargetException(e);
75 } catch (BindingException e) {
76 throw new InvocationTargetException(e);
82 void exportModel(SubMonitor mon) throws IOException, DatabaseException, SerializationException, BindingException{
84 doExport(mon, exportModel.exportLocation, exportModel);
85 } catch (ExecutionException e) {
87 Logger.defaultLogError(e);
88 mon.setCanceled(true);
89 ShowMessage.showError("Export failed.", "Internal application error in export. See log for details.");
91 mon.setWorkRemaining(0);
95 private static Set<Resource> resolveContainingModels(Collection<Resource> res) throws DatabaseException {
96 return Simantics.getSession().syncRequest(new UniqueRead<Set<Resource>>() {
98 public Set<Resource> perform(ReadGraph graph) throws DatabaseException {
99 Set<Resource> models = new HashSet<>();
100 for (Resource r : res) {
101 Resource m = graph.syncRequest(new PossibleModel(r));
110 public static void doExport(IProgressMonitor monitor, final File f, final CSVExportPlan plan) throws ExecutionException, IOException {
111 IScopeContext context = InstanceScope.INSTANCE;
112 Preferences node = context.getNode(CSVPreferences.P_NODE);
114 node.putDouble(CSVPreferences.P_CSV_START_TIME, plan.startTime);
115 node.putDouble(CSVPreferences.P_CSV_TIME_STEP, plan.timeStep);
116 node.put(CSVPreferences.P_CSV_DECIMAL_SEPARATOR, plan.decimalSeparator.toPreference());
117 node.put(CSVPreferences.P_CSV_COLUMN_SEPARATOR, plan.columnSeparator.toPreference());
119 node.putBoolean(CSVPreferences.P_CSV_RESAMPLE, plan.resample);
120 node.put(CSVPreferences.P_CSV_SAMPLING_MODE, plan.samplingMode.toPreference());
122 node.putInt(CSVPreferences.P_CSV_TIME_DIGITS, plan.timeDigits);
123 node.putInt(CSVPreferences.P_CSV_FLOAT_DIGITS, plan.floatDigits);
124 node.putInt(CSVPreferences.P_CSV_DOUBLE_DIGITS, plan.doubleDigits);
128 } catch (BackingStoreException ex) {
129 Activator.getDefault().getLog().log(
130 new Status(IStatus.WARNING, Activator.PLUGIN_ID, "Could not store preferences for node " + node.absolutePath()));
133 Set<Resource> models;
135 models = resolveContainingModels(plan.items);
136 } catch (DatabaseException e3) {
137 throw new ExecutionException("Containing model resolution failed.", e3);
139 if (models.isEmpty())
140 throw new ExecutionException("Selected resources are not part of any model");
141 if (models.size() > 1)
142 throw new ExecutionException("Selected resources are part of several models, only subscriptions from a single model can be selected");
143 Resource model = models.iterator().next();
144 Key chartDataKey = ChartKeys.chartSourceKey(model);
146 final ChartData data = Simantics.getProject().getHint(chartDataKey);
147 if ( data == null ) {
148 throw new ExecutionException("There is no "+chartDataKey);
150 if ( data.history == null ) {
151 throw new ExecutionException("There is no history in "+chartDataKey);
154 final CSVFormatter csv = new CSVFormatter();
156 csv.setStartTime( plan.startTime );
157 csv.setTimeStep( plan.timeStep );
158 csv.setDecimalSeparator( plan.decimalSeparator );
159 csv.setColumnSeparator( plan.columnSeparator );
160 csv.setResample( plan.resample );
161 csv.setNumberInterpolation( plan.samplingMode );
162 csv.setTimeFormat( FormattingUtils.significantDigitFormat( plan.timeDigits ) );
163 csv.setFloatFormat( FormattingUtils.significantDigitFormat( plan.floatDigits ) );
164 csv.setNumberFormat( FormattingUtils.significantDigitFormat( plan.doubleDigits ) );
167 Simantics.getSession().syncRequest(
168 new CSVParamsQuery(data.history, csv,
169 new ArrayList<>(plan.items)) );
172 // Ensure all views are built.
173 monitor.beginTask("Exporting Time Series as CSV...", IProgressMonitor.UNKNOWN);
174 data.collector.flush();
176 // Truncate existing file it if happens to exist.
177 try (RandomAccessFile raf = new RandomAccessFile(f, "rw")) {
182 try (PrintStream ps = new PrintStream(
183 new BufferedOutputStream(
184 new FileOutputStream(f, true) )))
186 csv.formulate2( new CSVProgressMonitor( monitor ), ps );
190 monitor.setTaskName("Done");
191 } catch (DatabaseException e2) {
192 throw new ExecutionException(e2.getMessage(), e2);
193 } catch (HistoryException e) {
194 throw new ExecutionException(e.getMessage(), e);