]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.charts/src/org/simantics/charts/TrendSupport.java
Sync git svn branch with SVN repository r33269.
[simantics/platform.git] / bundles / org.simantics.charts / src / org / simantics / charts / TrendSupport.java
1 /*******************************************************************************\r
2  * Copyright (c) 2012 Association for Decentralized Information Management in\r
3  * 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  *     VTT Technical Research Centre of Finland - initial API and implementation\r
11  *******************************************************************************/\r
12 package org.simantics.charts;\r
13 \r
14 import java.io.File;\r
15 import java.io.FileNotFoundException;\r
16 import java.io.IOException;\r
17 \r
18 import org.eclipse.core.runtime.IPath;\r
19 import org.eclipse.core.runtime.Platform;\r
20 import org.simantics.Simantics;\r
21 import org.simantics.charts.editor.ChartData;\r
22 import org.simantics.databoard.util.URIUtil;\r
23 import org.simantics.db.ReadGraph;\r
24 import org.simantics.db.Resource;\r
25 import org.simantics.db.common.utils.NameUtils;\r
26 import org.simantics.db.exception.DatabaseException;\r
27 import org.simantics.db.exception.ValidationException;\r
28 import org.simantics.db.layer0.request.PossibleModel;\r
29 import org.simantics.history.History;\r
30 import org.simantics.history.HistoryException;\r
31 import org.simantics.history.HistoryManager;\r
32 import org.simantics.modeling.subscription.CollectSubscriptions;\r
33 import org.simantics.modeling.subscription.ModelHistoryCollector;\r
34 import org.simantics.project.IProject;\r
35 import org.simantics.simulation.experiment.IDynamicExperiment;\r
36 import org.simantics.utils.FileUtils;\r
37 \r
38 /**\r
39  * This class contains utilities for initializing history collection and makes\r
40  * trending of subscribed dynamic experiment data possible.\r
41  * \r
42  * @author Tuukka Lehtonen\r
43  */\r
44 public class TrendSupport {\r
45 \r
46     // Input\r
47     private IDynamicExperiment experiment;\r
48     private String workspaceDataDirectoryName;\r
49 \r
50     // Internals\r
51     private ModelHistoryCollector historyCollector;\r
52     private ChartData chartData;\r
53 \r
54     public TrendSupport(IDynamicExperiment experiment, String workspaceDataDirectoryName) {\r
55         this.experiment = experiment;\r
56         this.workspaceDataDirectoryName = workspaceDataDirectoryName;\r
57     }\r
58 \r
59     public void initializeHistoryCollection(ReadGraph graph) throws DatabaseException {\r
60         final IProject project = Simantics.peekProject();\r
61         if (project == null)\r
62             return;\r
63 \r
64         try {\r
65             File workarea = getExperimentDirectory(graph, experiment.getResource(), true, "result-" + experiment.getIdentifier());\r
66             final HistoryManager history = History.openFileHistory(workarea);\r
67 \r
68             historyCollector = ModelHistoryCollector.createCollector(\r
69                     experiment,\r
70                     history,\r
71                     Activator.getDefault().getLog(),\r
72                     () ->  {\r
73                         CollectSubscriptions cs = new CollectSubscriptions(TrendSupport.this.experiment, 0.1);\r
74                         return cs;\r
75                     }, \r
76                     () -> {\r
77                         // Reset chart data every time subscriptions change\r
78                         // to make sure that trend editor react.\r
79                         if (chartData != null)\r
80                             Charts.resetChartEditorData(project, experiment.getModel(), chartData);\r
81                     });\r
82 \r
83             historyCollector.initialize(graph, 0, true);\r
84 \r
85             // Initialize chart source to support trend viewing\r
86             HistoryManager historyManager = History.openFileHistory(historyCollector.getWorkarea());\r
87             chartData = new ChartData(experiment.getModel(), null,\r
88                     experiment, experiment.getDatasource(), historyManager,\r
89                     historyCollector.getCollector());\r
90             Charts.resetChartEditorData(project, experiment.getModel(), chartData);\r
91         } catch (IOException e) {\r
92             throw new DatabaseException(e);\r
93         } catch (HistoryException e) {\r
94             throw new DatabaseException(e);\r
95         } catch (InterruptedException e) {\r
96             throw new DatabaseException(e);\r
97         }\r
98     }\r
99 \r
100     public void dispose() {\r
101         if (historyCollector != null) {\r
102             historyCollector.dispose();\r
103             historyCollector = null;\r
104         }\r
105         if (chartData != null) {\r
106             final IProject project = Simantics.peekProject();\r
107             if (project != null)\r
108                 Charts.resetChartEditorData(project, experiment.getModel(), null);\r
109             chartData = null;\r
110         }\r
111     }\r
112 \r
113     /**\r
114      * @param g\r
115      * @param experiment\r
116      * @param ensureExistence\r
117      * @param subdirs\r
118      * @return\r
119      * @throws DatabaseException\r
120      * @throws IOException\r
121      */\r
122     protected File getExperimentDirectory(ReadGraph g, Resource experiment, boolean ensureExistence, String... subdirs) throws DatabaseException, IOException {\r
123         Resource model = g.syncRequest(new PossibleModel(experiment));\r
124         if (model == null)\r
125             throw new ValidationException(\r
126                     "Experiment '" + NameUtils.getSafeName(g, experiment)\r
127                     + "' is not part of any model. Has the experiment been removed already? Database may also be corrupted?");\r
128 \r
129         String[] dirs = new String[3 + subdirs.length];\r
130         dirs[0] = workspaceDataDirectoryName;\r
131         dirs[1] = "model-" + model.getResourceId();\r
132         dirs[2] = "experiment-" + experiment.getResourceId();\r
133         System.arraycopy(subdirs, 0, dirs, 3, subdirs.length);\r
134 \r
135         File experimentPath = getWorkspacePath(false, dirs);\r
136         if (ensureExistence)\r
137             ensureDirectoryExistence(experimentPath);\r
138 \r
139         return experimentPath;\r
140     }\r
141 \r
142     /**\r
143      * @param dir the directory that needs to be created if it does not exist\r
144      * @return the requested directory if created or deemed existing\r
145      * @throws IOException if the requested directory cannot be created\r
146      */\r
147     protected static File ensureDirectoryExistence(File dir) throws IOException {\r
148         if (dir.exists() && !dir.isDirectory())\r
149             FileUtils.deleteAll(dir);\r
150 \r
151         dir.mkdirs();\r
152         if (!dir.exists() || !dir.isDirectory())\r
153             throw new FileNotFoundException("Could not create directory '" + dir + "'. Out of disk space?");\r
154 \r
155         return dir;\r
156     }\r
157 \r
158     /**\r
159      * @param escapeNames <code>true</code> to run each path segment through\r
160      *        {@link URIUtil#encodeFilename(String)}\r
161      * @param relativeSegments path segments to append to the workspace root\r
162      *        path\r
163      * @return the designated path within the workspace\r
164      */\r
165     protected static File getWorkspacePath(boolean escapeNames, String... relativeSegments) {\r
166         IPath finalPath = Platform.getLocation();\r
167         for (int i = 0; i < relativeSegments.length; ++i)\r
168             finalPath = finalPath.append(escapeNames ? URIUtil.encodeFilename(relativeSegments[i]) : relativeSegments[i]);\r
169 \r
170         return finalPath.toFile();\r
171     }\r
172 \r
173 }\r