Managing Contributor Licenses using the Java API

The question how to manage licenses using the plain java client libraries came up recently. There used to be a blog post in the internet that explained it, but that has been taken down. Questions on Jazz.net are not very clear for this, so I dug into the API myself. Here is the result.

License

The post contains published code, so our lawyers reminded me to state that the code in this post is derived from examples from Jazz.net as well as the RTC SDK. The usage of code from that example source code is governed by this license. Therefore this code is governed by this license. I found a section relevant to source code at the and of the license. Please also remember, as stated in the disclaimer, that this code comes with the usual lack of promise or guarantee. Enjoy!

Just starting with extending RTC?

If you just get started with extending Rational Team Concert, or create API based automation, start with the post Learning To Fly: Getting Started with the RTC Java API’s and follow the linked resources.

You should be able to use the following code in this environment and get your own automation or extension working.

Solution

The service to access and assign licenses is the class com.ibm.team.repository.common.ILicenseAdminService.

Note that this class is not available as a client library such as other common and client services. The way to get this class in a client extension or a plain java API base application looks as follows:

ILicenseAdminService licenseAdminService = (ILicenseAdminService) ((IClientLibraryContext) teamRepository).getServiceInterface(ILicenseAdminService.class);

To access the class in a server extension like a pre-condition/advisor or a follow up action/participant is however using the typical com.ibm.team.repository.service.AbstractService.getService(Class) that is usually used e.g.:

ILicenseAdminService licenseService = getService(ILicenseAdminService.class);

The licensing code should work against each of the CLM applications JTS, CCM, QM, RM and should work for any available license.

This code can be used to print the license information for the available license types:

	IContributorLicenseType[] Licensetypes = licenseAdminService.getLicenseTypes();

	for (IContributorLicenseType iContributorLicenseType : Licensetypes) {
		System.out.println("License Type: ");
		System.out.println("License Type ID: " + iContributorLicenseType.getId());
		System.out.println("License Type Name: " + iContributorLicenseType.getName());
		System.out.println("License Type Description: " + iContributorLicenseType.getDescription());
		System.out.println("License Type ProductName: "	+ iContributorLicenseType.getProductName());
	}

The resulting list of licenses would look like below.

