Automating Modeling Compare Merge: Running an Ant task on the IBM Rational Software Delivery Platform

Generating a list of changes between two UML models through the command line

Learn how to create and invoke an Ant task capable of running in headless (command line) mode to produce a list of changes between two UML models. Prerequisite: Version 7.0.0.5 of any of these tools: IBM® Rational® Application Developer, Rational® Software Architect, or Rational® Software Modeler.

IBM® Rational® Software Architect and its related products (see Note) offer powerful UML modeling technologies for model-driven development (MDD) and for team or parallel development. These include transformations and compare-and-merge technologies.

Note:
In this article, "Rational software" means any of these products: Rational Software Architect, Rational® Application Developer, or Rational® Software Modeler.

There are several situations where it is advantageous to generate a list of differences between models by using a command-line tool, perhaps as a step in a build process or equivalent. For example:

  • At any point in the evolution of a model, it is possible to select a couple of versions -- perhaps the latest version and the version in a previously built baseline -- and to generate a list of differences for publishing to a Wiki or other Web page for review purposes.
  • In simple ad hoc modeling, it is possible to run this process on a pair of independently developed models that have similar structures and have evolved with shared semantic data, such as classes and actors that have the same names. Again, with alignment, these models can be compared in this way.
  • In advanced model-driven development scenarios, where a software architect would like to reconcile an evolving model to a generated code base that has also been evolving, the Java to UML transformation capability can generate a model that can be aligned to the original source model and compared to it to create and publish the review list.

This article focuses on the MDD scenario, because this is the most likely scenario in which this technology is needed. Adaptation of the technique to the other scenarios is relatively straight-forward.

Options for generating the delta list between code and model

Depending on the scale of the project, the changes to the master model can come from multiple developers. An architect may need to review sets of changes from an individual contributor before introducing them into the master model. Typically, this is achieved by running a transformation, such as Java-to-UML. The transformation generates a UML model that reflects the current state of the Java code. To see the differences between the master model and a model that was generated from the code, several approaches can be taken.

One approach is to set the target transformation output as the master model. Running the transformation in the Rational software environment will then initiate a visual structural merge session (also known as fusion--see Note below), which will present the list of changes before applying them to the master (target) model. This approach will modify the master model upon committing the structural merge session.

Note:Fusion (a structural compare) is a technology that compares models using only qualified names and provides a mechanism to capture structural changes from one model to another whether they share an ancestry or not. It is also stimulated by the combine models command. Fusion is used extensively in the reconcile work flow for MDD.

However, this technology cannot yet be automated from the command line. Instead, the alignment technology (see Note below) is used to change the problem into an identity comparison. A generated model can be saved into a placeholder (an empty model), aligned with the master model, and then a compare session can be run to create a list of changes (see Figure 1). Both the alignment tool and the identity comparison technology allow for automation and command-line invocation.

Note: A model alignment is a technology that is capable of changing a target model's element identities to match the same elements in a source model. It uses a sophisticated identity matcher to generate keys that are then matched up between the models so the element IDs can be migrated forward. This effectively creates an ancestry relationship between the models, as if they had evolved directly from one to the other. This makes them comparable using the technology as described in this article.

Figure 1. Compare session between two aligned models
Changes listed on left, merge result view on right

Figure 2 shows how the delta list would be saved when the Save deltas button is clicked during a visual merge between these models. Given that this log must be generated from a visual session, and because this file would be very difficult to parse to create more sophisticated review tools, an alternative mechanism and file format is used.

Figure 2. Delta log file contents
Screen output

Automation by running an Ant task

This approach is automated by an Apache Ant task. The Ant task can be run in a batch mode from a command line, which produces a list of changes and saves them to a file. Moreover, the generated list can be saved in a navigable format. The facilities in Compare Merge enable loading such files into Rational software and reviewing them with a Delta Annotation Viewer, as Figure 3 shows (see Resources for where to learn more about deltas).

Figure 3. Delta annotation viewer
ModelDeltas tab

Creating an Eclipse Ant project

