-/*******************************************************************************\r
- * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
- * in Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.workbench.internal;\r
-\r
-import java.lang.reflect.InvocationTargetException;\r
-import java.net.InetSocketAddress;\r
-import java.util.HashSet;\r
-import java.util.Set;\r
-\r
-import org.eclipse.core.runtime.IProgressMonitor;\r
-import org.eclipse.core.runtime.IStatus;\r
-import org.eclipse.core.runtime.MultiStatus;\r
-import org.eclipse.core.runtime.Status;\r
-import org.eclipse.jface.action.IAction;\r
-import org.eclipse.jface.dialogs.ProgressMonitorDialog;\r
-import org.eclipse.jface.operation.IRunnableWithProgress;\r
-import org.eclipse.swt.widgets.Display;\r
-import org.eclipse.ui.IWorkbenchWindow;\r
-import org.simantics.application.arguments.ApplicationUtils;\r
-import org.simantics.application.arguments.IArguments;\r
-import org.simantics.application.arguments.SimanticsArguments;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.Session;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.SimanticsKeys;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.db.management.discovery.InetAddressUtils;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.project.IProject;\r
-import org.simantics.project.ProjectKeys;\r
-import org.simantics.project.ProjectUtil;\r
-import org.simantics.project.exception.ProjectException;\r
-import org.simantics.project.utils.GraphPathUtils;\r
-import org.simantics.ui.db.SessionData;\r
-import org.simantics.ui.db.SessionRestoreUtils;\r
-import org.simantics.ui.internal.Activator;\r
-import org.simantics.ui.workbench.action.ChooseActionRequest;\r
-import org.simantics.utils.ui.ExceptionUtils;\r
-import org.simantics.utils.ui.action.IPriorityAction;\r
-import org.simantics.utils.ui.dialogs.ShowMessage;\r
-\r
-public class Initializer implements Runnable {\r
-\r
- private final IArguments args;\r
-\r
-// private String defaultPerspectiveId;\r
-\r
- /**\r
- * This will be !ok if something fatal for startup has happened.\r
- */\r
- private final IStatus status = Status.OK_STATUS;\r
-\r
- private ISessionContext ctx;\r
-\r
- private IProject project;\r
-\r
- private Resource model;\r
-\r
- private final IWorkbenchWindow window;\r
-\r
-// private Resource experiment;\r
-\r
-\r
- public Initializer(IArguments args, IWorkbenchWindow window) {\r
- this.args = args;\r
- this.window = window;\r
-// this.defaultPerspectiveId = defaultPerspectiveId;\r
- }\r
-\r
- @Override\r
- public void run() {\r
- try {\r
- perform();\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- } catch (ProjectException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
-\r
- public IStatus getStatus() {\r
- return status;\r
- }\r
-\r
- public ISessionContext getSessionContext() {\r
- return ctx;\r
- }\r
-\r
- public IProject getProject() {\r
- return project;\r
- }\r
-\r
- public Resource getModel() {\r
- return model;\r
- }\r
-\r
- public boolean perform() throws DatabaseException, ProjectException {\r
- // Nothing further can be done if no server is specified\r
- if (!args.contains(SimanticsArguments.SERVER))\r
- return true;\r
-\r
- // Try to connect to designated server and project.\r
- // Use null local server location to indicate checkout\r
- String server = args.get(SimanticsArguments.SERVER);\r
- if(server.indexOf(':') == -1 && args.contains(SimanticsArguments.PORT)) {\r
- server = server+":"+args.get(SimanticsArguments.PORT);\r
- }\r
- InetSocketAddress serverAddress = InetAddressUtils.parseUnresolved(server);\r
- String[] projectPath = ApplicationUtils.decodePath(args.get(SimanticsArguments.PROJECT));\r
- final SessionData data = new SessionData(null, serverAddress, projectPath);\r
-\r
- final MultiStatus status = new MultiStatus(Activator.PLUGIN_ID, IStatus.OK, "Database session could not be initialized.", null);\r
- // final ProgressMonitorDialog dialog = new ProgressMonitorDialog(null);\r
-\r
- final ProgressMonitorDialog dialog = new ProgressMonitorDialog(null);\r
- try {\r
- dialog.run(false, true, new IRunnableWithProgress() {\r
- @Override\r
- public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {\r
- ctx = SessionRestoreUtils.restoreSession(status, monitor, data);\r
- //ctx = sessionResult;\r
- }\r
- });\r
- } catch (InvocationTargetException e) {\r
- ExceptionUtils.logAndShowError(e);\r
- } catch (InterruptedException e) {\r
- ExceptionUtils.logAndShowError(e);\r
- }\r
-\r
- //IDiscoveryModel model =\r
-\r
-\r
-// IDiscoveryData[] iData = ProjectPlugin.getWorkspace().getDiscoveryModel().getDataSources();\r
-// for(int i = 0; i < iData.length; i++) {\r
-// IDiscoveryData d = iData[i];\r
-// if(d.getLabel().equals(IWorkspaceConstants.DIRECT_SERVERS_LABEL)) {\r
-// ServerInfo serverInfo = new ServerInfo(d.getLabel(), serverAddress);\r
-// ServerData serverData = new ServerData(null, serverInfo, null);\r
-// IServerData[] iServerData = d.getServers();\r
-//\r
-// IServerData[] newServerData = new IServerData[iServerData.length+1];\r
-//\r
-// int y;\r
-// for(y = 0; y < iServerData.length; y++) {\r
-// newServerData[y] = iServerData[y];\r
-// }\r
-//\r
-// newServerData[y] = serverData;\r
-//\r
-// d.setServers(newServerData);\r
-// ProjectPlugin.getWorkspace().getDiscoveryModel().updateDataSource(d);\r
-// break;\r
-// }\r
-//\r
-// }\r
-\r
- //status = sessionResult.status;\r
- //if (!status.isOK()) {\r
- // return false;\r
- //}\r
-\r
- if (ctx == null) {\r
- // Its okay to start the workbench, it will just be reset as the\r
- // connection failed.\r
- return true;\r
- }\r
-\r
- // FIXME: COMPLETE HACK for simupedia\r
- // Add a discovery service to get in touch\r
- /*\r
- IDiscoveryModel discoveryModel = ProjectPlugin.getWorkspace().getDiscoveryModel();\r
- File discoveryFile = ProjectPlugin.getDefault().getStateLocation().append("simupedia-discovery.txt").toFile();\r
- FileWriter fw = null;\r
- try {\r
- // Overwrite the file.\r
- fw = new FileWriter(discoveryFile, false);\r
- String serverLine = String.format("'%s' %s\n", data.getAddress().getHostName(), server);\r
- fw.write(serverLine);\r
- } catch (IOException e) {\r
- e.printStackTrace();\r
- } finally {\r
- FileUtils.uncheckedClose(fw);\r
- }\r
- try {\r
- // Add a non-persistent simupedia discovery\r
- DiscoveryData d = new DiscoveryData(IDiscoveryType.REMOTE, "Simupedia", discoveryFile);\r
- discoveryModel.addDataSource(d);\r
- } catch (MalformedURLException e) {\r
- // Should never happen.\r
- throw new Error(e);\r
- }\r
- */\r
-\r
- // Initialize project\r
- if (args.contains(SimanticsArguments.NEW_PROJECT)) {\r
- throw new UnsupportedOperationException();\r
- //project = newProject(ctx);\r
- } else if (args.contains(SimanticsArguments.PROJECT)) {\r
- project = loadProject(ctx, projectPath);\r
- }\r
-\r
- // Only proceed with model and experiment loading if a project was\r
- // successfully created or loaded.\r
- if (project != null) {\r
- ctx.setHint(ProjectKeys.KEY_PROJECT, project);\r
- ctx.setHint(SimanticsKeys.KEY_PROJECT, project.get());\r
-\r
- // Load model\r
- if (args.contains(SimanticsArguments.NEW_MODEL)) {\r
- //model = newModel(ctx.getSession(), project);\r
- } else if (args.contains(SimanticsArguments.MODEL)) {\r
- String[] modelPath = ApplicationUtils.decodePath(args.get(SimanticsArguments.MODEL));\r
- model = findModel(ctx.getSession(), project, modelPath);\r
- }\r
-// if (model != null) {\r
-// findDiagram(ctx.getSession(), model, project);\r
-// }\r
-\r
- // TODO: load experiment\r
- if (args.contains(SimanticsArguments.EXPERIMENT)) {\r
- // String[] experimentPath = decodePath(args.get(ProConfArguments.EXPERIMENT));\r
- }\r
- }\r
-\r
- return true;\r
- }\r
-\r
- IProject loadProject(ISessionContext ctx, final String[] projectNamePath) throws DatabaseException, ProjectException {\r
-\r
- IProject project = ctx.getSession().syncRequest(new Read<IProject>() {\r
-\r
- @Override\r
- public IProject perform(ReadGraph graph) throws DatabaseException {\r
- Resource projects = graph.getResource("http://Projects");\r
- Resource[] path = GraphPathUtils.toResourcePath(graph, projects, projectNamePath, graph\r
- .getBuiltins().ConsistsOf);\r
- if (path.length == 0) {\r
- IllegalArgumentException e = new IllegalArgumentException("");\r
- ShowMessage.showError("Error loading the existing project", e.getMessage());\r
- throw new DatabaseException(e);\r
- }\r
- return ProjectUtil.loadProject(graph, path[path.length - 1]);\r
- }\r
-\r
- });\r
-\r
- project.activate();\r
-\r
- return project;\r
-\r
-// final GraphRequestWithResult<IProject> request = new GraphRequestWithResult<IProject>() {\r
-// @Override\r
-// public IProject performWithResult(Graph g) throws Exception {\r
-// }\r
-// };\r
-// ctx.getSession().syncRead(request);\r
-// if (request.getException() != null) {\r
-// ShowMessage.showError("Error loading the existing project", request.getException().getMessage());\r
-// return null;\r
-// }\r
-// return request.getResult();\r
- }\r
-\r
- Resource findModel(final Session session, final IProject project, final String[] modelPath) throws DatabaseException {\r
-\r
- return session.syncRequest(new Read<Resource>() {\r
-\r
- @Override\r
- public Resource perform(ReadGraph graph) throws DatabaseException {\r
- Resource[] path = GraphPathUtils.toResourcePath(graph, project.get(), modelPath, graph\r
- .getBuiltins().ConsistsOf);\r
- if (path.length == 0) {\r
- IllegalArgumentException e = new IllegalArgumentException("");\r
- ShowMessage.showError("Error loading the existing project", e.getMessage());\r
- throw new DatabaseException(e);\r
- }\r
- else return path[path.length - 1];\r
- }\r
-\r
- });\r
-\r
-// final GraphRequestWithResult<Resource> request = new GraphRequestWithResult<Resource>() {\r
-// @Override\r
-// public Resource performWithResult(Graph g) {\r
-// Resource[] path = GraphPathUtils.toResourcePath(g, project.getResource(), modelPath,\r
-// g.getBuiltins().ConsistsOf);\r
-// if (path.length == 0)\r
-// throw new IllegalArgumentException("");\r
-// return path[path.length - 1];\r
-// }\r
-// };\r
-// session.syncRead(request);\r
-// if (request.getException() != null) {\r
-// ShowMessage.showError("Error loading the existing project", request.getException().getMessage());\r
-// return null;\r
-// }\r
-// return request.getResult();\r
- }\r
-\r
- final Set<String> reservedProjectNames = new HashSet<String>();\r
-// IProject newProject(final ISessionContext ctx) throws DatabaseException {\r
-// // ---------------------------------------------------------------------\r
-// // Show the wizard to the user.\r
-// final NewProjectModel2 model = ProjectWizardUtil.initializeNewProjectModel2(new NullProgressMonitor(), ctx);\r
-// final NewProjectWizard2 wizard = new NewProjectWizard2(ctx.getSession(), model, null);\r
-// int ok = new WizardDialog(null, wizard).open();\r
-// if (ok != Window.OK) {\r
-// // User cancelled the wizard.\r
-// return null;\r
-// }\r
-//\r
-// final DataContainer<IProject> project = new DataContainer<IProject>();\r
-//\r
-// ctx.getSession().syncRequest(new WriteRequest() {\r
-//\r
-// @Override\r
-// public void perform(WriteGraph g) {\r
-//\r
-// try {\r
-//\r
-// // TODO: add features\r
-// System.out.println("TODO: add features to project");\r
-// Collection<IProjectFeatureDescriptor> fds = Collections.emptyList();\r
-// Resource res = ProjectUtil.createProject(g, model.projectName, fds);\r
-// project.set(ProjectUtil.loadProject(g, res, false));\r
-//\r
-// } catch (Exception e) {\r
-// ShowMessage.showError("Error creating new project", e.getMessage());\r
-// }\r
-//\r
-// }\r
-//\r
-// });\r
-//\r
-// return project.get();\r
-//\r
-// }\r
-\r
- /*\r
- Resource newModel(final Session session, final IProject project) {\r
- final ISimulationProjectParticipant sim = project.getSingleParticipant(ISimulationProjectParticipant.class);\r
- if (sim == null)\r
- return null;\r
-\r
- final Resource[] result = { null };\r
- final Semaphore sem = new Semaphore(0);\r
- findModelLibrary(session, project.getResource(), new RunnableWithParameter<Resource>() {\r
- @Override\r
- public void run(Resource modelLibrary) {\r
- sim.createModel(modelLibrary,\r
- new RunnableWithParameter<Resource>() {\r
- @Override\r
- public void run(Resource model) {\r
- result[0] = model;\r
- sem.release();\r
- }\r
- },\r
- new RunnableWithParameter<Throwable>() {\r
- @Override\r
- public void run(Throwable e) {\r
- ErrorLogger.defaultLogError("New model creation failed, see exception for details.", e);\r
- sem.release();\r
- }\r
- });\r
- }\r
- },\r
- new RunnableWithParameter<Throwable>() {\r
- @Override\r
- public void run(Throwable e) {\r
- if (e != null)\r
- ErrorLogger.defaultLogError("New model creation failed, see exception for details.", e);\r
- else\r
- ErrorLogger.defaultLogError("New model creation failed, no model library found.", null);\r
- sem.release();\r
- }\r
- });\r
-\r
- // Wait until the model creation has finished or failed.\r
- try {\r
- sem.acquire();\r
- } catch (InterruptedException e) {\r
- }\r
- return result[0];\r
- }\r
- */\r
-\r
- /*\r
- void findModelLibrary(Session session,\r
- final Resource project,\r
- final RunnableWithParameter<Resource> libraryAction,\r
- final RunnableWithParameter<Throwable> errorCallback)\r
- {\r
- // TODO: all of this is not that generic, what is someone decices he/she\r
- // doesn't want a model library called Models at the root of his/her\r
- // project ??\r
-\r
- // If the new model consists of a single diagram, open it.\r
- session.asyncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph g) throws Exception {\r
- Resource modelLibrary = null;\r
- try {\r
- Builtins b = g.getBuiltins();\r
- for (Resource r : g.getObjects2(project, b.ConsistsOf)) {\r
- if (g.isInstanceOf2(r, b.ModelLibrary)) {\r
- modelLibrary = r;\r
- break;\r
- }\r
- }\r
- // FIXME: this is definitely project specific, not generic.\r
- if (modelLibrary == null) {\r
- modelLibrary = InstanceFactory.instantiate(g, b.ModelLibrary);\r
- GraphUtils.addRelatedScalarString(g, modelLibrary, b.HasName, "Models");\r
- g.claim(project, b.ConsistsOf, modelLibrary);\r
- }\r
- libraryAction.run(modelLibrary);\r
- } catch (Exception e) {\r
- errorCallback.run(e);\r
- }\r
- }\r
- });\r
- }\r
- */\r
-\r
-// void findDiagram(Session session, final Resource model, final IProject project) {\r
-// // If the new model consists of a single diagram, open it.\r
-// session.asyncRequest(new ReadRequest() {\r
-// @Override\r
-// public void run(ReadGraph g) throws DatabaseException {\r
-// Builtins b = g.getBuiltins();\r
-// DiagramResource dr = DiagramResource.getInstance(g);\r
-// for (Resource r : g.getObjects(model, b.ConsistsOf)) {\r
-// if (g.isInstanceOf(r, dr.Diagram)) {\r
-// String defaultPerspective = project.getHint(ProjectKeys.DEFAULT_PERSPECTIVE);\r
-// openPreferredEditor(ctx.getSession(), r, defaultPerspective);\r
-// break;\r
-// }\r
-// }\r
-// }\r
-// });\r
-// }\r
-\r
- void openPreferredEditor(Session s, final Resource r, final String defaultPerspective) {\r
-\r
- s.asyncRequest(new ReadRequest() {\r
-\r
- @Override\r
- public void run(ReadGraph g) throws DatabaseException {\r
- final String resourceName = NameUtils.getSafeName(g, r);\r
- final IPriorityAction[] actions = ChooseActionRequest.findActions(g, r, defaultPerspective);\r
- if (actions == null)\r
- return;\r
- Display.getDefault().asyncExec(new Runnable() {\r
- @Override\r
- public void run() {\r
- IAction action = ChooseActionRequest.chooseAction(null, actions, resourceName);\r
- if (action == null)\r
- return;\r
- action.run();\r
- }\r
- });\r
- }\r
-\r
- });\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management
+ * in Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * VTT Technical Research Centre of Finland - initial API and implementation
+ *******************************************************************************/
+package org.simantics.workbench.internal;
+
+import java.lang.reflect.InvocationTargetException;
+import java.net.InetSocketAddress;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.MultiStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.dialogs.ProgressMonitorDialog;
+import org.eclipse.jface.operation.IRunnableWithProgress;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.simantics.application.arguments.ApplicationUtils;
+import org.simantics.application.arguments.IArguments;
+import org.simantics.application.arguments.SimanticsArguments;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.Session;
+import org.simantics.db.common.request.ReadRequest;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.SimanticsKeys;
+import org.simantics.db.management.ISessionContext;
+import org.simantics.db.management.discovery.InetAddressUtils;
+import org.simantics.db.request.Read;
+import org.simantics.project.IProject;
+import org.simantics.project.ProjectKeys;
+import org.simantics.project.ProjectUtil;
+import org.simantics.project.exception.ProjectException;
+import org.simantics.project.utils.GraphPathUtils;
+import org.simantics.ui.db.SessionData;
+import org.simantics.ui.db.SessionRestoreUtils;
+import org.simantics.ui.internal.Activator;
+import org.simantics.ui.workbench.action.ChooseActionRequest;
+import org.simantics.utils.ui.ExceptionUtils;
+import org.simantics.utils.ui.action.IPriorityAction;
+import org.simantics.utils.ui.dialogs.ShowMessage;
+
+public class Initializer implements Runnable {
+
+ private final IArguments args;
+
+// private String defaultPerspectiveId;
+
+ /**
+ * This will be !ok if something fatal for startup has happened.
+ */
+ private final IStatus status = Status.OK_STATUS;
+
+ private ISessionContext ctx;
+
+ private IProject project;
+
+ private Resource model;
+
+ private final IWorkbenchWindow window;
+
+// private Resource experiment;
+
+
+ public Initializer(IArguments args, IWorkbenchWindow window) {
+ this.args = args;
+ this.window = window;
+// this.defaultPerspectiveId = defaultPerspectiveId;
+ }
+
+ @Override
+ public void run() {
+ try {
+ perform();
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ } catch (ProjectException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public IStatus getStatus() {
+ return status;
+ }
+
+ public ISessionContext getSessionContext() {
+ return ctx;
+ }
+
+ public IProject getProject() {
+ return project;
+ }
+
+ public Resource getModel() {
+ return model;
+ }
+
+ public boolean perform() throws DatabaseException, ProjectException {
+ // Nothing further can be done if no server is specified
+ if (!args.contains(SimanticsArguments.SERVER))
+ return true;
+
+ // Try to connect to designated server and project.
+ // Use null local server location to indicate checkout
+ String server = args.get(SimanticsArguments.SERVER);
+ if(server.indexOf(':') == -1 && args.contains(SimanticsArguments.PORT)) {
+ server = server+":"+args.get(SimanticsArguments.PORT);
+ }
+ InetSocketAddress serverAddress = InetAddressUtils.parseUnresolved(server);
+ String[] projectPath = ApplicationUtils.decodePath(args.get(SimanticsArguments.PROJECT));
+ final SessionData data = new SessionData(null, serverAddress, projectPath);
+
+ final MultiStatus status = new MultiStatus(Activator.PLUGIN_ID, IStatus.OK, "Database session could not be initialized.", null);
+ // final ProgressMonitorDialog dialog = new ProgressMonitorDialog(null);
+
+ final ProgressMonitorDialog dialog = new ProgressMonitorDialog(null);
+ try {
+ dialog.run(false, true, new IRunnableWithProgress() {
+ @Override
+ public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
+ ctx = SessionRestoreUtils.restoreSession(status, monitor, data);
+ //ctx = sessionResult;
+ }
+ });
+ } catch (InvocationTargetException e) {
+ ExceptionUtils.logAndShowError(e);
+ } catch (InterruptedException e) {
+ ExceptionUtils.logAndShowError(e);
+ }
+
+ //IDiscoveryModel model =
+
+
+// IDiscoveryData[] iData = ProjectPlugin.getWorkspace().getDiscoveryModel().getDataSources();
+// for(int i = 0; i < iData.length; i++) {
+// IDiscoveryData d = iData[i];
+// if(d.getLabel().equals(IWorkspaceConstants.DIRECT_SERVERS_LABEL)) {
+// ServerInfo serverInfo = new ServerInfo(d.getLabel(), serverAddress);
+// ServerData serverData = new ServerData(null, serverInfo, null);
+// IServerData[] iServerData = d.getServers();
+//
+// IServerData[] newServerData = new IServerData[iServerData.length+1];
+//
+// int y;
+// for(y = 0; y < iServerData.length; y++) {
+// newServerData[y] = iServerData[y];
+// }
+//
+// newServerData[y] = serverData;
+//
+// d.setServers(newServerData);
+// ProjectPlugin.getWorkspace().getDiscoveryModel().updateDataSource(d);
+// break;
+// }
+//
+// }
+
+ //status = sessionResult.status;
+ //if (!status.isOK()) {
+ // return false;
+ //}
+
+ if (ctx == null) {
+ // Its okay to start the workbench, it will just be reset as the
+ // connection failed.
+ return true;
+ }
+
+ // FIXME: COMPLETE HACK for simupedia
+ // Add a discovery service to get in touch
+ /*
+ IDiscoveryModel discoveryModel = ProjectPlugin.getWorkspace().getDiscoveryModel();
+ File discoveryFile = ProjectPlugin.getDefault().getStateLocation().append("simupedia-discovery.txt").toFile();
+ FileWriter fw = null;
+ try {
+ // Overwrite the file.
+ fw = new FileWriter(discoveryFile, false);
+ String serverLine = String.format("'%s' %s\n", data.getAddress().getHostName(), server);
+ fw.write(serverLine);
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
+ FileUtils.uncheckedClose(fw);
+ }
+ try {
+ // Add a non-persistent simupedia discovery
+ DiscoveryData d = new DiscoveryData(IDiscoveryType.REMOTE, "Simupedia", discoveryFile);
+ discoveryModel.addDataSource(d);
+ } catch (MalformedURLException e) {
+ // Should never happen.
+ throw new Error(e);
+ }
+ */
+
+ // Initialize project
+ if (args.contains(SimanticsArguments.NEW_PROJECT)) {
+ throw new UnsupportedOperationException();
+ //project = newProject(ctx);
+ } else if (args.contains(SimanticsArguments.PROJECT)) {
+ project = loadProject(ctx, projectPath);
+ }
+
+ // Only proceed with model and experiment loading if a project was
+ // successfully created or loaded.
+ if (project != null) {
+ ctx.setHint(ProjectKeys.KEY_PROJECT, project);
+ ctx.setHint(SimanticsKeys.KEY_PROJECT, project.get());
+
+ // Load model
+ if (args.contains(SimanticsArguments.NEW_MODEL)) {
+ //model = newModel(ctx.getSession(), project);
+ } else if (args.contains(SimanticsArguments.MODEL)) {
+ String[] modelPath = ApplicationUtils.decodePath(args.get(SimanticsArguments.MODEL));
+ model = findModel(ctx.getSession(), project, modelPath);
+ }
+// if (model != null) {
+// findDiagram(ctx.getSession(), model, project);
+// }
+
+ // TODO: load experiment
+ if (args.contains(SimanticsArguments.EXPERIMENT)) {
+ // String[] experimentPath = decodePath(args.get(ProConfArguments.EXPERIMENT));
+ }
+ }
+
+ return true;
+ }
+
+ IProject loadProject(ISessionContext ctx, final String[] projectNamePath) throws DatabaseException, ProjectException {
+
+ IProject project = ctx.getSession().syncRequest(new Read<IProject>() {
+
+ @Override
+ public IProject perform(ReadGraph graph) throws DatabaseException {
+ Resource projects = graph.getResource("http://Projects");
+ Resource[] path = GraphPathUtils.toResourcePath(graph, projects, projectNamePath, graph
+ .getBuiltins().ConsistsOf);
+ if (path.length == 0) {
+ IllegalArgumentException e = new IllegalArgumentException("");
+ ShowMessage.showError("Error loading the existing project", e.getMessage());
+ throw new DatabaseException(e);
+ }
+ return ProjectUtil.loadProject(graph, path[path.length - 1]);
+ }
+
+ });
+
+ project.activate();
+
+ return project;
+
+// final GraphRequestWithResult<IProject> request = new GraphRequestWithResult<IProject>() {
+// @Override
+// public IProject performWithResult(Graph g) throws Exception {
+// }
+// };
+// ctx.getSession().syncRead(request);
+// if (request.getException() != null) {
+// ShowMessage.showError("Error loading the existing project", request.getException().getMessage());
+// return null;
+// }
+// return request.getResult();
+ }
+
+ Resource findModel(final Session session, final IProject project, final String[] modelPath) throws DatabaseException {
+
+ return session.syncRequest(new Read<Resource>() {
+
+ @Override
+ public Resource perform(ReadGraph graph) throws DatabaseException {
+ Resource[] path = GraphPathUtils.toResourcePath(graph, project.get(), modelPath, graph
+ .getBuiltins().ConsistsOf);
+ if (path.length == 0) {
+ IllegalArgumentException e = new IllegalArgumentException("");
+ ShowMessage.showError("Error loading the existing project", e.getMessage());
+ throw new DatabaseException(e);
+ }
+ else return path[path.length - 1];
+ }
+
+ });
+
+// final GraphRequestWithResult<Resource> request = new GraphRequestWithResult<Resource>() {
+// @Override
+// public Resource performWithResult(Graph g) {
+// Resource[] path = GraphPathUtils.toResourcePath(g, project.getResource(), modelPath,
+// g.getBuiltins().ConsistsOf);
+// if (path.length == 0)
+// throw new IllegalArgumentException("");
+// return path[path.length - 1];
+// }
+// };
+// session.syncRead(request);
+// if (request.getException() != null) {
+// ShowMessage.showError("Error loading the existing project", request.getException().getMessage());
+// return null;
+// }
+// return request.getResult();
+ }
+
+ final Set<String> reservedProjectNames = new HashSet<String>();
+// IProject newProject(final ISessionContext ctx) throws DatabaseException {
+// // ---------------------------------------------------------------------
+// // Show the wizard to the user.
+// final NewProjectModel2 model = ProjectWizardUtil.initializeNewProjectModel2(new NullProgressMonitor(), ctx);
+// final NewProjectWizard2 wizard = new NewProjectWizard2(ctx.getSession(), model, null);
+// int ok = new WizardDialog(null, wizard).open();
+// if (ok != Window.OK) {
+// // User cancelled the wizard.
+// return null;
+// }
+//
+// final DataContainer<IProject> project = new DataContainer<IProject>();
+//
+// ctx.getSession().syncRequest(new WriteRequest() {
+//
+// @Override
+// public void perform(WriteGraph g) {
+//
+// try {
+//
+// // TODO: add features
+// System.out.println("TODO: add features to project");
+// Collection<IProjectFeatureDescriptor> fds = Collections.emptyList();
+// Resource res = ProjectUtil.createProject(g, model.projectName, fds);
+// project.set(ProjectUtil.loadProject(g, res, false));
+//
+// } catch (Exception e) {
+// ShowMessage.showError("Error creating new project", e.getMessage());
+// }
+//
+// }
+//
+// });
+//
+// return project.get();
+//
+// }
+
+ /*
+ Resource newModel(final Session session, final IProject project) {
+ final ISimulationProjectParticipant sim = project.getSingleParticipant(ISimulationProjectParticipant.class);
+ if (sim == null)
+ return null;
+
+ final Resource[] result = { null };
+ final Semaphore sem = new Semaphore(0);
+ findModelLibrary(session, project.getResource(), new RunnableWithParameter<Resource>() {
+ @Override
+ public void run(Resource modelLibrary) {
+ sim.createModel(modelLibrary,
+ new RunnableWithParameter<Resource>() {
+ @Override
+ public void run(Resource model) {
+ result[0] = model;
+ sem.release();
+ }
+ },
+ new RunnableWithParameter<Throwable>() {
+ @Override
+ public void run(Throwable e) {
+ ErrorLogger.defaultLogError("New model creation failed, see exception for details.", e);
+ sem.release();
+ }
+ });
+ }
+ },
+ new RunnableWithParameter<Throwable>() {
+ @Override
+ public void run(Throwable e) {
+ if (e != null)
+ ErrorLogger.defaultLogError("New model creation failed, see exception for details.", e);
+ else
+ ErrorLogger.defaultLogError("New model creation failed, no model library found.", null);
+ sem.release();
+ }
+ });
+
+ // Wait until the model creation has finished or failed.
+ try {
+ sem.acquire();
+ } catch (InterruptedException e) {
+ }
+ return result[0];
+ }
+ */
+
+ /*
+ void findModelLibrary(Session session,
+ final Resource project,
+ final RunnableWithParameter<Resource> libraryAction,
+ final RunnableWithParameter<Throwable> errorCallback)
+ {
+ // TODO: all of this is not that generic, what is someone decices he/she
+ // doesn't want a model library called Models at the root of his/her
+ // project ??
+
+ // If the new model consists of a single diagram, open it.
+ session.asyncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph g) throws Exception {
+ Resource modelLibrary = null;
+ try {
+ Builtins b = g.getBuiltins();
+ for (Resource r : g.getObjects2(project, b.ConsistsOf)) {
+ if (g.isInstanceOf2(r, b.ModelLibrary)) {
+ modelLibrary = r;
+ break;
+ }
+ }
+ // FIXME: this is definitely project specific, not generic.
+ if (modelLibrary == null) {
+ modelLibrary = InstanceFactory.instantiate(g, b.ModelLibrary);
+ GraphUtils.addRelatedScalarString(g, modelLibrary, b.HasName, "Models");
+ g.claim(project, b.ConsistsOf, modelLibrary);
+ }
+ libraryAction.run(modelLibrary);
+ } catch (Exception e) {
+ errorCallback.run(e);
+ }
+ }
+ });
+ }
+ */
+
+// void findDiagram(Session session, final Resource model, final IProject project) {
+// // If the new model consists of a single diagram, open it.
+// session.asyncRequest(new ReadRequest() {
+// @Override
+// public void run(ReadGraph g) throws DatabaseException {
+// Builtins b = g.getBuiltins();
+// DiagramResource dr = DiagramResource.getInstance(g);
+// for (Resource r : g.getObjects(model, b.ConsistsOf)) {
+// if (g.isInstanceOf(r, dr.Diagram)) {
+// String defaultPerspective = project.getHint(ProjectKeys.DEFAULT_PERSPECTIVE);
+// openPreferredEditor(ctx.getSession(), r, defaultPerspective);
+// break;
+// }
+// }
+// }
+// });
+// }
+
+ void openPreferredEditor(Session s, final Resource r, final String defaultPerspective) {
+
+ s.asyncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph g) throws DatabaseException {
+ final String resourceName = NameUtils.getSafeName(g, r);
+ final IPriorityAction[] actions = ChooseActionRequest.findActions(g, r, defaultPerspective);
+ if (actions == null)
+ return;
+ Display.getDefault().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ IAction action = ChooseActionRequest.chooseAction(null, actions, resourceName);
+ if (action == null)
+ return;
+ action.run();
+ }
+ });
+ }
+
+ });
+ }
+
+}