License Type: 
License Type ID: com.ibm.team.clm.stakeholder
License Type Name: Stakeholder
License Type Description: Diese Stakeholder-Lizenz ist zur Unterstützung von peripheren Benutzern gedacht, z. B. von externen Kunden, von Mitarbeitern der Benutzerunterstützung oder von Benutzern, die Arbeitselemente modifizieren und den Projektfortschritt beobachten müssen. Ein Benutzer mit zugewiesener Clientzugriffslizenz für Stakeholder hat Lese- und Schreibzugriff auf Change Management sowie Lesezugriff auf Berichte und Planungsfunktionen, sofern rollenbasierte Prozessberechtigungen keine diesbezüglichen Einschränkungen beinhalten. Floating-Lizenzen werden dynamisch von einem Lizenzserver zugewiesen. Ein Benutzer mit zugewiesener Floating-Lizenz kann in den Pool der Benutzer aufgenommen werden, die die verfügbaren, auf dem Lizenzserver installierten Floating-Lizenzen gemeinsam nutzen. Führt ein solcher Benutzer eine Operation aus, für die diese Lizenz erforderlich ist, wird ihm vom Lizenzserver dynamisch eine Floating-Clientzugriffslizenz zugewiesen, wenn eine solche verfügbar ist. 
License Type ProductName: Rational solution for Collaborative Lifecycle Management
License Type: 
License Type ID: com.ibm.team.clm.practitioner
License Type Name: Practitioner
License Type Description: Diese Lizenz 'CLM Practitioner' ist für Anwender bestimmt, die aktiv an Projekten der Rational-Lösung für Collaborative Lifecycle Management mitwirken. Ein Benutzer mit zugewiesener Clientzugriffslizenz 'CLM Practitioner' hat vollen Lese- und Schreibzugriff auf das Änderungsmanagement, auf die Anpassung von Berichten, auf die Planung, auf das Softwarekonfigurationsmanagement, auf die Automation (Buildsystem), auf bestimmte Erweiterungen für IBM Unternehmensplattformen, auf Funktionen für Anforderungsdefinition und -management sowie Qualitätsmanagement und Lesezugriff auf Funktionen des Designmanagements, sofern rollenbasierte Prozessberechtigungen keine diesbezüglichen Einschränkungen beinhalten.
License Type ProductName: Rational solution for Collaborative Lifecycle Management
License Type: 
License Type ID: com.ibm.team.rrc.reviewer
License Type Name: Contributor
License Type Description: Diese Mitarbeiterlizenz ist für professionelle Teammitglieder bestimmt, die keine Entwickler sind, aber aktiv am Projekt beteiligt sind. Ein Benutzer mit zugewiesener Clientzugriffslizenz für Mitarbeiter hat vollen Lese- und Schreibzugriff auf das Änderungsmanagement, auf die Anpassung von Berichten und auf die Planung. Diese Lizenz ermöglicht außerdem den Lesezugriff auf Funktionen des Anforderungsmanagements, des Softwarekonfigurationsmanagements, der Automation (Buildsystem), des Testmanagements und des Designmanagements, sofern rollenbasierte Prozessberechtigungen keine diesbezüglichen Einschränkungen beinhalten.
License Type ProductName: Rational DOORS Next Generation
License Type ID: com.ibm.team.rtc.contributor
License Type Name: Contributor
License Type Description: Diese Mitarbeiterlizenz ist für professionelle Teammitglieder bestimmt, die keine Entwickler sind, aber aktiv am Projekt beteiligt sind. Ein Benutzer mit zugewiesener Clientzugriffslizenz für Mitarbeiter hat vollen Lese- und Schreibzugriff auf das Änderungsmanagement, auf die Anpassung von Berichten und auf die Planung. Diese Lizenz ermöglicht außerdem den Lesezugriff auf das Softwarekonfigurationsmanagement, auf die Automation (Build-System), auf das Anforderungsmanagement, das Testmanagement und das Designmanagement, sofern rollenbasierte Prozessberechtigungen keine diesbezüglichen Einschränkungen beinhalten.
License Type ProductName: Rational Team Concert
License Type: 
License Type ID: com.ibm.team.rtc.stakeholder
License Type Name: Stakeholder
License Type Description: Diese Stakeholder-Lizenz ist zur Unterstützung von peripheren Benutzern gedacht, z. B. von externen Kunden, von Mitarbeitern der Benutzerunterstützung oder von Benutzern, die Arbeitselemente modifizieren und den Projektfortschritt beobachten müssen. Ein Benutzer mit zugewiesener Clientzugriffslizenz für Stakeholder hat Lese- und Schreibzugriff auf Change Management sowie Lesezugriff auf Berichte und Planungsfunktionen, sofern rollenbasierte Prozessberechtigungen keine diesbezüglichen Einschränkungen beinhalten.
License Type ProductName: Rational Team Concert
License Type: 
License Type ID: com.ibm.team.rtc.buildsystem
License Type Name: Build System
License Type Description: Die Clientzugriffslizenz 'Build System' kann nur einer Benutzer-ID zugewiesen werden, die von einem automatisierten Build-System verwendet wird. Damit haben Einheiten des Build-Systems Lesezugriff auf das gesamte Leistungsspektrum sowie Schreibzugriff auf alle Leistungsmerkmale, sofern rollenbasierte Prozessberechtigungen keine diesbezüglichen Einschränkungen beinhalten.
License Type ProductName: Rational Team Concert
License Type: 
License Type ID: com.ibm.team.rtc.developer
License Type Name: Developer
License Type Description: Diese Lizenz ist für professionelle Entwickler bestimmt, die aktiv am Projekt beteiligt sind. Ein Benutzer mit zugewiesener Clientzugriffslizenz für Entwickler hat vollen Lese- und Schreibzugriff auf das Änderungsmanagement, auf die Anpassung von Berichten, auf die Planung, auf das Softwarekonfigurationsmanagement und auf die Automation (Buildsystem). Diese Lizenz ermöglicht außerdem den Lesezugriff auf das Anforderungsmanagement, das Testmanagement und das Designmanagement, sofern rollenbasierte Prozessberechtigungen keine diesbezüglichen Einschränkungen beinhalten.
License Type ProductName: Rational Team Concert
License Type: 
License Type ID: com.ibm.team.clm.contributor
License Type Name: Contributor
License Type Description: Diese Mitarbeiterlizenz ist für professionelle Teammitglieder bestimmt, die keine Entwickler sind, aber aktiv am Projekt beteiligt sind. Ein Benutzer mit zugewiesener Clientzugriffslizenz für Mitarbeiter hat vollen Lese- und Schreibzugriff auf das Änderungsmanagement, auf die Anpassung von Berichten und auf die Planung. Diese Lizenz ermöglicht außerdem den Lesezugriff auf das Softwarekonfigurationsmanagement, auf die Automation (Buildsystem), auf das Anforderungsmanagement, das Testmanagement und das Designmanagement, sofern rollenbasierte Prozessberechtigungen keine diesbezüglichen Einschränkungen beinhalten. Floating-Lizenzen werden dynamisch von einem Lizenzserver zugewiesen. Ein Benutzer mit zugewiesener Floating-Lizenz kann in den Pool der Benutzer aufgenommen werden, die die verfügbaren, auf dem Lizenzserver installierten Floating-Lizenzen gemeinsam nutzen. Führt ein solcher Benutzer eine Operation aus, für die diese Lizenz erforderlich ist, wird ihm vom Lizenzserver dynamisch eine Floating-Clientzugriffslizenz zugewiesen, wenn eine solche verfügbar ist. 
License Type ProductName: Rational solution for Collaborative Lifecycle Management

The license type ID can be used to assign a license to the user.

	IContributor licenseContributor = teamRepository.contributorManager().fetchContributorByUserId(licenseUser, monitor);
	licenseAdminService.assignLicenseWithResult(licenseContributor,	licenseID);

For Example for user “bob” and the license type ID “com.ibm.team.rtc.developer”:

	IContributor licenseContributor = teamRepository.contributorManager().fetchContributorByUserId("bob", monitor);
	licenseAdminService.assignLicenseWithResult(licenseContributor,	"com.ibm.team.rtc.developer");

To remove a license use the code below and provide the license type ID

	IContributor licenseContributor = teamRepository.contributorManager().fetchContributorByUserId(licenseUser, monitor);
	licenseAdminService.assignLicenseWithResult(licenseContributor,	licenseID);

	licenseAdminService.unassignLicense(licenseContributor, licenseID);