Consider this scenario:

  • A Java-to-UML transformation must be run to produce UML model.
  • This model must be saved, aligned with a master model, and then the two models must be compared to each other.
  • A list of differences between the two models needs to be saved to be reviewed later.
  • It is important to be able to run this job in a batch (headless) mode.

To satisfy these requirements, you will create an Ant task class that you can deploy by command.

  1. First. create a sample Eclipse plug-in, as Figure 4 shows. (You can find the complete plug-in with the source code at com.acme.headless.ant_1.0.0.jar).
Figure 4. Create the headless Ant plug-in
Package Explorer view
  1. Add the dependencies shown in Listing 1 to the manifest file.
Listing 1. Dependencies to add to the manifest file
  Manifest-Version: 1.0
  Bundle-ManifestVersion: 2
  Bundle-Name: Ant Plug-in
  Bundle-SymbolicName: com.acme.headless.ant;singleton:=true 
  Bundle-Version: 1.0.0 
  Bundle-Activator: com.acme.headless.ant.Activator
  Bundle-Vendor: ACME
  Bundle-Localization: plugin
  Require-Bundle: org.eclipse.ui,
  org.eclipse.core.runtime,
  org.eclipse.ant.core,
  org.apache.ant,
  org.eclipse.gmf.runtime.emf.core.compatibility,
  com.ibm.xtools.transform.core,
  com.ibm.xtools.uml.core, 
  com.ibm.xtools.uml.msl,
  com.ibm.xtools.comparemerge.modelconverter,
  com.ibm.xtools.comparemerge.delta.annotation.ui,
  com.ibm.xtools.comparemerge.core
  Eclipse-LazyStart: true
  1. Create a Differences Logger class as Listing 2 shows and add a few attributes to the class. Public attributes will be used as Ant task arguments.
Listing 2. Creating a Differences Logger class with added attributes
package com.acme.headless.ant.task;

public class DifferencesLogger extends org.apache.tools.ant.Task {
// ant task parameter variables
// absolute path to transformation configuration (.tc) file
public String transformConfigPath; 
// absolute path to the master model to be compared to
public String masterModelPath; 
// absolute path to the auto-generated changes log (the file does not have pre-exist) 
public String deltaLogFileName;
// absolute path to a blank model template
public String blankModelPath; 

// private members
private String tempModelName = "HTBlankModel"; //$NON-NLS-1$
private URI tempModelURI = null;
}
  1. Now create the tasks execute() method (see Listing 3).
