1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
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.modeling;
15 import java.io.IOException;
16 import java.text.DateFormat;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.Collections;
20 import java.util.Date;
21 import java.util.HashMap;
22 import java.util.HashSet;
23 import java.util.List;
26 import java.util.TreeMap;
28 import org.eclipse.core.runtime.CoreException;
29 import org.eclipse.core.runtime.IProgressMonitor;
30 import org.eclipse.core.runtime.NullProgressMonitor;
31 import org.eclipse.core.runtime.Path;
32 import org.eclipse.jface.dialogs.Dialog;
33 import org.eclipse.jface.dialogs.IDialogConstants;
34 import org.eclipse.jface.dialogs.MessageDialog;
35 import org.eclipse.jface.layout.GridDataFactory;
36 import org.eclipse.jface.layout.GridLayoutFactory;
37 import org.eclipse.jface.resource.ImageDescriptor;
38 import org.eclipse.jface.viewers.IStructuredSelection;
39 import org.eclipse.jface.viewers.StructuredSelection;
40 import org.eclipse.jface.window.Window;
41 import org.eclipse.jface.wizard.WizardDialog;
42 import org.eclipse.swt.SWT;
43 import org.eclipse.swt.widgets.Composite;
44 import org.eclipse.swt.widgets.Control;
45 import org.eclipse.swt.widgets.Display;
46 import org.eclipse.swt.widgets.FileDialog;
47 import org.eclipse.swt.widgets.Shell;
48 import org.eclipse.ui.IWorkbenchWizard;
49 import org.eclipse.ui.PlatformUI;
50 import org.eclipse.ui.wizards.IWizardDescriptor;
51 import org.simantics.Simantics;
52 import org.simantics.annotation.ontology.AnnotationResource;
53 import org.simantics.databoard.Bindings;
54 import org.simantics.databoard.binding.Binding;
55 import org.simantics.databoard.binding.mutable.Variant;
56 import org.simantics.databoard.container.DataContainer;
57 import org.simantics.databoard.container.DataContainers;
58 import org.simantics.databoard.container.DataFormatException;
59 import org.simantics.databoard.container.FormatHandler;
60 import org.simantics.databoard.serialization.SerializationException;
61 import org.simantics.databoard.type.Datatype;
62 import org.simantics.databoard.util.URIStringUtils;
63 import org.simantics.datatypes.literal.GUID;
64 import org.simantics.db.MetadataI;
65 import org.simantics.db.ReadGraph;
66 import org.simantics.db.RequestProcessor;
67 import org.simantics.db.Resource;
68 import org.simantics.db.Session;
69 import org.simantics.db.Statement;
70 import org.simantics.db.VirtualGraph;
71 import org.simantics.db.WriteGraph;
72 import org.simantics.db.common.Indexing;
73 import org.simantics.db.common.NamedResource;
74 import org.simantics.db.common.QueryMemoryWatcher;
75 import org.simantics.db.common.changeset.GenericChangeListener;
76 import org.simantics.db.common.primitiverequest.IsInstanceOf;
77 import org.simantics.db.common.procedure.adapter.TransientCacheAsyncListener;
78 import org.simantics.db.common.procedure.adapter.TransientCacheListener;
79 import org.simantics.db.common.request.IndexRoot;
80 import org.simantics.db.common.request.ObjectsWithType;
81 import org.simantics.db.common.request.PossibleIndexRoot;
82 import org.simantics.db.common.request.ReadRequest;
83 import org.simantics.db.common.request.ResourceRead2;
84 import org.simantics.db.common.request.WriteRequest;
85 import org.simantics.db.common.request.WriteResultRequest;
86 import org.simantics.db.common.utils.ListUtils;
87 import org.simantics.db.common.utils.Logger;
88 import org.simantics.db.common.utils.NameUtils;
89 import org.simantics.db.common.utils.OrderedSetUtils;
90 import org.simantics.db.common.utils.VersionInfo;
91 import org.simantics.db.common.utils.VersionInfoRequest;
92 import org.simantics.db.common.utils.Versions;
93 import org.simantics.db.exception.DatabaseException;
94 import org.simantics.db.layer0.QueryIndexUtils;
95 import org.simantics.db.layer0.SelectionHints;
96 import org.simantics.db.layer0.adapter.CopyHandler;
97 import org.simantics.db.layer0.adapter.GenericRelationIndex;
98 import org.simantics.db.layer0.adapter.Instances;
99 import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;
100 import org.simantics.db.layer0.adapter.impl.ImportAdvisorFactory;
101 import org.simantics.db.layer0.genericrelation.DependenciesRelation.DependencyChangesRequest;
102 import org.simantics.db.layer0.genericrelation.DependencyChanges;
103 import org.simantics.db.layer0.genericrelation.IndexedRelations;
104 import org.simantics.db.layer0.migration.MigratedImportResult;
105 import org.simantics.db.layer0.migration.MigrationUtils;
106 import org.simantics.db.layer0.request.ActivateModel;
107 import org.simantics.db.layer0.request.ActiveModels;
108 import org.simantics.db.layer0.request.Configuration;
109 import org.simantics.db.layer0.request.IsLinkedTo;
110 import org.simantics.db.layer0.request.PossibleModel;
111 import org.simantics.db.layer0.util.ClipboardUtils;
112 import org.simantics.db.layer0.util.DraftStatusBean;
113 import org.simantics.db.layer0.util.ExternalDownloadBean;
114 import org.simantics.db.layer0.util.Layer0Utils;
115 import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest;
116 import org.simantics.db.layer0.util.PasteEventHandler;
117 import org.simantics.db.layer0.util.RemoverUtil;
118 import org.simantics.db.layer0.util.SimanticsClipboard;
119 import org.simantics.db.layer0.util.SimanticsClipboard.Representation;
120 import org.simantics.db.layer0.util.SimanticsClipboardImpl;
121 import org.simantics.db.layer0.util.SimanticsKeys;
122 import org.simantics.db.layer0.util.TransferableGraphConfiguration2;
123 import org.simantics.db.layer0.variable.Variable;
124 import org.simantics.db.layer0.variable.Variables;
125 import org.simantics.db.request.Read;
126 import org.simantics.db.service.ClusterControl;
127 import org.simantics.db.service.CollectionSupport;
128 import org.simantics.db.service.GraphChangeListenerSupport;
129 import org.simantics.db.service.QueryControl;
130 import org.simantics.db.service.VirtualGraphSupport;
131 import org.simantics.diagram.stubs.DiagramResource;
132 import org.simantics.diagram.stubs.G2DResource;
133 import org.simantics.diagram.synchronization.graph.AddElement;
134 import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
135 import org.simantics.graph.db.IImportAdvisor2;
136 import org.simantics.graph.db.ImportAdvisors;
137 import org.simantics.graph.db.MissingDependencyException;
138 import org.simantics.graph.db.StreamingTransferableGraphFileReader;
139 import org.simantics.graph.db.TransferableGraphException;
140 import org.simantics.graph.db.TransferableGraphSource;
141 import org.simantics.graph.db.TransferableGraphs;
142 import org.simantics.graph.representation.Identity;
143 import org.simantics.graph.representation.Root;
144 import org.simantics.graph.representation.TransferableGraph1;
145 import org.simantics.graph.representation.TransferableGraphUtils;
146 import org.simantics.issues.common.IssueSourceUtils;
147 import org.simantics.issues.ontology.IssueResource;
148 import org.simantics.layer0.Layer0;
149 import org.simantics.layer0.utils.direct.GraphUtils;
150 import org.simantics.modeling.adapters.ChangeInformation;
151 import org.simantics.modeling.template2d.ontology.Template2dResource;
152 import org.simantics.modeling.utils.OntologicalRequirementTracker;
153 import org.simantics.operation.Layer0X;
154 import org.simantics.project.ontology.ProjectResource;
155 import org.simantics.scenegraph.profile.ProfileUtils;
156 import org.simantics.scl.runtime.function.Function1;
157 import org.simantics.scl.runtime.tuple.Tuple;
158 import org.simantics.simulation.ontology.SimulationResource;
159 import org.simantics.structural.stubs.StructuralResource2;
160 import org.simantics.structural2.modelingRules.IModelingRules;
161 import org.simantics.structural2.scl.StructuralComponent;
162 import org.simantics.structural2.utils.StructuralUtils;
163 import org.simantics.utils.ObjectUtils;
164 import org.simantics.utils.datastructures.Pair;
165 import org.simantics.utils.datastructures.Triple;
166 import org.simantics.utils.datastructures.hints.HintContext;
167 import org.simantics.utils.ui.dialogs.ListDialog;
170 * @author Hannu Niemistö
172 public class ModelingUtils {
175 private WriteGraph wg;
177 private StructuralResource2 sr;
178 private DiagramResource dr;
179 public ModelingResources mr;
180 public SimulationResource SIMU;
182 public ModelingUtils(WriteGraph g) {
185 b = Layer0.getInstance(g);
186 sr = StructuralResource2.getInstance(g);
187 dr = DiagramResource.getInstance(g);
188 mr = ModelingResources.getInstance(g);
189 SIMU = SimulationResource.getInstance(g);
193 public Resource createSymbol2(String name) throws DatabaseException {
194 return createSymbol2(name, dr.Composite);
198 public Resource createSymbol2(String name, Resource diagramType) throws DatabaseException {
199 return createSymbol2(name, diagramType, dr.DefinedElement);
202 public Resource createSymbol2(String name, Resource diagramType, Resource symbolType) throws DatabaseException {
203 G2DResource g2d = G2DResource.getInstance(g);
205 // Resource visibleTag = wg.newResource();
206 // wg.claim(visibleTag, b.SubrelationOf, null, dr.IsVisible);
207 // Resource focusableTag = wg.newResource();
208 // wg.claim(focusableTag, b.SubrelationOf, null, dr.IsFocusable);
210 Double boxDimension = 6.0;
211 Collection<Statement> grid = g.getAssertedStatements(diagramType, dr.HasGridSize);
212 if(grid.size() == 1) {
213 Double d = g.getPossibleValue(grid.iterator().next().getObject(), Bindings.DOUBLE);
214 if(d != null) boxDimension = 2*d;
218 Resource element = GraphUtils.create(wg,
219 b.InstanceOf, dr.SVGElement,
221 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" +
222 // REMOVED by Tuukka, because This will cause
223 // parsers to get on the net and get the doctype
224 // definitions which can stall the UI for a long time.
225 // Besides, we're not using the validation for anything
226 // so it's useless to us.
227 //"<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">" +
228 "<svg xmlns=\"http://www.w3.org/2000/svg\" overflow=\"visible\" version=\"1.1\">" +
229 "<rect x=\"-" + boxDimension + "\" y=\"-" + boxDimension + "\" width=\"" + (2*boxDimension) + "\" height=\"" + (2*boxDimension) + "\" fill=\"none\" stroke=\"rgb(0,0,0)\" stroke-width=\"0.1\"/>" +
233 // wg.claim(element, visibleTag, element);
234 // wg.claim(element, focusableTag, element);
236 Resource orderedSet = OrderedSetUtils.create(wg, diagramType, element);
238 // wg.claim(orderedSet, dr.HasLayer, GraphUtils.create2(wg, dr.Layer,
239 // b.HasName, "Default",
240 // dr.IsActive, Boolean.TRUE,
241 // dr.HasVisibleTag, visibleTag,
242 // dr.HasFocusableTag, focusableTag));
244 Resource result = GraphUtils.create(wg,
247 sr.IsDefinedBy, orderedSet);
249 wg.claim(result, b.ConsistsOf, orderedSet);
250 wg.claimLiteral(orderedSet, b.HasName, "__DIAGRAM__", Bindings.STRING);
251 AddElement.claimFreshElementName(wg, orderedSet, element);
252 wg.claim(orderedSet, b.ConsistsOf, element);
254 wg.claim(result, b.Inherits, null, symbolType);
258 public static Collection<Resource> getElementCorrespondendences(ReadGraph g, Resource element) throws DatabaseException {
259 DiagramResource dr = DiagramResource.getInstance(g);
260 ModelingResources mr = ModelingResources.getInstance(g);
261 if(g.isInstanceOf(element, dr.Connection)) {
262 Resource mappedComponent = g.getPossibleObject(element, mr.ElementToComponent);
263 if(mappedComponent != null) return Collections.singletonList(mappedComponent);
264 Resource mappedConnection = g.getPossibleObject(element, mr.DiagramConnectionToConnection);
265 if(mappedConnection == null)
266 return Collections.emptyList();
267 ArrayList<Resource> result = new ArrayList<Resource>();
268 Collection<Resource> relatedMappedConnections = StructuralUtils.getRelatedConnections(g, mappedConnection);
269 for(Resource relatedMappedConnection : relatedMappedConnections)
270 for(Resource relatedConnection : g.getObjects(relatedMappedConnection, mr.ConnectionToDiagramConnection))
271 result.addAll(g.getObjects(relatedConnection, mr.ElementToComponent));
275 return g.getObjects(element, mr.ElementToComponent);
278 public static Resource getPossibleElement(ReadGraph g, Resource component) throws DatabaseException {
279 ModelingResources mr = ModelingResources.getInstance(g);
280 return g.getPossibleObject(component, mr.ComponentToElement);
283 public static Resource getPossibleElementCorrespondendence(ReadGraph g, Resource element) throws DatabaseException {
284 Collection<Resource> corrs = getElementCorrespondendences(g, element);
285 if(corrs.size() != 1) return null;
286 else return corrs.iterator().next();
289 public static Resource getSingleElementCorrespondendence(ReadGraph g, Resource element) throws DatabaseException {
290 Collection<Resource> corrs = getElementCorrespondendences(g, element);
291 if(corrs.size() != 1) throw new DatabaseException("Expected 1 element correspondence, got " + corrs.size());
292 else return corrs.iterator().next();
295 public static Resource createExperiment(WriteGraph graph, Resource model) throws DatabaseException {
297 Layer0 L0 = Layer0.getInstance(graph);
298 SimulationResource SIMU = SimulationResource.getInstance(graph);
299 Resource experiment = graph.newResource();
300 graph.claim(experiment, L0.InstanceOf, SIMU.Experiment);
301 graph.claimLiteral(experiment, L0.HasName, "Experiment");
302 graph.claim(model, L0.ConsistsOf, experiment);
307 public static Resource createModel(WriteGraph graph, Resource type) throws DatabaseException {
308 return createModel(graph, type, Simantics.getProjectResource(), null);
311 public static Resource createModel(WriteGraph graph, Resource type, String name) throws DatabaseException {
312 return createModel(graph, type, Simantics.getProjectResource(), name);
315 public static Resource createModel(WriteGraph graph, Resource type, final Resource target, String name) throws DatabaseException {
317 Layer0 L0 = Layer0.getInstance(graph);
318 SimulationResource SIMU = SimulationResource.getInstance(graph);
319 StructuralResource2 STR = StructuralResource2.getInstance(graph);
320 ModelingResources MOD = ModelingResources.getInstance(graph);
323 name = NameUtils.findFreshName(graph, "Model", target, L0.ConsistsOf, "%s%d");
325 final Resource model = graph.newResource();
326 graph.newClusterSet(model);
327 graph.claim(model, L0.InstanceOf, null, type);
328 graph.claimLiteral(model, L0.HasName, name);
330 graph.claim(target, L0.ConsistsOf, model);
332 Resource configurationType = graph.getPossibleObject(model, MOD.StructuralModel_HasConfigurationType);
333 if(configurationType == null) configurationType = STR.Composite;
335 Resource configuration = graph.newResource();
336 graph.claimLiteral(configuration, L0.HasName, "Configuration", Bindings.STRING);
337 graph.claim(configuration, L0.InstanceOf, null, configurationType);
338 graph.claim(model, L0.ConsistsOf, configuration);
339 graph.claim(model, SIMU.HasConfiguration, configuration);
341 Resource joinClusterSet = graph.newResource();
342 graph.newClusterSet(joinClusterSet);
343 graph.claim(joinClusterSet, L0.InstanceOf, L0.ClusterSet);
344 graph.claim(model, STR.HasJoinClusterSet, joinClusterSet);
346 linkOntologyDependenciesToModel(graph, model, target);
348 Resource ontology = graph.syncRequest(new PossibleIndexRoot(type));
349 if(ontology != null) {
350 graph.claim(model, L0.IsLinkedTo, ontology);
353 VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);
354 graph.asyncRequest(new WriteRequest(support.getWorkspacePersistent("activations")) {
357 public void perform(WriteGraph graph) throws DatabaseException {
358 Layer0X L0X = Layer0X.getInstance(graph);
359 Collection<Resource> actives = graph.syncRequest(new ActiveModels(target));
360 if(actives.isEmpty()) {
361 graph.claim(model, L0X.IsActivatedBy, target);
371 public static void linkOntologyDependenciesToModel(WriteGraph graph, Resource model, Resource target)
372 throws DatabaseException {
373 Layer0 L0 = Layer0.getInstance(graph);
374 ProjectResource PROJ = ProjectResource.getInstance(graph);
375 for(Resource dep : graph.getObjects(target, L0.IsLinkedTo)) {
376 if(graph.isInstanceOf(dep, PROJ.NamespaceRequirement)) {
377 for(Resource req : graph.getObjects(dep, PROJ.RequiresNamespace)) {
378 String uri = graph.getPossibleValue(req, Bindings.STRING);
380 Resource ns = graph.getResource(uri);
382 graph.claim(model, L0.IsLinkedTo, null, ns);
390 public static void addSCLMainToModel(WriteGraph graph, Resource model)
391 throws DatabaseException {
392 addSCLMainToModel(graph, model, "SCLMain", "include \"Simantics/All\"\n");
395 public static void addSCLMainToModel(WriteGraph graph, Resource model, String name, String contents)
396 throws DatabaseException {
397 Layer0 L0 = Layer0.getInstance(graph);
398 Resource sclmain = GraphUtils.create2(graph, L0.SCLModule, L0.PartOf, model, L0.HasName, name);
399 graph.claimLiteral(sclmain, L0.SCLModule_definition, contents, Bindings.STRING);
402 public static Resource createLocalLibrary(WriteGraph graph, Resource container, String name) throws DatabaseException {
403 Layer0 L0 = Layer0.getInstance(graph);
404 ModelingResources MOD = ModelingResources.getInstance(graph);
405 Resource library = graph.newResource();
406 graph.claim(library, L0.InstanceOf, null, L0.Library);
407 graph.addLiteral(library, L0.HasName, L0.NameOf, "Library", Bindings.STRING);
408 if (container != null) {
409 graph.claim(container, L0.ConsistsOf, L0.PartOf, library);
410 graph.claim(container, MOD.HasLocalLibrary, MOD.IsLocalLibraryOf, library);
415 public static void importModel(String fileName) {
417 Resource project = Simantics.getProject().get();
419 try (StreamingTransferableGraphFileReader importer = new StreamingTransferableGraphFileReader(new File(fileName))) {
420 TransferableGraphSource tg = importer.readTG();
422 final DefaultPasteImportAdvisor advisor = new DefaultPasteImportAdvisor(project) {
424 public void analyzeType(ReadGraph graph, Root root) throws DatabaseException {
427 public Resource analyzeRoot(ReadGraph graph, Root root) throws DatabaseException {
428 library = Simantics.getProjectResource();
429 String newName = newName(graph, library, root.name);
430 nameMappings.put(root.name, newName);
434 TransferableGraphs.importGraph1(Simantics.getSession(), tg, advisor);
436 } catch (MissingDependencyException e) {
438 final Set<String> missingURIs = e.getMissingURIs();
440 class ErrorMessageDialog extends MessageDialog {
442 public ErrorMessageDialog(Shell shell) {
444 "Unsatisfied dependencies", null,
445 "The following dependencies were missing. Please import the dependencies and try again.",
446 MessageDialog.ERROR, new String[] { "Continue" }, 0);
450 protected Control createCustomArea(Composite composite) {
451 GridLayoutFactory.fillDefaults().applyTo(composite);
453 org.eclipse.swt.widgets.List list = new org.eclipse.swt.widgets.List(composite, SWT.BORDER | SWT.READ_ONLY);
454 GridDataFactory.fillDefaults().grab(true, true).applyTo(list);
455 for(String s : missingURIs) list.add(s);
461 Display display = Display.getCurrent();
462 if(display != null) {
463 ErrorMessageDialog md = new ErrorMessageDialog(display.getActiveShell());
466 Display.getDefault().asyncExec(new Runnable() {
470 Shell shell = Display.getCurrent().getActiveShell();
471 ErrorMessageDialog md = new ErrorMessageDialog(shell);
479 } catch (Exception e) {
480 Logger.defaultLogError(e);
485 public static void primeVirtualGraphs() {
486 VirtualGraphSupport support = Simantics.getSession().getService(VirtualGraphSupport.class);
487 support.getWorkspacePersistent("activations");
488 support.getWorkspacePersistent("experiments");
489 support.getWorkspacePersistent("issues");
490 support.getWorkspacePersistent("preferences");
493 public static Resource createProfileEntry(WriteGraph graph, String name, Resource style, Resource group) throws DatabaseException {
495 Layer0 L0 = Layer0.getInstance(graph);
496 DiagramResource DIA = DiagramResource.getInstance(graph);
498 Resource entry = graph.newResource();
499 graph.claim(entry, L0.InstanceOf, null, DIA.GroupStyleProfileEntry);
500 graph.claimLiteral(entry, L0.HasName, name);
501 graph.claimLiteral(entry, L0.HasLabel, name);
502 graph.claim(entry, DIA.ProfileEntry_HasStyle, style);
503 graph.claim(entry, DIA.ProfileEntry_HasGroup, group);
509 public static Resource createProfile(WriteGraph graph, String profileName, Resource... entries) throws DatabaseException {
511 Layer0 L0 = Layer0.getInstance(graph);
512 DiagramResource DIA = DiagramResource.getInstance(graph);
514 Resource list = ListUtils.create(graph, DIA.Profile, entries);
516 Resource profile = graph.newResource();
517 graph.claim(profile, L0.InstanceOf, null, DIA.Profile);
518 graph.claimLiteral(profile, L0.HasName, profileName);
519 graph.claim(profile, DIA.HasEntries, null, list);
525 public static Resource createProfile(WriteGraph graph, String profileName, Collection<Resource> entries) throws DatabaseException {
526 return createProfile(graph, profileName, entries.toArray(new Resource[entries.size()]));
529 public static Resource createToplevelProfile(WriteGraph graph, Resource model, String name, Resource ... profiles) throws DatabaseException {
531 Resource work = createProfile(graph, name, profiles);
533 Layer0 L0 = Layer0.getInstance(graph);
534 DiagramResource DIA = DiagramResource.getInstance(graph);
536 graph.deny(model, DIA.HasActiveProfile);
537 graph.claim(model, DIA.HasActiveProfile, work);
538 graph.claim(model, L0.ConsistsOf, L0.PartOf, work);
544 public static Resource createToplevelProfile(WriteGraph graph, Resource model, String name, Collection<Resource> profiles) throws DatabaseException {
545 return createToplevelProfile(graph, model, name, profiles.toArray(new Resource[profiles.size()]));
548 public static void activateProfileEntries(WriteGraph graph, final Resource profile, final Resource ... entries) {
550 VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);
551 graph.asyncRequest(new WriteRequest(support.getWorkspacePersistent("profiles")) {
554 public void perform(WriteGraph graph) throws DatabaseException {
555 SimulationResource SIMU = SimulationResource.getInstance(graph);
556 for(Resource entry : entries)
557 graph.claim(profile, SIMU.IsActive, entry);
564 public static void activateProfileEntries(WriteGraph graph, Resource profile, Collection<Resource> entries) {
565 activateProfileEntries(graph, profile, entries.toArray(new Resource[entries.size()]));
568 public static void toggleProfileGroup(WriteGraph graph, Resource runtimeProfile, String groupName, boolean enabled) throws DatabaseException {
569 Layer0 L0 = Layer0.getInstance(graph);
570 for (Resource group : ProfileUtils.getProfileChildren(graph, runtimeProfile)) {
571 String name = graph.getRelatedValue2(group, L0.HasName);
572 if (name.equals(groupName)) {
573 toggleProfileGroup(graph, runtimeProfile, group, enabled);
579 public static void toggleProfileGroup(WriteGraph graph, Resource runtimeProfile, Resource group, boolean enabled) throws DatabaseException {
580 DiagramResource DIA = DiagramResource.getInstance(graph);
582 if(graph.isInstanceOf(group, DIA.Profile)) {
584 for(Resource child : ProfileUtils.getProfileChildren(graph, group)) {
585 toggleProfileGroup(graph, runtimeProfile, child, enabled);
588 } else if(graph.isInstanceOf(group, DIA.ProfileEntry)) {
591 graph.claim(runtimeProfile, SimulationResource.getInstance(graph).IsActive, null, group);
593 graph.denyStatement(runtimeProfile, SimulationResource.getInstance(graph).IsActive, group);
599 public static void untrackDependencies() {
600 untrackDependencies(Simantics.getSession());
603 public static void untrackDependencies(RequestProcessor processor) {
606 processor.syncRequest(new ReadRequest() {
609 public void run(ReadGraph graph) throws DatabaseException {
610 Layer0X L0X = Layer0X.getInstance(graph);
611 GenericRelationIndex index = graph.adapt(L0X.DependenciesRelation, GenericRelationIndex.class);
612 index.untrack(graph.getSession(), graph.getRootLibrary());
616 } catch (DatabaseException e) {
617 Logger.defaultLogError(e);
622 public static void trackDependencies() {
623 trackDependencies(Simantics.getSession());
626 public static void trackDependencies(RequestProcessor processor) {
629 processor.syncRequest(new ReadRequest() {
632 public void run(ReadGraph graph) throws DatabaseException {
633 Layer0X L0X = Layer0X.getInstance(graph);
634 GenericRelationIndex index = graph.adapt(L0X.DependenciesRelation, GenericRelationIndex.class);
635 index.trackAndIndex(graph.getSession(), graph.getRootLibrary());
639 } catch (DatabaseException e) {
640 Logger.defaultLogError(e);
645 public static void trackOntologicalRequirements() {
646 Session session = Simantics.getSession();
647 GraphChangeListenerSupport changeListenerSupport = session.getService(GraphChangeListenerSupport.class);
648 changeListenerSupport.addMetadataListener( OntologicalRequirementListener.getInstance() );
651 public static void untrackOntologicalRequirements() {
652 Session session = Simantics.getSession();
653 GraphChangeListenerSupport changeListenerSupport = session.getService(GraphChangeListenerSupport.class);
654 changeListenerSupport.removeMetadataListener( OntologicalRequirementListener.getInstance() );
657 public static class OntologicalRequirementListener extends GenericChangeListener<DependencyChangesRequest, DependencyChanges> {
659 private static OntologicalRequirementListener INSTANCE;
661 public static OntologicalRequirementListener getInstance() {
662 if(INSTANCE == null) {
663 INSTANCE = new OntologicalRequirementListener();
668 private OntologicalRequirementListener() {
671 private OntologicalRequirementTracker changeInformationUpdater = new OntologicalRequirementTracker();
674 public boolean preEventRequest() {
675 return !Indexing.isDependenciesIndexingDisabled();
679 public void onEvent(ReadGraph graph, MetadataI metadata, DependencyChanges event) throws DatabaseException {
680 changeInformationUpdater.update(graph, metadata, event);
685 public static void removeIndex(WriteGraph graph, Resource model) throws DatabaseException {
686 Layer0X L0X = Layer0X.getInstance(graph);
687 IndexedRelations ir = graph.getService(IndexedRelations.class);
688 // Deletes index files
689 ir.reset(null, graph, L0X.DependenciesRelation, model);
692 public static void resetIssueSources(WriteGraph graph, Resource model) throws DatabaseException {
693 Layer0 L0 = Layer0.getInstance(graph);
694 IssueResource ISSUE = IssueResource.getInstance(graph);
695 for(Resource source : graph.sync(new ObjectsWithType(model, L0.ConsistsOf, ISSUE.ContinuousIssueSource))) {
696 IssueSourceUtils.update(graph, source);
700 public static void copyAnnotationTypes(WriteGraph graph, Resource sourceModel, Resource targetModel) throws DatabaseException {
702 Layer0 L0 = Layer0.getInstance(graph);
703 AnnotationResource ANNO = AnnotationResource.getInstance(graph);
705 Instances query = graph.adapt(ANNO.AnnotationType, Instances.class);
707 Resource library = graph.getPossibleObject(targetModel, ANNO.HasAnnotationTypeRoot);
709 if(library == null) {
710 library = graph.newResource();
711 graph.claim(library, L0.InstanceOf, null, ANNO.AnnotationTypeLibrary);
712 graph.claimLiteral(library, L0.HasName, L0.NameOf, L0.String, "Annotation types", Bindings.STRING);
713 graph.claim(library, L0.PartOf, L0.ConsistsOf, targetModel);
714 graph.claim(targetModel, ANNO.HasAnnotationTypeRoot, library);
717 for(Resource type : query.find(graph, sourceModel)) {
718 String name = graph.getRelatedValue(type, L0.HasName);
719 Resource existing = Layer0Utils.getPossibleChild(graph, library, name);
720 if(existing != null) {
721 RemoverUtil.remove(graph, existing);
723 Layer0Utils.copyTo(graph, library, type);
728 public static void deleteIndex(WriteGraph graph, Resource model) throws DatabaseException {
729 Layer0X L0X = Layer0X.getInstance(graph);
730 IndexedRelations ir = graph.getService(IndexedRelations.class);
731 // Deletes index files
732 ir.reset(null, graph, L0X.DependenciesRelation, model);
735 public static void disableDependencies(WriteGraph graph, Resource dummy) {
736 Layer0Utils.setDependenciesIndexingDisabled(graph, true);
739 public static void releaseMemory(WriteGraph graph) {
741 QueryControl qc = graph.getService(QueryControl.class);
742 ClusterControl cc = graph.getService(ClusterControl.class);
748 public static List<Resource> filterByIndexRoot(ReadGraph graph, Resource indexRoot, List<Resource> resources) throws DatabaseException {
749 ArrayList<Resource> result = new ArrayList<Resource>(resources.size());
750 for (Resource r : resources) {
751 Resource root = graph.syncRequest(new PossibleIndexRoot(r));
752 if (indexRoot.equals(root))
759 public static List<Resource> searchByTypeShallow(ReadGraph graph, Resource model, Resource type) throws DatabaseException {
760 return QueryIndexUtils.searchByTypeShallow(graph, model, type);
764 public static List<Resource> searchByType(ReadGraph graph, Resource model, Resource type) throws DatabaseException {
765 return QueryIndexUtils.searchByType(graph, model, type);
769 public static List<Resource> searchByGUID(ReadGraph graph, Resource indexRoot, GUID guid) throws DatabaseException {
770 return QueryIndexUtils.searchByGUID(graph, indexRoot, guid);
774 public static List<Resource> searchByGUID(ReadGraph graph, Resource indexRoot, String indexString) throws DatabaseException {
775 return QueryIndexUtils.searchByGUID(graph, indexRoot, indexString);
779 public static List<Resource> searchByQueryShallow(ReadGraph graph, Resource model, String query) throws DatabaseException {
780 return QueryIndexUtils.searchByQueryShallow(graph, model, query);
784 public static List<Resource> searchByQuery(ReadGraph graph, Resource model, String query) throws DatabaseException {
785 return QueryIndexUtils.searchByQuery(graph, model, query);
789 public static List<Resource> searchByTypeAndFilter(ReadGraph graph, Resource model, Resource type, Function1<Resource,Boolean> filter) throws DatabaseException {
790 return QueryIndexUtils.searchByTypeAndFilter(graph, model, type, filter);
794 public static List<Triple<Resource, Resource, String>> getIndexEntries(ReadGraph graph, Resource model, String filter) throws DatabaseException {
795 return QueryIndexUtils.getIndexEntries(graph, model, filter);
799 public static String listIndexEntries(ReadGraph graph, Resource model, String filter) throws DatabaseException {
800 return QueryIndexUtils.listIndexEntries(graph, model, filter);
804 public static List<Resource> searchByTypeAndName(ReadGraph graph, Resource model, Resource type, String name) throws DatabaseException {
805 return QueryIndexUtils.searchByTypeAndName(graph, model, type, name);
809 public static List<Resource> searchByTypeAndNameShallow(ReadGraph graph, Resource model, Resource type, String name) throws DatabaseException {
810 return QueryIndexUtils.searchByTypeAndNameShallow(graph, model, type, name);
815 * database write access
816 * @param sourceContainer
817 * the source container to look for annotationProperty from to be
818 * used as the copy source
819 * @param targetContainer
820 * the target container for the copied annotationProperty
822 * @param annotationProperty
823 * the annotation property relation
824 * @return created copy of the original annotation or <code>null</code> if
825 * there was nothing to copy
826 * @throws DatabaseException
828 public static Resource copyPossibleAnnotation(WriteGraph graph, Resource sourceContainer, Resource targetContainer, Resource annotationProperty) throws DatabaseException {
829 return copyPossibleAnnotation2(graph, sourceContainer, targetContainer, annotationProperty, null);
832 public static List<String> getPossibleNamePath(ReadGraph graph, Resource resource) throws DatabaseException {
833 return getPossibleNamePath(graph, resource, null);
836 private static List<String> getPossibleNamePath(ReadGraph graph, Resource resource, List<String> result) throws DatabaseException {
838 Layer0 L0 = Layer0.getInstance(graph);
839 String name = graph.getPossibleRelatedValue(resource, L0.HasName, Bindings.STRING);
840 if(name == null) return null;
842 if(result == null) result = new ArrayList<String>();
844 SimulationResource SIMU = SimulationResource.getInstance(graph);
845 if(graph.isInstanceOf(resource, SIMU.Model)) return result;
847 Resource parent = graph.getPossibleObject(resource, L0.PartOf);
849 getPossibleNamePath(graph, parent, result);
860 public static Resource claimLibraryPath(WriteGraph graph, Resource resource, List<String> path) throws DatabaseException {
861 Layer0 L0 = Layer0.getInstance(graph);
862 for(int i=0;i<path.size()-1;i++) {
863 String p = path.get(i);
864 Resource child = Layer0Utils.getPossibleChild(graph, resource, p);
866 child = graph.newResource();
867 graph.claim(child, L0.InstanceOf, L0.Library);
868 graph.addLiteral(child, L0.HasName, L0.NameOf, L0.String, p, Bindings.STRING);
869 graph.claim(resource, L0.ConsistsOf, L0.PartOf, child);
878 * database write access
879 * @param sourceContainer
880 * the source container to look for annotationProperty from to be
881 * used as the copy source
882 * @param targetContainer
883 * the target container for the copied annotationProperty
885 * @param annotationProperty
886 * the annotation property relation
887 * @param annotationProperty
888 * the 2nd level annotation property relation or
889 * <code>null</code> if no 2nd level annotation exists
890 * @return created copy of the original annotation or <code>null</code> if
891 * there was nothing to copy
892 * @throws DatabaseException
894 public static Resource copyPossibleAnnotation2(WriteGraph graph,
895 Resource sourceContainer, Resource targetContainer,
896 Resource annotationProperty, Resource entryType) throws DatabaseException {
898 // Delete existing target value first
899 Layer0 L0 = Layer0.getInstance(graph);
900 Resource targetValue = graph.getPossibleObject(targetContainer, annotationProperty);
901 if (targetValue != null) {
902 if(!graph.hasStatement(targetValue, L0.PartOf))
903 RemoverUtil.remove(graph, targetValue);
904 graph.deny(targetContainer, annotationProperty);
907 Resource sourceValue = graph.getPossibleObject(sourceContainer, annotationProperty);
908 if (sourceValue == null)
911 List<String> sourceValuePath = getPossibleNamePath(graph, sourceValue);
912 if(sourceValuePath != null) {
913 Resource targetModel = graph.sync(new PossibleModel(targetContainer));
914 if(targetModel == null) throw new DatabaseException("No target model found for " + targetContainer);
915 Resource library = claimLibraryPath(graph, targetModel, sourceValuePath);
916 Resource existing = Layer0Utils.getPossibleChild(graph, library, sourceValuePath.get(sourceValuePath.size()-1));
917 if(existing == null) {
918 existing = doCopyPossibleAnnotation2(graph, sourceContainer, targetContainer, annotationProperty, entryType);
919 graph.claim(library, L0.ConsistsOf, L0.PartOf, existing);
921 graph.claim(targetContainer, annotationProperty, existing);
924 return doCopyPossibleAnnotation2(graph, sourceContainer, targetContainer, annotationProperty, entryType);
929 private static Resource doCopyPossibleAnnotation2(WriteGraph graph,
930 Resource sourceContainer, Resource targetContainer,
931 Resource annotationProperty, Resource entryType) throws DatabaseException {
933 Resource sourceValue = graph.getPossibleObject(sourceContainer, annotationProperty);
934 if (sourceValue == null)
937 // Copy 1st level annotation
938 Resource targetValue = createAnnotation(graph, targetContainer, annotationProperty, sourceValue);
940 // Copy possible 2nd level annotations and attach to 1st if entry
941 // property is defined.
942 Layer0 L0 = Layer0.getInstance(graph);
943 if (entryType != null) {
945 AnnotationResource ANNO = AnnotationResource.getInstance(graph);
946 for (Resource entry : graph.getObjects(sourceValue, ANNO.Annotation_HasEntry)) {
948 String name = graph.getRelatedValue(entry, L0.HasName, Bindings.STRING);
950 List<String> entryPath = getPossibleNamePath(graph, entry);
951 if(entryPath != null) {
952 Resource targetModel = graph.sync(new PossibleModel(targetContainer));
953 if(targetModel == null) throw new DatabaseException("No target model found for " + targetContainer);
954 Resource library = claimLibraryPath(graph, targetModel, entryPath);
955 Resource existing = Layer0Utils.getPossibleChild(graph, library, entryPath.get(entryPath.size()-1));
956 if(existing == null) {
957 existing = createTypedAnnotation(graph, null, null, entry, entryType, name);
958 graph.claim(library, L0.ConsistsOf, L0.PartOf, existing);
960 graph.claim(targetValue, ANNO.Annotation_HasEntry, existing);
962 Resource result = createTypedAnnotation(graph, null, null, entry, entryType, name);
963 graph.claim(targetValue, ANNO.Annotation_HasEntry, result);
975 * database write access
977 * the container resource to attach the new annotation to
979 * the annotation property relation. The type of the created
980 * annotation is decided from this property relation's range
981 * @param sourceAnnotation
982 * the annotation to copy data from or <code>null</code> if
983 * nothing shall be copied
984 * @return the newly created annotation resource or <code>null</code> if the
985 * annotation property relation didn't have a single range type
986 * @throws DatabaseException
988 public static Resource createAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation) throws DatabaseException {
989 return createAnnotation(graph, container, property, sourceAnnotation, null);
994 * database write access
996 * the container resource to attach the new annotation to
998 * the annotation property relation. The type of the created
999 * annotation is decided from this property relation's range
1000 * @param sourceAnnotation
1001 * the annotation to copy data from or <code>null</code> if
1002 * nothing shall be copied
1004 * name for newly created annotation or <code>null</code> to copy
1005 * name from source if available
1006 * @return the newly created annotation resource or <code>null</code> if the
1007 * annotation property relation didn't have a single range type
1008 * @throws DatabaseException
1010 public static Resource createAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation, String name) throws DatabaseException {
1012 Layer0 L0 = Layer0.getInstance(graph);
1013 Resource annotationType = graph.getSingleObject(property, L0.HasRange);
1014 if (annotationType == null)
1017 return createTypedAnnotation(graph, container, property, sourceAnnotation, annotationType, name);
1023 * database write access
1025 * the container resource to attach the new annotation to
1027 * the annotation property relation
1028 * @param sourceAnnotation
1029 * the annotation to copy data from or <code>null</code> if
1030 * nothing shall be copied
1031 * @param annotationType
1032 * the type of the new annotation
1033 * @return the newly created annotation resource
1034 * @throws DatabaseException
1036 public static Resource createTypedAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation, Resource annotationType) throws DatabaseException {
1037 return createTypedAnnotation(graph, container, property, sourceAnnotation, annotationType, null);
1042 * database write access
1044 * the container resource to attach the new annotation to
1046 * the annotation property relation
1047 * @param sourceAnnotation
1048 * the annotation to copy data from or <code>null</code> if
1049 * nothing shall be copied
1050 * @param annotationType
1051 * the type of the new annotation
1053 * name for newly created annotation or <code>null</code> to copy
1054 * name from source if available
1055 * @return the newly created annotation resource
1056 * @throws DatabaseException
1058 public static Resource createTypedAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation, Resource annotationType, String name) throws DatabaseException {
1060 Layer0 L0 = Layer0.getInstance(graph);
1062 Resource anno = graph.newResource();
1064 graph.claim(anno, L0.InstanceOf, null, annotationType);
1067 graph.addLiteral(anno, L0.HasName, L0.NameOf, L0.String, name, Bindings.STRING);
1069 if (sourceAnnotation != null) {
1072 String sourceName = graph.getPossibleRelatedValue(sourceAnnotation, L0.HasName, Bindings.STRING);
1073 if(sourceName != null) graph.addLiteral(anno, L0.HasName, L0.NameOf, L0.String, sourceName, Bindings.STRING);
1076 Resource sourceType = graph.getSingleType(sourceAnnotation);
1077 List<AnnotationMap> am = getAnnotationMap(graph, annotationType, sourceType);
1078 for (AnnotationMap a : am) {
1079 Resource object = graph.getSingleObject(sourceAnnotation, a.sourcePredicate);
1080 Collection<Resource> objectTypes = graph.getTypes(object);
1081 if (objectTypes.contains(L0.Literal)) {
1082 Object value = graph.getValue(object, a.defaultValueBinding);
1083 if (!ObjectUtils.objectEquals(value, a.defaultValue)) {
1084 graph.addLiteral(anno, a.annotationPredicate, a.annotationPredicateInverse, a.defaultValueType, value, a.defaultValueBinding);
1090 if (container != null && property != null) {
1091 graph.claim(container, property, anno);
1098 private static class AnnotationMap {
1100 final public Resource sourcePredicate;
1101 final public Resource sourcePredicateInverse;
1103 final public Resource annotationPredicate;
1104 final public Resource annotationPredicateInverse;
1106 final public Resource defaultValueType;
1107 final public Object defaultValue;
1108 final public Binding defaultValueBinding;
1110 public AnnotationMap(Resource sp, Resource spi, Resource tp, Resource tpi, Resource defaultValueType, Object defaultValue, Binding defaultValueBinding) {
1111 sourcePredicate = sp;
1112 sourcePredicateInverse = spi;
1113 annotationPredicate = tp;
1114 annotationPredicateInverse = tpi;
1115 this.defaultValueType = defaultValueType;
1116 this.defaultValue = defaultValue;
1117 this.defaultValueBinding = defaultValueBinding;
1122 public static List<AnnotationMap> getAnnotationMap(ReadGraph graph, Resource annotationType, Resource sourceType) throws DatabaseException {
1123 return graph.syncRequest(new AnnotationMapRequest(annotationType, sourceType), TransientCacheListener.<List<AnnotationMap>>instance());
1126 static class AnnotationMapRequest extends ResourceRead2<List<AnnotationMap>> {
1128 public AnnotationMapRequest(Resource annotationType, Resource sourceType) {
1129 super(annotationType, sourceType);
1133 public List<AnnotationMap> perform(ReadGraph graph) throws DatabaseException {
1135 Layer0 L0 = Layer0.getInstance(graph);
1137 ArrayList<AnnotationMap> result = new ArrayList<AnnotationMap>();
1139 Map<String, Resource> annotationPredicates = new HashMap<String, Resource>();
1140 for(Resource predicate : graph.getObjects(resource, L0.DomainOf)) {
1141 String name = graph.getRelatedValue(predicate, L0.HasName, Bindings.STRING);
1142 annotationPredicates.put(name, predicate);
1144 Map<String, Resource> sourcePredicates = new HashMap<String, Resource>();
1145 for(Resource predicate : graph.getObjects(resource2, L0.DomainOf)) {
1146 String name = graph.getRelatedValue(predicate, L0.HasName, Bindings.STRING);
1147 sourcePredicates.put(name, predicate);
1150 for(String key : sourcePredicates.keySet()) {
1151 Resource sourcePredicate = sourcePredicates.get(key);
1152 Resource anno = annotationPredicates.get(key);
1153 if(sourcePredicate != null && anno != null) {
1154 Resource defaultValueType = graph.getSingleObject(anno, L0.HasRange);
1155 Binding defaultValueBinding = null;
1156 Object defaultValue = null;
1157 Resource assertion = graph.getPossibleObject(anno, L0.HasPredicateInverse);
1158 if (assertion != null) {
1159 Resource object = graph.getPossibleObject(assertion, L0.HasObject);
1160 if (object != null) {
1161 if(graph.isInstanceOf(object, L0.Literal)) {
1162 Datatype dt = graph.getDataType(object);
1163 defaultValueBinding = Bindings.getBeanBinding(dt);
1164 defaultValue = graph.getPossibleValue(object);
1168 result.add(new AnnotationMap(
1169 sourcePredicate, graph.getInverse(sourcePredicate),
1170 anno, graph.getInverse(anno),
1171 defaultValueType, defaultValue, defaultValueBinding));
1181 public static final String DRAWING_TEMPLATE_FORMAT = "drawingTemplate";
1182 public static final String DRAWING_TEMPLATE_FORMAT_V1 = DRAWING_TEMPLATE_FORMAT + ":1";
1183 public static final String DRAWING_TEMPLATE_FORMAT_V2 = DRAWING_TEMPLATE_FORMAT + ":2";
1185 public static Resource importDrawingTemplate(final Resource model, final File file) throws IOException, SerializationException, DatabaseException, TransferableGraphException {
1189 final Resource library = Simantics.sync(new WriteResultRequest<Resource>() {
1192 public Resource perform(WriteGraph graph) throws DatabaseException {
1194 Layer0 L0 = Layer0.getInstance(graph);
1195 Template2dResource TEMPLATE = Template2dResource.getInstance(graph);
1196 Resource root = graph.getPossibleObject(model, TEMPLATE.HasDrawingTemplateRoot);
1198 Template2dResource TEMPLATE2D = Template2dResource.getInstance(graph);
1199 root = graph.newResource();
1200 graph.claim(root, L0.InstanceOf, null, TEMPLATE2D.DrawingTemplateLibrary);
1201 graph.claim(root, L0.InstanceOf, null, TEMPLATE2D.DrawingTemplateLibraryUI);
1202 graph.claimLiteral(root, L0.HasName, L0.NameOf, L0.String, "Diagram Templates", Bindings.STRING);
1203 graph.claim(root, L0.PartOf, L0.ConsistsOf, model);
1204 graph.claim(model, TEMPLATE2D.HasDrawingTemplateRoot, root);
1207 String name = new Path(file.getAbsolutePath()).removeFileExtension().lastSegment();
1209 Resource existing = Layer0Utils.getPossibleChild(graph, root, name);
1210 if(existing != null)
1211 graph.deny(root, L0.ConsistsOf, existing);
1220 final DefaultPasteImportAdvisor advisor = new DefaultPasteImportAdvisor(library);
1223 HashMap<String, FormatHandler<Object>> handlers = new HashMap<String, FormatHandler<Object>>();
1224 FormatHandler<Object> handler = new FormatHandler<Object>() {
1226 public Binding getBinding() {
1227 return TransferableGraph1.BINDING;
1231 public Object process(DataContainer container) throws Exception {
1232 TransferableGraphs.importGraph1(Simantics.getSession(), (TransferableGraph1)container.content.getValue(),
1237 handlers.put(DRAWING_TEMPLATE_FORMAT_V1, handler);
1238 handlers.put(DRAWING_TEMPLATE_FORMAT_V2, handler);
1240 DataContainers.readFile(file, handlers);
1241 } catch(DataFormatException e) {
1242 throw new IOException(e);
1243 } catch(IOException e) {
1245 } catch(Exception e) {
1246 if(e instanceof RuntimeException)
1247 throw (RuntimeException)e;
1249 throw new RuntimeException(e);
1252 } catch(IOException e) {
1255 return advisor.getRoot();
1257 } catch (Throwable t) {
1258 Logger.defaultLogError("Unexpected exception while importing diagram template.", t);
1266 public static Collection<Variable> getMappedVariables(ReadGraph graph, Variable source) throws DatabaseException {
1268 ArrayList<Variable> result = new ArrayList<Variable>();
1269 Resource represents = source.getPossibleRepresents(graph);
1270 if(represents == null) return Collections.emptyList();
1271 ModelingResources MOD = ModelingResources.getInstance(graph);
1272 for(Resource r : getElementCorrespondendences(graph, represents)) {
1273 result.add(Variables.getVariable(graph, r));
1275 for(Resource r : graph.getObjects(represents, MOD.ComponentToElement)) {
1276 result.add(Variables.getVariable(graph, r));
1278 for(Resource r : graph.getObjects(represents, MOD.DiagramToComposite)) {
1279 result.add(Variables.getVariable(graph, r));
1281 for(Resource r : graph.getObjects(represents, MOD.CompositeToDiagram)) {
1282 result.add(Variables.getVariable(graph, r));
1288 public static Resource getPossibleModel(ReadGraph graph, Resource resource) throws DatabaseException {
1290 PossibleModel pm = new PossibleModel(resource);
1291 Resource model = pm.perform(graph);
1295 public static Resource possibleIndexRoot(ReadGraph graph, Resource resource) throws DatabaseException {
1296 return graph.syncRequest(new PossibleIndexRoot(resource));
1299 public static Object getMonitorValue(StructuralComponent _variable, ReadGraph graph, String path) throws DatabaseException {
1300 Variable variable = ((VariableStructuralContext)_variable).variable;
1301 Variable var = variable.browse(graph, path);
1302 return var.getValue(graph);
1305 public static void createSharedOntologyWithUI(ReadGraph graph, Variable variable, Resource baseType) throws DatabaseException {
1306 createSharedOntologyWithUI(graph, baseType);
1309 public static void createSharedOntologyWithUI(ReadGraph graph, Resource baseType) throws DatabaseException {
1311 // Resource indexRoot_ = variable.getPossibleRepresents(graph);
1312 // if(indexRoot_ == null) return;
1314 final Map<Resource, Pair<String,ImageDescriptor>> map = new HashMap<Resource, Pair<String,ImageDescriptor>>();
1316 Layer0 L0 = Layer0.getInstance(graph);
1317 SimulationResource SIMU = SimulationResource.getInstance(graph);
1318 Instances query = graph.adapt(L0.IndexRootType, Instances.class);
1319 for(Resource ontology : Layer0Utils.listOntologies(graph)) {
1320 for(Resource type : query.find(graph, ontology)) {
1321 if(graph.isInheritedFrom(type, SIMU.Model)) continue;
1322 if(graph.hasStatement(type, L0.Abstract)) continue;
1323 if(!graph.isInheritedFrom(type, baseType)) continue;
1324 String name = graph.getPossibleRelatedValue(type, L0.HasLabel, Bindings.STRING);
1325 if(name == null) name = graph.getRelatedValue(type, L0.HasName, Bindings.STRING);
1326 map.put(type, new Pair<String,ImageDescriptor>(name, null));
1330 Display.getDefault().asyncExec(new Runnable() {
1333 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1334 CreateSharedOntologyDialog page = new CreateSharedOntologyDialog(shell, map, "Select type and name of new shared library");
1335 if (page.open() == Window.OK) {
1336 Object[] result = page.getResult();
1337 if (result != null && result.length == 1) {
1338 final Resource res = (Resource)result[0];
1339 final String name = "http://" + page.getName();
1340 Simantics.getSession().asyncRequest(new WriteRequest() {
1343 public void perform(WriteGraph graph) throws DatabaseException {
1344 graph.markUndoPoint();
1345 Resource target = Simantics.applySCL("Simantics/SharedOntologies", "createSharedOntology", graph, name+"@A", res);
1347 ProjectResource PROJ = ProjectResource.getInstance(graph);
1348 Layer0 L0 = Layer0.getInstance(graph);
1349 for(Resource dep : graph.getObjects(Simantics.getProjectResource(), L0.IsLinkedTo)) {
1350 if(graph.isInstanceOf(dep, PROJ.NamespaceRequirement)) {
1351 for(Resource req : graph.getObjects(dep, PROJ.RequiresNamespace)) {
1352 String uri = graph.getPossibleValue(req, Bindings.STRING);
1354 Resource ns = graph.getResource(uri);
1356 graph.claim(target, L0.IsLinkedTo, null, ns);
1373 public static void unlinkSharedOntologyWithUI(ReadGraph graph, Variable variable, final List<Resource> libraries) throws DatabaseException {
1375 final Resource indexRoot = variable.getPossibleRepresents(graph);
1376 if(indexRoot == null) return;
1378 StructuralResource2 STR = StructuralResource2.getInstance(graph);
1380 final List<String> instances = new ArrayList<String>();
1382 DiagramResource DIA = DiagramResource.getInstance(graph);
1384 for(Resource library : libraries) {
1385 for(Resource type : ModelingUtils.searchByTypeShallow(graph, library, STR.ComponentType)) {
1386 for(Resource instance : ModelingUtils.searchByTypeShallow(graph, indexRoot, type)) {
1388 if(graph.isInstanceOf(instance, DIA.Element)) continue;
1389 String name = Versions.getStandardPathNameString(graph, instance);
1390 instances.add(name);
1395 if(instances.isEmpty()) {
1396 graph.getSession().asyncRequest(new WriteRequest() {
1399 public void perform(WriteGraph graph) throws DatabaseException {
1400 Layer0 L0 = Layer0.getInstance(graph);
1401 for(Resource library : libraries)
1402 graph.deny(indexRoot, L0.IsLinkedTo, library);
1409 PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
1413 if (!PlatformUI.isWorkbenchRunning())
1416 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1417 ListDialog<String> dialog = new ListDialog<String>(
1420 "Cannot unlink selected libraries",
1421 "Libraries cannot be unlinked since the following instances are referring to them.") {
1423 protected void createButtonsForButtonBar(Composite parent) {
1424 createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,true);
1428 int result = dialog.open();
1429 if (result != Dialog.OK)
1437 public static MigratedImportResult importSharedOntologyWithResult(String fileName) throws Exception {
1439 DataContainer dc = DataContainers.readFile(new File(fileName));
1440 TransferableGraph1 tg = (TransferableGraph1)dc.content.getValue(TransferableGraph1.BINDING);
1441 Variant draftStatus = dc.metadata.get(DraftStatusBean.EXTENSION_KEY);
1442 return MigrationUtils.importSharedOntology(Simantics.getSession(), tg, draftStatus == null);
1443 } catch (Exception e) {
1444 Logger.defaultLogError(e);
1449 public static void importSharedOntology(String fileName) throws Exception {
1450 importSharedOntologyWithResult(fileName);
1453 public static List<Resource> importSharedOntology2(String fileName) throws Exception {
1454 MigratedImportResult result = importSharedOntologyWithResult(fileName);
1455 return new ArrayList<Resource>(result.roots);
1458 public static void importSharedOntologyWithUI(ReadGraph graph, final Variable variable) throws DatabaseException {
1460 Display.getDefault().asyncExec(new Runnable() {
1464 IStructuredSelection sel = new StructuredSelection(variable);
1465 openWizard(Display.getCurrent(), sel, "org.simantics.modeling.ui.sharedOntologyImportWizard");
1472 public static class LibraryInfo implements Comparable<LibraryInfo> {
1473 public NamedResource library;
1474 public DraftStatusBean draft;
1475 public LibraryInfo(String name, Resource r, DraftStatusBean draft) {
1476 library = new NamedResource(name, r);
1480 public int compareTo(LibraryInfo o) {
1481 return library.compareTo(o.library);
1484 public int hashCode() {
1485 return library.hashCode();
1488 public boolean equals(Object object) {
1491 else if (object == null)
1493 else if (!(object instanceof LibraryInfo))
1495 LibraryInfo info = (LibraryInfo)object;
1496 return info.library.equals(library);
1501 public static void exportSharedOntologyWithUI(final Resource sharedOntology) {
1503 Display.getDefault().asyncExec(new Runnable() {
1507 HintContext hc = new HintContext();
1508 hc.setHint(SelectionHints.KEY_MAIN, sharedOntology);
1509 IStructuredSelection sel = new StructuredSelection(hc);
1510 openWizard(Display.getCurrent(), sel, "org.simantics.modeling.ui.sharedOntologyExportWizard");
1517 public static TransferableGraph1 exportSharedOntology(IProgressMonitor monitor, RequestProcessor processor, File location, String format, int version, final LibraryInfo info) throws DatabaseException, IOException {
1519 if(monitor == null) monitor = new NullProgressMonitor();
1520 final IProgressMonitor finalMonitor = monitor;
1521 // TODO: figure out a way to make the TG go directly into a file
1522 // instead of having it all in memory at once.
1524 monitor.beginTask("Exporting shared library...", 100);
1525 SimanticsClipboard clipboard = processor.syncRequest(new Read<SimanticsClipboard>() {
1527 public SimanticsClipboard perform(ReadGraph graph) throws DatabaseException {
1528 CopyHandler ch = graph.adapt(info.library.getResource(), CopyHandler.class);
1529 SimanticsClipboardImpl clipboard = new SimanticsClipboardImpl();
1530 ch.copyToClipboard(graph, clipboard, finalMonitor);
1535 TreeMap<String,Variant> metadata = getExportMetadata();
1536 DraftStatusBean draft = info.draft;
1538 metadata.put(DraftStatusBean.EXTENSION_KEY, new Variant(DraftStatusBean.BINDING ,draft));
1541 for (Set<Representation> object : clipboard.getContents()) {
1543 TransferableGraph1 tg = ClipboardUtils.accept(processor, object, SimanticsKeys.KEY_TRANSFERABLE_GRAPH);
1546 Variant edb = tg.extensions.get(ExternalDownloadBean.EXTENSION_KEY);
1548 metadata.put(ExternalDownloadBean.EXTENSION_KEY, edb);
1551 if(location != null) {
1552 monitor.setTaskName("Writing transferable graph...");
1553 DataContainers.writeFile(location, new DataContainer(
1555 metadata, new Variant(TransferableGraph1.BINDING, tg)));
1563 throw new DatabaseException("Failed to export");
1567 public static TreeMap<String, Variant> getExportMetadata() {
1569 TreeMap<String,Variant> metadata = new TreeMap<String,Variant>();
1570 metadata.put("date", Variant.ofInstance(DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date())));
1571 metadata.put("author", Variant.ofInstance(System.getProperty("user.name", "")));
1577 public static void createNewVersionWithoutUI(WriteGraph graph, Resource resource) throws DatabaseException {
1578 VersionInfo info = graph.syncRequest(new VersionInfoRequest(resource));
1579 int currentVersion = Integer.parseInt(info.version);
1580 String result = Integer.toString(currentVersion + 1);
1581 createNewVersion(graph, resource, info, result);
1584 public static void createNewVersionWithUI(ReadGraph graph, final Resource resource) throws DatabaseException {
1586 final VersionInfo info = graph.syncRequest(new VersionInfoRequest(resource));
1588 Display.getDefault().asyncExec(new Runnable() {
1591 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1592 CreateVersionDialog dialog = new CreateVersionDialog(shell, info);
1593 if (dialog.open() == Window.OK) {
1594 final String result = dialog.getResult();
1595 Simantics.getSession().asyncRequest(new WriteRequest() {
1597 public void perform(WriteGraph graph) throws DatabaseException {
1598 createNewVersion(graph, resource, info, result);
1607 public static void createNewVersion(WriteGraph graph, Resource resource, final VersionInfo info, final String result) throws DatabaseException {
1608 graph.markUndoPoint();
1609 Layer0 L0 = Layer0.getInstance(graph);
1610 Resource parent = graph.getPossibleObject(resource, L0.PartOf);
1611 if(parent == null) return;
1612 final String parentURI = graph.getPossibleURI(parent);
1613 if(parentURI == null) return;
1614 Layer0Utils.copyTo(graph, parent, resource, new PasteEventHandler() {
1617 public void postProcess(WriteGraph graph, Resource root) throws DatabaseException {
1618 Layer0 L0 = Layer0.getInstance(graph);
1619 graph.deny(root, L0.Entity_published);
1623 public IImportAdvisor2 createAdvisor(ReadGraph graph, ImportAdvisorFactory factory, Resource target) throws DatabaseException {
1624 Map<String,Object> context = new HashMap<String,Object>();
1625 String base = parentURI + "/" + URIStringUtils.escape( info.baseName ) + "@";
1626 Map<String,String> renameMap = new HashMap<String,String>();
1627 renameMap.put(base + info.version, base + result);
1628 renameMap.put(info.baseName + "@" + info.version, info.baseName + "@" + result);
1629 context.put(ImportAdvisors.RENAME_MAP, renameMap);
1630 return factory.create(graph, target, context);
1634 Layer0Utils.addCommentMetadata(graph, "Created new version of " + info.baseName);
1637 public static boolean isUserComponent(ReadGraph graph, Resource type) throws DatabaseException {
1638 StructuralResource2 STR = StructuralResource2.getInstance(graph);
1639 if(graph.isInstanceOf(type, STR.ProceduralComponentType)) return true;
1640 else if (graph.hasStatement(type, STR.IsDefinedBy)) return true;
1644 public static void publishComponentTypeWithUI(WriteGraph graph, final Resource componentType) throws DatabaseException {
1646 Layer0 L0 = Layer0.getInstance(graph);
1647 StructuralResource2 STR = StructuralResource2.getInstance(graph);
1648 Resource composite = graph.getPossibleObject(componentType, STR.IsDefinedBy);
1649 final List<String> instances = new ArrayList<String>();
1650 if(composite != null) {
1651 for(Resource component : graph.syncRequest(new ObjectsWithType(composite, L0.ConsistsOf, STR.Component))) {
1652 Resource type = graph.getPossibleType(component, STR.Component);
1653 if(type != null && isUserComponent(graph, type)) {
1654 if(!Layer0Utils.isPublished(graph, type)) instances.add(Versions.getStandardPathNameString(graph, component));
1659 if(instances.isEmpty()) {
1660 graph.getSession().asyncRequest(new WriteRequest() {
1663 public void perform(WriteGraph graph) throws DatabaseException {
1664 graph.markUndoPoint();
1665 publish(graph, componentType);
1672 PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
1676 if (!PlatformUI.isWorkbenchRunning())
1679 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1680 ListDialog<String> dialog = new ListDialog<String>(
1683 "Cannot publish user component",
1684 "The following instances are referring to unpublished user components.") {
1686 protected void createButtonsForButtonBar(Composite parent) {
1687 createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,true);
1691 int result = dialog.open();
1692 if (result != Dialog.OK)
1700 public static void publishSharedOntologyWithUI(WriteGraph graph, final Resource sharedOntology) throws DatabaseException {
1702 Layer0 L0 = Layer0.getInstance(graph);
1703 DiagramResource DIA = DiagramResource.getInstance(graph);
1704 StructuralResource2 STR = StructuralResource2.getInstance(graph);
1705 final List<String> instances = new ArrayList<String>();
1706 for(Resource type : searchByTypeShallow(graph, sharedOntology, STR.ComponentType)) {
1708 if(graph.isInheritedFrom(type, DIA.Element)) continue;
1709 if(!Layer0Utils.isPublished(graph, type)) instances.add(Versions.getStandardPathNameString(graph, type));
1711 for(Resource dep : graph.syncRequest(new ObjectsWithType(sharedOntology, L0.IsLinkedTo, L0.SharedOntology))) {
1712 if(!Layer0Utils.isPublished(graph, dep)) instances.add(Versions.getStandardPathNameString(graph, dep));
1715 if(instances.isEmpty()) {
1716 graph.getSession().asyncRequest(new WriteRequest() {
1719 public void perform(WriteGraph graph) throws DatabaseException {
1720 graph.markUndoPoint();
1721 publish(graph, sharedOntology);
1728 PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
1732 if (!PlatformUI.isWorkbenchRunning())
1735 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1736 ListDialog<String> dialog = new ListDialog<String>(
1739 "Cannot publish shared library",
1740 "The following dependencies are unpublished.") {
1742 protected void createButtonsForButtonBar(Composite parent) {
1743 createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,true);
1747 int result = dialog.open();
1748 if (result != Dialog.OK)
1756 public static Resource createSCLModuleDefault(WriteGraph graph, Resource target) throws DatabaseException {
1757 String name = NameUtils.findFreshEscapedName(graph, "SCLModule", target);
1758 return createSCLModule(graph, target, name);
1761 public static Resource createSCLModule(WriteGraph graph, Resource target, String name) throws DatabaseException {
1762 graph.markUndoPoint();
1763 Layer0 L0 = Layer0.getInstance(graph);
1764 Resource sclModule = GraphUtils.create2(graph, L0.SCLModule,
1767 L0.SCLModule_definition, "");
1768 Layer0Utils.addCommentMetadata(graph, "Created SCL Module " + name + " " + sclModule.toString());
1772 public static Resource setSCLModuleDefinition(WriteGraph graph, Resource module, String definition) throws DatabaseException {
1773 graph.markUndoPoint();
1774 Layer0 L0 = Layer0.getInstance(graph);
1775 graph.claimLiteral(module, L0.SCLModule_definition, definition, Bindings.STRING);
1776 Layer0Utils.addCommentMetadata(graph, "Set SCL module " + module + " definition.");
1780 public static Resource createSCLScriptDefault(WriteGraph graph, Resource target) throws DatabaseException {
1781 String name = NameUtils.findFreshEscapedName(graph, "SCLScript", target);
1782 return createSCLScript(graph, target, name);
1785 public static Resource createSCLScript(WriteGraph graph, Resource target, String name) throws DatabaseException {
1786 graph.markUndoPoint();
1787 Layer0 L0 = Layer0.getInstance(graph);
1788 Resource sclModule = GraphUtils.create2(graph, L0.SCLScript,
1791 L0.SCLScript_definition, "");
1792 Layer0Utils.addCommentMetadata(graph, "Created SCL Script " + name + " " + sclModule.toString());
1796 public static Resource setSCLScriptDefinition(WriteGraph graph, Resource script, String definition) throws DatabaseException {
1797 graph.markUndoPoint();
1798 Layer0 L0 = Layer0.getInstance(graph);
1799 graph.claimLiteral(script, L0.SCLScript_definition, definition, Bindings.STRING);
1800 Layer0Utils.addCommentMetadata(graph, "Set SCL script " + script + " definition.");
1804 public static Resource createPGraphDefault(WriteGraph graph, Resource target) throws DatabaseException {
1805 String name = NameUtils.findFreshEscapedName(graph, "Ontology Definition File", target);
1806 return createPGraph(graph, target, name);
1809 public static Resource createPGraph(WriteGraph graph, Resource target, String name) throws DatabaseException {
1810 graph.markUndoPoint();
1811 Layer0 L0 = Layer0.getInstance(graph);
1812 Resource file = GraphUtils.create2(graph, L0.PGraph,
1815 L0.PGraph_definition, "");
1816 Layer0Utils.addCommentMetadata(graph, "Created Ontology Definition File " + name + " " + file.toString());
1820 public static Resource setPGraphDefinition(WriteGraph graph, Resource pgraph, String definition) throws DatabaseException {
1821 graph.markUndoPoint();
1822 Layer0 L0 = Layer0.getInstance(graph);
1823 graph.claimLiteral(pgraph, L0.PGraph_definition, definition, Bindings.STRING);
1824 Layer0Utils.addCommentMetadata(graph, "Set PGraph " + pgraph + " definition.");
1828 public static void publish(WriteGraph graph, Resource target) throws DatabaseException {
1829 Layer0 L0 = Layer0.getInstance(graph);
1830 graph.claimLiteral(target, L0.Entity_published, true, Bindings.BOOLEAN);
1831 Layer0Utils.addCommentMetadata(graph, "Published " + graph.getPossibleRelatedValue2(target, L0.HasName, Bindings.STRING) + " " + target.toString());
1834 public static boolean isLinkedToDeep(ReadGraph graph, Resource r1, Resource r2) throws DatabaseException {
1835 return graph.syncRequest(new IsLinkedTo(r1, r2));
1838 public static void openWizard(Display display, IStructuredSelection selection, String id) {
1839 // First see if this is a "new wizard".
1840 IWizardDescriptor descriptor = PlatformUI.getWorkbench()
1841 .getNewWizardRegistry().findWizard(id);
1842 // If not check if it is an "import wizard".
1843 if (descriptor == null) {
1844 descriptor = PlatformUI.getWorkbench().getImportWizardRegistry()
1847 // Or maybe an export wizard
1848 if (descriptor == null) {
1849 descriptor = PlatformUI.getWorkbench().getExportWizardRegistry()
1853 // Then if we have a wizard, open it.
1854 if (descriptor != null) {
1855 IWorkbenchWizard wizard = descriptor.createWizard();
1856 wizard.init(PlatformUI.getWorkbench(), selection);
1857 WizardDialog wd = new WizardDialog(display.getActiveShell(), wizard);
1858 wd.setTitle(wizard.getWindowTitle());
1861 } catch (CoreException e) {
1862 e.printStackTrace();
1866 public static String withinEpsilon(double value, double reference, double epsilon) {
1867 if(Math.abs(value-reference) < epsilon) return "True";
1868 else return "Not within epsilon value=" + value + ", reference=" + reference + " , epsilon=" + epsilon;
1871 public static boolean needsIdentifier(ReadGraph graph, Resource r) throws DatabaseException {
1872 Layer0 L0 = Layer0.getInstance(graph);
1873 Collection<Resource> types = graph.getPrincipalTypes(r);
1874 for(Resource type : types)
1875 if(graph.syncRequest(new IsInstanceOf(type, L0.TypeWithIdentifier), TransientCacheAsyncListener.<Boolean>instance()))
1880 public static boolean needsModificationInfo(ReadGraph graph, Resource r) throws DatabaseException {
1881 ModelingResources MOD = ModelingResources.getInstance(graph);
1882 Collection<Resource> types = graph.getPrincipalTypes(r);
1883 for(Resource type : types)
1884 if(graph.syncRequest(new IsInstanceOf(type, MOD.TypeWithChangeInformation), TransientCacheAsyncListener.<Boolean>instance()))
1889 public static void attachCreationInformation(IProgressMonitor monitor, WriteGraph graph, Resource model) throws DatabaseException {
1891 if(monitor == null) monitor = new NullProgressMonitor();
1893 final String author = System.getProperty("user.name", "");
1894 final long time = System.currentTimeMillis();
1896 monitor.setTaskName("Attach creation information");
1898 ModelingResources MOD = ModelingResources.getInstance(graph);
1899 Collection<Resource> rs = ModelingUtils.searchByType(graph, model, MOD.TypeWithChangeInformation);
1900 Collection<Resource> supers = ModelingUtils.getMostUnspecificTypes(graph, rs);
1902 CollectionSupport cs = graph.getService(CollectionSupport.class);
1903 Collection<Resource> set = cs.createSet();
1904 for(Resource type : supers) {
1905 set.addAll(ModelingUtils.searchByTypeShallow(graph, model, type));
1907 Collection<Resource> instances = Layer0Utils.sortByCluster(graph, set);
1909 int pc = instances.size() / 100;
1913 for(Resource instance : instances) {
1914 ChangeInformation info = graph.getPossibleRelatedValue(instance, MOD.changeInformation, ChangeInformation.BINDING);
1916 info = new ChangeInformation();
1917 info.createdAt = time;
1918 info.createdBy = author;
1919 info.modifiedAt = time;
1920 info.modifiedBy = author;
1921 graph.claimLiteral(instance, MOD.changeInformation, MOD.changeInformation_Inverse, MOD.ChangeInformation, info, ChangeInformation.BINDING);
1926 Double d = (100.0*done)/instances.size();
1927 monitor.setTaskName("Attach creation information " + d.intValue() + "%");
1932 monitor.setTaskName("Attach creation information - commit");
1936 public static class DiagramComponentInfo {
1938 private static String CHILD_PREFIX = "child:";
1940 final private String compositePathAndName;
1941 final private String componentName;
1942 final private GUID guid;
1944 public DiagramComponentInfo(String compositePathAndName, String componentName, GUID guid) {
1945 this.compositePathAndName = compositePathAndName;
1946 this.componentName = componentName;
1950 public static boolean isDiagramComponent(String tgName) {
1951 return tgName.startsWith(CHILD_PREFIX);
1954 public String getTGName(CompositeInfo info) {
1955 return CHILD_PREFIX + info.getOriginalPath() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + info.getEscapedName() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + getEscapedComponentName() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + guid.indexString();
1958 public boolean existsGUID(ReadGraph graph, Resource indexRoot) throws DatabaseException {
1959 Collection<Resource> res = ModelingUtils.searchByGUID(graph, indexRoot, guid);
1960 return !res.isEmpty();
1963 public static DiagramComponentInfo fromResource(ReadGraph graph, CompositeInfo info, Resource resource) throws DatabaseException {
1964 Layer0 L0 = Layer0.getInstance(graph);
1965 GUID childId = graph.getRelatedValue(resource, L0.identifier, GUID.BINDING);
1966 String childName = graph.getRelatedValue(resource, L0.HasName, Bindings.STRING);
1967 return new DiagramComponentInfo(info.getStateKey(), URIStringUtils.escape(childName), childId);
1970 public GUID getGUID() {
1974 public String getEscapedCompositePathAndName() {
1975 return compositePathAndName;
1978 public String getEscapedComponentName() {
1979 return componentName;
1982 public String getUnescapedComponentName() {
1983 return URIStringUtils.unescape(getEscapedComponentName());
1986 // "child:path#compositeName#componentName#guid"
1987 public static DiagramComponentInfo parse(String tgName) {
1989 String name = tgName.substring(CHILD_PREFIX.length());
1990 String compositePathAndName = "";
1991 String moduleName = name;
1992 GUID guid = GUID.invalid();
1993 int lastHash = name.lastIndexOf(ModelingUtils.COMPOSITE_SEPARATOR_CHAR);
1995 String first = name.substring(0, lastHash);
1996 String second = name.substring(lastHash+1);
1997 lastHash = first.lastIndexOf(ModelingUtils.COMPOSITE_SEPARATOR_CHAR);
1999 compositePathAndName = first.substring(0, lastHash);
2000 moduleName = first.substring(lastHash+1);
2001 guid = GUID.parseIndexString(second);
2003 compositePathAndName = first;
2004 moduleName = second;
2007 return new DiagramComponentInfo(compositePathAndName, moduleName, guid);
2013 public int hashCode() {
2014 final int prime = 31;
2016 result = prime * result + ((compositePathAndName == null) ? 0 : compositePathAndName.hashCode());
2017 result = prime * result + ((componentName == null) ? 0 : componentName.hashCode());
2022 public boolean equals(Object obj) {
2027 if (getClass() != obj.getClass())
2029 DiagramComponentInfo other = (DiagramComponentInfo) obj;
2030 if (compositePathAndName == null) {
2031 if (other.compositePathAndName != null)
2033 } else if (!compositePathAndName.equals(other.compositePathAndName))
2035 if (componentName == null) {
2036 if (other.componentName != null)
2038 } else if (!componentName.equals(other.componentName))
2045 public static class CompositeInfo {
2047 public static String COMPOSITE_PREFIX = "composite:";
2049 final private boolean useGuids;
2050 final private boolean applyPaths;
2051 final private String path;
2052 final private String name;
2053 final private GUID guid;
2055 private CompositeInfo(boolean useGuids, boolean applyPaths, String path, String name, GUID guid) {
2056 this.useGuids = useGuids;
2057 this.applyPaths = applyPaths;
2064 public String toString() {
2065 return "CompositeInfo[useGuids=" + useGuids + ", applyPaths=" + applyPaths + ", path=" + path + ", name=" + name + ", guid=" + guid.indexString() + "]";
2068 public static boolean isComposite(String tgName) {
2069 return tgName.startsWith(COMPOSITE_PREFIX);
2072 public String getTGName() {
2073 return COMPOSITE_PREFIX + getOriginalPath() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + getEscapedName() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + guid.indexString();
2076 public boolean existsGUID(ReadGraph graph, Resource indexRoot) throws DatabaseException {
2077 Collection<Resource> res = ModelingUtils.searchByGUID(graph, indexRoot, guid);
2078 return !res.isEmpty();
2081 public static CompositeInfo fromResource(ReadGraph graph, Resource resource) throws DatabaseException {
2083 Layer0 L0 = Layer0.getInstance(graph);
2084 GUID rootId = graph.getRelatedValue(resource, L0.identifier, GUID.BINDING);
2085 String rootName = graph.getRelatedValue(resource, L0.HasName, Bindings.STRING);
2086 String escapedRootName = URIStringUtils.escape(rootName);
2087 String escapedPath = ModelingUtils.getDiagramCompositePath(graph, resource);
2088 return new CompositeInfo(true, true, escapedPath, escapedRootName, rootId);
2092 public static CompositeInfo parse(String tgName) {
2093 return parse(tgName, true, true);
2097 * Index 0 is root-relative folder path separated with '/' or null if target-relative positioning is used
2098 * Index 1 is diagram name
2100 public static CompositeInfo parse(String tgName, boolean applyPaths, boolean useGuids) {
2101 if(!tgName.startsWith(COMPOSITE_PREFIX)) return null;
2102 tgName = tgName.substring(COMPOSITE_PREFIX.length());
2103 if(!tgName.contains(COMPOSITE_SEPARATOR)) {
2104 if(useGuids) throw new IllegalStateException("GUID identifiers were not found for diagrams.");
2105 return new CompositeInfo(useGuids, applyPaths, null, tgName, null);
2107 String[] parts = tgName.split(COMPOSITE_SEPARATOR);
2108 if(parts.length == 2) {
2109 String name = parts[1];
2110 String path = applyPaths ? parts[0] : null;
2111 if(useGuids) throw new IllegalStateException("GUID identifiers were not found for diagrams.");
2112 return new CompositeInfo(useGuids, applyPaths, path, name, null);
2113 } else if(parts.length == 3) {
2114 String path = parts[0];
2115 String name = parts[1];
2116 GUID guid = GUID.parseIndexString(parts[2]);
2117 return new CompositeInfo(useGuids, applyPaths, path, name, guid);
2123 public GUID getGUID() {
2127 public String getEscapedName() {
2131 public String getUnescapedName() {
2132 return URIStringUtils.unescape(name);
2135 public String getOriginalPath() {
2139 public String getFinalPath() {
2140 if(applyPaths) return path;
2144 public CompositeInfo renamed(String newName) {
2145 return new CompositeInfo(useGuids, applyPaths, path, newName, guid);
2148 public String getStateKey() {
2149 return path + "#" + getEscapedName();
2152 private Resource getFromFolder(ReadGraph graph, Resource target) throws DatabaseException {
2153 Resource diagram = Layer0Utils.getPossibleChild(graph, target, URIStringUtils.unescape(name));
2154 if(diagram == null) return null;
2155 StructuralResource2 STR = StructuralResource2.getInstance(graph);
2156 return graph.isInstanceOf(diagram, STR.Composite) ? diagram : null;
2159 public Resource resolve(ReadGraph graph, Resource target) throws DatabaseException {
2161 if(useGuids && guid != null) {
2162 Resource indexRoot = graph.syncRequest(new IndexRoot(target));
2163 Collection<Resource> queryResult = searchByGUID(graph, indexRoot, guid);
2164 if(queryResult.size() == 1) {
2165 Resource composite = queryResult.iterator().next();
2166 StructuralResource2 STR = StructuralResource2.getInstance(graph);
2167 if(!graph.isInstanceOf(composite, STR.Composite)) return null;
2173 Resource folder = resolveFolder(graph, target);
2174 if(folder == null) return null;
2175 return getFromFolder(graph, folder);
2177 return getFromFolder(graph, target);
2182 public Resource resolveFolder(ReadGraph graph, Resource target) throws DatabaseException {
2184 String path = getFinalPath();
2185 if(path == null) return target;
2187 Resource folder = graph.syncRequest(new Configuration(target));
2188 String[] segments = path.split("/");
2189 for(int i=0;i<segments.length;i++) {
2190 if(segments[i].isEmpty()) continue;
2191 folder = Layer0Utils.getPossibleChild(graph, folder, URIStringUtils.unescape(segments[i]));
2192 if(folder == null) return null;
2201 public int hashCode() {
2203 if(useGuids) return guid.hashCode();
2205 final int prime = 31;
2206 int result = name.hashCode();
2207 result = prime * result + ((path == null) ? 0 : path.hashCode());
2213 public boolean equals(Object obj) {
2219 if (getClass() != obj.getClass())
2222 CompositeInfo other = (CompositeInfo) obj;
2224 if(useGuids) return guid.equals(other.guid);
2226 if (!name.equals(other.name))
2230 if (!path.equals(other.path))
2239 public static char COMPOSITE_SEPARATOR_CHAR = '#';
2240 public static String COMPOSITE_SEPARATOR = String.valueOf(COMPOSITE_SEPARATOR_CHAR);
2242 public static CompositeInfo parseCompositeNameFromRoot(Root root, boolean applyPaths, boolean useGuids) {
2243 return CompositeInfo.parse(root.name, applyPaths, useGuids);
2246 public static CompositeInfo parseCompositeNameFromRoot(Identity root, boolean applyPaths, boolean useGuids) {
2247 String coded = TransferableGraphUtils.getName(root);
2248 return CompositeInfo.parse(coded, applyPaths, useGuids);
2251 private static StringBuilder getDiagramCompositePathInternal(ReadGraph graph, Resource folder, StringBuilder builder) throws DatabaseException {
2252 SimulationResource SIMU = SimulationResource.getInstance(graph);
2253 Resource model = graph.getPossibleObject(folder, SIMU.IsConfigurationOf);
2254 if (model != null) return builder;
2256 Layer0 L0 = Layer0.getInstance(graph);
2257 String name = graph.getPossibleRelatedValue(folder, L0.HasName, Bindings.STRING);
2258 if (name == null) return null;
2259 Resource parent = graph.getPossibleObject(folder, L0.PartOf);
2260 if (parent == null) return null;
2262 StringBuilder sb = getDiagramCompositePathInternal(graph, parent, builder);
2263 if (sb == null) return null;
2264 if (sb.length() > 0)
2265 sb.append(URIStringUtils.NAMESPACE_PATH_SEPARATOR);
2266 sb.append( URIStringUtils.escape(name) );
2273 * @return diagram/folder path up until model configuration root with each
2274 * segment escaped using {@link URIStringUtils#escape(String)} and
2275 * {@value URIStringUtils#NAMESPACE_PATH_SEPARATOR} between each
2276 * segment or <code>null</code> if the specified diagram composite
2277 * is not part of any model configuration structure.
2278 * @throws DatabaseException
2280 public static String getDiagramCompositePath(ReadGraph graph, Resource diagram) throws DatabaseException {
2281 Layer0 L0 = Layer0.getInstance(graph);
2282 Resource parent = graph.getPossibleObject(diagram, L0.PartOf);
2283 if(parent == null) return null;
2284 StringBuilder sb = getDiagramCompositePathInternal(graph, parent, new StringBuilder());
2285 return sb != null ? sb.toString() : null;
2288 public static void exportModel(ReadGraph graph, Resource model, String fileName, String format, int version) throws DatabaseException {
2289 TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, model, true, false);
2290 exportModel(graph, conf, fileName, format, version);
2293 public static void exportModel(ReadGraph graph, TransferableGraphConfiguration2 conf, String fileName, String format, int version) throws DatabaseException {
2296 TransferableGraphSource s = graph.syncRequest(new ModelTransferableGraphSourceRequest(conf));
2297 TransferableGraphs.writeTransferableGraph(graph, format, version, s, new File(fileName));
2298 } catch (DatabaseException e) {
2300 } catch (Exception e) {
2301 throw new DatabaseException(e);
2306 public static TransferableGraph1 exportSharedOntology(ReadGraph graph, Resource library, String fileName, String format, int version) throws DatabaseException {
2308 Layer0 L0 = Layer0.getInstance(graph);
2309 String name = graph.getRelatedValue(library, L0.HasName, Bindings.STRING);
2311 DraftStatusBean draft = null;
2312 boolean published = Layer0Utils.isPublished(graph, library);
2313 if(!published) draft = new DraftStatusBean(new String[0]);
2315 LibraryInfo info = new LibraryInfo(name, library, draft);
2318 return exportSharedOntology(new NullProgressMonitor(), graph, fileName != null ? new File(fileName) : null, format, version, info);
2319 } catch (IOException e) {
2320 throw new DatabaseException(e);
2325 public static DraftStatusBean getDependencyDraftStatus(ReadGraph graph, Resource library) throws DatabaseException {
2326 Layer0 L0 = Layer0.getInstance(graph);
2327 List<String> drafts = new ArrayList<>();
2328 for (Resource shared : graph.syncRequest(new ObjectsWithType(library, L0.IsLinkedTo, L0.SharedOntology))) {
2329 boolean published = Layer0Utils.isPublished(graph, shared);
2331 drafts.add(graph.getURI(shared));
2333 return drafts.isEmpty() ? null : new DraftStatusBean(drafts);
2336 public static Set<Resource> getMostUnspecificTypes(final ReadGraph graph, Collection<Resource> types) throws DatabaseException {
2338 final Set<Resource> work = new HashSet<Resource>(types);
2339 for(Resource type : types) {
2340 Set<Resource> supers = graph.getSupertypes(type);
2341 if(!Collections.disjoint(supers, work)) work.remove(type);
2348 public static void rewriteGUIDS(WriteGraph graph, Resource root, boolean deep) throws DatabaseException {
2349 List<Resource> todo = new ArrayList<Resource>();
2351 Layer0 L0 = Layer0.getInstance(graph);
2352 while(!todo.isEmpty()) {
2353 Resource resource = todo.remove(todo.size()-1);
2354 Layer0Utils.claimNewIdentifier(graph, resource, false);
2356 todo.addAll(graph.getObjects(resource, L0.ConsistsOf));
2360 public static void createMissingGUIDs(IProgressMonitor monitor, WriteGraph graph, Collection<Resource> roots) throws DatabaseException {
2362 if(monitor == null) monitor = new NullProgressMonitor();
2364 Layer0 L0 = Layer0.getInstance(graph);
2366 // Allow this process to make 50k queries
2367 QueryMemoryWatcher memory = new QueryMemoryWatcher(graph, 50000);
2369 for(Resource root : roots) {
2371 boolean madeChanges = false;
2373 monitor.setTaskName("Creating missing GUID identifiers " + NameUtils.getSafeName(graph, root));
2374 Resource indexRoot = graph.syncRequest(new PossibleIndexRoot(root));
2375 for(Resource r : searchByTypeShallow(graph, indexRoot, L0.Entity)) {
2379 if(graph.isImmutable(r)) continue;
2381 if(!ModelingUtils.needsIdentifier(graph, r)) continue;
2383 GUID existing = graph.getPossibleRelatedValue(r, L0.identifier, GUID.BINDING);
2384 if(existing == null) {
2385 Layer0Utils.claimNewIdentifier(graph, r, true);
2392 ModelingUtils.deleteIndex(graph, root);
2399 public static boolean activateModel(WriteGraph graph, Resource model) throws DatabaseException {
2400 return graph.syncRequest(new ActivateModel(Simantics.getProjectResource(), model));
2403 public static File fileDialog(String title, List<Tuple> namesAndExtensions) {
2404 return new Runnable() {
2405 private File result;
2408 Display.getDefault().syncExec(this);
2414 result = showDialog();
2417 private File showDialog() {
2418 Display display = Display.getCurrent();
2419 Shell shell = display.getActiveShell();
2421 FileDialog dialog = new FileDialog(shell, SWT.OPEN);
2422 dialog.setText(title);
2424 String[] extensions = new String[namesAndExtensions.size()];
2425 String[] filterNames = new String[namesAndExtensions.size()];
2427 for(Tuple t : namesAndExtensions) {
2428 String filterName = (String)t.get(0);
2429 String extension = (String)t.get(1);
2430 filterNames[index] = filterName;
2431 extensions[index] = extension;
2435 dialog.setFilterExtensions(extensions);
2436 dialog.setFilterNames(filterNames);
2437 final String fileName = dialog.open();
2438 if (fileName == null) return null;
2440 return new File(fileName);
2445 public static Resource createLibrary(WriteGraph graph, Resource parent) throws DatabaseException {
2446 Layer0 l0 = Layer0.getInstance(graph);
2447 return createLibrary(graph, parent, NameUtils.findFreshName(graph, "Library", parent, l0.ConsistsOf));
2450 public static Resource createLibrary(WriteGraph graph, Resource parent, String name) throws DatabaseException {
2451 graph.markUndoPoint();
2452 Layer0 l0 = Layer0.getInstance(graph);
2454 Resource library = graph.newResource();
2455 graph.claim(library, l0.InstanceOf, null, l0.Library);
2456 graph.addLiteral(library, l0.HasName, l0.NameOf, l0.String, name, Bindings.STRING);
2457 graph.claim(library, l0.PartOf, parent);
2459 Layer0Utils.addCommentMetadata(graph, "Created new Library named " + name + ", resource " + library);
2464 public static IModelingRules getModelingRules(ReadGraph graph, Resource diagramResource) throws DatabaseException {
2465 return DiagramGraphUtil.getModelingRules(graph, diagramResource, null);
2468 public static void markChanged(WriteGraph graph, Resource r) throws DatabaseException {
2469 VirtualGraphSupport support = Simantics.getSession().getService(VirtualGraphSupport.class);
2470 VirtualGraph vg = support.getWorkspacePersistent("changeInformation");
2471 graph.syncRequest(new WriteRequest(vg) {
2473 public void perform(WriteGraph graph) throws DatabaseException {
2474 ModelingResources MOD = ModelingResources.getInstance(graph);
2475 graph.claim(r, MOD.changed, MOD.changed, r);