Assigning licenses in a batch file

Using a plain java API application is not the only way to assign licenses. It is also possible to use the repo tools to do that. I use the following batch file to assign licenses to the users created for the JKE Banking sample life cycle project that I use to explore CLM.

echo on
set SERVERFOLDER="C:\CLM2016\6.0.3\JazzTeamServer\server"
set REPOSITORY="https://clm.example.com:9443/jts"
set USERID="myadmin"
set PASSWORD="myadmin"


rem primary users
call %SERVERFOLDER%\repotools-jts -createUser userId=bob licenseId=com.ibm.team.rrc.author repositoryURL=%REPOSITORY% adminUserId=%USERID% adminPassword=%PASSWORD%
call %SERVERFOLDER%\repotools-jts -createUser userId=marco licenseId=com.ibm.rqm.tester repositoryURL=%REPOSITORY% adminUserId=%USERID% adminPassword=%PASSWORD%
call %SERVERFOLDER%\repotools-jts -createUser userId=marco licenseId=com.ibm.team.rtc.developer repositoryURL=%REPOSITORY% adminUserId=%USERID% adminPassword=%PASSWORD%
call %SERVERFOLDER%\repotools-jts -createUser userId=deb licenseId=com.ibm.team.rtc.developer repositoryURL=%REPOSITORY% adminUserId=%USERID% adminPassword=%PASSWORD%
call %SERVERFOLDER%\repotools-jts -createUser userId=tanuj licenseId=com.ibm.rqm.tester repositoryURL=%REPOSITORY% adminUserId=%USERID% adminPassword=%PASSWORD%
call %SERVERFOLDER%\repotools-jts -createUser userId=rebecca licenseId=com.ibm.team.rtc.developer repositoryURL=%REPOSITORY% adminUserId=%USERID% adminPassword=%PASSWORD%

rem Build user
call %SERVERFOLDER%\repotools-jts -createUser userId=build licenseId=com.ibm.team.rtc.buildsystem repositoryURL=%REPOSITORY% adminUserId=%USERID% adminPassword=%PASSWORD%

rem secondary users
call %SERVERFOLDER%\repotools-jts -createUser userId=ursula licenseId=com.ibm.team.rrc.author repositoryURL=%REPOSITORY% adminUserId=%USERID% adminPassword=%PASSWORD%
call %SERVERFOLDER%\repotools-jts -createUser userId=curtis licenseId=com.ibm.rqm.viewer repositoryURL=%REPOSITORY% adminUserId=%USERID% adminPassword=%PASSWORD%
call %SERVERFOLDER%\repotools-jts -createUser userId=tammy licenseId=com.ibm.rqm.tester repositoryURL=%REPOSITORY% adminUserId=%USERID% adminPassword=%PASSWORD%
call %SERVERFOLDER%\repotools-jts -createUser userId=sally licenseId=com.ibm.team.rrc.author repositoryURL=%REPOSITORY% adminUserId=%USERID% adminPassword=%PASSWORD%
rem Design Manager License 
rem %SERVERFOLDER%\repotools-jts -createUser userId=al licenseId= repositoryURL=%REPOSITORY% adminUserId=%USERID% adminPassword=%PASSWORD%
pause

This works very well, except that it takes a long time to run since each repotools command has to individually log in.

Download and Compatibility

This code has been used with RTC 6.0 and is prepared to be used with RTC 6.0.x with no changes and it is pretty safe to assume, that the code will work with newer versions of RTC. It should however run with any version of RTC that has the specific API already implemented. The code shown below should work with almost all versions of RTC.

The post shows client, common API that are available in the RTC Server SDK and the RTC Plain Java Client Libraries.

You can download the Eclipse project with the application to print and assign a license to a user here.

You can download the batch file to assign the licenses for the JKE Banking Example in a zip archive here.

Related posts

Summary

The code above can be used to assign and remove licenses from users in RTC and CLM. An alternative method is using the repotools. as always I hope that this helps users out there with their tasks.

DIY stream naming convention advisors

Organizations might be interested in enforcing naming conventions for streams or make sure that stream names must be unique. This post shows some simple example advisor that check for a naming convention and make sure the stream name is unique.

License

The post contains published code, so our lawyers reminded me to state that the code in this post is derived from examples from Jazz.net as well as the RTC SDK. The usage of code from that example source code is governed by this license. Therefore this code is governed by this license. I found a section relevant to source code at the and of the license. Please also remember, as stated in the disclaimer, that this code comes with the usual lack of promise or guarantee. Enjoy!

Just Starting With Extending RTC?

If you just get started with extending Rational Team Concert, or create API based automation, start with the post Learning To Fly: Getting Started with the RTC Java API’s and follow the linked resources.

You should be able to use the following code in this environment and get your own automation or extension working.

The example in this blog post shows RTC Server and Common API.

Compatibility

This code has been used with RTC 6.0 and is prepared to be used with RTC 6.0.x with no changes and it is pretty safe to assume, that the code will work with newer versions of RTC. It should run with any version that provides the operation ID.

The code in this post uses common and server libraries/services that are available in the RTC Server SDK.

Download

The code can be downloaded from here. Please note, there might be restrictions to access Dropbox and therefore the code in your company or download location.

Solution

Since some versions of RTC the operation ID com.ibm.team.scm.server.modifyStream has been made available. The operation allows to write RTC advisors (pre-conditions) and participants (follow up actions) that trigger on saving of a stream. The data that is made available in these operations allows to detect a variety of change types including a rename  of a stream.

RTC (version 6.x) ships the following out of the box preconditions for this operation ID:

  1. Ensure that snapshot names are unique for streams in the process area.
  2. Prevent Adding Component to Stream When Component and Stream Owners are Different.
  3. Prevent Adding User Owned Component
  4. Restrict Stream Visibility to be set to Public

The implementing classes are shipped with the SDK

  1. com.ibm.team.scm.service.internal.process.advisors.UniqueBaselineSetNameAdvisor
  2. com.ibm.team.scm.service.internal.process.advisors.StreamAddComponentAdvisor
  3. com.ibm.team.scm.service.internal.process.advisors.StreamAddUserOwnedComponentAdvisor
  4. com.ibm.team.scm.service.internal.process.advisors.StreamVisibilityAdvisor

Looking at the source code can be a great inspiration.

This post shows two advisors

  1. StreamNamingPatternAdvisor
  2. UniqueStreamNameAdvisor

StreamNamingPatternAdvisor checks for a simple naming convention and prevents creation or renaming of streams that violate the naming convention.

UniqueStreamNameAdvisor checks if the name of the stream is already used by another stream and prevents saving the stream if that is the case. Please note, the operation com.ibm.team.scm.server.modifyStream does not trigger if someone creates or saves a user repository workspace. This means it is not possible to provide this capability for  them.

General Approach

The operation ID provides a special interface IModifyStreamOperationData which makes the type of change and the related data available.

imodifystreamoperationdata

The code for the advisors first checks if the operation data provided is of the type IModifyStreamOperationData.If not, the operation terminates. If so, it casts to be able to use the interface to access the change details. If the data indicates anything other than a IModifyStreamOperationData.CHANGES, the advisor terminates.

IModifyStreamOperationData opData = (IModifyStreamOperationData) operationData;
if (!opData.isOperationType(IModifyStreamOperationData.CHANGES)) {
	// Nothing to do
	return;
}

