How to create a diagram in a specific model using OpenAPI?

Hi guys,
When i create a new diagram,for example a new breakdown structure diagram by the following codes, the new diagram will be create in the root directory of project model structure.

IBreakdownStructureUIModel breakdown =(IBreakdownStructureUIModel) diagramManager.createDiagram(IDiagramTypeConstants.DIAGRAM_TYPE_BREAKDOWN_STRUCTURE);

breakdown.setName(“New Breakdown Structure Diagram”);

Now consider i have a hierarchical model structure and i want to create the new diagram in a desire model .
How to do it ?
you can see my sample model structure in the attached image.

Capture

Thanks in advance

Hi Mohammad,

To make a diagram under a model element, you call:

modelElement.addSubDiagram(diagram) ;

To locate a model element, you need to know whether it has a parent or not.

If it has a parent, it is quite straightforward:

IModelElement child = parent.getChildByName(modelType, name);

(or just pass name if you don’t care/know its model type)

If the model element is at root, currently there is no utility method to get by name (just id/address), so you need to write yourself:

private static IModelElement findRootModelElementByName(String name, String modelType) {
	IModelElement result = null;
	
	@SuppressWarnings("unchecked")
	Iterator<IModelElement> rootModelElementIterator = ApplicationManager.instance().getProjectManager().getProject().modelElementIterator(modelType);
	
	if (rootModelElementIterator != null &&
		rootModelElementIterator.hasNext()) {
		
		do {
			IModelElement rootModelElement = rootModelElementIterator.next();
			
			if (name.equals(rootModelElement.getNickname())) {
				result = rootModelElement;
			}
		} while (result == null &&
				 rootModelElementIterator.hasNext());
	}
	
	return result;
}

Let’s wrap the code into a method to make it easier to use:

private static IModelElement findModelElementByName(String name, String modelType, IModelElement parent) {
	IModelElement result;
	
	if (parent == null) {
		result = findRootModelElementByName(name, modelType);
	} else {
		result = parent.getChildByName(modelType, name);
	}
	
	return result;
}

And more specifically, just look for Model as for your requirement:

private static IModel findModelByName(String name, IModelElement parent) {
	return (IModel) findModelElementByName(name, IModelElementFactory.MODEL_TYPE_MODEL, parent);
}

Then it becomes quite easy to achieve what you want:

	IModel model_2 = findModelByName("Model 2", null);
	IModel model_2_1 = findModelByName("Model 2_1", model_2);
	
	IBreakdownStructureUIModel breakdown =(IBreakdownStructureUIModel) ApplicationManager.instance().getDiagramManager().createDiagram(IDiagramTypeConstants.DIAGRAM_TYPE_BREAKDOWN_STRUCTURE);
	breakdown.setName("New Breakdown Structure Diagram");
	
	model_2_1.addSubDiagram(breakdown);

Hope this helps,

Antony.

1 Like

Thank you
This is exactly what i want :ok_hand: