IBM Support

Rational Rhapsody JAVA API – Code Snippets & Helper Apps.

White Papers


Abstract

A compilation of various questions and requirements that different users of IBM Rational Rhapsody (Java APIs) have raised with Rational Client Support.

Content

Authors: Ashirbad Dash, Ankur Kacker, Chris Sutton, Jin Zhou, Yukihiro Yoshida




Table of Contents:




Preface

"I know about the Rational Rhapsody Java APIs and that it can be a very useful means to automate and customize the functionalities provided by the tool. Even better, to extend its functionalities beyond its prescribed capabilities. I know of a few good training materials and documents and am aware of different API interfaces and functions. Still, it feels challenging to develop complete Java API applications and helpers utilities, which can be useful in my day-to-day business with Rational Rhapsody.

Do we have any compilation of sample Java API code (complete or snippets) that address various real-time requirements while working with Rational Rhapsody? One, which could be used for a practical understanding and analysis of the various API interfaces and functions in different ways and varied scenarios?"

If you have had ever been bothered or concerned of the above, then this is the document you are looking for. Even if you have not been thoughtful of the above until now, some of the samples provided would surely draw your attention. You could easily relate to the problem, requirement, or something similar that is being addressed by the sample.

This document is not a Rational Rhapsody Java API tutorial and does not intend to teach users the basic usage of the Java API; creation, execution, debugging, etc. There are already various tutorials, presentations, and documents available to address that requirement. This document is focused on practical implementation of the various Rational Rhapsody Java API interfaces and functions. The document can serve as a reference of how various complex requirements, including ones that are not directly supported, can be achieved using the Rational Rhapsody Java APIs.

We would like to thank all our Rhapsody customers, who have reached out to Rational Client Support with respect to their questions and requirements on Rational Rhapsody API or otherwise. We would also like to thank Rhapsody Product Development and Management teams for their support and guidance. Last but not the least, special thanks to the world wide Rhapsody Support Team; this document would not have been a reality without specific inputs form each and every individual.


Rational Client Support – Rational Rhapsody WW Team.
August 2014






Introduction

This document may be referred to as a CODE BOOK. It provides solutions, to the various questions / requirements that different end users of Rational Rhapsody (Java APIs) have raised with Rational Client Support for the years now.

The code has been written as per the Java programming language standards. The samples have been tested for correct execution, as and when required. We have made every effort to insure that they are clear and correct, but errors are bound to occur, and for this we apologize in advance, in case of any such instance. We would encourage anyone who finds defects in this document to alert us at (support_ap@au1.ibm.com or sw_support_emea@nl.ibm.com or sw_support@us.ibm.com). Or you could write directly to any of the authors at the below mentioned IDs:

Ashirbad Dash – ashirbad.dash@in.ibm.com
Ankur Kacker - ankurkacker@in.ibm.com
Chris Sutton - chrisjsutton@uk.ibm.com
Jin Zhou - jinzhou@au1.ibm.com
Yukihiro Yoshida - yukihir@au1.ibm.com

The CODE BOOK can be broadly divided into two sections:

  1. Sample Java API usage code snippets
    • Providing examples of Rhapsody Java API functions usage

  2. Sample Helper application code
    • Providing complete code based solutions to specific client requirements.

A study of this CODE BOOK, preferably used in conjunction with Rational Rhapsody Java API – Help and other tutorials, will teach you good Rational Rhapsody Java API programming skills. The solutions provided may not be absolute (the only possible solution to the question / requirement) and one can surely modify the same, as per ones needs.







Overview

IBM Rational Rhapsody has come a long way to become a way of life for systems and software engineering enthusiasts and in the process, using the Rational Rhapsody Java APIs has become a daily chore.

Many end users and organizations prefer maintaining an ever growing set of Rational Rhapsody Java API custom apps and helper utilities, to aid their day to day systems / software engineering / development activities. The immense power of the APIs and its ability to achieve more in a faster and efficient way has made it a choice of almost every systems / software engineer using Rational Rhapsody.

Professional helper applications like:

Reverse Engineering Simulink files into Rational Rhapsody model,
Creating MATLAB built in types,
Import ARXML file from another application to Rational Rhapsody, etc.

just to name just a few, are no longer held in awe for the simple reason that their familiar, reliable presence has made them an inherent part of the scenery. Rational Rhapsody JAVA API – Code Snippets & Helper Apps gives you a better reason to eye such custom helper applications with confidence.

This first of its kind document, Rational Rhapsody JAVA API – Code Snippets & Helper Apps is a veritable treasure for all those who have a working knowledge of Rational Rhapsody Java API and an incentive to learn Rational Rhapsody Java API, for those who haven't. It puts the unbounded potential of Rational Rhapsody Java API, to work in wide range of sample code snippets and helper application, as outlined in the ‘Table of Contents’.

Rhapsody JAVA API – Code Snippets & Helper Apps, provides you with thousands of lines of (Rational Rhapsody API’s) Java source code; and that's a lot of code. No longer are the complex custom Rational Rhapsody helper applications out of reach. You can now enter the fascinating world of creating complex custom Rational Rhapsody helper applications, and greet the arrival of any new helper application, with the wisdom of one who knows!!







 
Disclaimer

All source code and/or binaries attached to this document are referred to here as "the Program". IBM is not providing program services of any kind for the Program. IBM is providing the Program on an "AS IS" basis without warranty of any kind. IBM WILL NOT BE LIABLE FOR ANY ACTUAL, DIRECT, SPECIAL, INCIDENTAL, OR INDIRECT DAMAGES OR FOR ANY ECONOMIC CONSEQUENTIAL DAMAGES (INCLUDING LOST PROFITS OR SAVINGS), EVEN IF IBM, OR ITS RESELLER, HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.








Sample Java API usage code snippets

Following examples provides information regarding Rhapsody Java API functions usage






I. Determine unresolved elements in a Rational Rhapsody model

In order to determine the unresolved elements you may consider using the API method getIsUnresolved() which would either return value as 1 (if the element is unresolved) or 0 (if it is resolved)

Consider the following instance where you have a reference to an unresolved event in a Sequence Diagram as the event is not present in the model.

The below code snippet iterates over all events in selected package and prints the ones that is found unresolved i.e., the ones which would return value as 1


IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPPackage pkg = (IRPPackage)app.getSelectedElement();
for(Object o: pkg.getEvents().toList())
{
IRPEvent evt = (IRPEvent)o;
if(evt.getIsUnresolved()==1)
System.out.println("Event :" + evt.getName());
}







II. Creating Flow and FlowItems model elements in Rational Rhapsody

Since Flow and FlowItems would be used to link other elements in addition to adding them in Rational Rhapsody model you would also need to make sure of setting the ends as well.

In regards to the same the API methods to be used are addFlows(String name), addFlowItems(String name), setEnd1(IRPModelElement end1), setEnd2(IRPModelElement end2), addConveyed(IRPModelElement pElement)

A simple code snippet for the same is below:


IRPFlow flow = pkg.addFlows(flowName);
flow.setEnd1(dependentmod);
flow.setEnd2(dependsOnmod);
IRPFlowItem flowItem = pkg.addFlowItems(((IRPOperation)oper).getName());
flow.addConveyed(flowItem);






III. Extracting dependency information both to/from in Rational Rhapsody model

In order to extract dependency information (to/from) using JAVA API in Rational Rhapsody you can use the API methods getDependent() which would retrieve the dependent model element and getDependsOn() which would retrieve the dependsOn model element

A code snippet of the same is below:


IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPModelElement myEle = myApp.getSelectedElement();
IRPDependency myDep = (IRPDependency) myEle;

System.out.println(myDep.getDependent().getName());
System.out.println(myDep.getDependsOn().getName());






IV. Language type being used in Rational Rhapsody model

You are interested to determine the language type on which the Rational Rhapsody model is built. In order to achieve the same you can use the API method getLanguage()

A code snippet of the same is below:


import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class Test
{
public static void main(String[] args)
{

IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
System.out.println(myApp.getLanguage());
}
}






V. Get ports for a Link or Connector in Rational Rhapsody model

Ports can be used in Rational Rhapsody either in UML profile model or a SysML profile based model. Hence we would have a look at both the methods

Method 1: For Standard ports connected via link or connector.

For standard ports you can make use of the API method calls IRPPort getFromPort() and IRPPort getToPort()

The following code snippet returns from and to ports correctly and no null pointer exception is thrown.


IRPModelElement moEle = app.getSelectedElement();
IRPLink link = (IRPLink)moEle;
System.out.println(link.getName());
System.out.println(link.getFromPort().getName());
System.out.println(link.getToPort().getName());


Method 2: For Flow ports (SysML ports) connected via link or connector.

For Flow ports you can make use of the API method calls IRPSysMLPort getFromSysMLPort() and IRPSysMLPort getToSysMLPort()

The following code snippet returns the from and to Flow [SysML] ports correctly and no null pointer exception is thrown.


IRPModelElement moEle = app.getSelectedElement();
IRPLink link = (IRPLink)moEle;
System.out.println(link.getName());
System.out.println(link.getFromSysMLPort().getName());
System.out.println(link.getToSysMLPort().getName());






VI. Select/highlight a specific model element in the Model Browser

You can use the API call highLightElement() available for the IRPModelElement interface in order to select any model element in the browser.

Note: In the following code you will search for a specific model element (in this case the attribute name attribute_0) in the project and then select / highlight the same in the browser.


import com.telelogic.rhapsody.core.*;

public class selectElementInBrowser
{
public static void main(String[] args)
{
IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject prj = app.activeProject();
IRPModelElement myEle = prj.findNestedElementRecursive("attribute_0", "Attribute");
myEle.highLightElement();
}
}






VII. Adding Tags in Rational Rhapsody model

You can use the following code snippet in order to add Tags to the model.


import com.telelogic.rhapsody.core.*;
public class testCls
{
public static void main(String[] args)
{
IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject prj = app.activeProject();
IRPPackage myPack = prj.addPackage("testPkg");
IRPTag myTag1 = (IRPTag) myPack.addNewAggr("Tag", "Tag1");
IRPClass myCls = myPack.addClass("testCls");
myTag1.setDescription("Description of Tag1");
IRPTag myTag2 = (IRPTag) myCls.addNewAggr("Tag", "Tag2");
myTag2.setDescription("Description of Tag2");
}
}







VIII. Creating Operations for implicit objects

In order to create operations for implicit objects in Rational Rhapsody model you can use API method getOtherClass()

A sample code snippet for same is below:


public static void main(String[] args)
{
IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject prj = app.activeProject();
IRPModelElement moEle = app.getSelectedElement();
IRPInstance myInst = (IRPInstance) moEle;
myInst.getOtherClass().addOperation("Hello");
}






IX. Access Flowports from a block

In order to access flowports from a block in Rational Rhapsody you can use the following code:

Note: The element selected in Rhapsody browser is related to the below code block.


IRPModelElement myEle = myApp.getSelectedElement();
for (Object obj : myEle.getNestedElementsRecursive().toList())
{
if(obj instanceof IRPSysMLPort)
{
IRPSysMLPort mySysMLPort = (IRPSysMLPort) obj;
System.out.println(mySysMLPort.getName());
}
}






X. Locating a Nested model element within a model

In order to locate a nested model element in Rational Rhapsody model you would need to use the API methods findNestedElement(java.lang.String name, java.lang.String metaClass) andfindNestedElementRecursive(java.lang.String name, java.lang.String metaClass) available for IRPModelElement interface

The first API call method searches only at the specific level where it is being called whereas the second API call method searches at the level it is being called as well as all levels below it recursively.

Below is a code snippet illustrating the use of the mentioned API methods:


IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject myPrj = myApp.activeProject();
myPrj.findNestedElement("package_0", "Package");
myPrj.findNestedElementRecursive("class_5", "Class");






XI. Performing model check

In order to perform model check using JAVA API in Rational Rhapsody you can make use of the API call checkModel() available for the IRPApplication interface as shown in below snippet:


IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
myApp.checkModel();






XII. Moving Packages within Rational Rhapsody model

In order to move packages in Rational Rhapsody use the following Java API code:

Note: The following Java API code snippet would move package named package_2 to package_0


IRPModelElement selEle = myApp.getSelectedElement();
IRPModelElement myEle = myPrj.findNestedElementRecursive("package_0","Package");
selEle.clone("package_2", myEle);
selEle.deleteFromProject();






XIII. Adding component to a package

In order to add a component to a package in Rational Rhapsody you can use the API method addNewAggr(String metaType, String name).

Following is a code snippet for the same:


IRPPackage MyPkg = prj.addPackage("TestPackage");
IRPComponent myComp = (IRPComponent) MyPkg.addNewAggr("Component","Test");






XIV. Creating SendAction model element inside of a StateChart diagram

You can use the addState(String name) API method to add a state to statechart and then use setStateType(String stateType) API mehtod to convert state to a SendAction.

The StateType to be used is EventState

A sample code snippet is as below:


IRPStatechart
MyChart = Mycls.addStatechart();
IRPState rootState = MyChart.getRootState();
IRPState sendAct = rootState.addState("SendAction");
sendAct.setStateType("EventState");
MyChart.createGraphics();






XV. Create Fork or Join Sync Bar model elements in a StateChart diagram

In order to be able to create a Fork or Join sync Bar elements in Rational Rhapsody you can use the API method addConnector(String type)

Find below a sample snippet:


IRPStatechart MyChart = Mycls.addStatechart();
IRPState rootState = MyChart.getRootState();
IRPConnector connector1 = rootState.addConnector("Join");
IRPConnector connector2 = rootState.addConnector("Fork");
MyChart.createGraphics();






XVI. Coloring of Ports in a Rational Rhapsody model

In order to color ports in Rational Rhapsody you can use the API method setGraphicalProperty("ForegroundColor", "255,0,0").

To identify if a node type is a port or not, use the API method getGraphicalProperty("Type").

Note: The below code looks for ports in a given diagram (selected in the browser in Rhapsody) and changes their color to Red.


IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPDiagram myDia = (IRPDiagram) myApp.getSelectedElement();
Iterator myIter = myDia.getGraphicalElements().toList().iterator();

while(myIter.hasNext())
{
Object myObj = myIter.next();
if(myObj instanceof IRPGraphNode)
{
IRPGraphNode myNode = (IRPGraphNode) myObj;
if(myNode.getGraphicalProperty("Type").getValue().equals("Port"))
myNode.setGraphicalProperty("ForegroundColor", "255,0,0");
}
}






XVII. Extract matrix view diagrams

In order to extract matrix view diagrams in Rational Rhapsody you can use the API method getImageCollection(String Folder, String sFilename, String sExtension).

Find below a code snippet for your reference:


IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPModelElement myEle = myApp.getSelectedElement();
IRPMatrixView myMV = (IRPMatrixView) myEle;
myMV.getImageCollection("C:\\Work\\Img\\", "Image", "jpg");






XVIII. Hide or Show ports on a diagram

In order to hide or show port(s) in a diagram in Rational Rhapsody you can use the API method setGraphicalProperty("isVisible", "FALSE") or "TRUE".

Find below a code snippet for your reference:


IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPDiagram myDia = (IRPDiagram) myApp.getSelectedElement();

Iterator myIter = myDia.getGraphicalElements().toList().iterator();
while(myIter.hasNext())
{
Object myObj = myIter.next();
if(myObj instanceof IRPGraphNode)
{
IRPGraphNode myNode = (IRPGraphNode) myObj;
if(myNode.getGraphicalProperty("Type").getValue().equals("Port"))
myNode.setGraphicalProperty("isVisible", "FALSE");
}
}






XIX. Coloring of Class nodes in a diagram

In order to color the class nodes in a diagram in Rational Rhapsody you can use the API method setGraphicalProperty("BackgroundColor", "255,0,0") [The value 255,0,0 is for the color red]

Find below a code snippet for your reference:

Note: The below code scans through all the nodes in the different diagrams and colors it red if it is not a template.


IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject myProj = myApp.activeProject();

Iterator myIter = myProj.getNestedElementsRecursive().toList().iterator();
while (myIter.hasNext())
{
Object myObj = myIter.next();
if(myObj instanceof IRPDiagram)
{
IRPDiagram myDiag = (IRPDiagram) myObj;
Iterator myIter1 = myDiag.getGraphicalElements().toList().iterator();
while(myIter1.hasNext())
{
Object myObj1 = myIter1.next();
if(myObj1 instanceof IRPGraphNode)
{
IRPGraphNode myNode = (IRPGraphNode) myObj1;
if(myNode.getModelObject().isATemplate() == 0)
myNode.setGraphicalProperty("BackgroundColor", "255,0,0")
}
}
}
}






XX. Adding a clickable hyperlink in description field a model element.

In order to add a clickable hyperlink in the description field of an element in Rational Rhapsody you can use the API method setDescriptionAndHyperlinks(String rtfText, IRPCollection targets).

Find below a code snippet for your reference:


IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject proj = myApp.activeProject();
IRPPackage pkg = proj.addPackage("myPkg");
IRPCollection targets = myApp.createNewCollection();
targets.setSize(1);
targets.setString(1, "http://www.google.com");
String rtfText = "{\\rtf1\\fbidis\\ansi\\ansicpg1255\\deff0\\deflang1037{\\fonttbl{\\f0\\fnil\\fcharset0 Arial;}}\n{\\colortbl;\\red0\\green0\\blue255;}\n\\viewkind4\\uc1\\pard\\ltrpar\\fs20 This is link to \\cf1\\ul\\protect google\\cf0\\ulnone\\protect0\\par\n}";
pkg.setDescriptionAndHyperlinks(rtfText, targets);







XXI. Adding a file under a package

In order to add a file under a package in Rational Rhapsody you can use the API method addModule(String name).

Find below a code snippet for your reference:


IRPPackage pkg = addNewPackageToProject("AnalysisPkg");
IRPModule m = (IRPModule) pkg.addModule("Test");







XXII. Adding a realization between classes

In order to add a realization between classes in Rational Rhapsody you can use the API methods findGeneralization(String name) and changeTo(String metaclass).

Find below a code snippet for your reference:


IRPPackage myPkg = myPrj.addPackage("Test");
IRPClass myCls1 = myPkg.addClass("Class1");
IRPClass myCls2 = myPkg.addClass("Class2");

myCls1.addGeneralization((IRPClassifier)myCls2);
IRPGeneralization myGen = myCls1.findGeneralization(myCls2.getName());
myGen.changeTo("Realization");





XXIII. Saving a model or model elements

There are different ways for saving a model or model elements using JAVA API in Rational Rhapsody. You can perform a save at the application, project or the unit level.

Below is a sample code snippet for your reference:


IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
//myApp.saveAll(); // 1st Method
IRPProject myPrj = myApp.activeProject();
//myPrj.save(); // 2nd Method
//myPrj.save(1); // 3rd Method
Iterator myIter = myPrj.getNestedSaveUnits().toList().iterator();

while (myIter.hasNext())
{
Object myObj = myIter.next();
IRPUnit myUnit = (IRPUnit) myObj;
//myUnit.save(0); // 4th method
myUnit.save(1); // 5th method
}


In the above example, the integer argument (0 or 1) refers to subunits. A '0' means without subunits and a '1' means with subunits..





XXIV. Determine Last Modified Time for a Unit

In order to get last modified time for an unit using JAVA API in Rational Rhapsody you can use the below code snippet as a reference:


IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();

IRPProject myPrj = myApp.activeProject();

IRPModelElement myEle = myApp.getSelectedElement();
IRPUnit myUnit = myEle.getSaveUnit();

System.out.println("Modified time through Rhapsody API : " + myUnit.getLastModifiedTime());

String unitFile = myUnit.getCurrentDirectory() + "\\" + myUnit.getFilename();
File file = new File(unitFile);

System.out.println( "Modified time through Java API : " + new Date(file.lastModified()) + " " + new Time(file.lastModified()) );





XXV. Saving model check outputs in a log file

In order to save model checks output in a log file in Rational Rhapsody you can use the API method setLog(String fullpathname).

Find below a code snippet for your reference:


IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
myApp.setLog("C:\\IBM\\Rational\\Rhapsody\\761\\Project\\Test.log");
myApp.checkModel();


In the above example, the Test.log file created in the project's root folder contains all the results of the model check performed.





XXVI. Regenerating Application Code

In order to regenerate application code in Rational Rhapsody using JAVA API you can use the API method regenerate() available for the IRPApplication interface.

Find below a code snippet for your reference:


import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.IRPProject;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class GenerateComponent
{
public static void main(String[] args)
{
IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
app.regenerate();
}
}







XXVII. Determine the Rational Rhapsody Build number

In order to get the build number in Rational Rhapsody you can use the API method getBuildNo().

Find below a code snippet for your reference:


import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class Test
{
public static void main(String[] args)
{
IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
System.out.println(myApp.getBuildNo());
}

}







XXVIII. Determine the OMROOT for a Rational Rhapsody model

In order to get the OMROOT in Rational Rhapsody you can use the API method getOMROOT().

Find below a code snippet for your reference:


import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class Test
{
public static void main(String[] args)
{
IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
System.out.println(myApp.getOMROOT());
}

}





XXIX. Determine the Rational Rhapsody Version number

In order to get the build number in Rational Rhapsody you can use the API method version() and versionNumberLong().

Find below a code snippet for your reference:


import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class Test
{
public static void main(String[] args)
{
IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
System.out.println(myApp.version());
System.out.println(myApp.versionNumberLong());
}
}






XXX. Run an application built for a project

In order to run an application built for a project in Rational Rhapsody you can use the API method runApplication().

Find below a code snippet for your reference:


import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class Test
{
public static void main(String[] args)
{
IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
myApp.runApplication();
}
}






XXXI. Terminate a running application built for a project

In order to terminate a running application built for the project in Rational Rhapsody you can use the API method terminateApplication().

Find below a code snippet for your reference:


import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class Test
{
public static void main(String[] args)
{
IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
myApp.terminateApplication();
}
}








XXXII. Complete all relations in Rational Rhapsody model

In order to complete all relations in Rational Rhapsody you can use the API method completeRelations(IRPCollection graphElements, int selectedToAll)

Find below the API code for your reference:


import java.util.Iterator;

import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.IRPDiagram;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class Test_completeRelations
{
public static void main(String[] args)
{
IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
Iterator myIter = myApp.activeProject().getNestedElementsRecursive().toList().iterator();


while(myIter.hasNext())
{
Object myObj = myIter.next();
if(myObj instanceof IRPDiagram)
{
IRPDiagram myDia = (IRPDiagram) myObj;
myDia.completeRelations(myDia.getGraphicalElements(), 1);
}
}
}
}





XXXIII. Using $name macro in properties

In order to use $name macro in properties not supporting the macro, using JAVA API in Rational Rhapsody you can use the below code as a reference.

The script below works for the properties C_CG.Type.InOut, C_CG.Type.Out, C_CG.Type.In and the $name macro, but you can extend the same to other properties and macros as per need


import java.util.Iterator;

import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.IRPModelElement;
import com.telelogic.rhapsody.core.IRPProject;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class nameMacro
{
public static void main(String[] args)
{
IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject myPrj = myApp.activeProject();
Iterator myIter = myPrj.getNestedElementsRecursive().toList().iterator();

while(myIter.hasNext())
{
Object myObj = myIter.next();
if(myObj instanceof IRPModelElement)
{
IRPModelElement myEle = (IRPModelElement) myObj;
String myInPrp = myEle.getPropertyValue("C_CG.Type.In");
String myOutPrp = myEle.getPropertyValue("C_CG.Type.Out");
String myInOutPrp = myEle.getPropertyValue("C_CG.Type.InOut");
if(myInPrp.contains("$name"))
myEle.setPropertyValue("C_CG.Type.In", myInPrp.replace("$name", myEle.getName()));
if(myOutPrp.contains("$name"))
myEle.setPropertyValue("C_CG.Type.Out", myInPrp.replace("name",
myEle.getName()));
if(myInOutPrp.contains("$name"))
myEle.setPropertyValue("C_CG.Type.InOut", myInOutPrp.replace("$name",
myEle.getName()));
}
}
}
}