If the operation is for such a change, the operation data can contain several different changes. So the code gets all the change ID’s for the changes in a set. The code then iterates the change ID’s and gets the change usinf the ID as IStreamChange. This interface allows to get more information, for example the identifier for the operation. In our case, if it is a name change IModifyStreamOperationData.NAME, the advisors are responsible to deal with it.

	// Get the set of change IDs and look through the changes
	Set changeIDs = opData.getChangeIds();
	for (String changeID : changeIDs) {
		IStreamChange change = opData.getChange(changeID);
		// Is this a stream name change?
		if (change.getIdentifier().equals(IModifyStreamOperationData.NAME)){
		........

The interface IStreamChange does not provide a whole lot of data to find out what actually happened. But the identifier gives a good idea. The IStreamChange is implemented by several interfaces that provide more information.

istreamchange

  • com.ibm.team.scm.common.process.IStreamComponentChanges is an interface to describe component changes on the stream
  • com.ibm.team.scm.common.process.IStreamFlowChange is an interface to describe flow target related changes on the stream
  • com.ibm.team.scm.common.process.IStreamPropertyChange is an interface to describe property changes such as a name change on the stream

The code can now cast to the specific interface IStreamPropertyChange and access the current and the new value of the property change. These values are the current name and the new name of the stream.

With the new name the code can run a basic validation. If the validation succeeds, the advisor terminates, otherwise it complains and fails the advisor.

The code below shows the whole advisor implementation. In this example the code looks for a very simple prefix ‘TEST_’ on the stream name. If the prefix is available it succeeds, it fails otherwise. This validation can be replaced by a more complex and potentially configurable method.

/*******************************************************************************

 * Licensed Materials - Property of IBM
 * (c) Copyright IBM Corporation 2017. All Rights Reserved. 
 *
 * Note to U.S. Government Users Restricted Rights:  Use, duplication or 
 * disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
 *******************************************************************************/
package com.ibm.js.scm.naming.advisor.service;

import java.util.Set;

import org.eclipse.core.runtime.IProgressMonitor;

import com.ibm.team.process.common.IProcessConfigurationElement;
import com.ibm.team.process.common.advice.AdvisableOperation;
import com.ibm.team.process.common.advice.IAdvisorInfo;
import com.ibm.team.process.common.advice.IAdvisorInfoCollector;
import com.ibm.team.process.common.advice.runtime.IOperationAdvisor;
import com.ibm.team.repository.common.TeamRepositoryException;
import com.ibm.team.scm.common.process.IModifyStreamOperationData;
import com.ibm.team.scm.common.process.IStreamChange;
import com.ibm.team.scm.common.process.IStreamPropertyChange;
import com.ibm.team.scm.service.internal.AbstractScmService;

@SuppressWarnings("restriction")
/**
 * This advisor tests the name of a stream against a naming convention pattern.
 * If the stream name does not match the pattern, the stream can not be saved.
 * 
 * Note that this extension point does not get any change events for repository workspaces. It only works for streams.
 * 
 * 
 * There are several examples for extensions that are shipped with the product that can be looked into in the SDK.
 * @see com.ibm.team.scm.service.internal.process.advisors.UniqueBaselineSetNameAdvisor
 * @see com.ibm.team.scm.service.internal.process.advisors.StreamVisibilityAdvisor
 * @see com.ibm.team.scm.service.internal.process.advisors.StreamAddComponentAdvisor
 * @see com.ibm.team.scm.service.internal.process.advisors.StreamAddUserOwnedComponentAdvisor
 *
 */
public class StreamNamingPatternAdvisor extends AbstractScmService implements
		IOperationAdvisor {

	public static final String REQUIRED_PREFIX = "TEST_";
	public static final String STREAM_NAMING_ADVISOR = "com.ibm.js.scm.naming.advisor.service.streamNaming";

	@Override
	public void run(AdvisableOperation operation,
			IProcessConfigurationElement advisorConfiguration,
			IAdvisorInfoCollector collector, IProgressMonitor monitor)
			throws TeamRepositoryException {
		Object operationData = operation.getOperationData();
		if (!(operationData instanceof IModifyStreamOperationData)) {
			// There are some stream modify operations that are not process
			// enabled so they do not provide any data.
			return;
		}
		// com.ibm.team.scm.server.modifyStream is only called for streams.
		// Saving a repository workspace (which is really like a stream) does
		// not trigger the extension point.
		// This especially implies that it is not possible to test for unique
		// names across streams and workspaces. It is possible to
		IModifyStreamOperationData opData = (IModifyStreamOperationData) operationData;
		if (!opData.isOperationType(IModifyStreamOperationData.CHANGES)) {
			// Nothing to do
			return;
		}

		// Get the set of change IDs and look through the changes
		Set changeIDs = opData.getChangeIds();
		for (String changeID : changeIDs) {
			IStreamChange change = opData.getChange(changeID);
			// Is this a stream name change?
			if (change.getIdentifier().equals(IModifyStreamOperationData.NAME)) {
				/***
				 * Get the change details based on the change we identified
				 * 
				 * The supported types of changes for this extension point are
				 * 
				 * @see com.ibm.team.scm.common.process.IStreamPropertyChange
				 * @see com.ibm.team.scm.common.process.IStreamComponentChanges
				 * @see com.ibm.team.scm.common.process.IStreamFlowChange
				 * 
				 *      A name change is stored as IStreamPropertyChange
				 */
				if (change instanceof IStreamPropertyChange) {
					IStreamPropertyChange streamPropertyChange = (IStreamPropertyChange) change;
					String newName = streamPropertyChange.getNewValue()
							.toString();
					if (validateName(newName)) {
						// We are fine
						return;
					}
					String description = "The stream name violates the naming conventions stream name must have prefix '"
							+ REQUIRED_PREFIX + "'!";
					String summary = description;
					IAdvisorInfo info = collector.createProblemInfo(summary,
							description, STREAM_NAMING_ADVISOR);//$NON-NLS-1$
					collector.addInfo(info);
				}
			}
		}
	}

	/**
	 * Validate the name against the convention
	 * 
	 * @param name
	 * @return
	 */
	private boolean validateName(String name) {
		// Implement your own naming convention here
		if (name.startsWith(REQUIRED_PREFIX)) {
			return true;
		}
		return false;
	}
}

The UniqueStreamNameAdvisor only replaces the validation with a more complex one querying the SCM system for streams with a given name.

The code creates workspace search criteria to search for a stream, that happens to have the same name as the new name for this stream will be. If so, it fails. The search is limited to streams, because it is not possible to do this check for repository workspaces and a conflict would be hard to handle.

/**
 * Validate the name against the convention a stream must have a unique name
 * 
 * @param name
 * @return
 * @throws TeamRepositoryException
 */
private boolean validateName(String name) throws TeamRepositoryException {
	// Get the query service and set criteria
	IScmQueryService queryService = getService(IScmQueryService.class);
	final IWorkspaceSearchCriteria criteria = IWorkspaceSearchCriteria.FACTORY
			.newInstance();
	criteria.setExactName(name); // Look for the same name
	// Only for streams, we can not prevent creation of workspaces with the
	// same name either and a user could create a workspace with the same
	// name and prevent us from saving the stream later.
	criteria.setKind(IWorkspaceSearchCriteria.STREAMS);
	// We only have to find one other
	ItemQueryResult result = queryService.findWorkspaces(criteria, 1, null);
	if (!result.getItemHandles().isEmpty()) {
		return false;
	}
	return true;
}

Consolidation

It is relatively obvious and straight forward to consider refactoring the solution shown here. Create an abstract class that contains all the shared code of both classes, with an abstract method validateName(). Create implementations providing the implementation for the method validateName() and provide these implementation classes in the plugin.xml. That way it is simple to provide new versions for various naming conventions.

Code Structure

The code structure follows the general approach that has been used in this blog for quite some time now. The code comes in the following Eclipse projects used for the purpose explained below.

com.ibm.js.scm.naming.advisor.common is the project that defines the jazz component to be used by this extension. It is in a separate project to allow to use it in case of implementing an aspect editor.

com.ibm.js.scm.naming.advisor.launches is a project that contains the launches that can be used to debug the extension with Jetty.

com.ibm.js.scm.naming.advisor.service is the project that contains the server side extension code.

com.ibm.js.scm.naming.advisor.service.feature defines is the feature for the server side deployment of the extension.

com.ibm.js.scm.naming.advisor.service.updatesite contains the update site to build the server side extension.

com.ibm.js.scm.naming.advisor.service.serverdeploy contains the provision profile as well as the folder structure needed for the final deployment. To prepare deployment Build the update site and copy the plugins and feature folder into the  js_scm_naming_advisor folder. To deploy copy the provision_profiles and the sites folder with all their contents into the server/conf/ccm folder of the RTC server.

codestructure

Configuring the precondition

When running the custom advisor in Jetty or finally deployed the advisor can be configured as usual.

configuring

If configured, the advisors prevent saving streams that do not conform to the specific naming condition. The advisor displays the problem like below.

fail_unique_name

Summary

As always I hope this helps someone out there with running RTC. Please keep in mind that this is as usual a very basic example with no or very limited testing and error handling. Please see the links in the getting started section for more examples, especially if you are just getting started.

A component naming convention advisor

Organizations sometimes would like to implement naming conventions for components based on the architecture for example. This post shows a simple example advisor that checks for a naming convention.

License

The post contains published code, so our lawyers reminded me to state that the code in this post is derived from examples from Jazz.net as well as the RTC SDK. The usage of code from that example source code is governed by this license. Therefore this code is governed by this license. I found a section relevant to source code at the and of the license. Please also remember, as stated in the disclaimer, that this code comes with the usual lack of promise or guarantee. Enjoy!

Just Starting With Extending RTC?

If you just get started with extending Rational Team Concert, or create API based automation, start with the post Learning To Fly: Getting Started with the RTC Java API’s and follow the linked resources.

You should be able to use the following code in this environment and get your own automation or extension working.

Compatibility

This code has been used with RTC 6.0 and is prepared to be used with RTC 6.0.x with no changes and it is pretty safe to assume, that the code will work with newer versions of RTC. It should run with any version that provides the operation ID.

The code in this post uses common and server libraries/services that are available in the RTC Server SDK.

Download

The code is included in the download in the post DIY stream naming convention advisors.

Solution

In the last few versions of RTC several operations have been made available for operational behavior. At least since RTC 5.0.2 the operation to modify a component is available with the operation ID com.ibm.team.scm.server.component. This allows to create advisors/preconditions as well as participants/follow up actions that operate on such events. An example shipped with the product is implemented in the class com.ibm.team.scm.service.UniqueComponentNameAdvisor.

There are examples shipped with the product in the SDK that you can look at for more sample code. For example: com.ibm.team.scm.service.internal.process.advisors.UniqueComponentNameAdvisor

The code below shows a very basic example how to test the component name for some simple naming schema.

The important information to take away is that the information about the save operation is provided in a special interface IComponentModificationData which allows access to the type of the operation, to old and new properties and to the component directly.

componentmodification

So it is possible to find out what operation is done on the component and based on that look at the properties that the component has.

The code below does exactly that. It checks what operation is going on and then takes the new name of the component and checks it.

/*******************************************************************************
 * Licensed Materials - Property of IBM
 * (c) Copyright IBM Corporation 2017. All Rights Reserved. 
 *
 * Note to U.S. Government Users Restricted Rights:  Use, duplication or 
 * disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
 *******************************************************************************/
package com.ibm.js.scm.naming.advisor.service;

import org.eclipse.core.runtime.IProgressMonitor;

import com.ibm.team.process.common.IProcessConfigurationElement;
import com.ibm.team.process.common.advice.AdvisableOperation;
import com.ibm.team.process.common.advice.IAdvisorInfo;
import com.ibm.team.process.common.advice.IAdvisorInfoCollector;
import com.ibm.team.process.common.advice.runtime.IOperationAdvisor;
import com.ibm.team.repository.common.TeamRepositoryException;
import com.ibm.team.scm.service.internal.AbstractScmService;
import com.ibm.team.scm.service.internal.process.IComponentModificationData;
import com.ibm.team.scm.service.internal.process.IComponentModificationData.OpType;

/**
 * An example advisor that checks the name of a component for some naming convention
 *
 * Also @see com.ibm.team.scm.service.UniqueComponentNameAdvisor for product example code
 */
@SuppressWarnings("restriction")
public class ComponentNamingAdvisor extends AbstractScmService implements
		IOperationAdvisor {
	public static final String REQUIRED_PREFIX = "TEST_";
	public static final String COMPONENT_NAMING_ADVISOR = "com.ibm.js.scm.naming.advisor.service.componentNaming";

	@Override
	public void run(AdvisableOperation operation,
			IProcessConfigurationElement advisorConfiguration,
			IAdvisorInfoCollector collector, IProgressMonitor monitor)
			throws TeamRepositoryException {

		IComponentModificationData data = (IComponentModificationData) operation
				.getOperationData();
		if (data == null) {
			throw new TeamRepositoryException("Missing component data"); //$NON-NLS-1$
		}

		String compName;

		if (data.getOpType() == OpType.CREATE) {
			compName = data.getNewName();
		} else if (data.getOpType() == OpType.RENAME) {
			compName = data.getNewName();
		} else {
			return;
		}
		if (validateName(compName)) {
			// Nothing to do
			return;
		}
		String description = "The component name violates the naming conventions component name must have prefix '"
				+ REQUIRED_PREFIX + "'!";
		String summary = description;
		IAdvisorInfo info = collector.createProblemInfo(summary, description,
				COMPONENT_NAMING_ADVISOR);//$NON-NLS-1$
		collector.addInfo(info);
	}

	/**
	 * Validate the name against the convention
	 * 
	 * @param compName
	 * @return
	 */
	private boolean validateName(String compName) {
		// Implement your own naming convention here
		if (compName.startsWith(REQUIRED_PREFIX)) {
			return true;
		}
		return false;
	}
}

Summary

This is as usual a very basic example with no or very limited testing and error handling. See the links in the getting started section for more examples. As always I hope this helps someone out there with running RTC.

Restrict Delivery of Changesets Associated to Wrong Work Item Types Advisor

How can I access work items associated to a change set in an Advisor or precondition on the server? Here is an Advisor example that prevents delivery of change sets if they are associated to the wrong work item type.

I tried to answer some questions in the forum. They were related to how to get the work item from a change set in an Advisor. I thought it would be simple because I had done a lot with the work item link API on client and server already. This is called hubris, I guess, and I found out the hard way, that the API from the Jazz SCM side is very different from what I was used to so far. Since it was so tough, I thought I should publish what I found, so that others can use it to jump start solving their own requirements.

License and how to get started with the RTC API’S

As always, our lawyers reminded me to state that the code in this post is derived from examples from Jazz.net as well as the RTC SDK. The usage of code from that example source code is governed by this license. Therefore this code is governed by this license, which basically means you can use it for internal usage, but not sell. Please also remember, as stated in the disclaimer, that this code comes with the usual lack of promise or guarantee. Enjoy!

If you just get started with extending Rational Team Concert, or create API based automation, start with the post Learning To Fly: Getting Started with the RTC Java API’s and follow the linked resources.

You should be able to use the following code in this environment and get your own automation or extension working.

The example in this blog shows RTC Server and Common API.

Download

The code for the example can be found here. The code uses the RTC 4.0 SDK and should work with lter versions of the SDK.

Advisors and Participants

I have already blogged about the RTC Update Parent Duration Estimation and Effort Participant. This blog is about an Advisor, so what is the difference?

A Participant is basically operational behavior that happens after a certain operation. It can fail and roll back the save, but does not have to. Participants are also called follow-up actions. An Advisor or precondition would be used If it is necessary to check certain conditions before an operation is performed. A good example for this is the Descriptive Change Sets Advisor that requires a comment or a work item associated to a change set before it can be delivered.

In general Advisors and Participants are very similar. Even most of the required API code can be used in both extension types. However there are some differences.

Participants

  • Extend the extension point com.ibm.team.process.service.operationParticipants
  • Implement the interface com.ibm.team.process.common.advice.runtime.IOperationParticipant
  • Are allowed to modify the changes they are triggered for

Advisors

They get different information when called but other than that most of the code is similar. It is also important for both implementations to extend com.ibm.team.repository.service.AbstractService in order to be able to get services and other vital information from the API.

Participants as well as Advisors need to provide an operation ID for the operation they want to be triggered and they need to specify a component and required services.

You can find a list of extension points and operation ID’s here in the Jazz Wiki. The Rational Team Concert 4.0 Extensions Workshop shows all the steps required to create a complete participant. The techniques used there have been used to create the Advisor in this post. Please note that all code below is for a Server extension.

How does that API Work?

The implementation started like any other Advisor or Participant. I looked at this question that originally started my effort and tried to figure out how to use the link API.

And I completely failed. I was able to locate similar code in the SDK but I could not figure out how to get the ProviderFactory needed to get the links. Now I did some really serious “search for references” in the SDK. I searched for plugins that extend the same extension point and use the same classes I was using, especially the link API.

As a side note, that is the only technique, besides using a search engine and scanning the SDK documentation for the RTC versions 3.x, 2.x and 1.x in the Jazz Team Wiki looking for examples, that I use to find around in the API.

The Eclipse Plugin Development Environment allows to search for references, declarations of classes, methods and extension points. It allows to use the Java search for classes and methods. It can also restrict to what kind of results one is looking for. This is really powerful and helped solving almost all my questions so far.

Robins blog about using the Plugin Spy to find Client API is also a great resource if looking for API. In most of the cases, the Client PAI works similar in the Server, only the Client Libraries need to be replaced by a Service.

Finally I found two classes that helped me solving the issue. Only, at first, I did not notice it was two classes. The Class com.ibm.team.filesystem.service.internal.ServerRequireWorkItemAdvisor uses the link code. It is the Descriptive Change Sets Advisor that requires a comment or a work item associated to a change set before it can be delivered. However, it gets the required factory in its constructor which does not match the way my implementation gets created by the extension point. I figured after a lot of confusion that this class is actually created by com.ibm.team.filesystem.service.internal.ServerRequireWorkItemAdvisorRunner which is the class that is called in the Advisor implementation. And it is able to get the factory I was looking for.

The Advisor Implementation Explained

So I tried the code and .. it did not compile. Another close look revealed that ServerRequireWorkItemAdvisorRunner extends AbstractScmService and not only AbstractService which allows it to get the data needed to get the factory. This finally led to my code below.

/*******************************************************************************
 * Licensed Materials - Property of IBM (c) Copyright IBM Corporation 2005-20012.
 * All Rights Reserved.
 * 
 * Note to U.S. Government Users Restricted Rights: Use, duplication or
 * disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
 ******************************************************************************/
package com.ibm.js.team.scm.extension.restrictdelivery.advisor;

import java.util.List;

import org.eclipse.core.runtime.IProgressMonitor;

import com.ibm.team.filesystem.common.workitems.ILinkConstants;
import com.ibm.team.links.common.ILink;
import com.ibm.team.process.common.IProcessConfigurationElement;
import com.ibm.team.process.common.advice.AdvisableOperation;
import com.ibm.team.process.common.advice.IAdvisorInfo;
import com.ibm.team.process.common.advice.IAdvisorInfoCollector;
import com.ibm.team.process.common.advice.runtime.IOperationAdvisor;
import com.ibm.team.repository.common.TeamRepositoryException;
import com.ibm.team.repository.service.IRepositoryItemService;
import com.ibm.team.scm.common.IChangeSetHandle;
import com.ibm.team.scm.common.links.ChangeSetLinks;
import com.ibm.team.scm.common.process.DeliverOperationData;
import com.ibm.team.scm.common.providers.ProviderFactory;
import com.ibm.team.scm.service.internal.AbstractScmService;
import com.ibm.team.scm.service.internal.utils.ServerProviderFactory;
import com.ibm.team.workitem.common.model.IWorkItem;
import com.ibm.team.workitem.common.model.IWorkItemHandle;
import com.ibm.team.workitem.service.IWorkItemServer;

/**
 * Finds the work items a changeset is related to and checks if they are od a
 * specific type. Prevents from delivery if the type iswrong.
 * 
 */
@SuppressWarnings("restriction")
public class RestrictDeliveryToWorkitemType extends AbstractScmService
		implements IOperationAdvisor {

	public static final String COM_IBM_JS_TEAM_SCM_EXTENSION_RESTRICTDELIVERY_ADVISOR_RESTRICTWORKITEMTYPE = "com.ibm.js.team.scm.extension.restrictdelivery.advisor.restrictworkitemtype";
	// Services we need
	private IWorkItemServer workItemServer;
	IRepositoryItemService itemService;

	@Override
	public void run(AdvisableOperation operation,
			IProcessConfigurationElement advisorConfiguration,
			IAdvisorInfoCollector collector, IProgressMonitor monitor)
			throws TeamRepositoryException {
		Object operationData = operation.getOperationData();
		if (!(operationData instanceof DeliverOperationData)) {
			return;
		}
		DeliverOperationData data = (DeliverOperationData) operationData;
		List changeSetHandles = data.getChangeSetHandles();

		// Get the required service interfaces
		workItemServer = getService(IWorkItemServer.class);
		// @see com.ibm.team.filesystem.service.internal.ServerRequireWorkItemAdvisorRunner
		// @see com.ibm.team.filesystem.service.internal.ServerRequireWorkItemAdvisor
		itemService = getService(IRepositoryItemService.class);

		// Get the ProviderFactory to be able to find the links
		ProviderFactory providerFactory = new ServerProviderFactory(this, itemService);

		// Check all relationships
		for (IChangeSetHandle iChangeSetHandle : changeSetHandles) {
			List links = ChangeSetLinks.findLinks(providerFactory,iChangeSetHandle,
					new String[] { ILinkConstants.CHANGESET_WORKITEM_LINKTYPE_ID },
					monitor);
			for (ILink link : links) {
				Object resolved = link.getTargetRef().resolve();
				if (resolved instanceof IWorkItemHandle) {
					checkWorkITemType(resolved, collector, monitor);
				}
			}
		}
	}
}

This part of the code basically gets the data, gets the Services and the ProviderFactory. Then it uses the ProviderFactory and iterates all links to find if it is associated to a work item. If it is it checks for a valid work item type.

To allow better display in this blog, I pulled checking the work item type into a method.

public void checkWorkITemType(Object resolved,
		IAdvisorInfoCollector collector, IProgressMonitor monitor)
		throws TeamRepositoryException {
	// We found a work item.
	IWorkItemHandle wiHandle = (IWorkItemHandle) resolved;
	IWorkItem workItem = (IWorkItem) workItemServer
		.getAuditableCommon().resolveAuditable(wiHandle,
		IWorkItem.FULL_PROFILE, monitor);
	String workitemType = workItem.getWorkItemType();

	if (!(workitemType.equalsIgnoreCase("defect") || workitemType.equalsIgnoreCase("task"))) {
		IAdvisorInfo info = collector.createProblemInfo(
		"Change Set associated to wrong work item type. Delivery denied ",
		"The change set is assotiated to work item " + workItem.getId()
		+ " of type " + workitemType
		+ ". Changesets are allowed only for work items of type Defect or Task. Please remove this assotiation",
		COM_IBM_JS_TEAM_SCM_EXTENSION_RESTRICTDELIVERY_ADVISOR_RESTRICTWORKITEMTYPE);
		collector.addInfo(info);
	}
}

If the code detects a wrong work item type, it creates a problem info and that provides the failure information.

If you are looking for the Client API, here are some code hints in this forum question. More information about the client SCM API can be found in this and  the related posts.

As usual the exception handling is very basic and you might want to improve that if using this code. In addition you probably want to add a schema to make the code configurable in the process configuration. However, I hope this is helpful and saves some cycles searching through the RTC SDK.