Skip to main content



      Home
Home » Modeling » GMF (Graphical Modeling Framework) » Creating a new editor with Diagram
Creating a new editor with Diagram [message #166321] Fri, 28 December 2007 06:48 Go to next message
Eclipse UserFriend
Hi all,
I am new in GMF, I generated a diagram which is working fine. along with
diagram the gmf generated an other editor that writes the description of
model elements immediately when I click save button after drawing elements
on diagram.

I want to create a new editor similar to the editor along with diagram for
description of model elements(but as an xml file). I explored diagram.part
(package)but it looks little complex.

I will be greatfull if some one can give me idea how can I solve this
problem.

Thanks in advance
Re: Creating a new editor with Diagram [message #166327 is a reply to message #166321] Fri, 28 December 2007 07:04 Go to previous messageGo to next message
Eclipse UserFriend
Originally posted by: trommas.yahoo.com

Hi Noor and welcome to GMF :)

Could you elaborate your exact issue?
Do you need help setting up a second editor?


Merry Christmas,

Tomas Zijdemans

Noor wrote:
> Hi all,
> I am new in GMF, I generated a diagram which is working fine. along with
> diagram the gmf generated an other editor that writes the description of
> model elements immediately when I click save button after drawing
> elements on diagram.
>
> I want to create a new editor similar to the editor along with diagram
> for description of model elements(but as an xml file). I explored
> diagram.part (package)but it looks little complex.
> I will be greatfull if some one can give me idea how can I solve this
> problem.
>
> Thanks in advance
>
>
Re: Creating a new editor with Diagram [message #166329 is a reply to message #166327] Fri, 28 December 2007 09:07 Go to previous messageGo to next message
Eclipse UserFriend
Dear tomas,
Thank you very much for the reply.
Merry Christmas and happy new year to you too.
actually I want to create an xml file from the diagram. I mean when I will
drag and drop components from pallete to diagram editor each component has
its properties to be given in property window.

I want to write those properties to an xml file. and if user delete a
component from diagram, it should be updated in that xml file.

the same thing is being done in componentfile(default.component) that is
automatically generated with gmf diagram. but I want an xml file.

Thanks again for your cooperation.
Re: Creating a new editor with Diagram [message #166402 is a reply to message #166329] Sat, 29 December 2007 07:38 Go to previous messageGo to next message
Eclipse UserFriend
Originally posted by: trommas.yahoo.com

Comments below.

Noor wrote:
> Dear tomas,
> Thank you very much for the reply. Merry Christmas and happy new year to
> you too.
> actually I want to create an xml file from the diagram. I mean when I
> will drag and drop components from pallete to diagram editor each
> component has its properties to be given in property window.
Ok, those properties are "EMF-specific" - to put it a bit awkward.
>
> I want to write those properties to an xml file. and if user delete a
> component from diagram, it should be updated in that xml file.
I cannot think of an easy way to do this, but as mentioned, this is more
tied to EMF. If you post the message on the EMF-list I am sure Ed or
someone else will help you out (Ed has saved me countless times :))

Sorry for not being able to help more (I hope the EMF people can).


Be careful with those fireworks...

Tomas Zijdemans
Re: Creating a new editor with Diagram [message #166418 is a reply to message #166402] Sat, 29 December 2007 08:04 Go to previous messageGo to next message
Eclipse UserFriend
Originally posted by: merks.ca.ibm.com

Noor,

It seems to me that GMF fully supports storing the model in a separate
file from the diagram description for how it's displayed graphically. I
don't know enough details to explain specifically what's needed but in
general the idea would be that you'd have two separate resources. One
for the diagram and one for the model. Just as the example Ecore editor
stores a .ecore file and a .ecore_diagram file. When you save after
making changes, both these files would be changed. Maybe there's even a
generation option for separating the diagram from the model instance, I
don't know, but it's certainly achievable and I suppose you could look
at the example ecore diagram editor to see how it's done. I believe I
was told that it's purely a generated editor with no hand written
changes, so that leads me to think it's a generator option...


Tomas Zijdemans wrote:
> Comments below.
>
> Noor wrote:
>> Dear tomas,
>> Thank you very much for the reply. Merry Christmas and happy new year
>> to you too.
>> actually I want to create an xml file from the diagram. I mean when I
>> will drag and drop components from pallete to diagram editor each
>> component has its properties to be given in property window.
> Ok, those properties are "EMF-specific" - to put it a bit awkward.
>>
>> I want to write those properties to an xml file. and if user delete a
>> component from diagram, it should be updated in that xml file.
> I cannot think of an easy way to do this, but as mentioned, this is
> more tied to EMF. If you post the message on the EMF-list I am sure Ed
> or someone else will help you out (Ed has saved me countless times :))
>
> Sorry for not being able to help more (I hope the EMF people can).
>
>
> Be careful with those fireworks...
>
> Tomas Zijdemans
Re: Creating a new editor with Diagram [message #166427 is a reply to message #166418] Sat, 29 December 2007 09:17 Go to previous messageGo to next message
Eclipse UserFriend
Hello Ed,

> after making changes, both these files would be changed. Maybe
> there's even a generation option for separating the diagram from the
> model instance, I don't know, but it's certainly achievable and I
Yes, you are right! There is a property in genmodel allowing to generate
editor storing model and diagram information in the same file (off by default).

-----------------
Alex Shatalin
Re: Creating a new editor with Diagram [message #166435 is a reply to message #166427] Sat, 29 December 2007 13:06 Go to previous messageGo to next message
Eclipse UserFriend
Dear Tomas, ed and Alex

Thank you very much for your help.

yes it generates an editor to store model component in xmi format.

now i want to extract data from this xmi editor to write in to an other
editor in different format (like a java file).

which api should I use to extract data from this xmi file.

Is xpath ok for this? or there is some alternate.

Thanks in advance.

Noor
Re: Creating a new editor with Diagram [message #166443 is a reply to message #166435] Sat, 29 December 2007 13:23 Go to previous messageGo to next message
Eclipse UserFriend
Originally posted by: merks.ca.ibm.com

Noor,

You'd normally use your generated model's API directly to load an
instance and manipulate it. If you invoke Generate Test Code on the
root GenModel in the Generator editor (you get when you open a
*.genmodel) you'll see it generates an XyzExample.java which shows how
to read and write instances of your model's file. I'm not exactly sure
the nature of the conversion you want to do though. It seems to me
should get both editors to serialize to the same format. But the
comment about "like java file" makes me think you're trying to generate
something from your model. You'd use JET or Xpand (from the M2T
project) for that type of thing...


Noor wrote:
> Dear Tomas, ed and Alex
>
> Thank you very much for your help.
> yes it generates an editor to store model component in xmi format.
>
> now i want to extract data from this xmi editor to write in to an
> other editor in different format (like a java file).
>
> which api should I use to extract data from this xmi file.
> Is xpath ok for this? or there is some alternate.
>
> Thanks in advance.
>
> Noor
>
Re: Creating a new editor with Diagram [message #166482 is a reply to message #166443] Tue, 01 January 2008 03:18 Go to previous messageGo to next message
Eclipse UserFriend
Dear Ed,
Happy 2008.
sorry for the basic question again. I tried to load resources from xmi
file which is auto generated after save diagram using tests package as you
told me before. but failed. I have one parent node on pallet and others
are children of it. Can you please give a simple example of loading the
contents of this xmi file to use them further. following is the xmi file:

<?xml version="1.0" encoding="UTF-8"?>
<visualcomponentprefix:componentDiagram xmi:version="2.0"
xmlns:xmi="http://www.omg.org/XMI"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:visualcomponentprefix="visualcomponenturi">
<hcomponents name="High Component">
<conns source="//@hcomponents.0/@components.0"
target="//@hcomponents.0/@components.1"/>
<conns source="//@hcomponents.0/@components.0"
target="//@hcomponents.0/@components.2"/>
<conns source="//@hcomponents.0/@components.1"
target="//@hcomponents.0/@components.3"/>
<conns source="//@hcomponents.0/@components.0"
target="//@hcomponents.0/@components.5"/>
<conns source="//@hcomponents.0/@components.0"
target="//@hcomponents.0/@components.4"/>
<conns source="//@hcomponents.0/@components.3"
target="//@hcomponents.0/@components.0"/>
<components xsi:type="visualcomponentprefix:Process"/>
<components xsi:type="visualcomponentprefix:Task" name="t"/>
<components xsi:type="visualcomponentprefix:Stream"/>
<components xsi:type="visualcomponentprefix:Bandwidth"/>
<components xsi:type="visualcomponentprefix:Function"/>
<components xsi:type="visualcomponentprefix:Function"/>
</hcomponents>
<hcomponents name="HC2">
<conns source="//@hcomponents.1/@components.0"
target="//@hcomponents.1/@components.1"/>
<components xsi:type="visualcomponentprefix:Task"/>
<components xsi:type="visualcomponentprefix:Stream"/>
</hcomponents>
<hcomponents name="HC3">
<conns source="//@hcomponents.2/@components.0"
target="//@hcomponents.2/@components.2"/>
<conns source="//@hcomponents.2/@components.1"
target="//@hcomponents.2/@components.2"/>
<conns source="//@hcomponents.2/@components.2"
target="//@hcomponents.2/@components.1"/>
<components xsi:type="visualcomponentprefix:Function"/>
<components xsi:type="visualcomponentprefix:Process"/>
<components xsi:type="visualcomponentprefix:Task"/>
</hcomponents>
<hcomponents name="HC4">
<conns source="//@hcomponents.3/@components.0"
target="//@hcomponents.3/@components.2"/>
<conns source="//@hcomponents.3/@components.1"
target="//@hcomponents.3/@components.2"/>
<conns source="//@hcomponents.3/@components.0"
target="//@hcomponents.3/@components.1"/>
<components xsi:type="visualcomponentprefix:Task"/>
<components xsi:type="visualcomponentprefix:Stream"/>
<components xsi:type="visualcomponentprefix:Function"/>
</hcomponents>
<hconnections source="//@hcomponents.0" target="//@hcomponents.1"/>
<hconnections source="//@hcomponents.0" target="//@hcomponents.2"/>
<hconnections source="//@hcomponents.3" target="//@hcomponents.2"/>
</visualcomponentprefix:componentDiagram>


Thanks in advance.
Re: Creating a new editor with Diagram [message #166490 is a reply to message #166482] Tue, 01 January 2008 07:30 Go to previous messageGo to next message
Eclipse UserFriend
Originally posted by: merks.ca.ibm.com

Noor,

The best I can do is point you at the generated example that's specific
to your model. If you run the XyzExample.java with no arguments it will
serialize just a simple root object so if you make the root object a
compomentDiagram (is your class name a lower case) will it look like the
root object below? If you're failing to load what was saved by GMF,
most likely a different resource implementation or different load/save
options are being used in the GMF case. From what you show below, it's
clear that GMF is using an XMIResourceImpl. I wonder though if your
model is based on an XML Schema in which case an XMLResourceImpl like
the one that created by the generated the XyzResourceFactoryImpl for
your model? Does your model have one of those generated in the util
package of the model? Is GMF using that one?

Noor wrote:
> Dear Ed,
> Happy 2008.
> sorry for the basic question again. I tried to load resources from xmi
> file which is auto generated after save diagram using tests package as
> you told me before. but failed. I have one parent node on pallet and
> others are children of it. Can you please give a simple example of
> loading the contents of this xmi file to use them further. following
> is the xmi file:
>
> <?xml version="1.0" encoding="UTF-8"?>
> <visualcomponentprefix:componentDiagram xmi:version="2.0"
> xmlns:xmi="http://www.omg.org/XMI"
> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
> xmlns:visualcomponentprefix="visualcomponenturi">
> <hcomponents name="High Component">
> <conns source="//@hcomponents.0/@components.0"
> target="//@hcomponents.0/@components.1"/>
> <conns source="//@hcomponents.0/@components.0"
> target="//@hcomponents.0/@components.2"/>
> <conns source="//@hcomponents.0/@components.1"
> target="//@hcomponents.0/@components.3"/>
> <conns source="//@hcomponents.0/@components.0"
> target="//@hcomponents.0/@components.5"/>
> <conns source="//@hcomponents.0/@components.0"
> target="//@hcomponents.0/@components.4"/>
> <conns source="//@hcomponents.0/@components.3"
> target="//@hcomponents.0/@components.0"/>
> <components xsi:type="visualcomponentprefix:Process"/>
> <components xsi:type="visualcomponentprefix:Task" name="t"/>
> <components xsi:type="visualcomponentprefix:Stream"/>
> <components xsi:type="visualcomponentprefix:Bandwidth"/>
> <components xsi:type="visualcomponentprefix:Function"/>
> <components xsi:type="visualcomponentprefix:Function"/>
> </hcomponents>
> <hcomponents name="HC2">
> <conns source="//@hcomponents.1/@components.0"
> target="//@hcomponents.1/@components.1"/>
> <components xsi:type="visualcomponentprefix:Task"/>
> <components xsi:type="visualcomponentprefix:Stream"/>
> </hcomponents>
> <hcomponents name="HC3">
> <conns source="//@hcomponents.2/@components.0"
> target="//@hcomponents.2/@components.2"/>
> <conns source="//@hcomponents.2/@components.1"
> target="//@hcomponents.2/@components.2"/>
> <conns source="//@hcomponents.2/@components.2"
> target="//@hcomponents.2/@components.1"/>
> <components xsi:type="visualcomponentprefix:Function"/>
> <components xsi:type="visualcomponentprefix:Process"/>
> <components xsi:type="visualcomponentprefix:Task"/>
> </hcomponents>
> <hcomponents name="HC4">
> <conns source="//@hcomponents.3/@components.0"
> target="//@hcomponents.3/@components.2"/>
> <conns source="//@hcomponents.3/@components.1"
> target="//@hcomponents.3/@components.2"/>
> <conns source="//@hcomponents.3/@components.0"
> target="//@hcomponents.3/@components.1"/>
> <components xsi:type="visualcomponentprefix:Task"/>
> <components xsi:type="visualcomponentprefix:Stream"/>
> <components xsi:type="visualcomponentprefix:Function"/>
> </hcomponents>
> <hconnections source="//@hcomponents.0" target="//@hcomponents.1"/>
> <hconnections source="//@hcomponents.0" target="//@hcomponents.2"/>
> <hconnections source="//@hcomponents.3" target="//@hcomponents.2"/>
> </visualcomponentprefix:componentDiagram>
>
>
> Thanks in advance.
>
>
Re: Creating a new editor with Diagram [message #166509 is a reply to message #166490] Tue, 01 January 2008 21:42 Go to previous messageGo to next message
Eclipse UserFriend
Dear Ed,
Thank you very much for your kind help.

sorry again for basic question. Actually I am new in Eclipse.

I tried in the visualcomponentexample.java to access. if I run this class
as java application it gives the following result:


Enter a list of file paths or URIs that have content like this:
<?xml version="1.0" encoding="ASCII"?>
<visualcomponentprefix:componentDiagram xmi:version="2.0"
xmlns:xmi="http://www.omg.org/XMI"
xmlns:visualcomponentprefix="visualcomponenturi"/>

I tried to print diagram name(System.out.println(root.getName());) but it
print null;
(please give me (hint or link to a tutorial) how to print classes and
attributes etc. from this class)

if you dont mind, I can send you my application to your email address (it
will be helpful form me).

Following are the VisualComponentExample.java(from Tests Package) and
VisualDiagramEditorUtil.java(from diagram package) classes.


sorry for too much code.


/**
* <copyright>
* </copyright>
*
* $Id$
*/
package visualcomponent.tests;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.Diagnostician;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;

import visualcomponent.VisualcomponentFactory;
import visualcomponent.VisualcomponentPackage;
import visualcomponent.componentDiagram;

/**
* <!-- begin-user-doc -->
* A sample utility for the '<em><b>visualcomponent</b></em>' package.
* <!-- end-user-doc -->
* @generated
*/
public class VisualcomponentExample {
/**
* <!-- begin-user-doc -->
* Load all the argument file paths or URIs as instances of the model.
* <!-- end-user-doc -->
* @param args the file paths or URIs.
* @generated
*/
public static void main(String[] args) {
// Create a resource set to hold the resources.
//
ResourceSet resourceSet = new ResourceSetImpl();

// Register the appropriate resource factory to handle all file
extensions.
//
resourceSet.getResourceFactoryRegistry().getExtensionToFacto ryMap().put
(Resource.Factory.Registry.DEFAULT_EXTENSION,
new XMIResourceFactoryImpl());

// Register the package to ensure it is available during loading.
//
resourceSet.getPackageRegistry().put
(VisualcomponentPackage.eNS_URI,
VisualcomponentPackage.eINSTANCE);




// If there are no arguments, emit an appropriate usage message.
//
if (args.length == 0) {
System.out.println("Enter a list of file paths or URIs that have
content like this:");
try {
Resource resource =
resourceSet.createResource(URI.createURI("my.component"));
componentDiagram root =
VisualcomponentFactory.eINSTANCE.createcomponentDiagram();


resource.getContents().add(root);

resource.save(System.out, null);

}
catch (IOException exception) {
exception.printStackTrace();
}
}
else {
// Iterate over all the arguments.
//
for (int i = 0; i < args.length; ++i) {
// Construct the URI for the instance file.
// The argument is treated as a file path only if it denotes an
existing file.
// Otherwise, it's directly treated as a URL.
//
File file = new File(args[i]);
URI uri = file.isFile() ? URI.createFileURI(file.getAbsolutePath()):
URI.createURI(args[0]);

try {
// Demand load resource for this file.
//
URI path=URI.createFileURI("my.component");
Resource resource = resourceSet.getResource(path, true);
System.out.println("Loaded " + path);


System.out.println(resource.getContents().get(0));

// Validate the contents of the loaded resource.
//
for (EObject eObject : resource.getContents()) {
Diagnostic diagnostic = Diagnostician.INSTANCE.validate(eObject);
if (diagnostic.getSeverity() != Diagnostic.OK) {
printDiagnostic(diagnostic, "");
}
}
}
catch (RuntimeException exception) {
System.out.println("Problem loading " + uri);
exception.printStackTrace();
}
}
}
}

/**
* <!-- begin-user-doc -->
* Prints diagnostics with indentation.
* <!-- end-user-doc -->
* @param diagnostic the diagnostic to print.
* @param indent the indentation for printing.
* @generated
*/
protected static void printDiagnostic(Diagnostic diagnostic, String
indent) {
System.out.print(indent);
System.out.println(diagnostic.getMessage());
for (Diagnostic child : diagnostic.getChildren()) {
printDiagnostic(child, indent + " ");
}
}

} //VisualcomponentExample



package visualcomponent.diagram.part;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.operations.OperationHistoryFactory ;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.emf.workspace.util.WorkspaceSynchronizer;
import org.eclipse.gef.EditPart;
import org.eclipse.gmf.runtime.common.core.command.CommandResult;
import org.eclipse.gmf.runtime.diagram.core.services.ViewService;
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart ;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditP art;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IPrimaryEditPar t;
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramGraphicalVi ewer;
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramWorkbenchPa rt;
import
org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTr ansactionalCommand;
import org.eclipse.gmf.runtime.emf.core.GMFEditingDomainFactory;
import org.eclipse.gmf.runtime.emf.core.util.EMFCoreUtil;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.FileEditorInput;

import visualcomponent.VisualcomponentFactory;
import visualcomponent.diagram.edit.parts.ComponentDiagramEditPart;

/**
* @generated
*/
public class VisualDiagramEditorUtil {

/**
* @generated
*/
public static Map getSaveOptions() {
Map saveOptions = new HashMap();
saveOptions.put(XMLResource.OPTION_ENCODING, "UTF-8"); //$NON-NLS-1$
saveOptions.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED,
Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER);
return saveOptions;
}

/**
* @generated
*/
public static boolean openDiagram(Resource diagram)
throws PartInitException {
String path = diagram.getURI().toPlatformString(true);
IResource workspaceResource = ResourcesPlugin.getWorkspace().getRoot()
.findMember(new Path(path));
if (workspaceResource instanceof IFile) {
IWorkbenchPage page = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage();
return null != page.openEditor(new FileEditorInput(
(IFile) workspaceResource), VisualDiagramEditor.ID);
}
return false;
}

/**
* @generated
*/
public static void setCharset(IFile file) {
if (file == null) {
return;
}
try {
file.setCharset("UTF-8", new NullProgressMonitor()); //$NON-NLS-1$

} catch (CoreException e) {
VisualDiagramEditorPlugin.getInstance().logError(
"Unable to set charset for file " + file.getFullPath(), e);
//$NON-NLS-1$
}
}

/**
* @generated
*/
public static String getUniqueFileName(IPath containerFullPath,
String fileName, String extension) {
if (containerFullPath == null) {
containerFullPath = new Path(""); //$NON-NLS-1$
}
if (fileName == null || fileName.trim().length() == 0) {
fileName = "default"; //$NON-NLS-1$
}
IPath filePath = containerFullPath.append(fileName);
if (extension != null && !extension.equals(filePath.getFileExtension()))
{
filePath = filePath.addFileExtension(extension);
}
extension = filePath.getFileExtension();
fileName = filePath.removeFileExtension().lastSegment();
int i = 1;
while (ResourcesPlugin.getWorkspace().getRoot().exists(filePath)) {
i++;
filePath = containerFullPath.append(fileName + i);
if (extension != null) {
filePath = filePath.addFileExtension(extension);
}
}
return filePath.lastSegment();
}

/**
* Runs the wizard in a dialog.
*
* @generated
*/
public static void runWizard(Shell shell, Wizard wizard, String
settingsKey) {
IDialogSettings pluginDialogSettings = VisualDiagramEditorPlugin
.getInstance().getDialogSettings();
IDialogSettings wizardDialogSettings = pluginDialogSettings
.getSection(settingsKey);
if (wizardDialogSettings == null) {
wizardDialogSettings = pluginDialogSettings
.addNewSection(settingsKey);
}
wizard.setDialogSettings(wizardDialogSettings);
WizardDialog dialog = new WizardDialog(shell, wizard);
dialog.create();
dialog.getShell().setSize(Math.max(500, dialog.getShell().getSize().x),
500);
dialog.open();
}

/**
* This method should be called within a workspace modify operation since
it creates resources.
* @generated
*/
public static Resource createDiagram(URI diagramURI, URI modelURI,
IProgressMonitor progressMonitor) {
TransactionalEditingDomain editingDomain =
GMFEditingDomainFactory.INSTANCE
.createEditingDomain();
progressMonitor.beginTask(
Messages.VisualDiagramEditorUtil_CreateDiagramProgressTask, 3);
final Resource diagramResource = editingDomain.getResourceSet()
.createResource(diagramURI);
final Resource modelResource = editingDomain.getResourceSet()
.createResource(modelURI);
final String diagramName = diagramURI.lastSegment();
AbstractTransactionalCommand command = new AbstractTransactionalCommand(
editingDomain,
Messages.VisualDiagramEditorUtil_CreateDiagramCommandLabel,
Collections.EMPTY_LIST) {
protected CommandResult doExecuteWithResult(
IProgressMonitor monitor, IAdaptable info)
throws ExecutionException {
visualcomponent.componentDiagram model = createInitialModel();
attachModelToResource(model, modelResource);

Diagram diagram = ViewService.createDiagram(model,
ComponentDiagramEditPart.MODEL_ID,
VisualDiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT);

if (diagram != null) {
diagramResource.getContents().add(diagram);
diagram.setName(diagramName);
diagram.setElement(model);
}

try {
modelResource
.save(visualcomponent.diagram.part.VisualDiagramEditorUtil
.getSaveOptions());
diagramResource
.save(visualcomponent.diagram.part.VisualDiagramEditorUtil
.getSaveOptions());
} catch (IOException e) {

VisualDiagramEditorPlugin.getInstance().logError(
"Unable to store model and diagram resources", e); //$NON-NLS-1$
}
return CommandResult.newOKCommandResult();
}
};
try {
OperationHistoryFactory.getOperationHistory().execute(comman d,
new SubProgressMonitor(progressMonitor, 1), null);
} catch (ExecutionException e) {
VisualDiagramEditorPlugin.getInstance().logError(
"Unable to create model and diagram", e); //$NON-NLS-1$
}
setCharset(WorkspaceSynchronizer.getFile(modelResource));
setCharset(WorkspaceSynchronizer.getFile(diagramResource));
return diagramResource;
}

/**
* Create a new instance of domain element associated with canvas.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static visualcomponent.componentDiagram createInitialModel() {

return VisualcomponentFactory.eINSTANCE.createcomponentDiagram();
}

/**
* Store model element in the resource.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static void attachModelToResource(
visualcomponent.componentDiagram model, Resource resource) {
resource.getContents().add(model);
}

/**
* @generated
*/
public static void selectElementsInDiagram(
IDiagramWorkbenchPart diagramPart, List/*EditPart*/editParts) {
diagramPart.getDiagramGraphicalViewer().deselectAll();

EditPart firstPrimary = null;
for (Iterator it = editParts.iterator(); it.hasNext();) {
EditPart nextPart = (EditPart) it.next();
diagramPart.getDiagramGraphicalViewer().appendSelection(next Part);
if (firstPrimary == null && nextPart instanceof IPrimaryEditPart) {
firstPrimary = nextPart;
}
}

if (!editParts.isEmpty()) {
diagramPart.getDiagramGraphicalViewer().reveal(
firstPrimary != null ? firstPrimary : (EditPart) editParts
.get(0));
}
}

/**
* @generated
*/
private static int findElementsInDiagramByID(DiagramEditPart diagramPart,
EObject element, List editPartCollector) {
IDiagramGraphicalViewer viewer = (IDiagramGraphicalViewer) diagramPart
.getViewer();
final int intialNumOfEditParts = editPartCollector.size();

if (element instanceof View) { // support notation element lookup
EditPart editPart = (EditPart) viewer.getEditPartRegistry().get(
element);
if (editPart != null) {
editPartCollector.add(editPart);
return 1;
}
}

String elementID = EMFCoreUtil.getProxyID(element);
List associatedParts = viewer.findEditPartsForElement(elementID,
IGraphicalEditPart.class);
// perform the possible hierarchy disjoint -> take the top-most parts
only
for (Iterator editPartIt = associatedParts.iterator(); editPartIt
.hasNext();) {
EditPart nextPart = (EditPart) editPartIt.next();
EditPart parentPart = nextPart.getParent();
while (parentPart != null && !associatedParts.contains(parentPart)) {
parentPart = parentPart.getParent();
}
if (parentPart == null) {
editPartCollector.add(nextPart);
}
}

if (intialNumOfEditParts == editPartCollector.size()) {
if (!associatedParts.isEmpty()) {
editPartCollector.add(associatedParts.iterator().next());
} else {
if (element.eContainer() != null) {
return findElementsInDiagramByID(diagramPart, element
.eContainer(), editPartCollector);
}
}
}
return editPartCollector.size() - intialNumOfEditParts;
}

/**
* @generated
*/
public static View findView(DiagramEditPart diagramEditPart,
EObject targetElement, LazyElement2ViewMap lazyElement2ViewMap) {
boolean hasStructuralURI = false;
if (targetElement.eResource() instanceof XMLResource) {
hasStructuralURI = ((XMLResource) targetElement.eResource())
.getID(targetElement) == null;
}

View view = null;
if (hasStructuralURI
&& !lazyElement2ViewMap.getElement2ViewMap().isEmpty()) {
view = (View) lazyElement2ViewMap.getElement2ViewMap().get(
targetElement);
} else if (findElementsInDiagramByID(diagramEditPart, targetElement,
lazyElement2ViewMap.editPartTmpHolder) > 0) {
EditPart editPart = (EditPart) lazyElement2ViewMap.editPartTmpHolder
.get(0);
lazyElement2ViewMap.editPartTmpHolder.clear();
view = editPart.getModel() instanceof View ? (View) editPart
.getModel() : null;
}

return (view == null) ? diagramEditPart.getDiagramView() : view;
}

/**
* @generated
*/
public static class LazyElement2ViewMap {
/**
* @generated
*/
private Map element2ViewMap;

/**
* @generated
*/
private View scope;

/**
* @generated
*/
private Set elementSet;

/**
* @generated
*/
public final List editPartTmpHolder = new ArrayList();

/**
* @generated
*/
public LazyElement2ViewMap(View scope, Set elements) {
this.scope = scope;
this.elementSet = elements;
}

/**
* @generated
*/
public final Map getElement2ViewMap() {
if (element2ViewMap == null) {
element2ViewMap = new HashMap();
// map possible notation elements to itself as these can't be found by
view.getElement()
for (Iterator it = elementSet.iterator(); it.hasNext();) {
EObject element = (EObject) it.next();
if (element instanceof View) {
View view = (View) element;
if (view.getDiagram() == scope.getDiagram()) {
element2ViewMap.put(element, element); // take only those that part
of our diagram
}
}
}

buildElement2ViewMap(scope, element2ViewMap, elementSet);
}
return element2ViewMap;
}

/**
* @generated
*/
static Map buildElement2ViewMap(View parentView, Map element2ViewMap,
Set elements) {
if (elements.size() == element2ViewMap.size())
return element2ViewMap;

if (parentView.isSetElement()
&& !element2ViewMap.containsKey(parentView.getElement())
&& elements.contains(parentView.getElement())) {
element2ViewMap.put(parentView.getElement(), parentView);
if (elements.size() == element2ViewMap.size())
return element2ViewMap;
}

for (Iterator it = parentView.getChildren().iterator(); it
.hasNext();) {
buildElement2ViewMap((View) it.next(), element2ViewMap,
elements);
if (elements.size() == element2ViewMap.size())
return element2ViewMap;
}
for (Iterator it = parentView.getSourceEdges().iterator(); it
.hasNext();) {
buildElement2ViewMap((View) it.next(), element2ViewMap,
elements);
if (elements.size() == element2ViewMap.size())
return element2ViewMap;
}
for (Iterator it = parentView.getSourceEdges().iterator(); it
.hasNext();) {
buildElement2ViewMap((View) it.next(), element2ViewMap,
elements);
if (elements.size() == element2ViewMap.size())
return element2ViewMap;
}
return element2ViewMap;
}
} //LazyElement2ViewMap

public static void main(String[] abc) {
}
}


Thanks a lot.
Re: Creating a new editor with Diagram [message #166548 is a reply to message #166509] Wed, 02 January 2008 08:01 Go to previous messageGo to next message
Eclipse UserFriend
Originally posted by: merks.ca.ibm.com

Noor,

Comments below.

Noor wrote:
> Dear Ed,
> Thank you very much for your kind help.
>
> sorry again for basic question. Actually I am new in Eclipse.
We all started out new at some point!
>
> I tried in the visualcomponentexample.java to access. if I run this
> class as java application it gives the following result:
>
> Enter a list of file paths or URIs that have content like this:
> <?xml version="1.0" encoding="ASCII"?>
> <visualcomponentprefix:componentDiagram xmi:version="2.0"
> xmlns:xmi="http://www.omg.org/XMI"
> xmlns:visualcomponentprefix="visualcomponenturi"/>
SO that seems promising since it implies you have an XMIResourceImpl
and this serialization appears to match the one you were showing before.
>
> I tried to print diagram name(System.out.println(root.getName());) but
> it print null; (please give me (hint or link to a tutorial) how to
> print classes and attributes etc. from this class)
It's pretty clear that the above instance has not set any properties at
all so all of them will be returning their default value which most
typically is null.
>
> if you dont mind, I can send you my application to your email address
> (it will be helpful form me).
You could, but at this point I'm still not sure the problem you have so
you'd need to be pretty clear what the problem is. I assume that in the
code you show below that you could call root.setName("abc") and then
you'd see it in your serialization. Doesn't the "else" case of the
example below correctly read the serialization you showed in another
posting? If not, what exception is being thrown? If so, you should
note that even in your previous example, there is no name property on
the root object in the resource. I imagine you could do something like
root.getHComponents() to access the list of all the hcomponents and that
each of these would have a name that would be non-null.
>
> Following are the VisualComponentExample.java(from Tests Package) and
> VisualDiagramEditorUtil.java(from diagram package) classes.
>
>
> sorry for too much code.
>
>
> /**
> * <copyright>
> * </copyright>
> *
> * $Id$
> */
> package visualcomponent.tests;
>
> import java.io.File;
> import java.io.IOException;
> import java.util.ArrayList;
>
> import org.eclipse.emf.common.util.Diagnostic;
> import org.eclipse.emf.common.util.URI;
> import org.eclipse.emf.ecore.EObject;
> import org.eclipse.emf.ecore.resource.Resource;
> import org.eclipse.emf.ecore.resource.ResourceSet;
> import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
> import org.eclipse.emf.ecore.util.Diagnostician;
> import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
>
> import visualcomponent.VisualcomponentFactory;
> import visualcomponent.VisualcomponentPackage;
> import visualcomponent.componentDiagram;
>
> /**
> * <!-- begin-user-doc -->
> * A sample utility for the '<em><b>visualcomponent</b></em>' package.
> * <!-- end-user-doc -->
> * @generated
> */
> public class VisualcomponentExample {
> /**
> * <!-- begin-user-doc -->
> * Load all the argument file paths or URIs as instances of the
> model.
> * <!-- end-user-doc -->
> * @param args the file paths or URIs.
> * @generated
> */
> public static void main(String[] args) {
> // Create a resource set to hold the resources.
> //
> ResourceSet resourceSet = new ResourceSetImpl();
>
> // Register the appropriate resource factory to handle all
> file extensions.
> //
>
> resourceSet.getResourceFactoryRegistry().getExtensionToFacto ryMap().put
> (Resource.Factory.Registry.DEFAULT_EXTENSION,
> new XMIResourceFactoryImpl());
>
> // Register the package to ensure it is available during loading.
> //
> resourceSet.getPackageRegistry().put
> (VisualcomponentPackage.eNS_URI,
> VisualcomponentPackage.eINSTANCE);
>
>
>
> // If there are no arguments, emit an appropriate usage message.
> //
> if (args.length == 0) {
> System.out.println("Enter a list of file paths or URIs
> that have content like this:");
> try {
> Resource resource =
> resourceSet.createResource(URI.createURI("my.component"));
> componentDiagram root =
> VisualcomponentFactory.eINSTANCE.createcomponentDiagram();
>
>
> resource.getContents().add(root);
>
> resource.save(System.out, null);
>
> }
> catch (IOException exception) {
> exception.printStackTrace();
> }
> }
> else {
> // Iterate over all the arguments.
> //
> for (int i = 0; i < args.length; ++i) {
> // Construct the URI for the instance file.
> // The argument is treated as a file path only if it
> denotes an existing file.
> // Otherwise, it's directly treated as a URL.
> //
> File file = new File(args[i]);
> URI uri = file.isFile() ?
> URI.createFileURI(file.getAbsolutePath()): URI.createURI(args[0]);
>
> try {
> // Demand load resource for this file.
> //
> URI path=URI.createFileURI("my.component");
> Resource resource = resourceSet.getResource(path,
> true);
> System.out.println("Loaded " + path);
>
>
> System.out.println(resource.getContents().get(0));
>
> // Validate the contents of the loaded resource.
> //
> for (EObject eObject : resource.getContents()) {
> Diagnostic diagnostic =
> Diagnostician.INSTANCE.validate(eObject);
> if (diagnostic.getSeverity() != Diagnostic.OK) {
> printDiagnostic(diagnostic, "");
> }
> }
> }
> catch (RuntimeException exception) {
> System.out.println("Problem loading " + uri);
> exception.printStackTrace();
> }
> }
> }
> }
>
> /**
> * <!-- begin-user-doc -->
> * Prints diagnostics with indentation.
> * <!-- end-user-doc -->
> * @param diagnostic the diagnostic to print.
> * @param indent the indentation for printing.
> * @generated
> */
> protected static void printDiagnostic(Diagnostic diagnostic,
> String indent) {
> System.out.print(indent);
> System.out.println(diagnostic.getMessage());
> for (Diagnostic child : diagnostic.getChildren()) {
> printDiagnostic(child, indent + " ");
> }
> }
>
> } //VisualcomponentExample
>
>
>
> package visualcomponent.diagram.part;
>
> import java.io.IOException;
> import java.util.ArrayList;
> import java.util.Collections;
> import java.util.HashMap;
> import java.util.Iterator;
> import java.util.List;
> import java.util.Map;
> import java.util.Set;
>
> import org.eclipse.core.commands.ExecutionException;
> import org.eclipse.core.commands.operations.OperationHistoryFactory ;
> import org.eclipse.core.resources.IFile;
> import org.eclipse.core.resources.IResource;
> import org.eclipse.core.resources.ResourcesPlugin;
> import org.eclipse.core.runtime.CoreException;
> import org.eclipse.core.runtime.IAdaptable;
> import org.eclipse.core.runtime.IPath;
> import org.eclipse.core.runtime.IProgressMonitor;
> import org.eclipse.core.runtime.NullProgressMonitor;
> import org.eclipse.core.runtime.Path;
> import org.eclipse.core.runtime.SubProgressMonitor;
> import org.eclipse.emf.common.util.URI;
> import org.eclipse.emf.ecore.EObject;
> import org.eclipse.emf.ecore.resource.Resource;
> import org.eclipse.emf.ecore.xmi.XMLResource;
> import org.eclipse.emf.transaction.TransactionalEditingDomain;
> import org.eclipse.emf.workspace.util.WorkspaceSynchronizer;
> import org.eclipse.gef.EditPart;
> import org.eclipse.gmf.runtime.common.core.command.CommandResult;
> import org.eclipse.gmf.runtime.diagram.core.services.ViewService;
> import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart ;
> import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditP art;
> import org.eclipse.gmf.runtime.diagram.ui.editparts.IPrimaryEditPar t;
> import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramGraphicalVi ewer;
> import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramWorkbenchPa rt;
> import
> org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTr ansactionalCommand;
>
> import org.eclipse.gmf.runtime.emf.core.GMFEditingDomainFactory;
> import org.eclipse.gmf.runtime.emf.core.util.EMFCoreUtil;
> import org.eclipse.gmf.runtime.notation.Diagram;
> import org.eclipse.gmf.runtime.notation.View;
> import org.eclipse.jface.dialogs.IDialogSettings;
> import org.eclipse.jface.wizard.Wizard;
> import org.eclipse.jface.wizard.WizardDialog;
> import org.eclipse.swt.widgets.Shell;
> import org.eclipse.ui.IWorkbenchPage;
> import org.eclipse.ui.PartInitException;
> import org.eclipse.ui.PlatformUI;
> import org.eclipse.ui.part.FileEditorInput;
>
> import visualcomponent.VisualcomponentFactory;
> import visualcomponent.diagram.edit.parts.ComponentDiagramEditPart;
>
> /**
> * @generated
> */
> public class VisualDiagramEditorUtil {
>
> /**
> * @generated
> */
> public static Map getSaveOptions() {
> Map saveOptions = new HashMap();
> saveOptions.put(XMLResource.OPTION_ENCODING, "UTF-8");
> //$NON-NLS-1$
> saveOptions.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED,
> Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER);
> return saveOptions;
> }
>
> /**
> * @generated
> */
> public static boolean openDiagram(Resource diagram)
> throws PartInitException {
> String path = diagram.getURI().toPlatformString(true);
> IResource workspaceResource =
> ResourcesPlugin.getWorkspace().getRoot()
> .findMember(new Path(path));
> if (workspaceResource instanceof IFile) {
> IWorkbenchPage page = PlatformUI.getWorkbench()
> .getActiveWorkbenchWindow().getActivePage();
> return null != page.openEditor(new FileEditorInput(
> (IFile) workspaceResource), VisualDiagramEditor.ID);
> }
> return false;
> }
>
> /**
> * @generated
> */
> public static void setCharset(IFile file) {
> if (file == null) {
> return;
> }
> try {
> file.setCharset("UTF-8", new NullProgressMonitor());
> //$NON-NLS-1$
>
> } catch (CoreException e) {
> VisualDiagramEditorPlugin.getInstance().logError(
> "Unable to set charset for file " +
> file.getFullPath(), e); //$NON-NLS-1$
> }
> }
>
> /**
> * @generated
> */
> public static String getUniqueFileName(IPath containerFullPath,
> String fileName, String extension) {
> if (containerFullPath == null) {
> containerFullPath = new Path(""); //$NON-NLS-1$
> }
> if (fileName == null || fileName.trim().length() == 0) {
> fileName = "default"; //$NON-NLS-1$
> }
> IPath filePath = containerFullPath.append(fileName);
> if (extension != null &&
> !extension.equals(filePath.getFileExtension())) {
> filePath = filePath.addFileExtension(extension);
> }
> extension = filePath.getFileExtension();
> fileName = filePath.removeFileExtension().lastSegment();
> int i = 1;
> while
> (ResourcesPlugin.getWorkspace().getRoot().exists(filePath)) {
> i++;
> filePath = containerFullPath.append(fileName + i);
> if (extension != null) {
> filePath = filePath.addFileExtension(extension);
> }
> }
> return filePath.lastSegment();
> }
>
> /**
> * Runs the wizard in a dialog.
> * * @generated
> */
> public static void runWizard(Shell shell, Wizard wizard, String
> settingsKey) {
> IDialogSettings pluginDialogSettings = VisualDiagramEditorPlugin
> .getInstance().getDialogSettings();
> IDialogSettings wizardDialogSettings = pluginDialogSettings
> .getSection(settingsKey);
> if (wizardDialogSettings == null) {
> wizardDialogSettings = pluginDialogSettings
> .addNewSection(settingsKey);
> }
> wizard.setDialogSettings(wizardDialogSettings);
> WizardDialog dialog = new WizardDialog(shell, wizard);
> dialog.create();
> dialog.getShell().setSize(Math.max(500,
> dialog.getShell().getSize().x),
> 500);
> dialog.open();
> }
>
> /**
> * This method should be called within a workspace modify
> operation since it creates resources.
> * @generated
> */
> public static Resource createDiagram(URI diagramURI, URI modelURI,
> IProgressMonitor progressMonitor) {
> TransactionalEditingDomain editingDomain =
> GMFEditingDomainFactory.INSTANCE
> .createEditingDomain();
> progressMonitor.beginTask(
>
> Messages.VisualDiagramEditorUtil_CreateDiagramProgressTask, 3);
> final Resource diagramResource = editingDomain.getResourceSet()
> .createResource(diagramURI);
> final Resource modelResource = editingDomain.getResourceSet()
> .createResource(modelURI);
> final String diagramName = diagramURI.lastSegment();
> AbstractTransactionalCommand command = new
> AbstractTransactionalCommand(
> editingDomain,
>
> Messages.VisualDiagramEditorUtil_CreateDiagramCommandLabel,
> Collections.EMPTY_LIST) {
> protected CommandResult doExecuteWithResult(
> IProgressMonitor monitor, IAdaptable info)
> throws ExecutionException {
> visualcomponent.componentDiagram model =
> createInitialModel();
> attachModelToResource(model, modelResource);
>
> Diagram diagram = ViewService.createDiagram(model,
> ComponentDiagramEditPart.MODEL_ID,
>
> VisualDiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT);
>
> if (diagram != null) {
> diagramResource.getContents().add(diagram);
> diagram.setName(diagramName);
> diagram.setElement(model);
> }
>
> try {
> modelResource
>
> .save(visualcomponent.diagram.part.VisualDiagramEditorUtil
> .getSaveOptions());
> diagramResource
>
> .save(visualcomponent.diagram.part.VisualDiagramEditorUtil
> .getSaveOptions());
> } catch (IOException e) {
>
> VisualDiagramEditorPlugin.getInstance().logError(
> "Unable to store model and diagram
> resources", e); //$NON-NLS-1$
> }
> return CommandResult.newOKCommandResult();
> }
> };
> try {
>
> OperationHistoryFactory.getOperationHistory().execute(comman d,
> new SubProgressMonitor(progressMonitor, 1), null);
> } catch (ExecutionException e) {
> VisualDiagramEditorPlugin.getInstance().logError(
> "Unable to create model and diagram", e);
> //$NON-NLS-1$
> }
> setCharset(WorkspaceSynchronizer.getFile(modelResource));
> setCharset(WorkspaceSynchronizer.getFile(diagramResource));
> return diagramResource;
> }
>
> /**
> * Create a new instance of domain element associated with canvas.
> * <!-- begin-user-doc -->
> * <!-- end-user-doc -->
> * @generated
> */
> private static visualcomponent.componentDiagram
> createInitialModel() {
>
> return VisualcomponentFactory.eINSTANCE.createcomponentDiagram();
> }
>
> /**
> * Store model element in the resource.
> * <!-- begin-user-doc -->
> * <!-- end-user-doc -->
> * @generated
> */
> private static void attachModelToResource(
> visualcomponent.componentDiagram model, Resource resource) {
> resource.getContents().add(model);
> }
>
> /**
> * @generated
> */
> public static void selectElementsInDiagram(
> IDiagramWorkbenchPart diagramPart,
> List/*EditPart*/editParts) {
> diagramPart.getDiagramGraphicalViewer().deselectAll();
>
> EditPart firstPrimary = null;
> for (Iterator it = editParts.iterator(); it.hasNext();) {
> EditPart nextPart = (EditPart) it.next();
>
> diagramPart.getDiagramGraphicalViewer().appendSelection(next Part);
> if (firstPrimary == null && nextPart instanceof
> IPrimaryEditPart) {
> firstPrimary = nextPart;
> }
> }
>
> if (!editParts.isEmpty()) {
> diagramPart.getDiagramGraphicalViewer().reveal(
> firstPrimary != null ? firstPrimary : (EditPart)
> editParts
> .get(0));
> }
> }
>
> /**
> * @generated
> */
> private static int findElementsInDiagramByID(DiagramEditPart
> diagramPart,
> EObject element, List editPartCollector) {
> IDiagramGraphicalViewer viewer = (IDiagramGraphicalViewer)
> diagramPart
> .getViewer();
> final int intialNumOfEditParts = editPartCollector.size();
>
> if (element instanceof View) { // support notation element lookup
> EditPart editPart = (EditPart)
> viewer.getEditPartRegistry().get(
> element);
> if (editPart != null) {
> editPartCollector.add(editPart);
> return 1;
> }
> }
>
> String elementID = EMFCoreUtil.getProxyID(element);
> List associatedParts = viewer.findEditPartsForElement(elementID,
> IGraphicalEditPart.class);
> // perform the possible hierarchy disjoint -> take the
> top-most parts only
> for (Iterator editPartIt = associatedParts.iterator(); editPartIt
> .hasNext();) {
> EditPart nextPart = (EditPart) editPartIt.next();
> EditPart parentPart = nextPart.getParent();
> while (parentPart != null &&
> !associatedParts.contains(parentPart)) {
> parentPart = parentPart.getParent();
> }
> if (parentPart == null) {
> editPartCollector.add(nextPart);
> }
> }
>
> if (intialNumOfEditParts == editPartCollector.size()) {
> if (!associatedParts.isEmpty()) {
> editPartCollector.add(associatedParts.iterator().next());
> } else {
> if (element.eContainer() != null) {
> return findElementsInDiagramByID(diagramPart, element
> .eContainer(), editPartCollector);
> }
> }
> }
> return editPartCollector.size() - intialNumOfEditParts;
> }
>
> /**
> * @generated
> */
> public static View findView(DiagramEditPart diagramEditPart,
> EObject targetElement, LazyElement2ViewMap
> lazyElement2ViewMap) {
> boolean hasStructuralURI = false;
> if (targetElement.eResource() instanceof XMLResource) {
> hasStructuralURI = ((XMLResource) targetElement.eResource())
> .getID(targetElement) == null;
> }
>
> View view = null;
> if (hasStructuralURI
> && !lazyElement2ViewMap.getElement2ViewMap().isEmpty()) {
> view = (View) lazyElement2ViewMap.getElement2ViewMap().get(
> targetElement);
> } else if (findElementsInDiagramByID(diagramEditPart,
> targetElement,
> lazyElement2ViewMap.editPartTmpHolder) > 0) {
> EditPart editPart = (EditPart)
> lazyElement2ViewMap.editPartTmpHolder
> .get(0);
> lazyElement2ViewMap.editPartTmpHolder.clear();
> view = editPart.getModel() instanceof View ? (View) editPart
> .getModel() : null;
> }
>
> return (view == null) ? diagramEditPart.getDiagramView() : view;
> }
>
> /**
> * @generated
> */
> public static class LazyElement2ViewMap {
> /**
> * @generated
> */
> private Map element2ViewMap;
>
> /**
> * @generated
> */
> private View scope;
>
> /**
> * @generated
> */
> private Set elementSet;
>
> /**
> * @generated
> */
> public final List editPartTmpHolder = new ArrayList();
>
> /**
> * @generated
> */
> public LazyElement2ViewMap(View scope, Set elements) {
> this.scope = scope;
> this.elementSet = elements;
> }
>
> /**
> * @generated
> */
> public final Map getElement2ViewMap() {
> if (element2ViewMap == null) {
> element2ViewMap = new HashMap();
> // map possible notation elements to itself as these
> can't be found by view.getElement()
> for (Iterator it = elementSet.iterator();
> it.hasNext();) {
> EObject element = (EObject) it.next();
> if (element instanceof View) {
> View view = (View) element;
> if (view.getDiagram() == scope.getDiagram()) {
> element2ViewMap.put(element, element); //
> take only those that part of our diagram
> }
> }
> }
>
> buildElement2ViewMap(scope, element2ViewMap, elementSet);
> }
> return element2ViewMap;
> }
>
> /**
> * @generated
> */
> static Map buildElement2ViewMap(View parentView, Map
> element2ViewMap,
> Set elements) {
> if (elements.size() == element2ViewMap.size())
> return element2ViewMap;
>
> if (parentView.isSetElement()
> &&
> !element2ViewMap.containsKey(parentView.getElement())
> && elements.contains(parentView.getElement())) {
> element2ViewMap.put(parentView.getElement(), parentView);
> if (elements.size() == element2ViewMap.size())
> return element2ViewMap;
> }
>
> for (Iterator it = parentView.getChildren().iterator(); it
> .hasNext();) {
> buildElement2ViewMap((View) it.next(), element2ViewMap,
> elements);
> if (elements.size() == element2ViewMap.size())
> return element2ViewMap;
> }
> for (Iterator it = parentView.getSourceEdges().iterator(); it
> .hasNext();) {
> buildElement2ViewMap((View) it.next(), element2ViewMap,
> elements);
> if (elements.size() == element2ViewMap.size())
> return element2ViewMap;
> }
> for (Iterator it = parentView.getSourceEdges().iterator(); it
> .hasNext();) {
> buildElement2ViewMap((View) it.next(), element2ViewMap,
> elements);
> if (elements.size() == element2ViewMap.size())
> return element2ViewMap;
> }
> return element2ViewMap;
> }
> } //LazyElement2ViewMap
>
> public static void main(String[] abc) {
> }
> }
>
>
> Thanks a lot.
>
>
>
Re: Creating a new editor with Diagram [message #166583 is a reply to message #166548] Wed, 02 January 2008 12:01 Go to previous messageGo to next message
Eclipse UserFriend
Dear Ed,
I set the values of the all comonents in diagam. and I set the name of
diagram in property window of the diagram that is
"diagramName-given-in-ropertyWindow"
and then I tried to access this diagram name in example.java and it
returned null.


when I set diagram name using root.setName("my diagram"); and run
example.java as java application it prints "my diagram";

and also I tried root.getHcomponents(); it prints "[]";

may be I am accessing it in wrong way. HComponent is container of other
components.

I am slso confused with if and else for args.length==0 (I need little
description for this plz.)

and also the extension of the file I am trying access is .visualcomponent.
as autogenerated. should it be as .xmi?






resource.getContents().add(root);
root.setName("my diagram");
root.getHcomponents();

System.out.println(root.getName());
System.out.println(root.getHcomponents());
resource.save(System.out, null);
the result is:
Enter a list of file paths or URIs that have content like this:
my diagram
[]
<?xml version="1.0" encoding="ASCII"?>
<visualcomponentprefix:componentDiagram xmi:version="2.0"
xmlns:xmi="http://www.omg.org/XMI"
xmlns:visualcomponentprefix="visualcomponenturi" name="my diagram"/>





the recently generated xmi is as under:


<?xml version="1.0" encoding="UTF-8"?>
<visualcomponentprefix:componentDiagram xmi:version="2.0"
xmlns:xmi="http://www.omg.org/XMI"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:visualcomponentprefix="visualcomponenturi"
name="diagramName-given-in-propertyWindow">
<hcomponents name="Hcomponent">
<conns source="//@hcomponents.0/@components.0"
target="//@hcomponents.0/@components.1"/>
<conns source="//@hcomponents.0/@components.0"
target="//@hcomponents.0/@components.2"/>
<components xsi:type="visualcomponentprefix:Process" name="p"
templateName="Temp"/>
<components xsi:type="visualcomponentprefix:Task" wce="3" bce="3"
deadline="3" name="t"/>
<components xsi:type="visualcomponentprefix:Function"
upperExpr="dsfdsfds" lowerExpr="dsadsa" name="f"/>
</hcomponents>
<hcomponents name="HComponent2">
<conns source="//@hcomponents.1/@components.0"
target="//@hcomponents.1/@components.1"/>
<components xsi:type="visualcomponentprefix:Task" wce="5" bce="5"
deadline="5" name="Task1"/>
<components xsi:type="visualcomponentprefix:Process" name="myprocess"
templateName="mytemp"/>
</hcomponents>
<hconnections source="//@hcomponents.0" target="//@hcomponents.1"/>
</visualcomponentprefix:componentDiagram>



/**
* <copyright>
* </copyright>
*
* $Id$
*/
package visualcomponent.tests;

import java.io.File;
import java.io.IOException;

import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.Diagnostician;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;

import visualcomponent.VisualcomponentFactory;
import visualcomponent.VisualcomponentPackage;
import visualcomponent.componentDiagram;

/**
* <!-- begin-user-doc -->
* A sample utility for the '<em><b>visualcomponent</b></em>' package.
* <!-- end-user-doc -->
* @generated
*/
public class VisualcomponentExample {
/**
* <!-- begin-user-doc -->
* Load all the argument file paths or URIs as instances of the model.
* <!-- end-user-doc -->
* @param args the file paths or URIs.
* @generated
*/
public static void main(String[] args) {
// Create a resource set to hold the resources.
//
ResourceSet resourceSet = new ResourceSetImpl();

// Register the appropriate resource factory to handle all file
extensions.
//
resourceSet.getResourceFactoryRegistry().getExtensionToFacto ryMap().put
(Resource.Factory.Registry.DEFAULT_EXTENSION,
new XMIResourceFactoryImpl());

// Register the package to ensure it is available during loading.
//
resourceSet.getPackageRegistry().put
(VisualcomponentPackage.eNS_URI,
VisualcomponentPackage.eINSTANCE);




// If there are no arguments, emit an appropriate usage message.
//
if (args.length == 0) {
System.out.println("Enter a list of file paths or URIs that have
content like this:");
try {
Resource resource =
resourceSet.createResource(URI.createURI("my.visualcomponent "));
componentDiagram root =
VisualcomponentFactory.eINSTANCE.createcomponentDiagram();


resource.getContents().add(root);
root.setName("my diagram");
root.getHcomponents();
System.out.println(root.getName());
System.out.println(root.getHcomponents());


resource.save(System.out, null);

}
catch (IOException exception) {
exception.printStackTrace();
}
}
else {
// Iterate over all the arguments.
//
for (int i = 0; i < args.length; ++i) {
// Construct the URI for the instance file.
// The argument is treated as a file path only if it denotes an
existing file.
// Otherwise, it's directly treated as a URL.
//
File file = new File(args[i]);
URI uri = file.isFile() ? URI.createFileURI(file.getAbsolutePath()):
URI.createURI(args[0]);

try {
// Demand load resource for this file.
//
URI path=URI.createFileURI("my.visualcomponent");
Resource resource = resourceSet.getResource(path, true);
System.out.println("Loaded " + path);


System.out.println(resource.getContents().get(0));

// Validate the contents of the loaded resource.
//
for (EObject eObject : resource.getContents()) {
Diagnostic diagnostic = Diagnostician.INSTANCE.validate(eObject);
if (diagnostic.getSeverity() != Diagnostic.OK) {
printDiagnostic(diagnostic, "");
}
}
}
catch (RuntimeException exception) {
System.out.println("Problem loading " + uri);
exception.printStackTrace();
}
}
}
}

/**
* <!-- begin-user-doc -->
* Prints diagnostics with indentation.
* <!-- end-user-doc -->
* @param diagnostic the diagnostic to print.
* @param indent the indentation for printing.
* @generated
*/
protected static void printDiagnostic(Diagnostic diagnostic, String
indent) {
System.out.print(indent);
System.out.println(diagnostic.getMessage());
for (Diagnostic child : diagnostic.getChildren()) {
printDiagnostic(child, indent + " ");
}
}

} //VisualcomponentExample


thanks a lot and sorry for inconvinience.
Re: Creating a new editor with Diagram [message #166607 is a reply to message #166583] Wed, 02 January 2008 13:57 Go to previous messageGo to next message
Eclipse UserFriend
Originally posted by: merks.ca.ibm.com

Noor,

Comments below.

Noor wrote:
> Dear Ed,
> I set the values of the all comonents in diagam. and I set the name of
> diagram in property window of the diagram that is
> "diagramName-given-in-ropertyWindow" and then I tried to access this
> diagram name in example.java and it returned null.
>
> when I set diagram name using root.setName("my diagram"); and run
> example.java as java application it prints "my diagram";
>
> and also I tried root.getHcomponents(); it prints "[]";
That would be how an empty list is printed.
>
> may be I am accessing it in wrong way. HComponent is container of
> other components.
>
> I am slso confused with if and else for args.length==0 (I need little
> description for this plz.)
If there are no arguments to the command line invocation (you can
specify them in your launch configuration) then it creates a simple
example and serializes it. If there are arguments, it assumes these are
file paths or URIs pointing at a instance of your model and will load
them and validate them.
>
> and also the extension of the file I am trying access is
> .visualcomponent. as autogenerated. should it be as .xmi?
No, .visualcomponent should be fine, but you can also change it if you
like. The generate example will parse any extension the same way.
>
>
>
>
>
> resource.getContents().add(root);
> root.setName("my diagram");
> root.getHcomponents();
>
> System.out.println(root.getName());
> System.out.println(root.getHcomponents());
> resource.save(System.out, null);
> the result is:
> Enter a list of file paths or URIs that have content like this:
> my diagram
> []
> <?xml version="1.0" encoding="ASCII"?>
> <visualcomponentprefix:componentDiagram xmi:version="2.0"
> xmlns:xmi="http://www.omg.org/XMI"
> xmlns:visualcomponentprefix="visualcomponenturi" name="my diagram"/>
>
> Try creating an HComponent and adding it to the list. Then you'll see
> some children.
>
>
>
> the recently generated xmi is as under:
>
>
> <?xml version="1.0" encoding="UTF-8"?>
> <visualcomponentprefix:componentDiagram xmi:version="2.0"
> xmlns:xmi="http://www.omg.org/XMI"
> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
> xmlns:visualcomponentprefix="visualcomponenturi"
> name="diagramName-given-in-propertyWindow">
> <hcomponents name="Hcomponent">
> <conns source="//@hcomponents.0/@components.0"
> target="//@hcomponents.0/@components.1"/>
> <conns source="//@hcomponents.0/@components.0"
> target="//@hcomponents.0/@components.2"/>
> <components xsi:type="visualcomponentprefix:Process" name="p"
> templateName="Temp"/>
> <components xsi:type="visualcomponentprefix:Task" wce="3" bce="3"
> deadline="3" name="t"/>
> <components xsi:type="visualcomponentprefix:Function"
> upperExpr="dsfdsfds" lowerExpr="dsadsa" name="f"/>
> </hcomponents>
> <hcomponents name="HComponent2">
> <conns source="//@hcomponents.1/@components.0"
> target="//@hcomponents.1/@components.1"/>
> <components xsi:type="visualcomponentprefix:Task" wce="5" bce="5"
> deadline="5" name="Task1"/>
> <components xsi:type="visualcomponentprefix:Process"
> name="myprocess" templateName="mytemp"/>
> </hcomponents>
> <hconnections source="//@hcomponents.0" target="//@hcomponents.1"/>
> </visualcomponentprefix:componentDiagram>
>
>
So it seems to me if you run the generated example with a command line
argument pointing at the file with the above serialization it will be
loaded correctly and then you'll be able to use your generated APIs to
walk the structure you've loaded. For example, after you load, try
doing resource.save(System.out, null) to see if it can write out the
same thing as it just finished loading. If that prints out the same
structure, you're set to go...
>
> /**
> * <copyright>
> * </copyright>
> *
> * $Id$
> */
> package visualcomponent.tests;
>
> import java.io.File;
> import java.io.IOException;
>
> import org.eclipse.emf.common.util.Diagnostic;
> import org.eclipse.emf.common.util.URI;
> import org.eclipse.emf.ecore.EObject;
> import org.eclipse.emf.ecore.resource.Resource;
> import org.eclipse.emf.ecore.resource.ResourceSet;
> import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
> import org.eclipse.emf.ecore.util.Diagnostician;
> import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
>
> import visualcomponent.VisualcomponentFactory;
> import visualcomponent.VisualcomponentPackage;
> import visualcomponent.componentDiagram;
>
> /**
> * <!-- begin-user-doc -->
> * A sample utility for the '<em><b>visualcomponent</b></em>' package.
> * <!-- end-user-doc -->
> * @generated
> */
> public class VisualcomponentExample {
> /**
> * <!-- begin-user-doc -->
> * Load all the argument file paths or URIs as instances of the
> model.
> * <!-- end-user-doc -->
> * @param args the file paths or URIs.
> * @generated
> */
> public static void main(String[] args) {
> // Create a resource set to hold the resources.
> //
> ResourceSet resourceSet = new ResourceSetImpl();
>
> // Register the appropriate resource factory to handle all
> file extensions.
> //
>
> resourceSet.getResourceFactoryRegistry().getExtensionToFacto ryMap().put
> (Resource.Factory.Registry.DEFAULT_EXTENSION,
> new XMIResourceFactoryImpl());
>
> // Register the package to ensure it is available during loading.
> //
> resourceSet.getPackageRegistry().put
> (VisualcomponentPackage.eNS_URI,
> VisualcomponentPackage.eINSTANCE);
>
>
>
> // If there are no arguments, emit an appropriate usage message.
> //
> if (args.length == 0) {
> System.out.println("Enter a list of file paths or URIs
> that have content like this:");
> try {
> Resource resource =
> resourceSet.createResource(URI.createURI("my.visualcomponent "));
> componentDiagram root =
> VisualcomponentFactory.eINSTANCE.createcomponentDiagram();
>
>
> resource.getContents().add(root);
> root.setName("my diagram");
> root.getHcomponents();
> System.out.println(root.getName());
> System.out.println(root.getHcomponents());
>
>
> resource.save(System.out, null);
>
> }
> catch (IOException exception) {
> exception.printStackTrace();
> }
> }
> else {
> // Iterate over all the arguments.
> //
> for (int i = 0; i < args.length; ++i) {
> // Construct the URI for the instance file.
> // The argument is treated as a file path only if it
> denotes an existing file.
> // Otherwise, it's directly treated as a URL.
> //
> File file = new File(args[i]);
> URI uri = file.isFile() ?
> URI.createFileURI(file.getAbsolutePath()): URI.createURI(args[0]);
>
> try {
> // Demand load resource for this file.
> //
> URI path=URI.createFileURI("my.visualcomponent");
> Resource resource = resourceSet.getResource(path,
> true);
> System.out.println("Loaded " + path);
>
>
> System.out.println(resource.getContents().get(0));
>
> // Validate the contents of the loaded resource.
> //
> for (EObject eObject : resource.getContents()) {
> Diagnostic diagnostic =
> Diagnostician.INSTANCE.validate(eObject);
> if (diagnostic.getSeverity() != Diagnostic.OK) {
> printDiagnostic(diagnostic, "");
> }
> }
> }
> catch (RuntimeException exception) {
> System.out.println("Problem loading " + uri);
> exception.printStackTrace();
> }
> }
> }
> }
>
> /**
> * <!-- begin-user-doc -->
> * Prints diagnostics with indentation.
> * <!-- end-user-doc -->
> * @param diagnostic the diagnostic to print.
> * @param indent the indentation for printing.
> * @generated
> */
> protected static void printDiagnostic(Diagnostic diagnostic,
> String indent) {
> System.out.print(indent);
> System.out.println(diagnostic.getMessage());
> for (Diagnostic child : diagnostic.getChildren()) {
> printDiagnostic(child, indent + " ");
> }
> }
>
> } //VisualcomponentExample
>
>
> thanks a lot and sorry for inconvinience.
>
Re: Creating a new editor with Diagram [message #166631 is a reply to message #166607] Thu, 03 January 2008 03:08 Go to previous messageGo to next message
Eclipse UserFriend
Dear Ed,

Thanks a lot for your help. now it is working. Yes I did as you advised.

now the control is directly going to the else part so I accessed that file
from else part.

Now I have some new thinngs to ask;

1. I have to write a file and I have to use the values of these
components(from xmi model) so while writing file how can I access the

individual component's values because right now it is printing the
whole
file at once in the console. using resource.save(System.out, null);
can you refer to a tutorial for writing like this. or some
example/hint.


2 Is it ok if I use visualcomponentExample.java for further work like
writing file etc. or should I use the similar .java file in diagram
package. or Is there any best alternate for this?

Thanks again for great help.
Re: Creating a new editor with Diagram [message #166705 is a reply to message #166631] Thu, 03 January 2008 07:29 Go to previous messageGo to next message
Eclipse UserFriend
Originally posted by: merks.ca.ibm.com

This is a multi-part message in MIME format.
--------------020806000808040303060200
Content-Type: text/plain; charset=ISO-8859-15; format=flowed
Content-Transfer-Encoding: 7bit

Noor,

Comments below.

Noor wrote:
> Dear Ed,
>
> Thanks a lot for your help. now it is working. Yes I did as you advised.
>
> now the control is directly going to the else part so I accessed that
> file from else part.
>
> Now I have some new thinngs to ask;
>
> 1. I have to write a file and I have to use the values of these
> components(from xmi model) so while writing file how can I access the
> individual component's values because right now it is printing the
> whole file at once in the console. using
> resource.save(System.out, null); can you refer to a tutorial for
> writing like this. or some example/hint.
I'm not sure I understand the question well. With EMF 2.3 you can use
this XMLResource save option to specify which particular objects within
the resource you want to save.

/**
* Write only the subtree starting at the specified list of EObjects,
* which must be objects contained by the resource.
*/
String OPTION_ROOT_OBJECTS = "ROOT_OBJECTS";

>
> 2 Is it ok if I use visualcomponentExample.java for further work like
> writing file etc. or should I use the similar .java file in
> diagram package. or Is there any best alternate for this?
The code is quite trivial. I'd expect you'd just copy it into whatever
utility is doing the reading or writing. Most of the code in the
example (all the registration of factories and packages) isn't needed
when running within Eclipse being in that environment, the registrations
in the plugin.xml do the same job transparently.
>
> Thanks again for great help.
>
>
>
>
>


--------------020806000808040303060200
Content-Type: text/html; charset=ISO-8859-15
Content-Transfer-Encoding: 8bit

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html;charset=ISO-8859-15"
http-equiv="Content-Type">
</head>
<body bgcolor="#ffffff" text="#000000">
Noor,<br>
<br>
Comments below.<br>
<br>
Noor wrote:
<blockquote
cite="mid:9e22b72bb3c22826a335a6fa7c662128$1@www.eclipse.org"
type="cite">Dear Ed,
<br>
<br>
Thanks a lot for your help. now it is working. Yes I did as you
advised.
<br>
<br>
now the control is directly going to the else part so I accessed that
file from else part.
<br>
<br>
Now I have some new thinngs to ask;
<br>
<br>
1.
Re: Creating a new editor with Diagram [message #166995 is a reply to message #166705] Sun, 06 January 2008 12:11 Go to previous messageGo to next message
Eclipse UserFriend
Dear Ed,
sorry for again question,
I am trying to access the elements of XMI file(EMF model i.e. auto
generated while saving diagram) but I cant access.

and also I want to write these elements to a file so which output stream
should I use(which one is supported in this case).


my code is as under:



ResourceSet resourceSet = new ResourceSetImpl();

resourceSet.getResourceFactoryRegistry().getExtensionToFacto ryMap().put
(Resource.Factory.Registry.DEFAULT_EXTENSION, new
XMIResourceFactoryImpl());

resourceSet.getPackageRegistry().put(VisualcomponentPackage. eNS_URI,
VisualcomponentPackage.eINSTANCE);


if (args.length == 0) {

System.out.println("Enter a list of file paths or URIs that have content
like this:");
try {
Resource resource =
resourceSet.createResource(URI.createURI(" C:/eclipse/workfolder/runtime-EclipseApplication/run/my.visu alcomponent "));
componentDiagram root =
VisualcomponentFactory.eINSTANCE.createcomponentDiagram();
resource.getContents().add(root);
resource.save(System.out, null);
}catch (IOException exception) {
exception.printStackTrace();
}
}




else {

try {
URI
path=URI.createFileURI(" C:/eclipse/workfolder/runtime-EclipseApplication/run/my.visu alcomponent ");
XMLResource xmlResource = new XMLResourceImpl(path);
System.out.println("Loaded " + path);

try{
Task root = VisualcomponentFactory.eINSTANCE.createTask();
Map options=new HashMap();
options.put(XMLResource.OPTION_ROOT_OBJECTS,"Task" );//also tried root here
//xmlResource.save(options);also tried
xmlResource.save(System.out,options);
}catch(IOException e){}

}
catch (RuntimeException exception) {
System.out.println("Problem loading ");
exception.printStackTrace();
}
}
}


and the errors are :

Loaded
file:/C:/eclipse/workfolder/runtime-EclipseApplication/run/m y.visualcomponent
Problem loading
java.lang.ClassCastException: java.lang.String cannot be cast to
java.util.List
at
org.eclipse.emf.ecore.xmi.impl.XMLHelperImpl.setOptions(XMLH elperImpl.java:206)
at org.eclipse.emf.ecore.xmi.impl.XMLSaveImpl.init(XMLSaveImpl. java:562)
at org.eclipse.emf.ecore.xmi.impl.XMLSaveImpl.save(XMLSaveImpl. java:246)
at
org.eclipse.emf.ecore.xmi.impl.XMLResourceImpl.doSave(XMLRes ourceImpl.java:205)
at
org.eclipse.emf.ecore.resource.impl.ResourceImpl.save(Resour ceImpl.java:1253)
at
visualcomponent.diagram.part.WriteComponents.main(WriteCompo nents.java:65)



Thanks a lot for your kind help.
Re: Creating a new editor with Diagram [message #167003 is a reply to message #166995] Sun, 06 January 2008 13:22 Go to previous messageGo to next message
Eclipse UserFriend
Originally posted by: merks.ca.ibm.com

Noor,

Comments below.

Noor wrote:
> Dear Ed,
> sorry for again question, I am trying to access the elements of XMI
> file(EMF model i.e. auto generated while saving diagram) but I cant
> access.
Why not. You have sample code that does it.
> and also I want to write these elements to a file so which output
> stream should I use(which one is supported in this case).
Again, you have sampel code that shows how to create an instance and
save it...
>
>
> my code is as under:
>
>
> ResourceSet resourceSet = new ResourceSetImpl();
>
> resourceSet.getResourceFactoryRegistry().getExtensionToFacto ryMap().put
> (Resource.Factory.Registry.DEFAULT_EXTENSION, new
> XMIResourceFactoryImpl());
>
> resourceSet.getPackageRegistry().put(VisualcomponentPackage. eNS_URI,
> VisualcomponentPackage.eINSTANCE);
>
> if (args.length == 0) {
>
> System.out.println("Enter a list of file paths or URIs that have
> content like this:");
> try {
> Resource resource =
> resourceSet.createResource(URI.createURI(" C:/eclipse/workfolder/runtime-EclipseApplication/run/my.visu alcomponent "));
>
> componentDiagram root =
> VisualcomponentFactory.eINSTANCE.createcomponentDiagram();
> resource.getContents().add(root);
> resource.save(System.out, null);
This saves to System.out and is like a "save as" to the given stream..
Using resource.save(null) will open a stream against the URI of the
resource itself and should save it in the give file. Within Eclipse
you'd usually use a URI.createPlatformResourceURI() with the full
workspace relative path instead.
> }catch (IOException exception) {
> exception.printStackTrace();
> }
> }
>
>
>
>
> else {
>
> try {
> URI
> path=URI.createFileURI(" C:/eclipse/workfolder/runtime-EclipseApplication/run/my.visu alcomponent ");
>
> XMLResource xmlResource = new XMLResourceImpl(path);
> System.out.println("Loaded " + path);
The generated example shows how to load a resource. Use that approach.
Don't use the approach of using new directly on a resource impl (and one
that won't read XMI at that).
>
> try{
> Task root = VisualcomponentFactory.eINSTANCE.createTask();
> Map options=new HashMap();
> options.put(XMLResource.OPTION_ROOT_OBJECTS,"Task" );//also tried root
> here
It's supposed to be an actual object contained by your resource. But
you haven't loaded the resource.
> //xmlResource.save(options);also tried
> xmlResource.save(System.out,options);
> }catch(IOException e){}
>
> }
> catch (RuntimeException exception) {
> System.out.println("Problem loading ");
> exception.printStackTrace();
> }
> }
> }
>
>
> and the errors are :
>
> Loaded
> file:/C:/eclipse/workfolder/runtime-EclipseApplication/run/m y.visualcomponent
>
> Problem loading java.lang.ClassCastException: java.lang.String cannot
> be cast to java.util.List
> at
> org.eclipse.emf.ecore.xmi.impl.XMLHelperImpl.setOptions(XMLH elperImpl.java:206)
>
> at
> org.eclipse.emf.ecore.xmi.impl.XMLSaveImpl.init(XMLSaveImpl. java:562)
> at
> org.eclipse.emf.ecore.xmi.impl.XMLSaveImpl.save(XMLSaveImpl. java:246)
> at
> org.eclipse.emf.ecore.xmi.impl.XMLResourceImpl.doSave(XMLRes ourceImpl.java:205)
>
> at
> org.eclipse.emf.ecore.resource.impl.ResourceImpl.save(Resour ceImpl.java:1253)
>
> at
> visualcomponent.diagram.part.WriteComponents.main(WriteCompo nents.java:65)
>
>
>
>
> Thanks a lot for your kind help.
I would highly recommend that you get the example program working
without modifying it first. Specifying the path for a file in the
command line should load it properly.
Re: Creating a new editor with Diagram [message #167212 is a reply to message #167003] Mon, 07 January 2008 13:49 Go to previous messageGo to next message
Eclipse UserFriend
Dear Ed,
sorry for many questions.

I tried to do as you advised and errors are gone but it prints the ecore
model information but not from xmi file. I think I am loading a node from
resource in wrong way. can you please make correction that where I am
doing it wrong.
I want to write the properties of function node but it is writing the
ecore attribute names of function node in xmi format instead of text
format.

following is the code in example.java.


URI
path=URI.createFileURI("C:/eclipse/workfolder/runtime-EclipseApplication/run/my.txt ");
XMLResource xmlResource = new XMLResourceImpl(path);
System.out.println("Loaded " + path);
try{
EClass root = VisualcomponentPackage.eINSTANCE.getFunction();
Map options=new HashMap();
options.put(XMLResource.OPTION_ROOT_OBJECTS,Collections.sing letonList(root));
xmlResource.save(options);
xmlResource.save(System.out,options);
}catch(IOException e){}


and the output is as under:
all this output is related to function node but these are names of fuction
class and its attributes (not from the generated XMI file).
------------------------------------------------------------ -----------

Loaded file:/C:/eclipse/workfolder/runtime-EclipseApplication/run/m y.txt
<?xml version="1.0" encoding="ASCII"?>
<ecore:EClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore" name="Function">
<eSuperTypes href="visualcomponenturi#//Component"/>
<eStructuralFeatures xsi:type="ecore:EAttribute" name="upperExpr">
<eType xsi:type="ecore:EDataType"
href="http://www.eclipse.org/emf/2002/Ecore#//EString"/>
</eStructuralFeatures>
<eStructuralFeatures xsi:type="ecore:EAttribute" name="lowerExpr">
<eType xsi:type="ecore:EDataType"
href="http://www.eclipse.org/emf/2002/Ecore#//EString"/>
</eStructuralFeatures>
<eStructuralFeatures xsi:type="ecore:EAttribute" name="name">
<eType xsi:type="ecore:EDataType"
href="http://www.eclipse.org/emf/2002/Ecore#//EString"/>
</eStructuralFeatures>
</ecore:EClass>



I want the output in text format like:
------------------------------------------------------------ -------
my function-name
my lower-expression
my upper-expression

Ed, thank you very much for kind help.
Re: Creating a new editor with Diagram [message #167221 is a reply to message #167212] Mon, 07 January 2008 14:07 Go to previous message
Eclipse UserFriend
Originally posted by: merks.ca.ibm.com

This is a multi-part message in MIME format.
--------------080009070306000901060009
Content-Type: text/plain; charset=ISO-8859-15; format=flowed
Content-Transfer-Encoding: 7bit

Noor,

Comments below.

Noor wrote:
> Dear Ed,
> sorry for many questions.
And I'm not generally patient either!
>
> I tried to do as you advised and errors are gone but it prints the
> ecore model information but not from xmi file. I think I am loading a
> node from resource in wrong way. can you please make correction that
> where I am doing it wrong.
> I want to write the properties of function node but it is writing the
> ecore attribute names of function node in xmi format instead of text
> format.
> following is the code in example.java.
>
>
> URI
> path=URI.createFileURI("C:/eclipse/workfolder/runtime-EclipseApplication/run/my.txt ");
>
> XMLResource xmlResource = new XMLResourceImpl(path);
> System.out.println("Loaded " + path);
You're still using "new XMLResourceImpl". The generated example uses
resourceSet.getResource(path, true). Why aren't you using the generated
code that actually works? Have you read the introductory overview ?

The Eclipse Modeling Framework Overview
< http://help.eclipse.org/help33/index.jsp?topic=/org.eclipse. emf.doc//references/overview/EMF.html>

The "Saving and Loading Resources" section will be helpful to answer
your questions. It's a little frustrating that a fully functional
generated example that acts as a basic Java command line utility for
loading a resource doesn't get you started in the right direction
> try{
> EClass root = VisualcomponentPackage.eINSTANCE.getFunction();
> Map options=new HashMap();
> options.put(XMLResource.OPTION_ROOT_OBJECTS,Collections.sing letonList(root));
>
This object isn't in the resource. You'd have to add it to the resource
like the first part of the generated example shows.
> xmlResource.save(options);
> xmlResource.save(System.out,options);
> }catch(IOException e){}
>
>
> and the output is as under:
> all this output is related to function node but these are names of
> fuction class and its attributes (not from the generated XMI file).
> ------------------------------------------------------------ -----------
>
> Loaded file:/C:/eclipse/workfolder/runtime-EclipseApplication/run/m y.txt
> <?xml version="1.0" encoding="ASCII"?>
> <ecore:EClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
> xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore" name="Function">
> <eSuperTypes href="visualcomponenturi#//Component"/>
> <eStructuralFeatures xsi:type="ecore:EAttribute" name="upperExpr">
> <eType xsi:type="ecore:EDataType"
> href="http://www.eclipse.org/emf/2002/Ecore#//EString"/>
> </eStructuralFeatures>
> <eStructuralFeatures xsi:type="ecore:EAttribute" name="lowerExpr">
> <eType xsi:type="ecore:EDataType"
> href="http://www.eclipse.org/emf/2002/Ecore#//EString"/>
> </eStructuralFeatures>
> <eStructuralFeatures xsi:type="ecore:EAttribute" name="name">
> <eType xsi:type="ecore:EDataType"
> href="http://www.eclipse.org/emf/2002/Ecore#//EString"/>
> </eStructuralFeatures>
> </ecore:EClass>
>
>
>
> I want the output in text format like:
> ------------------------------------------------------------ -------
> my function-name
> my lower-expression
> my upper-expression
>
> Ed, thank you very much for kind help.
>


--------------080009070306000901060009
Content-Type: text/html; charset=ISO-8859-15
Content-Transfer-Encoding: 8bit

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html;charset=ISO-8859-15"
http-equiv="Content-Type">
</head>
<body bgcolor="#ffffff" text="#000000">
Noor,<br>
<br>
Comments below.<br>
<br>
Noor wrote:
<blockquote
cite="mid:08ea2eff28a1310835a9895aad31cc1c$1@www.eclipse.org"
type="cite">Dear Ed,
<br>
sorry for many questions.
<br>
</blockquote>
And I'm not generally patient either!<br>
<blockquote
cite="mid:08ea2eff28a1310835a9895aad31cc1c$1@www.eclipse.org"
type="cite"><br>
I tried to do as you advised and errors are gone but it prints the
ecore model information but not from xmi file. I think I am loading a
node from resource in wrong way. can you please make correction that
where I am doing it wrong.
<br>
I want to write the properties of function node but it is writing the
ecore attribute names of function node in xmi format instead of text
format. <br>
following is the code in example.java.
<br>
<br>
<br>
URI
path=URI.createFileURI("C:/eclipse/workfolder/runtime-EclipseApplication/run/my.txt ");
<br>
XMLResource xmlResource = new XMLResourceImpl(path);
System.out.println("Loaded " + path);
<br>
</blockquote>
You're still using "new XMLResourceImpl".
Previous Topic:Mapping options
Next Topic:Using Custom Figures
Goto Forum:
  


Current Time: Thu Jul 17 01:10:57 EDT 2025

Powered by FUDForum. Page generated in 0.07251 seconds
.:: Contact :: Home ::.

Powered by: FUDforum 3.0.2.
Copyright ©2001-2010 FUDforum Bulletin Board Software

Back to the top