XXXIV. Creating Global Object inside a Rational Rhapsody model project

Objects are referred to as global objects in the API. In order to create an object you can use the method IRPPackage.addGlobalObject(java.lang.String name, java.lang.String otherClassName, java.lang.String otherClassPackageName)

The first argument is the name of the new object to be created, the second is the existing class from which the object is to be created from, and the third is the name of the object's parent package.


IRPRelation rel = pack.addGlobalObject("test", "class_0", "Default")





XXXV. Adding a Referenced Sequence diagram to a Use Case diagram

In order to add a Referenced Sequence Diagram you can use API method IRPUseCase.addDescribingDiagram (diagram As RPDiagram)
In the below code snippet assuming you have a package selected in the browser

Note: Error checking not included


import com.telelogic.rhapsody.core.*;

public class process
{
public static void main(String[] args)
{
IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPPackage pkg = (IRPPackage)app.getSelectedElement();
IRPUseCaseDiagram ucd = pkg.addUseCaseDiagram("MyUCD");
IRPUseCase uc = pkg.addUseCase("MyUseCase");
IRPSequenceDiagram sq = pkg.addSequenceDiagram("MySD");
uc.addDescribingDiagram(sq);
}
}






XXXVI. Adding Template functions to a model

In order to add a Template function to a Rational Rhapsody model you can use the API method addNewAggr()

A sample code snippet is below:


IRPClass cls = (IRPClass)RhapsodyAppServer.getActiveRhapsodyApplication().getSelectedElement();
IRPOperation op = cls.addOperation("TestOP");
IRPClass tempCls = cls.addClass("T");
tempCls.setPropertyValue("Model.Class.IsTemplateParameterType", "True");
IRPTemplateParameter tempPara = (IRPTemplateParameter)op.addNewAggr("TemplateParameter",
tempCls.getName());
tempPara.setClassType();





XXXVII. Retrieving Source Artifacts in Rational Rhapsody model

In order to retrieve source artifacts using Java API, execute the code mentioned below:


IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPClassifier blah = (IRPClassifier)app.getSelectedElement();
IRPCollection SAs = blah.getSourceArtifacts();
for (Object obj : SAs.toList())
{
IRPModelElement el = (IRPModelElement)obj;
System.out.println(el.getName());
}






XXXVIII. Creating Sequence diagram in Rational Rhapsody model

In order to create a Sequence diagram using Java API you would need to create a Collaboration object first, and then add the classes and operations to that object.

Procedure:

// setup objects for sequence diagram

IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPPackage pkg = (IRPPackage)app.getSelectedElement();
IRPClass ClassA = pkg.addClass("ClassA");
IRPClass ClassB = pkg.addClass("ClassB");
IRPOperation OpB = ClassB.addOperation("OperationB");


//create collaboration for SD behaviour

IRPCollaboration Collab = app.activeProject().getNewCollaboration();

// add objects to collab object

IRPClassifierRole crClassA = Collab.addClassifierRole("ClassA", ClassA);
IRPClassifierRole crClassB = Collab.addClassifierRole("ClassB", ClassB);
IRPMessage msg = Collab.addMessage(OpB, "", crClassA, crClassB);

// Create sequence diagram from collaboration object

IRPSequenceDiagram SD = Collab.generateSequence("MySD", pkg);






XXIX. Adding execution occurrences to a Sequence diagram in Rational Rhapsody model

In order to add execution occurrences to a sequence diagram you can use the API method IRPCollaboration.getExecutionOccurrences(). However you would also need to add the IRPCollaboration.addExecutionOccurrence() method separately.

Procedure:

Setup objects for sequence diagram:


IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPPackage pkg = (IRPPackage)app.getSelectedElement();
IRPClass ClassA = pkg.addClass("ClassA");
IRPClass ClassB = pkg.addClass("ClassB");
IRPOperation OpB = ClassB.addOperation("OperationB");


Create collaboration for SD behaviour:

IRPCollaboration Collab = app.activeProject().getNewCollaboration();


Add objects to Collab object:


IRPClassifierRole crClassA = Collab.addClassifierRole("ClassA", ClassA);
IRPClassifierRole crClassB = Collab.addClassifierRole("ClassB", ClassB);
IRPMessage msg = Collab.addMessage(OpB, "", crClassA, crClassB);


Add SE to message:


IRPExecutionOccurrence eo = msg.addSourceExecutionOccurrence();


Create sequence diagram from collaboration object:


IRPSequenceDiagram SD = Collab.generateSequence("MySD", pkg);







XL. Accessing FlowItems (SysML) from a Flow in Rational Rhapsody model

The API method IRPFlow.getConveyed() will return a collection of IRPFlowItem objects contained within an IRPFlow object.

You can do the reverse access (Flowitems > Flow) by using the IRPItemFlow.getReferences() method. You will need to run a condition to check for IRPFlow types in the collection that is returned.

A sample code for the same is below:


IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPFlow el = (IRPFlow)app.getSelectedElement();

// access the collection of itemflows
List<IRPFlowItem> ListOfItemFlows = el.getConveyed().toList();
System.out.println("Item flows under "+el.getName()+" flow:");
for (IRPFlowItem itemflow : ListOfItemFlows)
{
System.out.print("\t" + itemflow.getName());

// access the flow that contains/owns the above flowitems

List<IRPModelElement> ItemFlowRefs = itemflow.getReferences().toList();

for (IRPModelElement ref : ItemFlowRefs)
{
if (ref instanceof IRPFlow) System.out.println(" (belongs to "+ref.getName()+")");
}
}




XLI. Setting Tag types in Rational Rhapsody model

You must use the API method setDeclaration(string declaration) to set the type of the tag to a specific metaclass.

The method setMetaclass(string tagMetaClass) sets the metaclass type that the tag should be applicable to, not the type of the actual tag itself.

The IRPTag interface inherits the method setDeclaration(string declaration) from the IRPVariable interface.

Example:

IRPTag tag = (IRPTag) flow.addNewAggr("Tag", "realization");
tag.setTagMetaClass("Link");


This will create a tag applicable to Link model elements, but the tag will default to type of string. Instead we should use setDeclaration(string declaration) to set the tag's type:

IRPTag tag = (IRPTag) flow.addNewAggr("Tag", "realization");
tag.setDeclaration("Link");






XLII. Preventing pop up message box when adding Simulink stereotype

You can prevent a pop-up message box by calling the IRPApplication::setHiddenUI with a True value first before calling any other APIs.

Note: To bring back the pop-up, call IRPApplication::setHiddenUI again with a False value.





XLIII. Setting Operation property inline

In order to set the operation property as inline in Rational Rhapsody, use the following Java API code:

public class Testcls
{
public static void main(String[] args)
{
IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject prj = app.activeProject();
IRPPackage MyPkg = prj.addPackage("TestPackage");
IRPClass Mycls = MyPkg.addClass("TestCls");
IRPOperation op = Mycls.addOperation("myop");
op.setPropertyValue("CPP_CG.Operation.Inline", "in_header");
}
}






XLIV. Determine the value of an attribute

To get the value of an attribute in Rational Rhapsody use the following Java API code:


import java.util.Iterator;
import com.telelogic.rhapsody.core.IRPInstance;
import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.IRPProject;
import com.telelogic.rhapsody.core.RhapsodyAppServer;
public class Example
{

public static void main(String[] args) {
IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
if(app != null)
printModelClasses(app);
}

private static void printModelClasses(IRPApplication app) {
IRPProject prj = app.activeProject();
if(prj == null) {
System.out.println("cannot get active project./n");
}

Iterator packIter = prj.getNestedElementsRecursive().toList().iterator();
while(packIter.hasNext())
{
Object packObj = packIter.next();
if(packObj instanceof IRPInstance)
{
IRPInstance cls = (IRPInstance)packObj;
System.out.println(cls.getName());
String str = "attribute_1";
System.out.println(cls.getAttributeValue(str));
}

}
}
}
.





XLV. Connecting to a specific Rational Rhapsody instance

Starting Rational Rhapsody 8.0.2, a new instance has been introduced and its version info along with the corresponding Process ID (PID) info will now be registered in ROT as a separated entry.

In addition, the following Java APIs are newly introduced into Rational Rhapsody version 8.0.2 and above to be used to attach to a specific instance:
RhapsodyAppServer.getActiveRhapsodyApplicationIDList()
RhapsodyAppServer.getActiveRhapsodyApplicationByID(String arg0)

Using COM API GetObject(,"Rhapsody.Application") will then always return the Rhapsody instance which is the last one being launched.
.
//retrieve all the entry info representing Rhapsody 8.0.2 or above instances from ROT
List<String> rhpInstanceList = RhapsodyAppServer.getActiveRhapsodyApplicationIDList();

//for each active instance ID, connect to the corresponding instance and output some info on GUI
for (String instanceID : rhpInstanceList)
{
IRPApplication app = RhapsodyAppServer.getActionRhapsodyApplicationByID(instanceID);
app.writeToOutputWindows("", instance ID);
}
.

Starting Rhapsody 8.0.2, using API IRPApplication.getApplicationConnectionString() coucanld retrieve the connection string of a specific Rhapsody instance from ROT to further pass the info to an external program if required (say plugin that invokes external Java process).






XLVI. Accessing the type of SyML FullPort

To access the type of a FullPort in Rational Rhapsody using the Java API, use the API method getOtherClass() on an object of type IRPPort. A sample code is below:

IRPClass theType = thePort.getOtherClass();
where thePort is an object of type IRPPort.

This is the same approach that is used for Parts and for all other kinds of Ports





XLVII. Difference between getFullPathName() and getCurrentDirectory() API methods

These two methods namely getFullPathName() and getCurrentDirectory() are available while declaring an instance of the interface IRPProject in the Rational Rhapsody API.

getFullPathName(): This method returns the internal path in a UML model that is loaded in Rational Rhapsody and not the local system path of the model location. If you invoke this method directly from IRPProject, it will most likely return an empty space as most models do not have their internal paths set. This is expected behavior.

getCurrentDirectory(): This method returns the system path (i.e. Windows or UNIX file path to the model itself)

Example: C:\Program Files\Models\modelexample.rpy

However it does not include the model name say
C\Program Files\Models\





XLVIII. Determine attribute value for a Base Class

In order to get the attribute value of the base class in Rational Rhapsody you can use the below JAVA API code snippet.

public class clsHidePort
{
public static void main(String[] args)
{
IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPInstance globalObj =(IRPInstance) app.getSelectedElement();
IRPClass cls = (IRPClass)globalObj.getOtherClass();
Iterator iter = cls.getAttributesIncludingBases().toList().iterator();

while(iter.hasNext())
{
IRPAttribute attr = (IRPAttribute)iter.next();
if(attr.getName().equals("myAttribute"))
{
System.out.println("Base Attribute Value : " + attr.getDefaultValue());
}
}
}
}




XLIX. Determine all objects being applied with same stereotype

In order to get all the objects being applied with same stereotype in Rational Rhapsody use the following Java API code:

public class ClsReqId
{
public static void main(String[] args)
{
IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject prj = app.activeProject();

for(Object o1:prj.getPackages().toList())
{
IRPPackage pkg = (IRPPackage)o1;
//System.out.println(pkg.getName());

for(Object o2:pkg.getGlobalObjects().toList())
{
IRPInstance obj = (IRPInstance)o2;
//System.out.println(obj.getName());

for(Object o3:obj.getStereotypes().toList())
{
IRPStereotype streo = (IRPStereotype)o3;
if(streo.getName().equals("pack1Stereo"))
System.out.println(obj.getName());
}
}
}
}
}