Listing 3. Create the execute() method
/*
* Execute task 
* (non-Javadoc)
* @see org.apache.tools.ant.Task#execute()
*/
public void execute() throws BuildException {

try {
// load transformation configuration file
IFile file = 
ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(
new Path(transformConfigPath));
ITransformConfig config = TransformConfigUtil.loadConfiguration(file);

//prepare Java to UML transformation forward context by switching its target container 
to point to a temporary, empty model file 
ITransformContext forwardContext = createTarget(config);
//execute transformation
IStatus status = 
TransformController.getInstance().
execute(config, forwardContext, false, true, null);

System.out.println("Completed transform execution, status = " + status.getMessage()); 

if (status.getCode() == IStatus.OK) {

// instantiate model alignment facade
ModelConverterFacade mc_facade = new ModelConverterFacade();

//verify that master copy does exist
File baseFile = new File(getMasterModelPath());
if (!baseFile.exists()) {
System.out.println("Invalid master copy path: " + getMasterModelPath()); 
System.out.println("Please correct the parameter and re-run the script"); 
return;
}

// obtain model file created by transformation. Verify it exits
File contributorFile = new File(getTemporaryModelURI().toFileString());
if (!contributorFile.exists()) {
System.out.println("Error during transformation: failed to create target file"); 
System.out.println("Verify that " + contributorFile.getParent() + " is not read-only”); 
return;
}

// align master and contributor files
if (!mc_facade.alignSingleModelFile(baseFile, contributorFile, null, contributorFile)) 
{
System.out.println("Error during model alignment"); 
System.out.println(contributorFile.getAbsolutePath() + " should exist!"); 
return;
}
// compare aligned models and save changes log
compareWithEachOther(baseFile, contributorFile);
} 
} catch (Exception e) {
e.printStackTrace();
System.out.println("Failed execution" + e.getLocalizedMessage()); 
}
}
  1. Create a plugin.xml file in the com.acme.headless plug-in, and declare the Ant task (Listing 4).
Listing 4. Create a plugin.xml file and declare the Ant task
<extension
point="org.eclipse.ant.core.antTasks">
<antTask
class="com.acme.headless.ant.task.DifferencesLogger"
library="delta_logger.jar"
name="diff_logger">
</antTask>
</extension>
  1. Update the build properties of the plug-in as Listing 5 shows.
Listing 5. Update the build properties of the plug-in
bin.includes = META-INF/,\
delta_logger.jar,\
plugin.xml
source.delta_logger.jar = src/
output.delta_logger.jar = bin/
  1. Right-click on the plugin.xml file, and create an Ant build.xml file by selecting PDE Tools > Create Ant Build File (see Figure 5).
Figure 5. Create the Ant build file
Drop-down menus showing selections described
  1. Right-click the build.xml file and select Run As > Ant Build. This will create a diff_logger.jar file in the plug-in root directory.
  2. Lastly, as Figure 6 illustrates, in the Project Explorer, select the com.acme.headless.ant plug-in and then click Export on the drop-down menu to export it to the Rational software plug-ins directory (C:\Program Files\IBM\SDP70\plugins, typically):as a deployable plug-in (com.acme.headless.ant_1.0.0.jar).
Figure 6. Export the com.acme.headless.ant plug-in
Shows the plug-in and then Export selected

Setting up the runtime environment

To illustrate this step, we have provided three example projects in the attached Projects.zip file (see Downloads). Follow these steps to use these projects:

  1. Use the existing workspace (C:\targets\my-workspace).or create a new workspace.
  2. Start your Rational software to use C:\targets\my-workspace.
  3. Extract the files from the Projects.zip file and Import the three projects into your workspace.
  4. Go to the AntRunnerPlugin project and right-click the plugin.xml file. Then select PDE Tools > Create Ant Build File. This will generate a build.xml file.
  5. Open the build.xml file and edit it as Listing 6 shows to add the last target.
    1. The first parameter (transformConfigPath) points to the Java-to-UML transformation configuration file.
    2. The masterModelPath parameter points to the location of your base UML model. This model will not be overridden by the task.
    3. The deltaLogFileName parameter points to the future location of the generated changes log file (it does not have to exist previously, and it does not have to be in the workspace).
    4. The blankModelPath parameter points to a location of an empty model template used by the task. This model will never be overridden by the task, because it is used merely as a template. The template can be any empty model, but you can use the one provided with this example for convenience.
Listing 6. Edit the build.xml file to add the last target
<target name='mytest'>
< diff_logger
transformConfigPath='C:\targets\my-workspace\Java Project\J2UML.tc'
masterModelPath='C:\targets\my-workspace\Model Project\Blank Model.emx'
deltaLogFileName='C:\targets\my-workspace\Model Project\changes_log.xml'
blankModelPath='C:\targets\my-workspace\Model Project\template\EmptyModel.emx'
/>
</target>
  1. Update the default task (the first line of the Ant build file) to mytest task:
    <project name="AntRunnerPlugin" default="mytest" basedir=".">

Note:
Make sure that C:\targets\my-workspace is replaced by the actual location of your workspace.

  1. Save the modified Ant build file.

The environment is now set up, and the task can be run within Rational software, as well as in headless mode.

  1. To run the Ant task within Rational software, select the build.xml file, right-click, and select Run As > Ant build.
  2. Notice that there is new file in the Model Project called changes_log.xml. This file can be rendered in the delta log viewer (Figure 7) by selecting Window > Show View > Other > Model Delta Annotation Viewer > Model deltas.
Figure 7. Viewing changes in the delta annotation viewer
build.xml tab on top, ModelDeltas tab on bottom
  1. Simply drag the generated file onto the viewer.

The EMF level deltas (individual changes), shown at the leaf nodes, are conveniently grouped into composite deltas at the UML level. These composites signify gestures or other logical groupings (such as a drag-and-drop multiple objects diagram, which would result in a group location change, package-related changes, such as changes to a specific package composite delta, and so forth).

Running the task in headless mode

  1. Remember the absolute location of your Ant build.xml file, and copy the runant.bat file from Listing 7 into the root folder of your Rational software (for example, C:\Program Files\IBM\SDP70).
Listing 7. The runant.bat file
setlocal
REM RUNANT_DIR=This directory (which may, or may not, be your current working directory)
set RUNANT_DIR=%~dp0

set debug=
if not '%1' == 'debug' goto studio
set debug=-Xdebug -Xnoagent -Djava.compiler=none ^
-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000

:studio
REM The root directory of your Studio installation
set STUDIO_DIR=C:\Program Files\IBM\SDP70
if not exist '%STUDIO_DIR%'\jdk\jre set STUDIO_DIR=%RUNANT_DIR%..\..\..
if not exist '%STUDIO_DIR%'\jdk\jre echo 
ERROR: incorrect STUDIO_DIR=%STUDIO_DIR%
if not exist '%STUDIO_DIR%'\jdk\jre goto done

:java
if not $%JAVA_DIR%$==$$ goto workspace
set JAVA_DIR=jdk\jre\bin
:workspace
if not $%WORKSPACE%$==$$ goto check
REM #######################################################
REM ##### you must edit the 'WORKSPACE' setting below #####
REM #######################################################
REM *********** The location of your workspace ************
set WORKSPACE=C:\targets\my-workspace
:check
REM ************* The location of your workspace *****************
if not exist '%WORKSPACE%' echo ERROR: 
incorrect workspace=%WORKSPACE%, edit this runAnt.bat and correct the WORKSPACE envar
if not exist '%WORKSPACE%' goto done

set LOCATIONS=-DSTUDIO.DIR=%STUDIO_DIR% -DSTUDIO.RUNANT=
%RUNANT_DIR% -DSTUDIO.WORKSPACE=%WORKSPACE%

:run
@echo on
'%JAVA_DIR%\java' -cp '%STUDIO_DIR%\startup.jar' 
%debug% org.eclipse.core.launcher.Main 
-debug -application org.eclipse.ant.core.antRunner -data 
'%WORKSPACE%' -file %WORKSPACE%\AntRunnerPlugin\build.xml
  1. Open and edit the file to reflect paths specific to your environment. These are the most important ones:
    • STUDIO_DIR: The root directory of your Studio installation (for example, C:\Program Files\IBM\SDP70)
    • JAVA_DIR: Absolute or relative to the batch file location Java Runtime Environment, or JRE (for example, jdk\jre\bin)
    • WORKSPACE: Location of your Rational software workspace (typically, C:\targets\my-workspace)
    • The last command line of the batch file: The location of your build.xml file relative to your workspace (for example, AntRunnerPlugin\build.xml)
  2. Modify the task path to point to the location of the build.xml file that was generated in Step 4.
  3. Run the antRun.bat file from the local command line to the location of the .bat file. The result should be the same as in Step 6.

Adapting a customer's transformation

  1. Create a Java-to-UML transformation (or use an existing transformation).
  2. Configure it and save the configuration file.
  3. Modify the Ant build.xml file generated in the previous step to point to your configuration file (see the transformConfigPath argument).
  4. Modify the masterModelPath argument to point to your master model file (this file will not be overridden).
  5. Modify the deltaLogFileName argument to point to the location of the delta log file.
  6. Modify the blankModelPath argument to point to the blank (empty) model template (this file will not be overridden).
  7. Run the Ant task as in the previous example.

Downloads

DescriptionNameSize
Sample projects for this articleProjects.zip8KB
Zip of jar filecom.achme.headless_1.zip12KB

Resources

Learn

Get products and technologies

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Rational software on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Rational, Open source
ArticleID=321225
ArticleTitle=Automating Modeling Compare Merge: Running an Ant task on the IBM Rational Software Delivery Platform
publish-date=07222008