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.WriteGraph;
71 import org.simantics.db.common.Indexing;
72 import org.simantics.db.common.NamedResource;
73 import org.simantics.db.common.QueryMemoryWatcher;
74 import org.simantics.db.common.changeset.GenericChangeListener;
75 import org.simantics.db.common.primitiverequest.IsInstanceOf;
76 import org.simantics.db.common.procedure.adapter.TransientCacheAsyncListener;
77 import org.simantics.db.common.procedure.adapter.TransientCacheListener;
78 import org.simantics.db.common.request.IndexRoot;
79 import org.simantics.db.common.request.ObjectsWithType;
80 import org.simantics.db.common.request.PossibleIndexRoot;
81 import org.simantics.db.common.request.ReadRequest;
82 import org.simantics.db.common.request.ResourceRead2;
83 import org.simantics.db.common.request.WriteRequest;
84 import org.simantics.db.common.request.WriteResultRequest;
85 import org.simantics.db.common.utils.ListUtils;
86 import org.simantics.db.common.utils.Logger;
87 import org.simantics.db.common.utils.NameUtils;
88 import org.simantics.db.common.utils.OrderedSetUtils;
89 import org.simantics.db.common.utils.VersionInfo;
90 import org.simantics.db.common.utils.VersionInfoRequest;
91 import org.simantics.db.common.utils.Versions;
92 import org.simantics.db.exception.DatabaseException;
93 import org.simantics.db.layer0.QueryIndexUtils;
94 import org.simantics.db.layer0.SelectionHints;
95 import org.simantics.db.layer0.adapter.CopyHandler;
96 import org.simantics.db.layer0.adapter.GenericRelationIndex;
97 import org.simantics.db.layer0.adapter.Instances;
98 import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;
99 import org.simantics.db.layer0.adapter.impl.ImportAdvisorFactory;
100 import org.simantics.db.layer0.genericrelation.DependenciesRelation.DependencyChangesRequest;
101 import org.simantics.db.layer0.genericrelation.DependencyChanges;
102 import org.simantics.db.layer0.genericrelation.IndexedRelations;
103 import org.simantics.db.layer0.migration.MigratedImportResult;
104 import org.simantics.db.layer0.migration.MigrationUtils;
105 import org.simantics.db.layer0.request.ActivateModel;
106 import org.simantics.db.layer0.request.ActiveModels;
107 import org.simantics.db.layer0.request.Configuration;
108 import org.simantics.db.layer0.request.IsLinkedTo;
109 import org.simantics.db.layer0.request.PossibleModel;
110 import org.simantics.db.layer0.util.ClipboardUtils;
111 import org.simantics.db.layer0.util.DraftStatusBean;
112 import org.simantics.db.layer0.util.ExternalDownloadBean;
113 import org.simantics.db.layer0.util.Layer0Utils;
114 import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest;
115 import org.simantics.db.layer0.util.PasteEventHandler;
116 import org.simantics.db.layer0.util.RemoverUtil;
117 import org.simantics.db.layer0.util.SimanticsClipboard;
118 import org.simantics.db.layer0.util.SimanticsClipboard.Representation;
119 import org.simantics.db.layer0.util.SimanticsClipboardImpl;
120 import org.simantics.db.layer0.util.SimanticsKeys;
121 import org.simantics.db.layer0.util.TransferableGraphConfiguration2;
122 import org.simantics.db.layer0.variable.Variable;
123 import org.simantics.db.layer0.variable.Variables;
124 import org.simantics.db.request.Read;
125 import org.simantics.db.service.ClusterControl;
126 import org.simantics.db.service.CollectionSupport;
127 import org.simantics.db.service.GraphChangeListenerSupport;
128 import org.simantics.db.service.QueryControl;
129 import org.simantics.db.service.VirtualGraphSupport;
130 import org.simantics.diagram.stubs.DiagramResource;
131 import org.simantics.diagram.stubs.G2DResource;
132 import org.simantics.diagram.synchronization.graph.AddElement;
133 import org.simantics.graph.db.IImportAdvisor2;
134 import org.simantics.graph.db.ImportAdvisors;
135 import org.simantics.graph.db.MissingDependencyException;
136 import org.simantics.graph.db.StreamingTransferableGraphFileReader;
137 import org.simantics.graph.db.TransferableGraphException;
138 import org.simantics.graph.db.TransferableGraphSource;
139 import org.simantics.graph.db.TransferableGraphs;
140 import org.simantics.graph.representation.Identity;
141 import org.simantics.graph.representation.Root;
142 import org.simantics.graph.representation.TransferableGraph1;
143 import org.simantics.graph.representation.TransferableGraphUtils;
144 import org.simantics.issues.common.IssueSourceUtils;
145 import org.simantics.issues.ontology.IssueResource;
146 import org.simantics.layer0.Layer0;
147 import org.simantics.layer0.utils.direct.GraphUtils;
148 import org.simantics.modeling.adapters.ChangeInformation;
149 import org.simantics.modeling.template2d.ontology.Template2dResource;
150 import org.simantics.modeling.utils.OntologicalRequirementTracker;
151 import org.simantics.operation.Layer0X;
152 import org.simantics.project.ontology.ProjectResource;
153 import org.simantics.scenegraph.profile.ProfileUtils;
154 import org.simantics.scl.runtime.function.Function1;
155 import org.simantics.scl.runtime.tuple.Tuple;
156 import org.simantics.simulation.ontology.SimulationResource;
157 import org.simantics.structural.stubs.StructuralResource2;
158 import org.simantics.structural2.scl.StructuralComponent;
159 import org.simantics.structural2.utils.StructuralUtils;
160 import org.simantics.utils.ObjectUtils;
161 import org.simantics.utils.datastructures.Pair;
162 import org.simantics.utils.datastructures.Triple;
163 import org.simantics.utils.datastructures.hints.HintContext;
164 import org.simantics.utils.ui.dialogs.ListDialog;
167 * @author Hannu Niemistö
169 public class ModelingUtils {
172 private WriteGraph wg;
174 private StructuralResource2 sr;
175 private DiagramResource dr;
176 public ModelingResources mr;
177 public SimulationResource SIMU;
179 public ModelingUtils(WriteGraph g) {
182 b = Layer0.getInstance(g);
183 sr = StructuralResource2.getInstance(g);
184 dr = DiagramResource.getInstance(g);
185 mr = ModelingResources.getInstance(g);
186 SIMU = SimulationResource.getInstance(g);
190 public Resource createSymbol2(String name) throws DatabaseException {
191 return createSymbol2(name, dr.Composite);
195 public Resource createSymbol2(String name, Resource diagramType) throws DatabaseException {
196 return createSymbol2(name, diagramType, dr.DefinedElement);
199 public Resource createSymbol2(String name, Resource diagramType, Resource symbolType) throws DatabaseException {
200 G2DResource g2d = G2DResource.getInstance(g);
202 // Resource visibleTag = wg.newResource();
203 // wg.claim(visibleTag, b.SubrelationOf, null, dr.IsVisible);
204 // Resource focusableTag = wg.newResource();
205 // wg.claim(focusableTag, b.SubrelationOf, null, dr.IsFocusable);
207 Double boxDimension = 6.0;
208 Collection<Statement> grid = g.getAssertedStatements(diagramType, dr.HasGridSize);
209 if(grid.size() == 1) {
210 Double d = g.getPossibleValue(grid.iterator().next().getObject(), Bindings.DOUBLE);
211 if(d != null) boxDimension = 2*d;
215 Resource element = GraphUtils.create(wg,
216 b.InstanceOf, dr.SVGElement,
218 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" +
219 // REMOVED by Tuukka, because This will cause
220 // parsers to get on the net and get the doctype
221 // definitions which can stall the UI for a long time.
222 // Besides, we're not using the validation for anything
223 // so it's useless to us.
224 //"<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">" +
225 "<svg xmlns=\"http://www.w3.org/2000/svg\" overflow=\"visible\" version=\"1.1\">" +
226 "<rect x=\"-" + boxDimension + "\" y=\"-" + boxDimension + "\" width=\"" + (2*boxDimension) + "\" height=\"" + (2*boxDimension) + "\" fill=\"none\" stroke=\"rgb(0,0,0)\" stroke-width=\"0.1\"/>" +
230 // wg.claim(element, visibleTag, element);
231 // wg.claim(element, focusableTag, element);
233 Resource orderedSet = OrderedSetUtils.create(wg, diagramType, element);
235 // wg.claim(orderedSet, dr.HasLayer, GraphUtils.create2(wg, dr.Layer,
236 // b.HasName, "Default",
237 // dr.IsActive, Boolean.TRUE,
238 // dr.HasVisibleTag, visibleTag,
239 // dr.HasFocusableTag, focusableTag));
241 Resource result = GraphUtils.create(wg,
244 sr.IsDefinedBy, orderedSet);
246 wg.claim(result, b.ConsistsOf, orderedSet);
247 wg.claimLiteral(orderedSet, b.HasName, "__DIAGRAM__", Bindings.STRING);
248 AddElement.claimFreshElementName(wg, orderedSet, element);
249 wg.claim(orderedSet, b.ConsistsOf, element);
251 wg.claim(result, b.Inherits, null, symbolType);
255 public static Collection<Resource> getElementCorrespondendences(ReadGraph g, Resource element) throws DatabaseException {
256 DiagramResource dr = DiagramResource.getInstance(g);
257 ModelingResources mr = ModelingResources.getInstance(g);
258 if(g.isInstanceOf(element, dr.Connection)) {
259 Resource mappedComponent = g.getPossibleObject(element, mr.ElementToComponent);
260 if(mappedComponent != null) return Collections.singletonList(mappedComponent);
261 Resource mappedConnection = g.getPossibleObject(element, mr.DiagramConnectionToConnection);
262 if(mappedConnection == null)
263 return Collections.emptyList();
264 ArrayList<Resource> result = new ArrayList<Resource>();
265 Collection<Resource> relatedMappedConnections = StructuralUtils.getRelatedConnections(g, mappedConnection);
266 for(Resource relatedMappedConnection : relatedMappedConnections)
267 for(Resource relatedConnection : g.getObjects(relatedMappedConnection, mr.ConnectionToDiagramConnection))
268 result.addAll(g.getObjects(relatedConnection, mr.ElementToComponent));
272 return g.getObjects(element, mr.ElementToComponent);
275 public static Resource getPossibleElement(ReadGraph g, Resource component) throws DatabaseException {
276 ModelingResources mr = ModelingResources.getInstance(g);
277 return g.getPossibleObject(component, mr.ComponentToElement);
280 public static Resource getPossibleElementCorrespondendence(ReadGraph g, Resource element) throws DatabaseException {
281 Collection<Resource> corrs = getElementCorrespondendences(g, element);
282 if(corrs.size() != 1) return null;
283 else return corrs.iterator().next();
286 public static Resource getSingleElementCorrespondendence(ReadGraph g, Resource element) throws DatabaseException {
287 Collection<Resource> corrs = getElementCorrespondendences(g, element);
288 if(corrs.size() != 1) throw new DatabaseException("Expected 1 element correspondence, got " + corrs.size());
289 else return corrs.iterator().next();
292 public static Resource createExperiment(WriteGraph graph, Resource model) throws DatabaseException {
294 Layer0 L0 = Layer0.getInstance(graph);
295 SimulationResource SIMU = SimulationResource.getInstance(graph);
296 Resource experiment = graph.newResource();
297 graph.claim(experiment, L0.InstanceOf, SIMU.Experiment);
298 graph.claimLiteral(experiment, L0.HasName, "Experiment");
299 graph.claim(model, L0.ConsistsOf, experiment);
304 public static Resource createModel(WriteGraph graph, Resource type) throws DatabaseException {
305 return createModel(graph, type, Simantics.getProjectResource(), null);
308 public static Resource createModel(WriteGraph graph, Resource type, String name) throws DatabaseException {
309 return createModel(graph, type, Simantics.getProjectResource(), name);
312 public static Resource createModel(WriteGraph graph, Resource type, final Resource target, String name) throws DatabaseException {
314 Layer0 L0 = Layer0.getInstance(graph);
315 SimulationResource SIMU = SimulationResource.getInstance(graph);
316 StructuralResource2 STR = StructuralResource2.getInstance(graph);
317 ModelingResources MOD = ModelingResources.getInstance(graph);
320 name = NameUtils.findFreshName(graph, "Model", target, L0.ConsistsOf, "%s%d");
322 final Resource model = graph.newResource();
323 graph.newClusterSet(model);
324 graph.claim(model, L0.InstanceOf, null, type);
325 graph.claimLiteral(model, L0.HasName, name);
327 graph.claim(target, L0.ConsistsOf, model);
329 Resource configurationType = graph.getPossibleObject(model, MOD.StructuralModel_HasConfigurationType);
330 if(configurationType == null) configurationType = STR.Composite;
332 Resource configuration = graph.newResource();
333 graph.claimLiteral(configuration, L0.HasName, "Configuration", Bindings.STRING);
334 graph.claim(configuration, L0.InstanceOf, null, configurationType);
335 graph.claim(model, L0.ConsistsOf, configuration);
336 graph.claim(model, SIMU.HasConfiguration, configuration);
338 Resource joinClusterSet = graph.newResource();
339 graph.newClusterSet(joinClusterSet);
340 graph.claim(joinClusterSet, L0.InstanceOf, L0.ClusterSet);
341 graph.claim(model, STR.HasJoinClusterSet, joinClusterSet);
343 linkOntologyDependenciesToModel(graph, model, target);
345 Resource ontology = graph.syncRequest(new PossibleIndexRoot(type));
346 if(ontology != null) {
347 graph.claim(model, L0.IsLinkedTo, ontology);
350 VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);
351 graph.asyncRequest(new WriteRequest(support.getWorkspacePersistent("activations")) {
354 public void perform(WriteGraph graph) throws DatabaseException {
355 Layer0X L0X = Layer0X.getInstance(graph);
356 Collection<Resource> actives = graph.syncRequest(new ActiveModels(target));
357 if(actives.isEmpty()) {
358 graph.claim(model, L0X.IsActivatedBy, target);
368 public static void linkOntologyDependenciesToModel(WriteGraph graph, Resource model, Resource target)
369 throws DatabaseException {
370 Layer0 L0 = Layer0.getInstance(graph);
371 ProjectResource PROJ = ProjectResource.getInstance(graph);
372 for(Resource dep : graph.getObjects(target, L0.IsLinkedTo)) {
373 if(graph.isInstanceOf(dep, PROJ.NamespaceRequirement)) {
374 for(Resource req : graph.getObjects(dep, PROJ.RequiresNamespace)) {
375 String uri = graph.getPossibleValue(req, Bindings.STRING);
377 Resource ns = graph.getResource(uri);
379 graph.claim(model, L0.IsLinkedTo, null, ns);
387 public static void addSCLMainToModel(WriteGraph graph, Resource model)
388 throws DatabaseException {
389 addSCLMainToModel(graph, model, "SCLMain", "include \"Simantics/All\"\n");
392 public static void addSCLMainToModel(WriteGraph graph, Resource model, String name, String contents)
393 throws DatabaseException {
394 Layer0 L0 = Layer0.getInstance(graph);
395 Resource sclmain = GraphUtils.create2(graph, L0.SCLModule, L0.PartOf, model, L0.HasName, name);
396 graph.claimLiteral(sclmain, L0.SCLModule_definition, contents, Bindings.STRING);
399 public static Resource createLocalLibrary(WriteGraph graph, Resource container, String name) throws DatabaseException {
400 Layer0 L0 = Layer0.getInstance(graph);
401 ModelingResources MOD = ModelingResources.getInstance(graph);
402 Resource library = graph.newResource();
403 graph.claim(library, L0.InstanceOf, null, L0.Library);
404 graph.addLiteral(library, L0.HasName, L0.NameOf, "Library", Bindings.STRING);
405 if (container != null) {
406 graph.claim(container, L0.ConsistsOf, L0.PartOf, library);
407 graph.claim(container, MOD.HasLocalLibrary, MOD.IsLocalLibraryOf, library);
412 public static void importModel(String fileName) {
414 Resource project = Simantics.getProject().get();
416 try (StreamingTransferableGraphFileReader importer = new StreamingTransferableGraphFileReader(new File(fileName))) {
417 TransferableGraphSource tg = importer.readTG();
419 final DefaultPasteImportAdvisor advisor = new DefaultPasteImportAdvisor(project) {
421 public void analyzeType(ReadGraph graph, Root root) throws DatabaseException {
424 public Resource analyzeRoot(ReadGraph graph, Root root) throws DatabaseException {
425 library = Simantics.getProjectResource();
426 String newName = newName(graph, library, root.name);
427 nameMappings.put(root.name, newName);
431 TransferableGraphs.importGraph1(Simantics.getSession(), tg, advisor);
433 } catch (MissingDependencyException e) {
435 final Set<String> missingURIs = e.getMissingURIs();
437 class ErrorMessageDialog extends MessageDialog {
439 public ErrorMessageDialog(Shell shell) {
441 "Unsatisfied dependencies", null,
442 "The following dependencies were missing. Please import the dependencies and try again.",
443 MessageDialog.ERROR, new String[] { "Continue" }, 0);
447 protected Control createCustomArea(Composite composite) {
448 GridLayoutFactory.fillDefaults().applyTo(composite);
450 org.eclipse.swt.widgets.List list = new org.eclipse.swt.widgets.List(composite, SWT.BORDER | SWT.READ_ONLY);
451 GridDataFactory.fillDefaults().grab(true, true).applyTo(list);
452 for(String s : missingURIs) list.add(s);
458 Display display = Display.getCurrent();
459 if(display != null) {
460 ErrorMessageDialog md = new ErrorMessageDialog(display.getActiveShell());
463 Display.getDefault().asyncExec(new Runnable() {
467 Shell shell = Display.getCurrent().getActiveShell();
468 ErrorMessageDialog md = new ErrorMessageDialog(shell);
476 } catch (Exception e) {
477 Logger.defaultLogError(e);
482 public static void primeVirtualGraphs() {
483 VirtualGraphSupport support = Simantics.getSession().getService(VirtualGraphSupport.class);
484 support.getWorkspacePersistent("activations");
485 support.getWorkspacePersistent("experiments");
486 support.getWorkspacePersistent("issues");
487 support.getWorkspacePersistent("preferences");
490 public static Resource createProfileEntry(WriteGraph graph, String name, Resource style, Resource group) throws DatabaseException {
492 Layer0 L0 = Layer0.getInstance(graph);
493 DiagramResource DIA = DiagramResource.getInstance(graph);
495 Resource entry = graph.newResource();
496 graph.claim(entry, L0.InstanceOf, null, DIA.GroupStyleProfileEntry);
497 graph.claimLiteral(entry, L0.HasName, name);
498 graph.claimLiteral(entry, L0.HasLabel, name);
499 graph.claim(entry, DIA.ProfileEntry_HasStyle, style);
500 graph.claim(entry, DIA.ProfileEntry_HasGroup, group);
506 public static Resource createProfile(WriteGraph graph, String profileName, Resource... entries) throws DatabaseException {
508 Layer0 L0 = Layer0.getInstance(graph);
509 DiagramResource DIA = DiagramResource.getInstance(graph);
511 Resource list = ListUtils.create(graph, DIA.Profile, entries);
513 Resource profile = graph.newResource();
514 graph.claim(profile, L0.InstanceOf, null, DIA.Profile);
515 graph.claimLiteral(profile, L0.HasName, profileName);
516 graph.claim(profile, DIA.HasEntries, null, list);
522 public static Resource createProfile(WriteGraph graph, String profileName, Collection<Resource> entries) throws DatabaseException {
523 return createProfile(graph, profileName, entries.toArray(new Resource[entries.size()]));
526 public static Resource createToplevelProfile(WriteGraph graph, Resource model, String name, Resource ... profiles) throws DatabaseException {
528 Resource work = createProfile(graph, name, profiles);
530 Layer0 L0 = Layer0.getInstance(graph);
531 DiagramResource DIA = DiagramResource.getInstance(graph);
533 graph.deny(model, DIA.HasActiveProfile);
534 graph.claim(model, DIA.HasActiveProfile, work);
535 graph.claim(model, L0.ConsistsOf, L0.PartOf, work);
541 public static Resource createToplevelProfile(WriteGraph graph, Resource model, String name, Collection<Resource> profiles) throws DatabaseException {
542 return createToplevelProfile(graph, model, name, profiles.toArray(new Resource[profiles.size()]));
545 public static void activateProfileEntries(WriteGraph graph, final Resource profile, final Resource ... entries) {
547 VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);
548 graph.asyncRequest(new WriteRequest(support.getWorkspacePersistent("profiles")) {
551 public void perform(WriteGraph graph) throws DatabaseException {
552 SimulationResource SIMU = SimulationResource.getInstance(graph);
553 for(Resource entry : entries)
554 graph.claim(profile, SIMU.IsActive, entry);
561 public static void activateProfileEntries(WriteGraph graph, Resource profile, Collection<Resource> entries) {
562 activateProfileEntries(graph, profile, entries.toArray(new Resource[entries.size()]));
565 public static void toggleProfileGroup(WriteGraph graph, Resource runtimeProfile, String groupName, boolean enabled) throws DatabaseException {
566 Layer0 L0 = Layer0.getInstance(graph);
567 for (Resource group : ProfileUtils.getProfileChildren(graph, runtimeProfile)) {
568 String name = graph.getRelatedValue2(group, L0.HasName);
569 if (name.equals(groupName)) {
570 toggleProfileGroup(graph, runtimeProfile, group, enabled);
576 public static void toggleProfileGroup(WriteGraph graph, Resource runtimeProfile, Resource group, boolean enabled) throws DatabaseException {
577 DiagramResource DIA = DiagramResource.getInstance(graph);
579 if(graph.isInstanceOf(group, DIA.Profile)) {
581 for(Resource child : ProfileUtils.getProfileChildren(graph, group)) {
582 toggleProfileGroup(graph, runtimeProfile, child, enabled);
585 } else if(graph.isInstanceOf(group, DIA.ProfileEntry)) {
588 graph.claim(runtimeProfile, SimulationResource.getInstance(graph).IsActive, null, group);
590 graph.denyStatement(runtimeProfile, SimulationResource.getInstance(graph).IsActive, group);
596 public static void untrackDependencies() {
597 untrackDependencies(Simantics.getSession());
600 public static void untrackDependencies(RequestProcessor processor) {
603 processor.syncRequest(new ReadRequest() {
606 public void run(ReadGraph graph) throws DatabaseException {
607 Layer0X L0X = Layer0X.getInstance(graph);
608 GenericRelationIndex index = graph.adapt(L0X.DependenciesRelation, GenericRelationIndex.class);
609 index.untrack(graph.getSession(), graph.getRootLibrary());
613 } catch (DatabaseException e) {
614 Logger.defaultLogError(e);
619 public static void trackDependencies() {
620 trackDependencies(Simantics.getSession());
623 public static void trackDependencies(RequestProcessor processor) {
626 processor.syncRequest(new ReadRequest() {
629 public void run(ReadGraph graph) throws DatabaseException {
630 Layer0X L0X = Layer0X.getInstance(graph);
631 GenericRelationIndex index = graph.adapt(L0X.DependenciesRelation, GenericRelationIndex.class);
632 index.trackAndIndex(graph.getSession(), graph.getRootLibrary());
636 } catch (DatabaseException e) {
637 Logger.defaultLogError(e);
642 public static void trackOntologicalRequirements() {
643 Session session = Simantics.getSession();
644 GraphChangeListenerSupport changeListenerSupport = session.getService(GraphChangeListenerSupport.class);
645 changeListenerSupport.addMetadataListener( OntologicalRequirementListener.getInstance() );
648 public static void untrackOntologicalRequirements() {
649 Session session = Simantics.getSession();
650 GraphChangeListenerSupport changeListenerSupport = session.getService(GraphChangeListenerSupport.class);
651 changeListenerSupport.removeMetadataListener( OntologicalRequirementListener.getInstance() );
654 public static class OntologicalRequirementListener extends GenericChangeListener<DependencyChangesRequest, DependencyChanges> {
656 private static OntologicalRequirementListener INSTANCE;
658 public static OntologicalRequirementListener getInstance() {
659 if(INSTANCE == null) {
660 INSTANCE = new OntologicalRequirementListener();
665 private OntologicalRequirementListener() {
668 private OntologicalRequirementTracker changeInformationUpdater = new OntologicalRequirementTracker();
671 public boolean preEventRequest() {
672 return !Indexing.isDependenciesIndexingDisabled();
676 public void onEvent(ReadGraph graph, MetadataI metadata, DependencyChanges event) throws DatabaseException {
677 changeInformationUpdater.update(graph, metadata, event);
682 public static void removeIndex(WriteGraph graph, Resource model) throws DatabaseException {
683 Layer0X L0X = Layer0X.getInstance(graph);
684 IndexedRelations ir = graph.getService(IndexedRelations.class);
685 // Deletes index files
686 ir.reset(null, graph, L0X.DependenciesRelation, model);
689 public static void resetIssueSources(WriteGraph graph, Resource model) throws DatabaseException {
690 Layer0 L0 = Layer0.getInstance(graph);
691 IssueResource ISSUE = IssueResource.getInstance(graph);
692 for(Resource source : graph.sync(new ObjectsWithType(model, L0.ConsistsOf, ISSUE.ContinuousIssueSource))) {
693 IssueSourceUtils.update(graph, source);
697 public static void copyAnnotationTypes(WriteGraph graph, Resource sourceModel, Resource targetModel) throws DatabaseException {
699 Layer0 L0 = Layer0.getInstance(graph);
700 AnnotationResource ANNO = AnnotationResource.getInstance(graph);
702 Instances query = graph.adapt(ANNO.AnnotationType, Instances.class);
704 Resource library = graph.getPossibleObject(targetModel, ANNO.HasAnnotationTypeRoot);
706 if(library == null) {
707 library = graph.newResource();
708 graph.claim(library, L0.InstanceOf, null, ANNO.AnnotationTypeLibrary);
709 graph.claimLiteral(library, L0.HasName, L0.NameOf, L0.String, "Annotation types", Bindings.STRING);
710 graph.claim(library, L0.PartOf, L0.ConsistsOf, targetModel);
711 graph.claim(targetModel, ANNO.HasAnnotationTypeRoot, library);
714 for(Resource type : query.find(graph, sourceModel)) {
715 String name = graph.getRelatedValue(type, L0.HasName);
716 Resource existing = Layer0Utils.getPossibleChild(graph, library, name);
717 if(existing != null) {
718 RemoverUtil.remove(graph, existing);
720 Layer0Utils.copyTo(graph, library, type);
725 public static void deleteIndex(WriteGraph graph, Resource model) throws DatabaseException {
726 Layer0X L0X = Layer0X.getInstance(graph);
727 IndexedRelations ir = graph.getService(IndexedRelations.class);
728 // Deletes index files
729 ir.reset(null, graph, L0X.DependenciesRelation, model);
732 public static void disableDependencies(WriteGraph graph, Resource dummy) {
733 Layer0Utils.setDependenciesIndexingDisabled(graph, true);
736 public static void releaseMemory(WriteGraph graph) {
738 QueryControl qc = graph.getService(QueryControl.class);
739 ClusterControl cc = graph.getService(ClusterControl.class);
745 public static List<Resource> filterByIndexRoot(ReadGraph graph, Resource indexRoot, List<Resource> resources) throws DatabaseException {
746 ArrayList<Resource> result = new ArrayList<Resource>(resources.size());
747 for (Resource r : resources) {
748 Resource root = graph.syncRequest(new PossibleIndexRoot(r));
749 if (indexRoot.equals(root))
756 public static List<Resource> searchByTypeShallow(ReadGraph graph, Resource model, Resource type) throws DatabaseException {
757 return QueryIndexUtils.searchByTypeShallow(graph, model, type);
761 public static List<Resource> searchByType(ReadGraph graph, Resource model, Resource type) throws DatabaseException {
762 return QueryIndexUtils.searchByType(graph, model, type);
766 public static List<Resource> searchByGUID(ReadGraph graph, Resource indexRoot, GUID guid) throws DatabaseException {
767 return QueryIndexUtils.searchByGUID(graph, indexRoot, guid);
771 public static List<Resource> searchByGUID(ReadGraph graph, Resource indexRoot, String indexString) throws DatabaseException {
772 return QueryIndexUtils.searchByGUID(graph, indexRoot, indexString);
776 public static List<Resource> searchByQueryShallow(ReadGraph graph, Resource model, String query) throws DatabaseException {
777 return QueryIndexUtils.searchByQueryShallow(graph, model, query);
781 public static List<Resource> searchByQuery(ReadGraph graph, Resource model, String query) throws DatabaseException {
782 return QueryIndexUtils.searchByQuery(graph, model, query);
786 public static List<Resource> searchByTypeAndFilter(ReadGraph graph, Resource model, Resource type, Function1<Resource,Boolean> filter) throws DatabaseException {
787 return QueryIndexUtils.searchByTypeAndFilter(graph, model, type, filter);
791 public static List<Triple<Resource, Resource, String>> getIndexEntries(ReadGraph graph, Resource model, String filter) throws DatabaseException {
792 return QueryIndexUtils.getIndexEntries(graph, model, filter);
796 public static String listIndexEntries(ReadGraph graph, Resource model, String filter) throws DatabaseException {
797 return QueryIndexUtils.listIndexEntries(graph, model, filter);
801 public static List<Resource> searchByTypeAndName(ReadGraph graph, Resource model, Resource type, String name) throws DatabaseException {
802 return QueryIndexUtils.searchByTypeAndName(graph, model, type, name);
806 public static List<Resource> searchByTypeAndNameShallow(ReadGraph graph, Resource model, Resource type, String name) throws DatabaseException {
807 return QueryIndexUtils.searchByTypeAndNameShallow(graph, model, type, name);
812 * database write access
813 * @param sourceContainer
814 * the source container to look for annotationProperty from to be
815 * used as the copy source
816 * @param targetContainer
817 * the target container for the copied annotationProperty
819 * @param annotationProperty
820 * the annotation property relation
821 * @return created copy of the original annotation or <code>null</code> if
822 * there was nothing to copy
823 * @throws DatabaseException
825 public static Resource copyPossibleAnnotation(WriteGraph graph, Resource sourceContainer, Resource targetContainer, Resource annotationProperty) throws DatabaseException {
826 return copyPossibleAnnotation2(graph, sourceContainer, targetContainer, annotationProperty, null);
829 public static List<String> getPossibleNamePath(ReadGraph graph, Resource resource) throws DatabaseException {
830 return getPossibleNamePath(graph, resource, null);
833 private static List<String> getPossibleNamePath(ReadGraph graph, Resource resource, List<String> result) throws DatabaseException {
835 Layer0 L0 = Layer0.getInstance(graph);
836 String name = graph.getPossibleRelatedValue(resource, L0.HasName, Bindings.STRING);
837 if(name == null) return null;
839 if(result == null) result = new ArrayList<String>();
841 SimulationResource SIMU = SimulationResource.getInstance(graph);
842 if(graph.isInstanceOf(resource, SIMU.Model)) return result;
844 Resource parent = graph.getPossibleObject(resource, L0.PartOf);
846 getPossibleNamePath(graph, parent, result);
857 public static Resource claimLibraryPath(WriteGraph graph, Resource resource, List<String> path) throws DatabaseException {
858 Layer0 L0 = Layer0.getInstance(graph);
859 for(int i=0;i<path.size()-1;i++) {
860 String p = path.get(i);
861 Resource child = Layer0Utils.getPossibleChild(graph, resource, p);
863 child = graph.newResource();
864 graph.claim(child, L0.InstanceOf, L0.Library);
865 graph.addLiteral(child, L0.HasName, L0.NameOf, L0.String, p, Bindings.STRING);
866 graph.claim(resource, L0.ConsistsOf, L0.PartOf, child);
875 * database write access
876 * @param sourceContainer
877 * the source container to look for annotationProperty from to be
878 * used as the copy source
879 * @param targetContainer
880 * the target container for the copied annotationProperty
882 * @param annotationProperty
883 * the annotation property relation
884 * @param annotationProperty
885 * the 2nd level annotation property relation or
886 * <code>null</code> if no 2nd level annotation exists
887 * @return created copy of the original annotation or <code>null</code> if
888 * there was nothing to copy
889 * @throws DatabaseException
891 public static Resource copyPossibleAnnotation2(WriteGraph graph,
892 Resource sourceContainer, Resource targetContainer,
893 Resource annotationProperty, Resource entryType) throws DatabaseException {
895 // Delete existing target value first
896 Layer0 L0 = Layer0.getInstance(graph);
897 Resource targetValue = graph.getPossibleObject(targetContainer, annotationProperty);
898 if (targetValue != null) {
899 if(!graph.hasStatement(targetValue, L0.PartOf))
900 RemoverUtil.remove(graph, targetValue);
901 graph.deny(targetContainer, annotationProperty);
904 Resource sourceValue = graph.getPossibleObject(sourceContainer, annotationProperty);
905 if (sourceValue == null)
908 List<String> sourceValuePath = getPossibleNamePath(graph, sourceValue);
909 if(sourceValuePath != null) {
910 Resource targetModel = graph.sync(new PossibleModel(targetContainer));
911 if(targetModel == null) throw new DatabaseException("No target model found for " + targetContainer);
912 Resource library = claimLibraryPath(graph, targetModel, sourceValuePath);
913 Resource existing = Layer0Utils.getPossibleChild(graph, library, sourceValuePath.get(sourceValuePath.size()-1));
914 if(existing == null) {
915 existing = doCopyPossibleAnnotation2(graph, sourceContainer, targetContainer, annotationProperty, entryType);
916 graph.claim(library, L0.ConsistsOf, L0.PartOf, existing);
918 graph.claim(targetContainer, annotationProperty, existing);
921 return doCopyPossibleAnnotation2(graph, sourceContainer, targetContainer, annotationProperty, entryType);
926 private static Resource doCopyPossibleAnnotation2(WriteGraph graph,
927 Resource sourceContainer, Resource targetContainer,
928 Resource annotationProperty, Resource entryType) throws DatabaseException {
930 Resource sourceValue = graph.getPossibleObject(sourceContainer, annotationProperty);
931 if (sourceValue == null)
934 // Copy 1st level annotation
935 Resource targetValue = createAnnotation(graph, targetContainer, annotationProperty, sourceValue);
937 // Copy possible 2nd level annotations and attach to 1st if entry
938 // property is defined.
939 Layer0 L0 = Layer0.getInstance(graph);
940 if (entryType != null) {
942 AnnotationResource ANNO = AnnotationResource.getInstance(graph);
943 for (Resource entry : graph.getObjects(sourceValue, ANNO.Annotation_HasEntry)) {
945 String name = graph.getRelatedValue(entry, L0.HasName, Bindings.STRING);
947 List<String> entryPath = getPossibleNamePath(graph, entry);
948 if(entryPath != null) {
949 Resource targetModel = graph.sync(new PossibleModel(targetContainer));
950 if(targetModel == null) throw new DatabaseException("No target model found for " + targetContainer);
951 Resource library = claimLibraryPath(graph, targetModel, entryPath);
952 Resource existing = Layer0Utils.getPossibleChild(graph, library, entryPath.get(entryPath.size()-1));
953 if(existing == null) {
954 existing = createTypedAnnotation(graph, null, null, entry, entryType, name);
955 graph.claim(library, L0.ConsistsOf, L0.PartOf, existing);
957 graph.claim(targetValue, ANNO.Annotation_HasEntry, existing);
959 Resource result = createTypedAnnotation(graph, null, null, entry, entryType, name);
960 graph.claim(targetValue, ANNO.Annotation_HasEntry, result);
972 * database write access
974 * the container resource to attach the new annotation to
976 * the annotation property relation. The type of the created
977 * annotation is decided from this property relation's range
978 * @param sourceAnnotation
979 * the annotation to copy data from or <code>null</code> if
980 * nothing shall be copied
981 * @return the newly created annotation resource or <code>null</code> if the
982 * annotation property relation didn't have a single range type
983 * @throws DatabaseException
985 public static Resource createAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation) throws DatabaseException {
986 return createAnnotation(graph, container, property, sourceAnnotation, null);
991 * database write access
993 * the container resource to attach the new annotation to
995 * the annotation property relation. The type of the created
996 * annotation is decided from this property relation's range
997 * @param sourceAnnotation
998 * the annotation to copy data from or <code>null</code> if
999 * nothing shall be copied
1001 * name for newly created annotation or <code>null</code> to copy
1002 * name from source if available
1003 * @return the newly created annotation resource or <code>null</code> if the
1004 * annotation property relation didn't have a single range type
1005 * @throws DatabaseException
1007 public static Resource createAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation, String name) throws DatabaseException {
1009 Layer0 L0 = Layer0.getInstance(graph);
1010 Resource annotationType = graph.getSingleObject(property, L0.HasRange);
1011 if (annotationType == null)
1014 return createTypedAnnotation(graph, container, property, sourceAnnotation, annotationType, name);
1020 * database write access
1022 * the container resource to attach the new annotation to
1024 * the annotation property relation
1025 * @param sourceAnnotation
1026 * the annotation to copy data from or <code>null</code> if
1027 * nothing shall be copied
1028 * @param annotationType
1029 * the type of the new annotation
1030 * @return the newly created annotation resource
1031 * @throws DatabaseException
1033 public static Resource createTypedAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation, Resource annotationType) throws DatabaseException {
1034 return createTypedAnnotation(graph, container, property, sourceAnnotation, annotationType, null);
1039 * database write access
1041 * the container resource to attach the new annotation to
1043 * the annotation property relation
1044 * @param sourceAnnotation
1045 * the annotation to copy data from or <code>null</code> if
1046 * nothing shall be copied
1047 * @param annotationType
1048 * the type of the new annotation
1050 * name for newly created annotation or <code>null</code> to copy
1051 * name from source if available
1052 * @return the newly created annotation resource
1053 * @throws DatabaseException
1055 public static Resource createTypedAnnotation(WriteGraph graph, Resource container, Resource property, Resource sourceAnnotation, Resource annotationType, String name) throws DatabaseException {
1057 Layer0 L0 = Layer0.getInstance(graph);
1059 Resource anno = graph.newResource();
1061 graph.claim(anno, L0.InstanceOf, null, annotationType);
1064 graph.addLiteral(anno, L0.HasName, L0.NameOf, L0.String, name, Bindings.STRING);
1066 if (sourceAnnotation != null) {
1069 String sourceName = graph.getPossibleRelatedValue(sourceAnnotation, L0.HasName, Bindings.STRING);
1070 if(sourceName != null) graph.addLiteral(anno, L0.HasName, L0.NameOf, L0.String, sourceName, Bindings.STRING);
1073 Resource sourceType = graph.getSingleType(sourceAnnotation);
1074 List<AnnotationMap> am = getAnnotationMap(graph, annotationType, sourceType);
1075 for (AnnotationMap a : am) {
1076 Resource object = graph.getSingleObject(sourceAnnotation, a.sourcePredicate);
1077 Collection<Resource> objectTypes = graph.getTypes(object);
1078 if (objectTypes.contains(L0.Literal)) {
1079 Object value = graph.getValue(object, a.defaultValueBinding);
1080 if (!ObjectUtils.objectEquals(value, a.defaultValue)) {
1081 graph.addLiteral(anno, a.annotationPredicate, a.annotationPredicateInverse, a.defaultValueType, value, a.defaultValueBinding);
1087 if (container != null && property != null) {
1088 graph.claim(container, property, anno);
1095 private static class AnnotationMap {
1097 final public Resource sourcePredicate;
1098 final public Resource sourcePredicateInverse;
1100 final public Resource annotationPredicate;
1101 final public Resource annotationPredicateInverse;
1103 final public Resource defaultValueType;
1104 final public Object defaultValue;
1105 final public Binding defaultValueBinding;
1107 public AnnotationMap(Resource sp, Resource spi, Resource tp, Resource tpi, Resource defaultValueType, Object defaultValue, Binding defaultValueBinding) {
1108 sourcePredicate = sp;
1109 sourcePredicateInverse = spi;
1110 annotationPredicate = tp;
1111 annotationPredicateInverse = tpi;
1112 this.defaultValueType = defaultValueType;
1113 this.defaultValue = defaultValue;
1114 this.defaultValueBinding = defaultValueBinding;
1119 public static List<AnnotationMap> getAnnotationMap(ReadGraph graph, Resource annotationType, Resource sourceType) throws DatabaseException {
1120 return graph.syncRequest(new AnnotationMapRequest(annotationType, sourceType), TransientCacheListener.<List<AnnotationMap>>instance());
1123 static class AnnotationMapRequest extends ResourceRead2<List<AnnotationMap>> {
1125 public AnnotationMapRequest(Resource annotationType, Resource sourceType) {
1126 super(annotationType, sourceType);
1130 public List<AnnotationMap> perform(ReadGraph graph) throws DatabaseException {
1132 Layer0 L0 = Layer0.getInstance(graph);
1134 ArrayList<AnnotationMap> result = new ArrayList<AnnotationMap>();
1136 Map<String, Resource> annotationPredicates = new HashMap<String, Resource>();
1137 for(Resource predicate : graph.getObjects(resource, L0.DomainOf)) {
1138 String name = graph.getRelatedValue(predicate, L0.HasName, Bindings.STRING);
1139 annotationPredicates.put(name, predicate);
1141 Map<String, Resource> sourcePredicates = new HashMap<String, Resource>();
1142 for(Resource predicate : graph.getObjects(resource2, L0.DomainOf)) {
1143 String name = graph.getRelatedValue(predicate, L0.HasName, Bindings.STRING);
1144 sourcePredicates.put(name, predicate);
1147 for(String key : sourcePredicates.keySet()) {
1148 Resource sourcePredicate = sourcePredicates.get(key);
1149 Resource anno = annotationPredicates.get(key);
1150 if(sourcePredicate != null && anno != null) {
1151 Resource defaultValueType = graph.getSingleObject(anno, L0.HasRange);
1152 Binding defaultValueBinding = null;
1153 Object defaultValue = null;
1154 Resource assertion = graph.getPossibleObject(anno, L0.HasPredicateInverse);
1155 if (assertion != null) {
1156 Resource object = graph.getPossibleObject(assertion, L0.HasObject);
1157 if (object != null) {
1158 if(graph.isInstanceOf(object, L0.Literal)) {
1159 Datatype dt = graph.getDataType(object);
1160 defaultValueBinding = Bindings.getBeanBinding(dt);
1161 defaultValue = graph.getPossibleValue(object);
1165 result.add(new AnnotationMap(
1166 sourcePredicate, graph.getInverse(sourcePredicate),
1167 anno, graph.getInverse(anno),
1168 defaultValueType, defaultValue, defaultValueBinding));
1178 public static final String DRAWING_TEMPLATE_FORMAT = "drawingTemplate";
1179 public static final String DRAWING_TEMPLATE_FORMAT_V1 = DRAWING_TEMPLATE_FORMAT + ":1";
1180 public static final String DRAWING_TEMPLATE_FORMAT_V2 = DRAWING_TEMPLATE_FORMAT + ":2";
1182 public static Resource importDrawingTemplate(final Resource model, final File file) throws IOException, SerializationException, DatabaseException, TransferableGraphException {
1186 final Resource library = Simantics.sync(new WriteResultRequest<Resource>() {
1189 public Resource perform(WriteGraph graph) throws DatabaseException {
1191 Layer0 L0 = Layer0.getInstance(graph);
1192 Template2dResource TEMPLATE = Template2dResource.getInstance(graph);
1193 Resource root = graph.getPossibleObject(model, TEMPLATE.HasDrawingTemplateRoot);
1195 Template2dResource TEMPLATE2D = Template2dResource.getInstance(graph);
1196 root = graph.newResource();
1197 graph.claim(root, L0.InstanceOf, null, TEMPLATE2D.DrawingTemplateLibrary);
1198 graph.claim(root, L0.InstanceOf, null, TEMPLATE2D.DrawingTemplateLibraryUI);
1199 graph.claimLiteral(root, L0.HasName, L0.NameOf, L0.String, "Diagram Templates", Bindings.STRING);
1200 graph.claim(root, L0.PartOf, L0.ConsistsOf, model);
1201 graph.claim(model, TEMPLATE2D.HasDrawingTemplateRoot, root);
1204 String name = new Path(file.getAbsolutePath()).removeFileExtension().lastSegment();
1206 Resource existing = Layer0Utils.getPossibleChild(graph, root, name);
1207 if(existing != null)
1208 graph.deny(root, L0.ConsistsOf, existing);
1217 final DefaultPasteImportAdvisor advisor = new DefaultPasteImportAdvisor(library);
1220 HashMap<String, FormatHandler<Object>> handlers = new HashMap<String, FormatHandler<Object>>();
1221 FormatHandler<Object> handler = new FormatHandler<Object>() {
1223 public Binding getBinding() {
1224 return TransferableGraph1.BINDING;
1228 public Object process(DataContainer container) throws Exception {
1229 TransferableGraphs.importGraph1(Simantics.getSession(), (TransferableGraph1)container.content.getValue(),
1234 handlers.put(DRAWING_TEMPLATE_FORMAT_V1, handler);
1235 handlers.put(DRAWING_TEMPLATE_FORMAT_V2, handler);
1237 DataContainers.readFile(file, handlers);
1238 } catch(DataFormatException e) {
1239 throw new IOException(e);
1240 } catch(IOException e) {
1242 } catch(Exception e) {
1243 if(e instanceof RuntimeException)
1244 throw (RuntimeException)e;
1246 throw new RuntimeException(e);
1249 } catch(IOException e) {
1252 return advisor.getRoot();
1254 } catch (Throwable t) {
1255 Logger.defaultLogError("Unexpected exception while importing diagram template.", t);
1263 public static Collection<Variable> getMappedVariables(ReadGraph graph, Variable source) throws DatabaseException {
1265 ArrayList<Variable> result = new ArrayList<Variable>();
1266 Resource represents = source.getPossibleRepresents(graph);
1267 if(represents == null) return Collections.emptyList();
1268 ModelingResources MOD = ModelingResources.getInstance(graph);
1269 for(Resource r : getElementCorrespondendences(graph, represents)) {
1270 result.add(Variables.getVariable(graph, r));
1272 for(Resource r : graph.getObjects(represents, MOD.ComponentToElement)) {
1273 result.add(Variables.getVariable(graph, r));
1275 for(Resource r : graph.getObjects(represents, MOD.DiagramToComposite)) {
1276 result.add(Variables.getVariable(graph, r));
1278 for(Resource r : graph.getObjects(represents, MOD.CompositeToDiagram)) {
1279 result.add(Variables.getVariable(graph, r));
1285 public static Resource getPossibleModel(ReadGraph graph, Resource resource) throws DatabaseException {
1287 PossibleModel pm = new PossibleModel(resource);
1288 Resource model = pm.perform(graph);
1292 public static Resource possibleIndexRoot(ReadGraph graph, Resource resource) throws DatabaseException {
1293 return graph.syncRequest(new PossibleIndexRoot(resource));
1296 public static Object getMonitorValue(StructuralComponent _variable, ReadGraph graph, String path) throws DatabaseException {
1297 Variable variable = ((VariableStructuralContext)_variable).variable;
1298 Variable var = variable.browse(graph, path);
1299 return var.getValue(graph);
1302 public static void createSharedOntologyWithUI(ReadGraph graph, Variable variable, Resource baseType) throws DatabaseException {
1303 createSharedOntologyWithUI(graph, baseType);
1306 public static void createSharedOntologyWithUI(ReadGraph graph, Resource baseType) throws DatabaseException {
1308 // Resource indexRoot_ = variable.getPossibleRepresents(graph);
1309 // if(indexRoot_ == null) return;
1311 final Map<Resource, Pair<String,ImageDescriptor>> map = new HashMap<Resource, Pair<String,ImageDescriptor>>();
1313 Layer0 L0 = Layer0.getInstance(graph);
1314 SimulationResource SIMU = SimulationResource.getInstance(graph);
1315 Instances query = graph.adapt(L0.IndexRootType, Instances.class);
1316 for(Resource ontology : Layer0Utils.listOntologies(graph)) {
1317 for(Resource type : query.find(graph, ontology)) {
1318 if(graph.isInheritedFrom(type, SIMU.Model)) continue;
1319 if(graph.hasStatement(type, L0.Abstract)) continue;
1320 if(!graph.isInheritedFrom(type, baseType)) continue;
1321 String name = graph.getPossibleRelatedValue(type, L0.HasLabel, Bindings.STRING);
1322 if(name == null) name = graph.getRelatedValue(type, L0.HasName, Bindings.STRING);
1323 map.put(type, new Pair<String,ImageDescriptor>(name, null));
1327 Display.getDefault().asyncExec(new Runnable() {
1330 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1331 CreateSharedOntologyDialog page = new CreateSharedOntologyDialog(shell, map, "Select type and name of new shared library");
1332 if (page.open() == Window.OK) {
1333 Object[] result = page.getResult();
1334 if (result != null && result.length == 1) {
1335 final Resource res = (Resource)result[0];
1336 final String name = "http://" + page.getName();
1337 Simantics.getSession().asyncRequest(new WriteRequest() {
1340 public void perform(WriteGraph graph) throws DatabaseException {
1341 graph.markUndoPoint();
1342 Resource target = Simantics.applySCL("Simantics/SharedOntologies", "createSharedOntology", graph, name+"@A", res);
1344 ProjectResource PROJ = ProjectResource.getInstance(graph);
1345 Layer0 L0 = Layer0.getInstance(graph);
1346 for(Resource dep : graph.getObjects(Simantics.getProjectResource(), L0.IsLinkedTo)) {
1347 if(graph.isInstanceOf(dep, PROJ.NamespaceRequirement)) {
1348 for(Resource req : graph.getObjects(dep, PROJ.RequiresNamespace)) {
1349 String uri = graph.getPossibleValue(req, Bindings.STRING);
1351 Resource ns = graph.getResource(uri);
1353 graph.claim(target, L0.IsLinkedTo, null, ns);
1370 public static void unlinkSharedOntologyWithUI(ReadGraph graph, Variable variable, final List<Resource> libraries) throws DatabaseException {
1372 final Resource indexRoot = variable.getPossibleRepresents(graph);
1373 if(indexRoot == null) return;
1375 StructuralResource2 STR = StructuralResource2.getInstance(graph);
1377 final List<String> instances = new ArrayList<String>();
1379 DiagramResource DIA = DiagramResource.getInstance(graph);
1381 for(Resource library : libraries) {
1382 for(Resource type : ModelingUtils.searchByTypeShallow(graph, library, STR.ComponentType)) {
1383 for(Resource instance : ModelingUtils.searchByTypeShallow(graph, indexRoot, type)) {
1385 if(graph.isInstanceOf(instance, DIA.Element)) continue;
1386 String name = Versions.getStandardPathNameString(graph, instance);
1387 instances.add(name);
1392 if(instances.isEmpty()) {
1393 graph.getSession().asyncRequest(new WriteRequest() {
1396 public void perform(WriteGraph graph) throws DatabaseException {
1397 Layer0 L0 = Layer0.getInstance(graph);
1398 for(Resource library : libraries)
1399 graph.deny(indexRoot, L0.IsLinkedTo, library);
1406 PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
1410 if (!PlatformUI.isWorkbenchRunning())
1413 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1414 ListDialog<String> dialog = new ListDialog<String>(
1417 "Cannot unlink selected libraries",
1418 "Libraries cannot be unlinked since the following instances are referring to them.") {
1420 protected void createButtonsForButtonBar(Composite parent) {
1421 createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,true);
1425 int result = dialog.open();
1426 if (result != Dialog.OK)
1434 public static MigratedImportResult importSharedOntologyWithResult(String fileName) throws Exception {
1436 DataContainer dc = DataContainers.readFile(new File(fileName));
1437 TransferableGraph1 tg = (TransferableGraph1)dc.content.getValue(TransferableGraph1.BINDING);
1438 Variant draftStatus = dc.metadata.get(DraftStatusBean.EXTENSION_KEY);
1439 return MigrationUtils.importSharedOntology(Simantics.getSession(), tg, draftStatus == null);
1440 } catch (Exception e) {
1441 Logger.defaultLogError(e);
1446 public static void importSharedOntology(String fileName) throws Exception {
1447 importSharedOntologyWithResult(fileName);
1450 public static List<Resource> importSharedOntology2(String fileName) throws Exception {
1451 MigratedImportResult result = importSharedOntologyWithResult(fileName);
1452 return new ArrayList<Resource>(result.roots);
1455 public static void importSharedOntologyWithUI(ReadGraph graph, final Variable variable) throws DatabaseException {
1457 Display.getDefault().asyncExec(new Runnable() {
1461 IStructuredSelection sel = new StructuredSelection(variable);
1462 openWizard(Display.getCurrent(), sel, "org.simantics.modeling.ui.sharedOntologyImportWizard");
1469 public static class LibraryInfo implements Comparable<LibraryInfo> {
1470 public NamedResource library;
1471 public DraftStatusBean draft;
1472 public LibraryInfo(String name, Resource r, DraftStatusBean draft) {
1473 library = new NamedResource(name, r);
1477 public int compareTo(LibraryInfo o) {
1478 return library.compareTo(o.library);
1481 public int hashCode() {
1482 return library.hashCode();
1485 public boolean equals(Object object) {
1488 else if (object == null)
1490 else if (!(object instanceof LibraryInfo))
1492 LibraryInfo info = (LibraryInfo)object;
1493 return info.library.equals(library);
1498 public static void exportSharedOntologyWithUI(final Resource sharedOntology) {
1500 Display.getDefault().asyncExec(new Runnable() {
1504 HintContext hc = new HintContext();
1505 hc.setHint(SelectionHints.KEY_MAIN, sharedOntology);
1506 IStructuredSelection sel = new StructuredSelection(hc);
1507 openWizard(Display.getCurrent(), sel, "org.simantics.modeling.ui.sharedOntologyExportWizard");
1514 public static TransferableGraph1 exportSharedOntology(IProgressMonitor monitor, RequestProcessor processor, File location, String format, int version, final LibraryInfo info) throws DatabaseException, IOException {
1516 if(monitor == null) monitor = new NullProgressMonitor();
1518 // TODO: figure out a way to make the TG go directly into a file
1519 // instead of having it all in memory at once.
1521 monitor.beginTask("Exporting shared library...", 100);
1522 SimanticsClipboard clipboard = processor.syncRequest(new Read<SimanticsClipboard>() {
1524 public SimanticsClipboard perform(ReadGraph graph) throws DatabaseException {
1525 CopyHandler ch = graph.adapt(info.library.getResource(), CopyHandler.class);
1526 SimanticsClipboardImpl clipboard = new SimanticsClipboardImpl();
1527 ch.copyToClipboard(graph, clipboard);
1532 TreeMap<String,Variant> metadata = getExportMetadata();
1533 DraftStatusBean draft = info.draft;
1535 metadata.put(DraftStatusBean.EXTENSION_KEY, new Variant(DraftStatusBean.BINDING ,draft));
1538 for (Set<Representation> object : clipboard.getContents()) {
1540 TransferableGraph1 tg = ClipboardUtils.accept(processor, object, SimanticsKeys.KEY_TRANSFERABLE_GRAPH);
1543 Variant edb = tg.extensions.get(ExternalDownloadBean.EXTENSION_KEY);
1545 metadata.put(ExternalDownloadBean.EXTENSION_KEY, edb);
1548 if(location != null) {
1549 monitor.setTaskName("Writing transferable graph...");
1550 DataContainers.writeFile(location, new DataContainer(
1552 metadata, new Variant(TransferableGraph1.BINDING, tg)));
1560 throw new DatabaseException("Failed to export");
1564 public static TreeMap<String, Variant> getExportMetadata() {
1566 TreeMap<String,Variant> metadata = new TreeMap<String,Variant>();
1567 metadata.put("date", Variant.ofInstance(DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date())));
1568 metadata.put("author", Variant.ofInstance(System.getProperty("user.name", "")));
1574 public static void createNewVersionWithoutUI(WriteGraph graph, Resource resource) throws DatabaseException {
1575 VersionInfo info = graph.syncRequest(new VersionInfoRequest(resource));
1576 int currentVersion = Integer.parseInt(info.version);
1577 String result = Integer.toString(currentVersion + 1);
1578 createNewVersion(graph, resource, info, result);
1581 public static void createNewVersionWithUI(ReadGraph graph, final Resource resource) throws DatabaseException {
1583 final VersionInfo info = graph.syncRequest(new VersionInfoRequest(resource));
1585 Display.getDefault().asyncExec(new Runnable() {
1588 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1589 CreateVersionDialog dialog = new CreateVersionDialog(shell, info);
1590 if (dialog.open() == Window.OK) {
1591 final String result = dialog.getResult();
1592 Simantics.getSession().asyncRequest(new WriteRequest() {
1594 public void perform(WriteGraph graph) throws DatabaseException {
1595 createNewVersion(graph, resource, info, result);
1604 public static void createNewVersion(WriteGraph graph, Resource resource, final VersionInfo info, final String result) throws DatabaseException {
1605 graph.markUndoPoint();
1606 Layer0 L0 = Layer0.getInstance(graph);
1607 Resource parent = graph.getPossibleObject(resource, L0.PartOf);
1608 if(parent == null) return;
1609 final String parentURI = graph.getPossibleURI(parent);
1610 if(parentURI == null) return;
1611 Layer0Utils.copyTo(graph, parent, resource, new PasteEventHandler() {
1614 public void postProcess(WriteGraph graph, Resource root) throws DatabaseException {
1615 Layer0 L0 = Layer0.getInstance(graph);
1616 graph.deny(root, L0.Entity_published);
1620 public IImportAdvisor2 createAdvisor(ReadGraph graph, ImportAdvisorFactory factory, Resource target) throws DatabaseException {
1621 Map<String,Object> context = new HashMap<String,Object>();
1622 String base = parentURI + "/" + URIStringUtils.escape( info.baseName ) + "@";
1623 Map<String,String> renameMap = new HashMap<String,String>();
1624 renameMap.put(base + info.version, base + result);
1625 renameMap.put(info.baseName + "@" + info.version, info.baseName + "@" + result);
1626 context.put(ImportAdvisors.RENAME_MAP, renameMap);
1627 return factory.create(graph, target, context);
1631 Layer0Utils.addCommentMetadata(graph, "Created new version of " + info.baseName);
1634 public static boolean isUserComponent(ReadGraph graph, Resource type) throws DatabaseException {
1635 StructuralResource2 STR = StructuralResource2.getInstance(graph);
1636 if(graph.isInstanceOf(type, STR.ProceduralComponentType)) return true;
1637 else if (graph.hasStatement(type, STR.IsDefinedBy)) return true;
1641 public static void publishComponentTypeWithUI(WriteGraph graph, final Resource componentType) throws DatabaseException {
1643 Layer0 L0 = Layer0.getInstance(graph);
1644 StructuralResource2 STR = StructuralResource2.getInstance(graph);
1645 Resource composite = graph.getPossibleObject(componentType, STR.IsDefinedBy);
1646 final List<String> instances = new ArrayList<String>();
1647 if(composite != null) {
1648 for(Resource component : graph.syncRequest(new ObjectsWithType(composite, L0.ConsistsOf, STR.Component))) {
1649 Resource type = graph.getPossibleType(component, STR.Component);
1650 if(type != null && isUserComponent(graph, type)) {
1651 if(!Layer0Utils.isPublished(graph, type)) instances.add(Versions.getStandardPathNameString(graph, component));
1656 if(instances.isEmpty()) {
1657 graph.getSession().asyncRequest(new WriteRequest() {
1660 public void perform(WriteGraph graph) throws DatabaseException {
1661 graph.markUndoPoint();
1662 publish(graph, componentType);
1669 PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
1673 if (!PlatformUI.isWorkbenchRunning())
1676 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1677 ListDialog<String> dialog = new ListDialog<String>(
1680 "Cannot publish user component",
1681 "The following instances are referring to unpublished user components.") {
1683 protected void createButtonsForButtonBar(Composite parent) {
1684 createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,true);
1688 int result = dialog.open();
1689 if (result != Dialog.OK)
1697 public static void publishSharedOntologyWithUI(WriteGraph graph, final Resource sharedOntology) throws DatabaseException {
1699 Layer0 L0 = Layer0.getInstance(graph);
1700 DiagramResource DIA = DiagramResource.getInstance(graph);
1701 StructuralResource2 STR = StructuralResource2.getInstance(graph);
1702 final List<String> instances = new ArrayList<String>();
1703 for(Resource type : searchByTypeShallow(graph, sharedOntology, STR.ComponentType)) {
1705 if(graph.isInheritedFrom(type, DIA.Element)) continue;
1706 if(!Layer0Utils.isPublished(graph, type)) instances.add(Versions.getStandardPathNameString(graph, type));
1708 for(Resource dep : graph.syncRequest(new ObjectsWithType(sharedOntology, L0.IsLinkedTo, L0.SharedOntology))) {
1709 if(!Layer0Utils.isPublished(graph, dep)) instances.add(Versions.getStandardPathNameString(graph, dep));
1712 if(instances.isEmpty()) {
1713 graph.getSession().asyncRequest(new WriteRequest() {
1716 public void perform(WriteGraph graph) throws DatabaseException {
1717 graph.markUndoPoint();
1718 publish(graph, sharedOntology);
1725 PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
1729 if (!PlatformUI.isWorkbenchRunning())
1732 Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
1733 ListDialog<String> dialog = new ListDialog<String>(
1736 "Cannot publish shared library",
1737 "The following dependencies are unpublished.") {
1739 protected void createButtonsForButtonBar(Composite parent) {
1740 createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,true);
1744 int result = dialog.open();
1745 if (result != Dialog.OK)
1753 public static Resource createSCLModuleDefault(WriteGraph graph, Resource target) throws DatabaseException {
1754 String name = NameUtils.findFreshEscapedName(graph, "SCLModule", target);
1755 return createSCLModule(graph, target, name);
1758 public static Resource createSCLModule(WriteGraph graph, Resource target, String name) throws DatabaseException {
1759 graph.markUndoPoint();
1760 Layer0 L0 = Layer0.getInstance(graph);
1761 Resource sclModule = GraphUtils.create2(graph, L0.SCLModule,
1764 L0.SCLModule_definition, "");
1765 Layer0Utils.addCommentMetadata(graph, "Created SCL Module " + name + " " + sclModule.toString());
1769 public static Resource setSCLModuleDefinition(WriteGraph graph, Resource module, String definition) throws DatabaseException {
1770 graph.markUndoPoint();
1771 Layer0 L0 = Layer0.getInstance(graph);
1772 graph.claimLiteral(module, L0.SCLModule_definition, definition, Bindings.STRING);
1773 Layer0Utils.addCommentMetadata(graph, "Set SCL module " + module + " definition.");
1777 public static Resource createSCLScriptDefault(WriteGraph graph, Resource target) throws DatabaseException {
1778 String name = NameUtils.findFreshEscapedName(graph, "SCLScript", target);
1779 return createSCLScript(graph, target, name);
1782 public static Resource createSCLScript(WriteGraph graph, Resource target, String name) throws DatabaseException {
1783 graph.markUndoPoint();
1784 Layer0 L0 = Layer0.getInstance(graph);
1785 Resource sclModule = GraphUtils.create2(graph, L0.SCLScript,
1788 L0.SCLScript_definition, "");
1789 Layer0Utils.addCommentMetadata(graph, "Created SCL Script " + name + " " + sclModule.toString());
1793 public static Resource setSCLScriptDefinition(WriteGraph graph, Resource script, String definition) throws DatabaseException {
1794 graph.markUndoPoint();
1795 Layer0 L0 = Layer0.getInstance(graph);
1796 graph.claimLiteral(script, L0.SCLScript_definition, definition, Bindings.STRING);
1797 Layer0Utils.addCommentMetadata(graph, "Set SCL script " + script + " definition.");
1801 public static Resource createPGraphDefault(WriteGraph graph, Resource target) throws DatabaseException {
1802 String name = NameUtils.findFreshEscapedName(graph, "Ontology Definition File", target);
1803 return createPGraph(graph, target, name);
1806 public static Resource createPGraph(WriteGraph graph, Resource target, String name) throws DatabaseException {
1807 graph.markUndoPoint();
1808 Layer0 L0 = Layer0.getInstance(graph);
1809 Resource file = GraphUtils.create2(graph, L0.PGraph,
1812 L0.PGraph_definition, "");
1813 Layer0Utils.addCommentMetadata(graph, "Created Ontology Definition File " + name + " " + file.toString());
1817 public static Resource setPGraphDefinition(WriteGraph graph, Resource pgraph, String definition) throws DatabaseException {
1818 graph.markUndoPoint();
1819 Layer0 L0 = Layer0.getInstance(graph);
1820 graph.claimLiteral(pgraph, L0.PGraph_definition, definition, Bindings.STRING);
1821 Layer0Utils.addCommentMetadata(graph, "Set PGraph " + pgraph + " definition.");
1825 public static void publish(WriteGraph graph, Resource target) throws DatabaseException {
1826 Layer0 L0 = Layer0.getInstance(graph);
1827 graph.claimLiteral(target, L0.Entity_published, true, Bindings.BOOLEAN);
1828 Layer0Utils.addCommentMetadata(graph, "Published " + graph.getPossibleRelatedValue2(target, L0.HasName, Bindings.STRING) + " " + target.toString());
1831 public static boolean isLinkedToDeep(ReadGraph graph, Resource r1, Resource r2) throws DatabaseException {
1832 return graph.syncRequest(new IsLinkedTo(r1, r2));
1835 public static void openWizard(Display display, IStructuredSelection selection, String id) {
1836 // First see if this is a "new wizard".
1837 IWizardDescriptor descriptor = PlatformUI.getWorkbench()
1838 .getNewWizardRegistry().findWizard(id);
1839 // If not check if it is an "import wizard".
1840 if (descriptor == null) {
1841 descriptor = PlatformUI.getWorkbench().getImportWizardRegistry()
1844 // Or maybe an export wizard
1845 if (descriptor == null) {
1846 descriptor = PlatformUI.getWorkbench().getExportWizardRegistry()
1850 // Then if we have a wizard, open it.
1851 if (descriptor != null) {
1852 IWorkbenchWizard wizard = descriptor.createWizard();
1853 wizard.init(PlatformUI.getWorkbench(), selection);
1854 WizardDialog wd = new WizardDialog(display.getActiveShell(), wizard);
1855 wd.setTitle(wizard.getWindowTitle());
1858 } catch (CoreException e) {
1859 e.printStackTrace();
1863 public static String withinEpsilon(double value, double reference, double epsilon) {
1864 if(Math.abs(value-reference) < epsilon) return "True";
1865 else return "Not within epsilon value=" + value + ", reference=" + reference + " , epsilon=" + epsilon;
1868 public static boolean needsIdentifier(ReadGraph graph, Resource r) throws DatabaseException {
1869 Layer0 L0 = Layer0.getInstance(graph);
1870 Collection<Resource> types = graph.getPrincipalTypes(r);
1871 for(Resource type : types)
1872 if(graph.syncRequest(new IsInstanceOf(type, L0.TypeWithIdentifier), TransientCacheAsyncListener.<Boolean>instance()))
1877 public static boolean needsModificationInfo(ReadGraph graph, Resource r) throws DatabaseException {
1878 ModelingResources MOD = ModelingResources.getInstance(graph);
1879 Collection<Resource> types = graph.getPrincipalTypes(r);
1880 for(Resource type : types)
1881 if(graph.syncRequest(new IsInstanceOf(type, MOD.TypeWithChangeInformation), TransientCacheAsyncListener.<Boolean>instance()))
1886 public static void attachCreationInformation(IProgressMonitor monitor, WriteGraph graph, Resource model) throws DatabaseException {
1888 if(monitor == null) monitor = new NullProgressMonitor();
1890 final String author = System.getProperty("user.name", "");
1891 final long time = System.currentTimeMillis();
1893 monitor.setTaskName("Attach creation information");
1895 ModelingResources MOD = ModelingResources.getInstance(graph);
1896 Collection<Resource> rs = ModelingUtils.searchByType(graph, model, MOD.TypeWithChangeInformation);
1897 Collection<Resource> supers = ModelingUtils.getMostUnspecificTypes(graph, rs);
1899 CollectionSupport cs = graph.getService(CollectionSupport.class);
1900 Collection<Resource> set = cs.createSet();
1901 for(Resource type : supers) {
1902 set.addAll(ModelingUtils.searchByTypeShallow(graph, model, type));
1904 Collection<Resource> instances = Layer0Utils.sortByCluster(graph, set);
1906 int pc = instances.size() / 100;
1910 for(Resource instance : instances) {
1911 ChangeInformation info = graph.getPossibleRelatedValue(instance, MOD.changeInformation, ChangeInformation.BINDING);
1913 info = new ChangeInformation();
1914 info.createdAt = time;
1915 info.createdBy = author;
1916 info.modifiedAt = time;
1917 info.modifiedBy = author;
1918 graph.claimLiteral(instance, MOD.changeInformation, MOD.changeInformation_Inverse, MOD.ChangeInformation, info, ChangeInformation.BINDING);
1923 Double d = (100.0*done)/instances.size();
1924 monitor.setTaskName("Attach creation information " + d.intValue() + "%");
1929 monitor.setTaskName("Attach creation information - commit");
1933 public static class DiagramComponentInfo {
1935 private static String CHILD_PREFIX = "child:";
1937 final private String compositePathAndName;
1938 final private String componentName;
1939 final private GUID guid;
1941 public DiagramComponentInfo(String compositePathAndName, String componentName, GUID guid) {
1942 this.compositePathAndName = compositePathAndName;
1943 this.componentName = componentName;
1947 public static boolean isDiagramComponent(String tgName) {
1948 return tgName.startsWith(CHILD_PREFIX);
1951 public String getTGName(CompositeInfo info) {
1952 return CHILD_PREFIX + info.getOriginalPath() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + info.getEscapedName() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + getEscapedComponentName() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + guid.indexString();
1955 public boolean existsGUID(ReadGraph graph, Resource indexRoot) throws DatabaseException {
1956 Collection<Resource> res = ModelingUtils.searchByGUID(graph, indexRoot, guid);
1957 return !res.isEmpty();
1960 public static DiagramComponentInfo fromResource(ReadGraph graph, CompositeInfo info, Resource resource) throws DatabaseException {
1961 Layer0 L0 = Layer0.getInstance(graph);
1962 GUID childId = graph.getRelatedValue(resource, L0.identifier, GUID.BINDING);
1963 String childName = graph.getRelatedValue(resource, L0.HasName, Bindings.STRING);
1964 return new DiagramComponentInfo(info.getStateKey(), URIStringUtils.escape(childName), childId);
1967 public GUID getGUID() {
1971 public String getEscapedCompositePathAndName() {
1972 return compositePathAndName;
1975 public String getEscapedComponentName() {
1976 return componentName;
1979 public String getUnescapedComponentName() {
1980 return URIStringUtils.unescape(getEscapedComponentName());
1983 // "child:path#compositeName#componentName#guid"
1984 public static DiagramComponentInfo parse(String tgName) {
1986 String name = tgName.substring(CHILD_PREFIX.length());
1987 String compositePathAndName = "";
1988 String moduleName = name;
1989 GUID guid = GUID.invalid();
1990 int lastHash = name.lastIndexOf(ModelingUtils.COMPOSITE_SEPARATOR_CHAR);
1992 String first = name.substring(0, lastHash);
1993 String second = name.substring(lastHash+1);
1994 lastHash = first.lastIndexOf(ModelingUtils.COMPOSITE_SEPARATOR_CHAR);
1996 compositePathAndName = first.substring(0, lastHash);
1997 moduleName = first.substring(lastHash+1);
1998 guid = GUID.parseIndexString(second);
2000 compositePathAndName = first;
2001 moduleName = second;
2004 return new DiagramComponentInfo(compositePathAndName, moduleName, guid);
2010 public int hashCode() {
2011 final int prime = 31;
2013 result = prime * result + ((compositePathAndName == null) ? 0 : compositePathAndName.hashCode());
2014 result = prime * result + ((componentName == null) ? 0 : componentName.hashCode());
2019 public boolean equals(Object obj) {
2024 if (getClass() != obj.getClass())
2026 DiagramComponentInfo other = (DiagramComponentInfo) obj;
2027 if (compositePathAndName == null) {
2028 if (other.compositePathAndName != null)
2030 } else if (!compositePathAndName.equals(other.compositePathAndName))
2032 if (componentName == null) {
2033 if (other.componentName != null)
2035 } else if (!componentName.equals(other.componentName))
2042 public static class CompositeInfo {
2044 public static String COMPOSITE_PREFIX = "composite:";
2046 final private boolean useGuids;
2047 final private boolean applyPaths;
2048 final private String path;
2049 final private String name;
2050 final private GUID guid;
2052 private CompositeInfo(boolean useGuids, boolean applyPaths, String path, String name, GUID guid) {
2053 this.useGuids = useGuids;
2054 this.applyPaths = applyPaths;
2061 public String toString() {
2062 return "CompositeInfo[useGuids=" + useGuids + ", applyPaths=" + applyPaths + ", path=" + path + ", name=" + name + ", guid=" + guid.indexString() + "]";
2065 public static boolean isComposite(String tgName) {
2066 return tgName.startsWith(COMPOSITE_PREFIX);
2069 public String getTGName() {
2070 return COMPOSITE_PREFIX + getOriginalPath() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + getEscapedName() + ModelingUtils.COMPOSITE_SEPARATOR_CHAR + guid.indexString();
2073 public boolean existsGUID(ReadGraph graph, Resource indexRoot) throws DatabaseException {
2074 Collection<Resource> res = ModelingUtils.searchByGUID(graph, indexRoot, guid);
2075 return !res.isEmpty();
2078 public static CompositeInfo fromResource(ReadGraph graph, Resource resource) throws DatabaseException {
2080 Layer0 L0 = Layer0.getInstance(graph);
2081 GUID rootId = graph.getRelatedValue(resource, L0.identifier, GUID.BINDING);
2082 String rootName = graph.getRelatedValue(resource, L0.HasName, Bindings.STRING);
2083 String escapedRootName = URIStringUtils.escape(rootName);
2084 String escapedPath = ModelingUtils.getDiagramCompositePath(graph, resource);
2085 return new CompositeInfo(true, true, escapedPath, escapedRootName, rootId);
2089 public static CompositeInfo parse(String tgName) {
2090 return parse(tgName, true, true);
2094 * Index 0 is root-relative folder path separated with '/' or null if target-relative positioning is used
2095 * Index 1 is diagram name
2097 public static CompositeInfo parse(String tgName, boolean applyPaths, boolean useGuids) {
2098 if(!tgName.startsWith(COMPOSITE_PREFIX)) return null;
2099 tgName = tgName.substring(COMPOSITE_PREFIX.length());
2100 if(!tgName.contains(COMPOSITE_SEPARATOR)) {
2101 if(useGuids) throw new IllegalStateException("GUID identifiers were not found for diagrams.");
2102 return new CompositeInfo(useGuids, applyPaths, null, tgName, null);
2104 String[] parts = tgName.split(COMPOSITE_SEPARATOR);
2105 if(parts.length == 2) {
2106 String name = parts[1];
2107 String path = applyPaths ? parts[0] : null;
2108 if(useGuids) throw new IllegalStateException("GUID identifiers were not found for diagrams.");
2109 return new CompositeInfo(useGuids, applyPaths, path, name, null);
2110 } else if(parts.length == 3) {
2111 String path = parts[0];
2112 String name = parts[1];
2113 GUID guid = GUID.parseIndexString(parts[2]);
2114 return new CompositeInfo(useGuids, applyPaths, path, name, guid);
2120 public GUID getGUID() {
2124 public String getEscapedName() {
2128 public String getUnescapedName() {
2129 return URIStringUtils.unescape(name);
2132 public String getOriginalPath() {
2136 public String getFinalPath() {
2137 if(applyPaths) return path;
2141 public CompositeInfo renamed(String newName) {
2142 return new CompositeInfo(useGuids, applyPaths, path, newName, guid);
2145 public String getStateKey() {
2146 return path + "#" + getEscapedName();
2149 private Resource getFromFolder(ReadGraph graph, Resource target) throws DatabaseException {
2150 Resource diagram = Layer0Utils.getPossibleChild(graph, target, URIStringUtils.unescape(name));
2151 if(diagram == null) return null;
2152 StructuralResource2 STR = StructuralResource2.getInstance(graph);
2153 return graph.isInstanceOf(diagram, STR.Composite) ? diagram : null;
2156 public Resource resolve(ReadGraph graph, Resource target) throws DatabaseException {
2158 if(useGuids && guid != null) {
2159 Resource indexRoot = graph.syncRequest(new IndexRoot(target));
2160 Collection<Resource> queryResult = searchByGUID(graph, indexRoot, guid);
2161 if(queryResult.size() == 1) {
2162 Resource composite = queryResult.iterator().next();
2163 StructuralResource2 STR = StructuralResource2.getInstance(graph);
2164 if(!graph.isInstanceOf(composite, STR.Composite)) return null;
2170 Resource folder = resolveFolder(graph, target);
2171 if(folder == null) return null;
2172 return getFromFolder(graph, folder);
2174 return getFromFolder(graph, target);
2179 public Resource resolveFolder(ReadGraph graph, Resource target) throws DatabaseException {
2181 String path = getFinalPath();
2182 if(path == null) return target;
2184 Resource folder = graph.syncRequest(new Configuration(target));
2185 String[] segments = path.split("/");
2186 for(int i=0;i<segments.length;i++) {
2187 if(segments[i].isEmpty()) continue;
2188 folder = Layer0Utils.getPossibleChild(graph, folder, URIStringUtils.unescape(segments[i]));
2189 if(folder == null) return null;
2198 public int hashCode() {
2200 if(useGuids) return guid.hashCode();
2202 final int prime = 31;
2203 int result = name.hashCode();
2204 result = prime * result + ((path == null) ? 0 : path.hashCode());
2210 public boolean equals(Object obj) {
2216 if (getClass() != obj.getClass())
2219 CompositeInfo other = (CompositeInfo) obj;
2221 if(useGuids) return guid.equals(other.guid);
2223 if (!name.equals(other.name))
2227 if (!path.equals(other.path))
2236 public static char COMPOSITE_SEPARATOR_CHAR = '#';
2237 public static String COMPOSITE_SEPARATOR = String.valueOf(COMPOSITE_SEPARATOR_CHAR);
2239 public static CompositeInfo parseCompositeNameFromRoot(Root root, boolean applyPaths, boolean useGuids) {
2240 return CompositeInfo.parse(root.name, applyPaths, useGuids);
2243 public static CompositeInfo parseCompositeNameFromRoot(Identity root, boolean applyPaths, boolean useGuids) {
2244 String coded = TransferableGraphUtils.getName(root);
2245 return CompositeInfo.parse(coded, applyPaths, useGuids);
2248 private static StringBuilder getDiagramCompositePathInternal(ReadGraph graph, Resource folder, StringBuilder builder) throws DatabaseException {
2249 SimulationResource SIMU = SimulationResource.getInstance(graph);
2250 Resource model = graph.getPossibleObject(folder, SIMU.IsConfigurationOf);
2251 if (model != null) return builder;
2253 Layer0 L0 = Layer0.getInstance(graph);
2254 String name = graph.getPossibleRelatedValue(folder, L0.HasName, Bindings.STRING);
2255 if (name == null) return null;
2256 Resource parent = graph.getPossibleObject(folder, L0.PartOf);
2257 if (parent == null) return null;
2259 StringBuilder sb = getDiagramCompositePathInternal(graph, parent, builder);
2260 if (sb == null) return null;
2261 if (sb.length() > 0)
2262 sb.append(URIStringUtils.NAMESPACE_PATH_SEPARATOR);
2263 sb.append( URIStringUtils.escape(name) );
2270 * @return diagram/folder path up until model configuration root with each
2271 * segment escaped using {@link URIStringUtils#escape(String)} and
2272 * {@value URIStringUtils#NAMESPACE_PATH_SEPARATOR} between each
2273 * segment or <code>null</code> if the specified diagram composite
2274 * is not part of any model configuration structure.
2275 * @throws DatabaseException
2277 public static String getDiagramCompositePath(ReadGraph graph, Resource diagram) throws DatabaseException {
2278 Layer0 L0 = Layer0.getInstance(graph);
2279 Resource parent = graph.getPossibleObject(diagram, L0.PartOf);
2280 if(parent == null) return null;
2281 StringBuilder sb = getDiagramCompositePathInternal(graph, parent, new StringBuilder());
2282 return sb != null ? sb.toString() : null;
2285 public static void exportModel(ReadGraph graph, Resource model, String fileName, String format, int version) throws DatabaseException {
2286 TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, model, true, false);
2287 exportModel(graph, conf, fileName, format, version);
2290 public static void exportModel(ReadGraph graph, TransferableGraphConfiguration2 conf, String fileName, String format, int version) throws DatabaseException {
2293 TransferableGraphSource s = graph.syncRequest(new ModelTransferableGraphSourceRequest(conf));
2294 TransferableGraphs.writeTransferableGraph(graph, format, version, s, new File(fileName));
2295 } catch (DatabaseException e) {
2297 } catch (Exception e) {
2298 throw new DatabaseException(e);
2303 public static TransferableGraph1 exportSharedOntology(ReadGraph graph, Resource library, String fileName, String format, int version) throws DatabaseException {
2305 Layer0 L0 = Layer0.getInstance(graph);
2306 String name = graph.getRelatedValue(library, L0.HasName, Bindings.STRING);
2308 DraftStatusBean draft = null;
2309 boolean published = Layer0Utils.isPublished(graph, library);
2310 if(!published) draft = new DraftStatusBean(new String[0]);
2312 LibraryInfo info = new LibraryInfo(name, library, draft);
2315 return exportSharedOntology(new NullProgressMonitor(), graph, fileName != null ? new File(fileName) : null, format, version, info);
2316 } catch (IOException e) {
2317 throw new DatabaseException(e);
2322 public static DraftStatusBean getDependencyDraftStatus(ReadGraph graph, Resource library) throws DatabaseException {
2323 Layer0 L0 = Layer0.getInstance(graph);
2324 List<String> drafts = new ArrayList<>();
2325 for (Resource shared : graph.syncRequest(new ObjectsWithType(library, L0.IsLinkedTo, L0.SharedOntology))) {
2326 boolean published = Layer0Utils.isPublished(graph, shared);
2328 drafts.add(graph.getURI(shared));
2330 return drafts.isEmpty() ? null : new DraftStatusBean(drafts);
2333 public static Set<Resource> getMostUnspecificTypes(final ReadGraph graph, Collection<Resource> types) throws DatabaseException {
2335 final Set<Resource> work = new HashSet<Resource>(types);
2336 for(Resource type : types) {
2337 Set<Resource> supers = graph.getSupertypes(type);
2338 if(!Collections.disjoint(supers, work)) work.remove(type);
2345 public static void rewriteGUIDS(WriteGraph graph, Resource root, boolean deep) throws DatabaseException {
2346 List<Resource> todo = new ArrayList<Resource>();
2348 Layer0 L0 = Layer0.getInstance(graph);
2349 while(!todo.isEmpty()) {
2350 Resource resource = todo.remove(todo.size()-1);
2351 Layer0Utils.claimNewIdentifier(graph, resource, false);
2353 todo.addAll(graph.getObjects(resource, L0.ConsistsOf));
2357 public static void createMissingGUIDs(IProgressMonitor monitor, WriteGraph graph, Collection<Resource> roots) throws DatabaseException {
2359 if(monitor == null) monitor = new NullProgressMonitor();
2361 Layer0 L0 = Layer0.getInstance(graph);
2363 // Allow this process to make 50k queries
2364 QueryMemoryWatcher memory = new QueryMemoryWatcher(graph, 50000);
2366 for(Resource root : roots) {
2368 boolean madeChanges = false;
2370 monitor.setTaskName("Creating missing GUID identifiers " + NameUtils.getSafeName(graph, root));
2371 Resource indexRoot = graph.syncRequest(new PossibleIndexRoot(root));
2372 for(Resource r : searchByTypeShallow(graph, indexRoot, L0.Entity)) {
2376 if(graph.isImmutable(r)) continue;
2378 if(!ModelingUtils.needsIdentifier(graph, r)) continue;
2380 GUID existing = graph.getPossibleRelatedValue(r, L0.identifier, GUID.BINDING);
2381 if(existing == null) {
2382 Layer0Utils.claimNewIdentifier(graph, r, true);
2389 ModelingUtils.deleteIndex(graph, root);
2396 public static boolean activateModel(WriteGraph graph, Resource model) throws DatabaseException {
2397 return graph.syncRequest(new ActivateModel(Simantics.getProjectResource(), model));
2400 public static File fileDialog(String title, List<Tuple> namesAndExtensions) {
2402 Display display = Display.getCurrent();
2403 Shell shell = display.getActiveShell();
2405 FileDialog dialog = new FileDialog(shell, SWT.OPEN);
2406 dialog.setText(title);
2408 String[] extensions = new String[namesAndExtensions.size()];
2409 String[] filterNames = new String[namesAndExtensions.size()];
2411 for(Tuple t : namesAndExtensions) {
2412 String filterName = (String)t.get(0);
2413 String extension = (String)t.get(1);
2414 filterNames[index] = filterName;
2415 extensions[index] = extension;
2419 dialog.setFilterExtensions(extensions);
2420 dialog.setFilterNames(filterNames);
2421 final String fileName = dialog.open();
2422 if (fileName == null) return null;
2424 return new File(fileName);
2428 public static Resource createLibrary(WriteGraph graph, Resource parent) throws DatabaseException {
2429 Layer0 l0 = Layer0.getInstance(graph);
2430 return createLibrary(graph, parent, NameUtils.findFreshName(graph, "Library", parent, l0.ConsistsOf));
2433 public static Resource createLibrary(WriteGraph graph, Resource parent, String name) throws DatabaseException {
2434 graph.markUndoPoint();
2435 Layer0 l0 = Layer0.getInstance(graph);
2437 Resource library = graph.newResource();
2438 graph.claim(library, l0.InstanceOf, null, l0.Library);
2439 graph.addLiteral(library, l0.HasName, l0.NameOf, l0.String, name, Bindings.STRING);
2440 graph.claim(library, l0.PartOf, parent);
2442 Layer0Utils.addCommentMetadata(graph, "Created new Library named " + name + ", resource " + library);