L. Insert a project into Rational Rhapsody model

In order to insert a project into the Rational Rhapsody Eclipse workspace you can use the API method insertProject(). Below is a code snippet for your reference:

import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class InsertProject
{
public static void main(String[] args)
{
IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
myApp.insertProject("C:\\Users\\IBM_ADMIN\\IBM\\Rational\\Rhapsody\\7.6.1\\Project\\Project.rpy");
}
}






LI. Determine if a unit is Unloaded

In order to check if a unit is unloaded in Rational Rhapsody use the following Java API code:

public class clsUnload
{
public static void main(String[] args)
{
IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPUnit myUnit = (IRPUnit)app.getSelectedElement();
if(myUnit.getIsStub() == 1)
System.out.println(myUnit.getName());
else
System.out.println("Hello");
}
}




LII. Exporting Object Model Diagrams from Rational Rhapsody mdoel

In order to export all Object Model Diagram from Rational Rhapsody using JAVA API you can use the below code as a reference. The code can be enhanced to include other specific diagram types

IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject myPrj = myApp.activeProject();

Iterator myIter1 = myPrj.getObjectModelDiagrams().toList().iterator();
while(myIter1.hasNext())
{
IRPDiagram myDia = (IRPDiagram) myIter1.next();
myDia.getPictureAs("C:\\Work\\Images\\"+myDia.getName()+".jpg", "JPEG", 0, null);
}





LIII. Add Source Artifacts to Rational Rhapsody model.

In order to add source artifacts using Java API, execute the code provided below (sample):

IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPModelElement target = (IRPClassifier) app.getSelectedElement();
IRPModelElement SA = target.addNewAggr("File", target.getName());
((IRPFile) SA).setFileType("Specification");
//or, set it to "Implementation", "logical" or "other"





Sample Helper application complete code

Following section provides complete code based solutions to specific client requirement





I. Extract operations from specific packages in Rational Rhapsody model

You can use the code below in order to extract operations from specific packages:

import java.io.*;

import com.telelogic.rhapsody.core.RhapsodyAppServer;
import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.IRPOperation;
import com.telelogic.rhapsody.core.IRPProject;
import com.telelogic.rhapsody.core.IRPPackage;
import com.telelogic.rhapsody.core.IRPModule;

public class getOperations
{
public static void main(String[] args)
{
try
{
BufferedWriter out = new BufferedWriter(new FileWriter("C:\\Temp\\FunctionsList.txt"));
String scrPkg = null, destPkg = null;
System.out.print("Enter the source package name : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
try
{
scrPkg = br1.readLine();
}
catch (IOException ioe)
{
System.out.println("IO error !!");
System.exit(1);
}
System.out.print("Enter the destination package name : ");
BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));
try
{
destPkg = br2.readLine();
}
catch (IOException ioe)
{
System.out.println("IO error !!");
System.exit(1);
}

IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject actPro = app.activeProject();
for(Object o1:actPro.getPackages().toList())
{
for(Object o3:((IRPPackage)o1).getPackages().toList())
{
if(((IRPPackage)o3).getName().equals(scrPkg) ||
((IRPPackage)o3).getName().equals(destPkg))
{
System.out.println("\n"+((IRPPackage)o3).getName()+"\n");
out.write("\n"+((IRPPackage)o3).getName()+"\n");out.newLine();
for(Object o2:((IRPPackage)o3).getModules().toList())
{
System.out.println("-----------------------------------------------------------");
for(Object 04:((IRPModule)o2).getNestedElementsRecursive().toList())
{
if(o4 instanceof IRPOperation)
{
System.out.print(((IRPOperation)o4).getOwner().getName()+"--> ");
System.out.println(((IRPOperation)o4).getName());
out.write(((IRPOperation)o4).getOwner().getName()+"--> ");
out.write(((IRPOperation)o4).getName());out.newLine();
}
}
System.out.println("-----------------------------------------------------------");
}
}
}
}
out.close();
}
catch (IOException e)
{
System.err.println("Something went wrong");
e.printStackTrace();
}
}
}




II. Extract information regarding Overridden properties in Rational Rhapsody model

In order to retrieve the information related to the overridden properties you would need to use the API method getOverriddenProperties(int recursive) available for the IRPModelElement interface

The argument (int recursive) determines if you want the overridden properties only at the level where the API method is called or that level and all levels (recursively) below it.

An illustration of the same is as below:

import com.telelogic.rhapsody.core.RhapsodyAppServer;
import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.IRPModelElement;
import com.telelogic.rhapsody.core.IRPProject;
import com.telelogic.rhapsody.core.IRPUnit;

public class getOverriddenProperties
{
public static void main(String[] args)
{
IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject actPro = app.activeProject();

for(Object o:actPro.getNestedElementsRecursive().toList())
{
IRPModelElement myEle = (IRPModelElement)o;

//if(!(myEle.getMetaClass() .contains("Diagram")))
IRPUnit unit = myEle.getSaveUnit();

if(unit.isReadOnly()== 0)
{
if(myEle.getOverriddenProperties(0).getCount()>0)
System.out.println("\n" + myEle.getName() + "\n");

for(Object o1:myEle.getOverriddenProperties(0).toList())
System.out.println(o1.toString());
}
}
}
}





III. Check for dependencies stereotyped as (say usage, trace…) in Rational Rhapsody

In order to check for a dependencies of a specific type you would need to use the API methods getStereotype() and getName() coupled with eclipse command equals

In the following code you would be checking for the dependency which are stereotypes as is used in

import com.telelogic.rhapsody.core.IRPCollection;
import com.telelogic.rhapsody.core.IRPExternalCheckRegistry;
import com.telelogic.rhapsody.core.IRPModelElement;
import com.telelogic.rhapsody.core.RPExternalCheck;
import com.telelogic.rhapsody.core.IRPDependency;

// This class implements the Rhapsody check
public class DependencyCheck extends RPExternalCheck
{
// Register this external check
public DependencyCheck(IRPExternalCheckRegistry extCR)
{
connect(extCR);
}

// Method which contains code for the actual check
@Override

public boolean check(IRPModelElement elem, IRPCollection failedElements)
{
boolean allOK = true;
IRPDependency dep = (IRPDependency)elem;

// check .....
if(dep.getStereotype() != null)
if(dep.getStereotype().getName().equals("is used in"))
if( !(dep.getDependsOn().getMetaClass().equals("Event") &&
dep.getDependent().getMetaClass().equals("Event")) )
allOK = false;
return allOK;
}

// Method called when Rhapsody is exited, used to unregister the check
@Override
public void doExit()
{
disconnect();
}

// Specifies whether check is for Completeness or Correctness (i.e. Integrity of the check)
@Override
public boolean getCompleteness()
{
return true;
}

// Specifies the domain (area of model searched) for this check
// e.g. Class Model (structural), Statechart (behavior), Common(both), etc.
@Override
public String getDomain()
{
return "Custom Check";
}

// Specifies the Metaclass to which this check should initially apply
@Override
public String getMetaclasses()
{
return "Dependency";
}

// Specifies the name of this check
@Override
public String getName()
{
return "Dependency with stereotype 'is used in' applicable only between events";
}

// Specifies the severity of this check - e.g. Error, Warning, Info
@Override
public String getSeverity()
{
return "Error";
}

// Specifies whether or not this check should be called during code generation
@Override
public boolean getShouldCallFromCG()
{
return true;
}
}





IV. Using DOM libraries via the API methods in Rational Rhapsody

In order to use DOM libraries with Java APIs in Rational Rhapsody you can use the below code snippet as a reference:

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.telelogic.rhapsody.core.IRPClass;
import com.telelogic.rhapsody.core.IRPCollection;
import com.telelogic.rhapsody.core.IRPExternalCheckRegistry;
import com.telelogic.rhapsody.core.IRPModelElement;
import com.telelogic.rhapsody.core.RPExternalCheck;


public class OperationCheck extends RPExternalCheck
{
// Register this external check
public OperationCheck(IRPExternalCheckRegistry extCR)
{
connect(extCR);
}

@Override
public boolean check(IRPModelElement elem, IRPCollection FailedElements)
{

// check .....
int numOfOp = getNumOfOp();
IRPClass cls = (IRPClass) elem;
if(cls.getOperations().toList().size() > numOfOp)
return false;
else
return true;
}

private int getNumOfOp()
{
try
{
File file = new File("C:\\Work\\PMR RELATED\\91059,019,866\\test.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();

NodeList nodeLst = doc.getElementsByTagName("class");
Node fstNode = nodeLst.item(0);
if (fstNode.getNodeType() == Node.ELEMENT_NODE)
{
Element fstEle = (Element) fstNode;
NodeList opEleLst = fstEle.getElementsByTagName("operations");
Element opEle = (Element) opEleLst.item(0);
NodeList op = opEle.getChildNodes();
return (Integer.parseInt(((Node) op.item(0)).getNodeValue()));
}
}
catch (Exception e)
{
e.printStackTrace();
}
return 0;
}

@Override
public void doExit()
{
disconnect();
}

@Override
public boolean getCompleteness()
{
return true;
}

@Override
public String getDomain()
{
return "Custom Check";
}

@Override
public String getMetaclasses()
{
return "Class";
}

@Override
public String getName()
{
return "Class with more than 5 operations";
}

@Override
public String getSeverity()
{
return "Warning";
}

@Override
public boolean getShouldCallFromCG()
{
return false;
}
}





V. Creating image files for matrix views

In order to create image files for the matrix views in Rational Rhapsody, you can use the API method getImageCollection(String folderName, String fileName, String extension)

Find below a sample code for the same:

import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.IRPMatrixView;
import com.telelogic.rhapsody.core.IRPModelElement;
import com.telelogic.rhapsody.core.IRPProject;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class MatrixViewUsage
{
public static void main(String[] args)
{
IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject prj = app.activeProject();
int count = 1;
for (Object obj : prj.getNestedElementsRecursive().toList())
{
IRPModelElement elem = (IRPModelElement) obj;
if(obj instanceof IRPMatrixView)
{
IRPMatrixView matObj = (IRPMatrixView)obj;
matObj.getImageCollection("C:\\Temp\\Test\\",
"MatrixView"+String.valueOf(count), "jpg");
count++;
}
}
}
}







VI. Determine full path of generated files in Rational Rhapsody model

In order to determine the full path of generated file from Rational Rhapsody model you can consider using the following code snippet:

import com.telelogic.rhapsody.core.*;

public class genFullPath
{
public static void main(String[] args)
{
IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject prj = app.activeProject();
String actConfPath="", modelPath="", finalPath="";
int pos=0;
IRPCollection elementsInScope = prj.getActiveComponent().getScopeElements();
for( int elementCount = 1; elementCount <= elementsInScope.getCount(); elementCount ++ )
{
actConfPath = prj.getActiveConfiguration().getPath(1);
finalPath += actConfPath+"/";
IRPModelElement element = (IRPModelElement)elementsInScope.getItem(elementCount);
System.out.println("Element: " + element.getName());
modelPath = element.getFullPathName();
pos = modelPath.indexOf("::");
while(pos != -1)
{
String tempStr = modelPath.substring(0, pos);
finalPath += tempStr+'/';
modelPath = modelPath.substring(pos+2);
pos = modelPath.indexOf("::");
}
System.out.println("ElementPath: " + finalPath + "\n");
finalPath = "";
}
}
}





VII. Applying diagram properties to existing diagram elements

You can use the following code snippet to achieve your requirement:

import com.telelogic.rhapsody.core.*;

public class updateTagDisplay
{
public static void main(String[] args)
{
IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject prj = app.activeProject();
for (Object obj : prj.getNestedElementsRecursive().toList())
if(obj instanceof IRPObjectModelDiagram)
{
IRPObjectModelDiagram myOMD = (IRPObjectModelDiagram) obj;
String grPrp = myOMD.getPropertyValue("ObjectModelGe.Tag.ShowName");
for(Object obj1 : myOMD.getGraphicalElements().toList())
if(obj1 instanceof IRPGraphNode)
{
IRPGraphNode myNode = (IRPGraphNode) obj1;
String eleType = myNode.getModelObject().getMetaClass();
if(eleType.equals("Tag"))
myNode.setGraphicalProperty("ShowName", grPrp);
}
}
}
}





VIII. Copying complete model

In order to copy a model using JAVA API in Rational Rhapsody you can use the below code snippet as a reference:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.IRPComponent;
import com.telelogic.rhapsody.core.IRPProject;
import com.telelogic.rhapsody.core.IRPUnit;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class CopyProject
{
public static void main(String[] args)
{
CopyProject cd = new CopyProject();
IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject prj = app.activeProject();

String source = prj.getCurrentDirectory();
String destination = source.substring(0, source.lastIndexOf('\\'))+"\\CopyOf"+prj.getName();

File src = new File(source);
File dst = new File(destination);

try
{
cd.copyDirectory(src,dst);
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println("Project copied.");
}

public void copyDirectory(File srcPath, File dstPath) throws IOException
{
if (srcPath.isDirectory())
{
if (!dstPath.exists())
{
dstPath.mkdir();
}
String files[] = srcPath.list();

for(int i = 0; i < files.length; i++)
{
copyDirectory(new File(srcPath, files[i]), new File(dstPath, files[i]));
}
}
else
{
if(!srcPath.exists())
{
System.out.println("File or directory does not exist.");
System.exit(0);
}
else
{
InputStream in = new FileInputStream(srcPath);
OutputStream out = new FileOutputStream(dstPath);
byte[] buf = new byte[1024];
int len;

while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}


in.close();
out.close();
}
}
}
}





IX. Searching for an Operation Call made from another Operation

In order to search for an Operation Call that is being called by other operations using JAVA API in Rational Rhapsody you can use the below code snippet as a reference:

Note: You need to have the desired operation selected in the Rational Rhapsody Browser, before executing the above code.


import java.util.Iterator;

import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.IRPModelElement;
import com.telelogic.rhapsody.core.IRPOperation;
import com.telelogic.rhapsody.core.IRPProject;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class findOpCall
{
public static void main(String[] args)
{
IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject myPrj = myApp.activeProject();

IRPModelElement myEle = myApp.getSelectedElement();
String searchEle = myEle.getName();

Iterator myIter = myPrj.getNestedElementsRecursive().toList().iterator();
while(myIter.hasNext())
{
Object myObj = (Object) myIter.next();
if (myObj instanceof IRPOperation)
{
IRPOperation myOp = (IRPOperation) myObj;
String temp = myOp.getBody();
if(temp.contains(searchEle))
{
System.out.println(myOp.getName());
}
}
}
}
}

.




X. Changing names of Action or Decision model element

In order to change names of Action/Decision using JAVA API in Rational Rhapsody you can use the below code as a reference.


import java.util.Iterator;

import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.IRPModelElement;
import com.telelogic.rhapsody.core.IRPProject;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class TestProject
{
public static void main(String[] args)
{
IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject prj = app.activeProject();

int count = 1;

Iterator myIter = prj.getNestedElementsRecursive().toList().iterator();
while(myIter.hasNext())
{
Object myObj = (Object) myIter.next();
IRPModelElement myEle = (IRPModelElement) myObj;

if(myEle.getMetaClass().equals("State") || myEle.getMetaClass().equals("Condition"))

if(!(myEle.getName().equals("ROOT")))
{
Iterator myIter2 = prj.getNestedElementsRecursive().toList().iterator();
while(myIter2.hasNext())
{
Object myObj2 = (Object) myIter2.next();
IRPModelElement myEle2 = (IRPModelElement) myObj2;
if(myEle2.getMetaClass().equals("State") ||
myEle.getMetaClass().equals("Condition"))
if(!(myEle2.getName().equals("ROOT")))
if(!(myEle.equals(myEle2)))
if(myEle.getName().equals(myEle2.getName()))
myEle2.setName(myEle2.getName()+"_Changed_"+count++);
}
}
}
}
}





XI. Update Associate relations post Reverse Engineering

In order to update association relation after Reverse Engineering using JAVA API in Rational Rhapsody you can use the below code as a reference:

import java.util.Iterator;

import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.IRPAttribute;
import com.telelogic.rhapsody.core.IRPClass;
import com.telelogic.rhapsody.core.IRPModelElement;
import com.telelogic.rhapsody.core.IRPProject;
import com.telelogic.rhapsody.core.IRPRelation;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class createAssociations
{
public static void main(String[] args)
{
IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject myPrj = myApp.activeProject();

Iterator myIter = myPrj.getNestedElementsRecursive().toList().iterator();
while(myIter.hasNext())
{
Object myObj = myIter.next();
if(myObj instanceof IRPAttribute)
{
IRPAttribute myAtt = (IRPAttribute) myObj;
String Temp = myAtt.getDeclaration();
if(Temp.contains("* *"))
{
String subTemp = Temp.substring(0,Temp.indexOf(' '));
IRPModelElement myEle = myPrj.findNestedElementRecursive(subTemp,"Class");
IRPClass myCls2 = null;

if(myEle==null)
myCls2 = (IRPClass) myAtt.getOwner().getOwner().addNewAggr("Class", subTemp);
else
myCls2 = (IRPClass) myEle;

IRPClass myCls1 = (IRPClass) myAtt.getOwner();
IRPRelation myRel = myCls1.addRelation(myCls2.getName(),
myCls2.getOwner().getName(), myAtt.getName(),
"Association", "", "","Association", "", "Test");
myRel.makeUnidirect();
myAtt.deleteFromProject();
}
}
}
}
}




XII. Achieve pointer type modeling for argument types

In order to achieve pointer (*) type modeling of argument types you would need to use the description field.
The following script leverages this idea of modeling argument types (using the description field) as pointer, constant, pointer pointer, etc and as per the modeling technique used specific argument properties are updated to generate the desired code.

The script understands the following modeling constructs (in the description field) for an argument:

@Constant : constant type
@Pointer : pointer type
@*Pointer : pointer pointer type
@*Constant : constant pointer type
Absence of above constructs : default type

The workflow for achieving the desired code generation:

Model the arguments in the model using the constructs as mentioned above
Once the desired modeling technique is achieved run the java script
Once the script execution is complete, generate the code

A sample code is below:


import java.util.Iterator;

import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.IRPArgument;
import com.telelogic.rhapsody.core.IRPProject;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class argTypeGen
{
public static void main(String[] args)
{
IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject myPrj = myApp.activeProject();

Iterator myIter = myPrj.getNestedElementsRecursive().toList().iterator();
while(myIter.hasNext())
{
Object myObj = myIter.next();
if(myObj instanceof IRPArgument)
{
IRPArgument myArg = (IRPArgument) myObj;
String argDesc = myArg.getDescription();
String argDir = myArg.getArgumentDirection();
String inPrpKey = "C_CG.Type.In";
String outPrpKey = "C_CG.Type.Out";
String inoutPrpKey = "C_CG.Type.InOut";
String cnstPrpVal = "const $type";
String pntrPrpVal = "$type*";
String pntrPntrPrpVal = "$type**";
String pntrCnstPrpVal = "const $type*";
String prpVal = "$type";

if(argDesc.contains("@Constant"))
{
if(argDir.equals("In"))
myArg.setPropertyValue(inPrpKey, cnstPrpVal);
else if(argDir.equals("Out"))
myArg.setPropertyValue(outPrpKey, cnstPrpVal);
else
myArg.setPropertyValue(inoutPrpKey, cnstPrpVal);
}

else if(argDesc.contains("@Pointer"))
{
if(argDir.equals("In"))
myArg.setPropertyValue(inPrpKey, pntrPrpVal);
else if(argDir.equals("Out"))
myArg.setPropertyValue(outPrpKey, pntrPrpVal);
else
myArg.setPropertyValue(inoutPrpKey, pntrPrpVal);
}

else if(argDesc.contains("@*Pointer"))
{
if(argDir.equals("In"))
myArg.setPropertyValue(inPrpKey, pntrPntrPrpVal);
else if(argDir.equals("Out"))
myArg.setPropertyValue(outPrpKey, pntrPntrPrpVal);
else
myArg.setPropertyValue(inoutPrpKey, pntrPntrPrpVal);
}

else if(argDesc.contains("@*Constant"))
{
if(argDir.equals("In"))
myArg.setPropertyValue(inPrpKey, pntrCnstPrpVal);
else if(argDir.equals("Out"))
myArg.setPropertyValue(outPrpKey, pntrCnstPrpVal);
else
myArg.setPropertyValue(inoutPrpKey, pntrCnstPrpVal);
}

else
{
if(argDir.equals("In"))
myArg.setPropertyValue(inPrpKey, prpVal);
else if(argDir.equals("Out"))
myArg.setPropertyValue(outPrpKey, prpVal);
else
myArg.setPropertyValue(inoutPrpKey, prpVal);
}
}
}
}
}





XIII. Reverse Engineering Simulink files into Rational Rhapsody model

In order to Reverse Engineer Simulink (.m) files using JAVA API in IBM Rational Rhapsody, you can use the below code as reference:

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Scanner;

import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.IRPAttribute;
import com.telelogic.rhapsody.core.IRPClass;
import com.telelogic.rhapsody.core.IRPClassifier;
import com.telelogic.rhapsody.core.IRPDependency;
import com.telelogic.rhapsody.core.IRPModelElement;
import com.telelogic.rhapsody.core.IRPPackage;
import com.telelogic.rhapsody.core.IRPProject;
import com.telelogic.rhapsody.core.IRPStereotype;
import com.telelogic.rhapsody.core.IRPType;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class RE_Simulink_Files
{
public static void main(String[] args)
{
IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject myPrj = myApp.activeProject();

System.out.println("Enter the path to the simulink files (use '\\\\' insetead of single '\\' for directory delimiters). Ex: \"C:\\\\Work\\\\mFiles\\\\DefaultConfig\".");
Scanner scan = new Scanner(System.in);
String path = scan.nextLine();

String pkgName = path.substring(path.lastIndexOf("\\\\")+2, path.length());
IRPPackage myPkg = myPrj.addPackage(pkgName);

IRPPackage myPkg1 = null;
IRPClass myCls = null;

IRPStereotype myStr1 = (IRPStereotype) myPrj.findNestedElementRecursive("ICD_Base",
"Stereotype");
IRPStereotype myStr2 = (IRPStereotype) myPrj.findNestedElementRecursive("ICD_Base_Type",
"Stereotype");
IRPStereotype myStr3 = (IRPStereotype) myPrj.findNestedElementRecursive("ICD_Message",
"Stereotype");
IRPStereotype myStr4 = (IRPStereotype) myPrj.findNestedElementRecursive("ICD_Signal",
"Stereotype");
IRPStereotype myStr5 = (IRPStereotype) myPrj.findNestedElementRecursive("ICD_Information",
"Stereotype");

File directory = new File(path);
File files[] = directory.listFiles();


for (File f : files)
{
if(f.toString().contains(".m"))
{
myPkg1 = myPkg.addNestedPackage(f.toString().substring(f.toString().lastIndexOf('\\')+1,
f.toString().length()-2) + "_pkg");
myCls = myPkg1.addClass(f.toString().substring(f.toString().lastIndexOf('\\')+1,
f.toString().length()-2));
myCls.setStereotype(myStr1);
}

try
{
FileInputStream fstream = new FileInputStream(f);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null)
{
IRPType myType = null;
if(strLine.contains("ICD_Base_Type:-") || strLine.contains("ICD_Message:-"))
{
if(strLine.contains("ICD_Message:-"))
{
myType = myPkg1.addType(strLine.substring(17, strLine.length()));
myType.setStereotype(myStr3);
IRPAttribute myAtt = myCls.addAttribute(strLine.substring(17,
strLine.length()));
IRPDependency myDep =
myAtt.addDependencyTo((IRPModelElement)myType);
myDep.setStereotype(myStr5);
}
else
{
myType = myPkg1.addType(strLine.substring(19, strLine.length()));
myType.setStereotype(myStr2);
}

myType.setKind("Structure");
while(!strLine.contains(" }} ..."))
{
strLine = br.readLine();
if(strLine.contains("}; ..."))
{
IRPAttribute myAtt = null;
try{
myAtt = myType.addAttribute(strLine.substring(7,
strLine.indexOf("\',")));
}
catch (Exception e){
myAtt = myType.addAttribute(strLine.substring(7,
strLine.indexOf("\' ")));
}

myAtt.setStereotype(myStr4);

strLine = strLine.substring(strLine.indexOf(", "));
int index1 = strLine.indexOf(", ");
strLine = strLine.substring(index1+2);
int index2 = strLine.indexOf(", ");
myAtt.setMultiplicity(strLine.substring(index1, index2));
strLine = strLine.substring(index1 = strLine.indexOf(", "));
strLine = strLine.substring(strLine.indexOf('\'')+1);
String typeStr = strLine.substring(0, strLine.indexOf('\''));

if(typeStr.equals("uint8")) typeStr = "Unsigned_8";
if(typeStr.equals("uint16")) typeStr = "Unsigned_16";
if(typeStr.equals("uint32")) typeStr = "Unsigned_32";
if(typeStr.equals("int8")) typeStr = "Integer_8";
if(typeStr.equals("int16")) typeStr = "Integer_16";
if(typeStr.equals("int32")) typeStr = "Integer_32";
if(typeStr.equals("fixdt(1, 16, 0)")) typeStr = "Fixed_16";
if(typeStr.equals("fixdt(1, 32, 0)")) typeStr = "Fixed_32";
if(typeStr.equals("fixdt(1, 64, 0)")) typeStr = "Fixed_64";
if(typeStr.equals("double")) typeStr = "Double";
if(typeStr.equals("boolean")) typeStr = "RhpBoolean";
IRPType myType12;

try {
myType12 = (IRPType) myPkg1.findNestedElementRecursive(typeStr, "Type");
myAtt.setType((IRPClassifier)myType12);
}
catch (Exception e){
myType12 = (IRPType) myPrj.findNestedElementRecursive(typeStr, "Type");
myAtt.setType((IRPClassifier)myType12);
}
}
}
}
}
in.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}






XIV. Achieve pointer type modeling for attribute types

In order to achieve pointer (*) type modeling of attribute types you can use the description field.

The following script leverages this idea of modeling attribute types (using @*Pointer in the description field) as pointer pointer:


import java.util.Iterator;

import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.IRPAttribute;
import com.telelogic.rhapsody.core.IRPProject;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class attTypeGen
{
public static void main(String[] args)
{
IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject myPrj = myApp.activeProject();

Iterator myIter = myPrj.getNestedElementsRecursive().toList().iterator();
while(myIter.hasNext())
{
Object myObj = myIter.next();
if(myObj instanceof IRPAttribute)
{
IRPAttribute myAtt = (IRPAttribute) myObj;
String attDesc = myAtt.getDescription();

String prpKey = "C_CG.Attribute.ReferenceImplementationPattern";
String prpVal = "**";

if(attDesc.contains("@*Pointer"))
{
myAtt.setIsReference(1);
myAtt.setPropertyValue(prpKey, prpVal);
}
}
}
}
}






XV. Achieve parameter type modeling for attribute types

In order to achieve array parameter type modeling of argument types we can use the description field.

The below script leverages this idea of modeling argument types (using @Array in the description field) as an array parameter.


import java.util.Iterator;
import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.IRPArgument;
import com.telelogic.rhapsody.core.IRPProject;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class argTypeGen
{
public static void main(String[] args)
{
IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject myPrj = myApp.activeProject();
Iterator myIter = myPrj.getNestedElementsRecursive().toList().iterator();

while(myIter.hasNext())
{
Object myObj = myIter.next();
if(myObj instanceof IRPArgument)
{
IRPArgument myArg = (IRPArgument) myObj;
String argDesc = myArg.getDescription();
String argDir = myArg.getArgumentDirection();
String inPrpKey = "C_CG.Type.In";
String outPrpKey = "C_CG.Type.Out";
String inoutPrpKey = "C_CG.Type.InOut";
String cnstPrpVal = "const $type";
String pntrPrpVal = "$type *";
String pntrPntrPrpVal = "$type **";
String pntrCnstPrpVal = "const $type *";
String prpVal = "$type";
String arrPrpVal = "$type";

if(argDesc.contains("@Array"))
{
int startPos = argDesc.indexOf('[');
int endPos = argDesc.indexOf(']');
arrPrpVal += "[" + argDesc.substring(startPos + 1, endPos) + "]";

if(argDir.equals("In"))
myArg.setPropertyValue(inPrpKey, arrPrpVal);

else if(argDir.equals("Out"))
myArg.setPropertyValue(outPrpKey, arrPrpVal);

else
myArg.setPropertyValue(inoutPrpKey, arrPrpVal);
}
}
}
}
}






XVI. Creating MATLAB built in types

In order to create MATLAB built-in types using JAVA API in IBM Rational Rhapsody, you can use the below code as reference:

import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.IRPClassifier;
import com.telelogic.rhapsody.core.IRPPackage;
import com.telelogic.rhapsody.core.IRPProject;
import com.telelogic.rhapsody.core.IRPTag;
import com.telelogic.rhapsody.core.IRPType;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class Simulink
{
public static void main(String[] args)
{
IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject myPrj = myApp.activeProject();
IRPPackage myPkg = myPrj.addPackage("Common_Types");
String myStr = myPrj.findNestedElementRecursive("ICD_Type", "Stereotype").getName();
IRPType myType1 = myPkg.addType("Double");

myType1.addStereotype(myStr, "Type");
IRPTag myTag1 = (IRPTag) myType1.addNewAggr("Tag", "Description");
myTag1.setDefaultValue("This is a 64 bit floating point number type.");
IRPTag myTag2 = (IRPTag) myType1.addNewAggr("Tag", "No_Bits");
myTag2.setDefaultValue("8*8");
IRPTag myTag3 = (IRPTag) myType1.addNewAggr("Tag", "Numeric_Type");
myTag3.setType((IRPClassifier) myPrj.findNestedElementRecursive("Numeric_Type", "Type"));
myTag3.setDefaultValue("Float");

IRPType myType2 = myPkg.addType("Fixed_16");
myType2.addStereotype(myStr, "Type");
IRPTag myTag4 = (IRPTag) myType2.addNewAggr("Tag", "No_Bits");
myTag4.setDefaultValue("2*8");
IRPTag myTag5 = (IRPTag) myType2.addNewAggr("Tag", "Numeric_Type");
myTag5.setType((IRPClassifier) myPrj.findNestedElementRecursive("Numeric_Type", "Type"));
myTag5.setDefaultValue("Fixed_Point");

IRPType myType3 = myPkg.addType("Fixed_32");
myType3.addStereotype(myStr, "Type");
IRPTag myTag6 = (IRPTag) myType3.addNewAggr("Tag", "No_Bits");
myTag6.setDefaultValue("4*8");
IRPTag myTag7 = (IRPTag) myType3.addNewAggr("Tag", "Numeric_Type");
myTag7.setType((IRPClassifier) myPrj.findNestedElementRecursive("Numeric_Type", "Type"));
myTag7.setDefaultValue("Fixed_Point");

IRPType myType4 = myPkg.addType("Fixed_64");
myType4.addStereotype(myStr, "Type");
IRPTag myTag8 = (IRPTag) myType4.addNewAggr("Tag", "No_Bits");
myTag8.setDefaultValue("8*8");
IRPTag myTag9 = (IRPTag) myType4.addNewAggr("Tag", "Numeric_Type");
myTag9.setType((IRPClassifier) myPrj.findNestedElementRecursive("Numeric_Type", "Type"));
myTag9.setDefaultValue("Fixed_Point");

IRPType myType5 = myPkg.addType("Integer_16");
myType5.addStereotype(myStr, "Type");
IRPTag myTag10 = (IRPTag) myType5.addNewAggr("Tag", "No_Bits");
myTag10.setDefaultValue("2*8");
IRPTag myTag11 = (IRPTag) myType5.addNewAggr("Tag", "Numeric_Type");
myTag11.setType((IRPClassifier) myPrj.findNestedElementRecursive("Numeric_Type", "Type"));
myTag11.setDefaultValue("Integer");
IRPTag myTag12 = (IRPTag) myType5.addNewAggr("Tag", "Description");
myTag12.setDefaultValue("This is a 16 bit signed numerical type.");
IRPTag myTag13 = (IRPTag) myType5.addNewAggr("Tag", "Max");
myTag13.setDefaultValue("32767");
IRPTag myTag14 = (IRPTag) myType5.addNewAggr("Tag", "Min");
myTag14.setDefaultValue("-32768");

IRPType myType6 = myPkg.addType("Integer_32");
myType6.addStereotype(myStr, "Type");
IRPTag myTag15 = (IRPTag) myType6.addNewAggr("Tag", "No_Bits");
myTag15.setDefaultValue("4*8");
IRPTag myTag16 = (IRPTag) myType6.addNewAggr("Tag", "Numeric_Type");
myTag16.setType((IRPClassifier) myPrj.findNestedElementRecursive("Numeric_Type", "Type"));
myTag16.setDefaultValue("Integer");
IRPTag myTag17 = (IRPTag) myType6.addNewAggr("Tag", "Description");
myTag17.setDefaultValue("This is a 32 bit signed numerical type.");
IRPTag myTag18 = (IRPTag) myType6.addNewAggr("Tag", "Max");
myTag18.setDefaultValue("2147483647");
IRPTag myTag19 = (IRPTag) myType6.addNewAggr("Tag", "Min");
myTag19.setDefaultValue("-2147483648");

IRPType myType7 = myPkg.addType("Integer_8");
myType7.addStereotype(myStr, "Type");
IRPTag myTag20 = (IRPTag) myType7.addNewAggr("Tag", "No_Bits");
myTag20.setDefaultValue("1*8");
IRPTag myTag21 = (IRPTag) myType7.addNewAggr("Tag", "Numeric_Type");
myTag21.setType((IRPClassifier) myPrj.findNestedElementRecursive("Numeric_Type", "Type"));
myTag21.setDefaultValue("Integer");
IRPTag myTag22 = (IRPTag) myType7.addNewAggr("Tag", "Description");
myTag22.setDefaultValue("This is an 8 bit signed numerical type.");
IRPTag myTag23 = (IRPTag) myType7.addNewAggr("Tag", "Max");
myTag23.setDefaultValue("127");
IRPTag myTag24 = (IRPTag) myType7.addNewAggr("Tag", "Min");
myTag24.setDefaultValue("-128");

IRPType myType8 = myPkg.addType("Single");
myType8.addStereotype(myStr, "Type");
IRPTag myTag25 = (IRPTag) myType8.addNewAggr("Tag", "Description");
myTag25.setDefaultValue("This is a 32 bit floating point number type.");
IRPTag myTag26 = (IRPTag) myType8.addNewAggr("Tag", "No_Bits");
myTag26.setDefaultValue("4*8");
IRPTag myTag27 = (IRPTag) myType8.addNewAggr("Tag", "Numeric_Type");
myTag27.setType((IRPClassifier) myPrj.findNestedElementRecursive("Numeric_Type", "Type"));
myTag27.setDefaultValue("Float");

IRPType myType9 = myPkg.addType("Unsigned_16");
myType9.addStereotype(myStr, "Type");
IRPTag myTag28 = (IRPTag) myType9.addNewAggr("Tag", "No_Bits");
myTag28.setDefaultValue("2*8");
IRPTag myTag29 = (IRPTag) myType9.addNewAggr("Tag", "Numeric_Type");
myTag29.setType((IRPClassifier) myPrj.findNestedElementRecursive("Numeric_Type", "Type"));
myTag29.setDefaultValue("Integer");
IRPTag myTag30 = (IRPTag) myType9.addNewAggr("Tag", "Description");
myTag30.setDefaultValue("This is a 16 bit positive numerical type.");
IRPTag myTag31 = (IRPTag) myType9.addNewAggr("Tag", "Max");
myTag31.setDefaultValue("65535");
IRPTag myTag32 = (IRPTag) myType9.addNewAggr("Tag", "Min");
myTag32.setDefaultValue("0");

IRPType myType10 = myPkg.addType("Unsigned_32");
myType10.addStereotype(myStr, "Type");
IRPTag myTag33 = (IRPTag) myType10.addNewAggr("Tag", "No_Bits");
myTag33.setDefaultValue("4*8");
IRPTag myTag34 = (IRPTag) myType10.addNewAggr("Tag", "Numeric_Type");
myTag34.setType((IRPClassifier) myPrj.findNestedElementRecursive("Numeric_Type", "Type"));
myTag34.setDefaultValue("Integer");
IRPTag myTag35 = (IRPTag) myType10.addNewAggr("Tag", "Description");
myTag35.setDefaultValue("This is a 32 bit positive numerical type.");
IRPTag myTag36 = (IRPTag) myType10.addNewAggr("Tag", "Max");
myTag36.setDefaultValue("4294967295");
IRPTag myTag37 = (IRPTag) myType10.addNewAggr("Tag", "Min");
myTag37.setDefaultValue("0");

IRPType myType11 = myPkg.addType("Unsigned_8");
myType11.addStereotype(myStr, "Type");
IRPTag myTag38 = (IRPTag) myType11.addNewAggr("Tag", "No_Bits");
myTag38.setDefaultValue("1*8");
IRPTag myTag39 = (IRPTag) myType11.addNewAggr("Tag", "Numeric_Type");
myTag39.setType((IRPClassifier) myPrj.findNestedElementRecursive("Numeric_Type", "Type")); myTag39.setDefaultValue("Integer");
IRPTag myTag40 = (IRPTag) myType11.addNewAggr("Tag", "Description");
myTag40.setDefaultValue("This is an 8 bit positive numerical type.");
IRPTag myTag41 = (IRPTag) myType11.addNewAggr("Tag", "Max");
myTag41.setDefaultValue("255");
IRPTag myTag42 = (IRPTag) myType11.addNewAggr("Tag", "Min");
myTag42.setDefaultValue("0");
}
}





XVII. Creating a table matrix for statechart elements

In order to create a text matrix for statechart elements you can use the below code as reference:

import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.IRPModelElement;
import com.telelogic.rhapsody.core.IRPProject;
import com.telelogic.rhapsody.core.IRPStateVertex;
import com.telelogic.rhapsody.core.IRPStatechart;
import com.telelogic.rhapsody.core.IRPTransition;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class Statechart_Info
{
public static void main(String[] args)
{
IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject prj = app.activeProject();
IRPModelElement moEle = app.getSelectedElement();
IRPStatechart mySC = (IRPStatechart) moEle;
String defTran=null;
for (Object obj : mySC.getNestedElementsRecursive().toList())
{
if(obj instanceof IRPTransition)
{
IRPTransition myTran = (IRPTransition) obj;
if(myTran.isDefaultTransition()==1)
defTran = myTran.getName();
}
}
for (Object obj : mySC.getNestedElementsRecursive().toList())
{
if(obj instanceof IRPStateVertex)
{
IRPStateVertex mySV = (IRPStateVertex) obj;
System.out.println("State: " + mySV.getName());
System.out.println("\nIncoming Transition(s) to " + mySV.getName());
for(Object obj1 : mySV.getInTransitions().toList())
{
IRPTransition myTran = (IRPTransition) obj1;
System.out.println("Transition: " + myTran.getName());
}
System.out.println("\nOutgoing Transition(s) from " + mySV.getName());
for(Object obj1 : mySV.getOutTransitions().toList())
{
IRPTransition myTran = (IRPTransition) obj1;
System.out.println("Transition: " + myTran.getName());
}
if(mySV.getName().equals("ROOT"))
System.out.println("Transition: " + defTran);
System.out.println("\n");
}
}
}
}




XVIII. Creating a file of dependency list

In order to create a file of dependency list using JAVA API you can use the below code as reference:

import java.io.*;

import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.IRPDependency;
import com.telelogic.rhapsody.core.IRPModule;
import com.telelogic.rhapsody.core.IRPClassifier;
import com.telelogic.rhapsody.core.IRPClass;
import com.telelogic.rhapsody.core.IRPModelElement;
import com.telelogic.rhapsody.core.IRPPackage;
import com.telelogic.rhapsody.core.IRPProject;
import com.telelogic.rhapsody.core.IRPOperation;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class CreateDependencyList
{
public static void main(String[] args)
{
try
{
BufferedWriter out = new BufferedWriter(new FileWriter("C:\\Temp\\DepList.txt"));
IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPModelElement selectedElem = (IRPModelElement)app.getSelectedElement();
if(selectedElem.getMetaClass().equals("Package"))
{
IRPPackage pkg = (IRPPackage)selectedElem;
for(Object o:pkg.getNestedElementsRecursive().toList()
{
if(o instanceof IRPDependency)
{
IRPDependency dep = (IRPDependency)o;
IRPModule dependentmod =null;
IRPModule dependsOnmod =null;
try
{

if (dep.getDependent().getUserDefinedMetaClass().equals("Class"))
dependentmod = (IRPModule)dep.getDependent().getOwner();
else
dependentmod =
(IRPModule)dep.getDependent().getOwner().getOwner();
if(dep.getDependsOn().getUserDefinedMetaClass().equals("Class"))
dependsOnmod=(IRPModule)dep.getDependsOn().getOwner();
else
dependsOnmod=
(IRPModule)dep.getDependsOn().getOwner().getOwner();
}
catch (ClassCastException e)
{
continue;
}
String flowName = dependentmod.getName()+" "+dependsOnmod.getName();
System.out.println(flowName);
out.write(flowName);out.newLine();
IRPClassifier myCls = (IRPClassifier) (dependentmod.getOfClass());
IRPModelElement myEle =
myCls.getOwner().findNestedElementRecursive(dependentmod.getName(),
"Class");
IRPClass myCls1 = (IRPClass) myEle;
for(Object o1:myCls1.getOperations().toList())
{
System.out.print(((IRPOperation)o1).getName()+" ");
out.write(((IRPOperation)o1).getName()+" ");
}
IRPClassifier myCls2 = (IRPClassifier) (dependsOnmod.getOfClass());
IRPModelElement myEle2 =
myCls2.getOwner().findNestedElementRecursive(dependsOnmod.getName(),
"Class");
IRPClass myCls3 = (IRPClass) myEle2;
for(Object o2:myCls3.getOperations().toList())
{
System.out.print(((IRPOperation)o2).getName()+" ");
out.write(((IRPOperation)o2).getName()+" ");
}
System.out.println();out.newLine();
}
}
}
else
System.out.println("OOPS !!! Package not selected.");
out.close();
}
catch (IOException e)
{
System.err.println("Something went wrong");
e.printStackTrace();
}
}
}





XIX. Get information regarding Activity diagram elements

In order to get Activity Diagram elements information using JAVA API in Rational Rhapsody you can use the below code as a reference. The code can be enhanced to include other specific element types.


import java.util.Iterator;

import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.IRPSwimlane;
import com.telelogic.rhapsody.core.IRPState;
import com.telelogic.rhapsody.core.IRPTag;
import com.telelogic.rhapsody.core.IRPTransition;
import com.telelogic.rhapsody.core.IRPStereotype;
import com.telelogic.rhapsody.core.IRPModelElement;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class ActivityDiagramInfo
{
public static void main (String[] args)
{
IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPModelElement myEle = myApp.getSelectedElement();
System.out.print("Activity Diagram --> ");
System.out.println(myEle.getName());
Iterator sterIter = myEle.getStereotypes().toList().iterator();

while(sterIter.hasNext())
{
Object contEleObj = sterIter.next();
IRPStereotype stereotype = (IRPStereotype) contEleObj;
System.out.print("Stereotype --> ");
System.out.println(stereotype.getName());
}

Iterator contEleIter = myEle.getNestedElementsRecursive().toList().iterator();

while(contEleIter.hasNext())
{
Object contEleObj = contEleIter.next();

if (contEleObj instanceof IRPTag)
{
IRPTag tag = (IRPTag) contEleObj;
System.out.print("Tag --> ");
System.out.print(tag.getName());
System.out.print("(Value: ");
System.out.print(tag.getValue());
System.out.println(")");
}

if (contEleObj instanceof IRPSwimlane)
{
IRPSwimlane flow = (IRPSwimlane) contEleObj;
System.out.print("Swimlane --> ");
System.out.println(flow.getDisplayName());
}

if (contEleObj instanceof IRPTransition)
{
IRPTransition flow = (IRPTransition) contEleObj;
System.out.print("Flow --> ");
System.out.println(flow.getDisplayName());
}

if (contEleObj instanceof IRPState)
{
IRPState action = (IRPState) contEleObj;
if(action.getName().contains("ROOT"))
continue;
System.out.print("Action --> ");
System.out.println(action.getName());
}
}
}
}





XX. Concatenate Activity name with Use Case name

In order to concatenate Activity name with UseCase name in Rational Rhapsody use the following Java API code:


public class ClsGetActivityUnderUC
{

public static void main(String[] args)
{
IRPApplication app = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject prj = app.activeProject();

for(Object o1: prj.getPackages().toList())
{
IRPPackage pkg = (IRPPackage)o1;

for(Object o3 : pkg.getUseCases().toList())
{
IRPUseCase au = (IRPUseCase)o3;

for(Object o4: au.getNestedElementsRecursive().toList() )
{
IRPModelElement uc = (IRPModelElement) o4;

if(uc.getMetaClass().equals("ActivityDiagram"))
uc.setName("ActivityOf" + au.getName());

}
}

}
}
}





XXI. Plugin to navigate from Use Case diagram to Sequence diagram

In order to get the sequence diagram under a use case in Rational Rhapsody, use the following Java API code:


public class Helper extends RPUserPlugin
{
private IRPApplication rhpApp ;
private IRPProject rhpPrj;

@Override
public void RhpPluginInit(IRPApplication rpyApplication)
{

rhpApp = rpyApplication;
rhpPrj = rhpApp.activeProject();
}

@Override
public void RhpPluginInvokeItem() {
// TODO Auto-generated method stub

}

@Override
public void OnMenuItemSelect(String menuItem) {
if(menuItem.equals("Navigate to Sequence Diagram"))
{
IRPUseCase uc = (IRPUseCase)rhpApp.getSelectedElement();
if(uc.getSequenceDiagrams()!=null)
{
/* Get the first Sequence diagram if UC has several SDs */

IRPSequenceDiagram sd = (IRPSequenceDiagram)uc.getSequenceDiagrams().toList().get(0);
sd.highLightElement();
/* Opens the SD */
sd.openDiagram();
}


}

}

@Override
public void OnTrigger(String trigger){
// TODO Auto-generated method stub

}

@Override
public boolean RhpPluginCleanup(){
// TODO Auto-generated method stub
return false;
}

@Override
public void RhpPluginFinalCleanup() {
// TODO Auto-generated method stub

}

}

.




XXII. Make Rational Rhapsody code Read Only

In Rational Rhapsody, when class elements are made as Read Only, then generated code for such read-only elements appear in Read-write mode.

If you wish to get a read-only generated code for any classes which are set to Read Only status, then the following Java API code needs to be executed.

The following piece of code would scan across all the Read Only classes present within the Rhapsody Model and if found any, it would make the corresponding generated code as Read Only.


import java.io.IOException;
import java.util.Iterator;
import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.IRPClass;
import com.telelogic.rhapsody.core.IRPConfiguration;
import com.telelogic.rhapsody.core.IRPProject;
import com.telelogic.rhapsody.core.IRPUnit;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class TestReadOnly
{
public static void main(String[] args)
{
IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject myPrj = myApp.activeProject();
IRPConfiguration myConf = myPrj.getActiveConfiguration();
Iterator myIter = myPrj.getNestedElementsRecursive().toList().iterator();
String pathName = myConf.getPath(1);
String command1,command2;
command1=command2=null;

while (myIter.hasNext())
{
Object myObj = myIter.next();
if((myObj instanceof IRPUnit) && (myObj instanceof IRPClass))
{
IRPUnit myUnit = (IRPUnit) myObj;
if(myUnit.isReadOnly()==1)
{
command1 = "attrib +r \""+pathName+"\\"+myUnit.getName()+".c\"";
System.out.println(command1);
command2 = "attrib +r \""+pathName+"\\"+myUnit.getName()+".h\"";
System.out.println(command2);

try
{
Process p1 = Runtime.getRuntime().exec(command1);
Process p2 = Runtime.getRuntime().exec(command2);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}




XXIII. CheckOut a Rational Rhapsody package from Rational ClearCase

In order to check out the Rational Rhapsody package along with its dependent packages from Rational Clear case, use the following Java API code:


import java.io.IOException;

import javax.swing.JOptionPane;

import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.IRPCollection;
import com.telelogic.rhapsody.core.IRPDependency;
import com.telelogic.rhapsody.core.IRPModelElement;
import com.telelogic.rhapsody.core.IRPProject;
import com.telelogic.rhapsody.core.IRPUnit;
import com.telelogic.rhapsody.core.RhapsodyAppServer;
import com.telelogic.rhapsody.core.RhapsodyRuntimeException;


public class CoWithDpen
{
/**
* @param args
*/
@SuppressWarnings("null")
public static void main(String[] args)
{
IRPApplication RhpApp = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject activeProject = RhpApp.activeProject();
IRPModelElement modelElement = RhpApp.getSelectedElement();
IRPUnit selectedUnit = (IRPUnit)modelElement;
JOptionPane.showMessageDialog(null, modelElement.getName());

////////////////search for dependencies///////////////////////////

IRPCollection allColl, allDep;
IRPModelElement temp;

allColl = modelElement.getNestedElementsByMetaClass("Class", 1);
for (int i = 1; i <= allColl.getCount(); i++)
{
IRPModelElement element = (IRPModelElement)allColl.getItem(i);
System.out.println(element.getName());
allDep = element.getDependencies();
for(int j=1; j<= allDep.getCount(); j++)
{
temp = (IRPModelElement)allDep.getItem(j);
System.out.println(temp.getName());
IRPModelElement myUnit =
(IRPModelElement) activeProject.findNestedElementRecursive(temp.getName(), "Class");
System.out.println(myUnit.getOwner().getName());
IRPUnit myUnit1 =
(IRPUnit) activeProject.findNestedElementRecursive(myUnit.getOwner().getName(),
"Package");

if((myUnit1.isReadOnly()) == (int)1)
{
JOptionPane.showMessageDialog(null, "Package of dependent class is not checked out ");

////////////////////////////////checkout////////////////////////////

try
{
String chkoutPath1,chkoutPath2 = null;
chkoutPath1 = "M:\\Administrator_view\\rhpvob\\Projectcc\\Project_rpy\\";
chkoutPath2 = myUnit1.getName() + ".sbs";
System.out.println(chkoutPath2);
if(selectedUnit.isReadOnly() == 1)
Runtime.getRuntime().exec("cleartool checkout -nc -reserved \"" + chkoutPath1 + selectedUnit.getName() + ".sbs" );
Runtime.getRuntime().exec("cleartool checkout -nc -reserved \"" + chkoutPath1 + chkoutPath2 );

myUnit1.load(1);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
System.out.println("\n");
}
}
}






XXIV. Determine Transition name and corresponding trigger event

In order to get the transition name and the corresponding trigger event on a state chart diagram in Rational Rhapsody, use the following Java API code:


public class EventName
{
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject myProj = myApp.activeProject();
IRPClass myClass = (IRPClass)myApp.getSelectedElement();
IRPCollection allColl;
IRPTransition myTran = null;
IRPTrigger myTrig = null;



allColl = myClass.getNestedElementsByMetaClass("Transition", 1);

for (int i = 1; i <= allColl.getCount(); i++)
{
IRPModelElement element = (IRPModelElement)allColl.getItem(i);
if(element instanceof IRPTransition &&
!element.getUserDefinedMetaClass().equals("DefaultTransition"))
{
myTran = (IRPTransition)element;
System.out.println(myTran.getName());
myTrig = myTran.getItsTrigger();
System.out.println(myTrig.getBody());
}

}
}
}







XXV. Remove undesired packages post Reverse Engineering

In order to remove the undesired packages post Reverse Engineering in Rational Rhapsody, use the following Java API code:

Note: In the code snippet below, rename the package named src and inc

import com.telelogic.rhapsody.core.IRPProject;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class movPkgContent
{
public static void main(String[] args)
{
IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject myPrj = myApp.activeProject();

Iterator pkgIter = myPrj.getNestedElementsRecursive().toList().iterator();

while(pkgIter.hasNext())
{
Object myObj = pkgIter.next();
if(myObj instanceof IRPPackage)
{
IRPPackage myPkg = (IRPPackage) myObj;


if( myPkg.getName().equals("inc") || myPkg.getName().equals("src") )
{

IRPPackage ownerPkg = (IRPPackage) myPkg.getOwner();
Iterator innerPkgIter = myPkg.getNestedElements().toList().iterator();
while (innerPkgIter.hasNext())
{
IRPModelElement myEle = (IRPModelElement) innerPkgIter.next();
if( myEle.getName().equals("src") || myEle.getName().equals("inc"))
continue;
else
myEle.clone(myEle.getName(), (IRPModelElement) ownerPkg);
}
myPkg.deleteFromProject()
}
}
}
}
}






XXVI. Import ARXML file from another application to Rational Rhapsody

In order to import ARXML file from another application to Rational Rhapsody using JAVA API you can use the below code as a reference.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

import com.telelogic.rhapsody.core.IRPApplication;
import com.telelogic.rhapsody.core.IRPModelElement;
import com.telelogic.rhapsody.core.IRPProject;
import com.telelogic.rhapsody.core.IRPTag;
import com.telelogic.rhapsody.core.RhapsodyAppServer;

public class ImportE2Es
{
public static void main(String[] args)
{
IRPApplication myApp = RhapsodyAppServer.getActiveRhapsodyApplication();
IRPProject myPrj = myApp.activeProject();
String file = "<Path to ARXML file>";
String tagValue = null;
String Name = null;

try
{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int found = 0;
while ((line = br.readLine()) != null)
{
if(line.contains("E2E"))
{
found = 1;
tagValue = line.substring(line.indexOf('\"')+1, line.indexOf('>')-1);
}

if(line.contains("SHORT-NAME") && found == 1 )
{
Name = line.substring(line.indexOf('>')+1, line.indexOf('/')-1);
found = 0;
IRPModelElement myEle = myPrj.findNestedElementRecursive(Name,
"ApplicationSoftwareComponentType");
Iterator myIter = myEle.getNestedElementsRecursive().toList().iterator();

while (myIter.hasNext())
{
IRPModelElement myEle1 = (IRPModelElement) myIter.next();

if(myEle1.getUserDefinedMetaClass().equals("Sdg"))
{
IRPTag myTag = (IRPTag) myEle1.addNewAggr("Tag", "E2E");
myTag.setValue(tagValue);
}
}
}
}
br.close();
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}





Conclusion

Rational Rhapsody Java API provides a whole new range of possibilities and is widely used in different domains due to its strengths and capabilities. A study of the various Rational Rhapsody Java API examples provided in this document would not only provide the reader with an implementation understanding of the Rational Rhapsody Java APIs; but also build confidence for creating useful utilities, that can add more value to day to day developmental activities.

After going through the different examples provided in this document, users will be able to visualize beneficial use of the Rational Rhapsody Java API across different scenarios, where instead of an existing tedious, time consuming and manual task; users will be able to find simpler, quicker and automated solutions.

Although quiet a lot of code based examples have been provided in this document, such a document is never absolute and there is always scope for further improvement. We at Rational Client Support are committed to continuous improvement to this document, based on the feedback from readers and deemed necessary from time to time.

Add any notes or warnings about the white paper content as needed.




Notes
  1. Details of the Java API can be found in the Javadoc output for the API, located at [Rational Rhapsody installation directory]\Doc\java_api\index.html

  2. Java API can be used on both Windows and Linux; this allows users to write cross-platform applications

  3. Use of the Java version of the API requires two files that can be found in the directory [Rational Rhapsody installation directory]/Share/JavaAPI:

    Rhapsody.jar - contains the Java classes and interfaces
    Rhapsody.dll (or Rhapsody.so for Linux) - native implementation of the Java interface

  4. The .jar file should be included in the CLASSPATH of the Java project, and the .dll (or .so file) should be included in the lib path

  5. If you are using the 32-bit version of Rational Rhapsody, but are using the Rhapsody API for applications that will be run with a 64-bit version of Java, use the 64-bit .dll file, located in the directory [Rational Rhapsody installation directory]/Share/JavaAPI/64Bit

  6. If you are using the 64-bit version of Rational Rhapsody, but are using the Rhapsody API for applications that will be run with a 32-bit version of Java, use the 32-bit .dll file, located in the directory [Rational Rhapsody installation directory]/Share/JavaAPI/32Bit

  7. To access the Rational Rhapsody application, you use the object RhapsodyAppServer

  8. An initialization script called rhp_env (located in the root of the Rational Rhapsody installation directory) must be run before using Rational Rhapsody on Linux.





References

The following were used as references or as other sources of information:









Disclaimer

THE INFORMATION CONTAINED IN THIS DOCUMENT IS PROVIDED FOR INFORMATIONAL PURPOSES ONLY. WHILE EFFORTS WERE MADE TO VERIFY THE COMPLETENESS AND ACCURACY OF THE INFORMATION CONTAINED IN THIS DOCUMENT, IT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. IN ADDITION, THIS INFORMATION IS BASED ON IBM’S CURRENT PRODUCT PLANS AND STRATEGY, WHICH ARE SUBJECT TO CHANGE BY IBM WITHOUT NOTICE. IBM SHALL NOT BE RESPONSIBLE FOR ANY DAMAGES ARISING OUT OF THE USE OF, OR OTHERWISE RELATED TO, THIS DOCUMENT OR ANY OTHER DOCUMENTATION. NOTHING CONTAINED IN THIS DOCUMENT IS INTENDED TO, NOR SHALL HAVE THE EFFECT OF, CREATING ANY WARRANTIES OR REDOCUMENTS FROM IBM (OR ITS SUPPLIERS OR LICENSORS), OR ALTERING THE TERMS AND CONDITIONS OF ANY AGREEMENT OR LICENSE GOVERNING THE USE OF IBM PRODUCTS OR SOFTWARE.

Original Publication Date

29 September 2014

[{"Product":{"code":"SSUVYQ","label":"IBM Engineering Systems Design Rhapsody"},"Business Unit":{"code":"BU055","label":"Cognitive Applications"},"Component":"Documentation","Platform":[{"code":"PF033","label":"Windows"}],"Version":"7.6;7.6.0.1;7.6.1;7.6.1.1;7.6.1.2;7.6.1.3;7.6.1.4;7.6.1.5;8.0;8.0.1;8.0.2;8.0.3;8.0.4;8.0.5;8.0.6;8.1;8.1.1","Edition":"","Line of Business":{"code":"LOB02","label":"AI Applications"}}]

Product Synonym

Rational Rhapsody

Document Information

Modified date:
17 June 2018

UID

swg27043596