Creating Link from RQM to RM
2 answers
A starting point for RQM and RM web application to be linked over OSLC can be found here- https://jazz.net/help-dev/clm/index.jsp?topic=%2Fcom.ibm.rational.test.qm.doc%2Ftopics%2Fr_link_domains.html
Comments
Hi Abhishek,
Thanks for the response.
I am able to create a link from Test Cases to Requirements using testCase.addValidatesRequirement(new Link(uris)) method.
Now since this method does not support back link i am creating a back link manually using oslc.
The method I am using here is : requirement.addValidatedBy(new Link(new URI(resultReverseURI[0])));
Is it the right way to do so coz its not responding as expected.
Stating : method not supported.
Thanks
Vaibhav
Hi,
package rb.com.CreateRequrementLink;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.xml.bind.JAXBException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.wink.client.ClientResponse;
import org.eclipse.lyo.client.exception.JazzAuthErrorException;
import org.eclipse.lyo.client.exception.JazzAuthFailedException;
import org.eclipse.lyo.client.exception.ResourceNotFoundException;
import org.eclipse.lyo.client.exception.RootServicesException;
import org.eclipse.lyo.client.oslc.OSLCConstants;
import org.eclipse.lyo.client.oslc.OslcClient;
import org.eclipse.lyo.client.oslc.jazz.JazzFormAuthClient;
import org.eclipse.lyo.client.oslc.jazz.JazzRootServicesHelper;
import org.eclipse.lyo.client.oslc.resources.OslcQuery;
import org.eclipse.lyo.client.oslc.resources.OslcQueryParameters;
import org.eclipse.lyo.client.oslc.resources.OslcQueryResult;
import org.eclipse.lyo.client.oslc.resources.Requirement;
import org.eclipse.lyo.client.oslc.resources.TestCase;
import org.eclipse.lyo.client.oslc.resources.TestResult;
import org.eclipse.lyo.oslc4j.core.model.Link;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import net.oauth.OAuthException;
public class CreateRequirementlink {
static Logger logger = Logger.getLogger(CreateRequirementlink.class.getName());
public static String username;
public static String password;
public static String projectArea;
public static String projectAreaID;
public static String serverUrl;
public static String serverUrlReq;
public static String projectAreaRequirement;
private static JazzRootServicesHelper rootServicesHelper = null;
private static JazzRootServicesHelper rootServicesHelperReq = null;
private static JazzRootServicesHelper rootServicesHelperReverseLink = null;
private static JazzFormAuthClient client = null;
private static JazzFormAuthClient clientTestCase = null;
private static JazzFormAuthClient clientReverseLink = null;
private static JazzFormAuthClient clientReq = null;
private static String excelFilePath;
public static void main(String[] args) throws RootServicesException, JazzAuthFailedException, JazzAuthErrorException, ResourceNotFoundException, IOException, OAuthException, URISyntaxException, SAXException, ParserConfigurationException, JAXBException {
logger.info("Execution started at " + new Timestamp(System.currentTimeMillis()));
readTestCase();
logger.info("Execution completed at " + new Timestamp(System.currentTimeMillis()));
logger.info("---------------------------------------------------------------------");
System.out.println("Execution Completed .");
}
public static Map<String,String> readTestCaseDetailsFromExcel(String excelFilePath) throws IOException{
Map<String, String> mapArtifactLinkDetails = new HashMap<String, String> ();
FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet firstSheet = workbook.getSheetAt(0);
// new code ---------------------------------------
int firstRowNum = firstSheet.getFirstRowNum();
int lastRowNum = firstSheet.getLastRowNum();
Row row1 = firstSheet.getRow(0);
int colNumTestCaseId = -1;
int colNumRQMId = -1;
try{
for (Cell cell : row1) {
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
if (cell.getRichStringCellValue().getString().trim().equalsIgnoreCase("ID")) {
colNumTestCaseId = cell.getColumnIndex(); }
}
}
for (Cell cell : row1) {
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
if (cell.getRichStringCellValue().getString().trim().equalsIgnoreCase("DNG_ID")) {
colNumRQMId = cell.getColumnIndex(); }
}
}
}
catch(Exception ex){
logger.info("Invalid Column Name. Please review the excel file.");
}
for(int i= firstRowNum+1; i<=lastRowNum; i++){
if(i>=firstRowNum && i<=lastRowNum)
{
Row row = firstSheet.getRow(i);
Cell cellKey = row.getCell(colNumTestCaseId);
Cell cellValue = row.getCell(colNumRQMId);
try{
mapArtifactLinkDetails.put(cellKey.getStringCellValue(), cellValue.getStringCellValue());
}
catch(Exception ex){
logger.info("Only String Type data can be read. Please change the ID and DNG_ID columns's cell type to Text.");
}
}
}
// old code --------------------------------
/ Iterator<Row> iterator = firstSheet.iterator();
String testCaseIdVar;
String requirementIdVar;
while (iterator.hasNext()) {
Row nextRow = iterator.next();
Cell cellKey = nextRow.getCell(0);
Cell cellValue = nextRow.getCell(1);
System.out.println("cellKey "+ cellKey.getStringCellValue());
System.out.println("cellValue "+ cellValue.getStringCellValue());
if((cellKey.getStringCellValue()).equalsIgnoreCase("Test Case Id")){
testCaseIdVar = cellKey.getStringCellValue();
cellKey.getColumnIndex();
}
else if((cellValue.getStringCellValue()).equalsIgnoreCase("DNG Id")){
requirementIdVar = cellValue.getStringCellValue();
cellValue.getColumnIndex();
}
} /
return mapArtifactLinkDetails;
}
public static void readTestCase() throws IOException, RootServicesException, JazzAuthFailedException, JazzAuthErrorException, ResourceNotFoundException, OAuthException, URISyntaxException, SAXException, ParserConfigurationException, JAXBException{
Properties properties = new Properties();
File file = new File("config.properties");
FileInputStream fileInputStream = new FileInputStream(file);
properties.load(fileInputStream);
serverUrl = properties.getProperty("serverUrl");
username = properties.getProperty("username");
password = properties.getProperty("password");
projectArea = properties.getProperty("projectArea");
serverUrlReq = properties.getProperty("serverUrlReq");
projectAreaRequirement = properties.getProperty("projectAreaRequirement");
excelFilePath = properties.getProperty("excelFilePath");
int totalTestCases=0;
int testCasesUpdated=0;
String serviceProviderUrl;
String testSpecURL = null;
ClientResponse response = null;
TestResult testResult;
TestCase testCase = null;
rootServicesHelper = new JazzRootServicesHelper(serverUrl, OSLCConstants.OSLC_QM_V2);
client = rootServicesHelper.initFormClient(username, password);
client.formLogin();
clientTestCase = rootServicesHelper.initFormClient(username, password);
clientTestCase.formLogin();
serviceProviderUrl = client.lookupServiceProviderUrl(rootServicesHelper.getCatalogUrl(), projectArea);
String queryCapability = client.lookupQueryCapability(serviceProviderUrl,OSLCConstants.OSLC_QM_V2, OSLCConstants.QM_TEST_CASE_QUERY);
OslcQueryParameters queryParams = new OslcQueryParameters();
OslcQuery query = new OslcQuery(client, queryCapability, Integer.MAX_VALUE, queryParams);
OslcQueryResult result = query.submit();
result.setMemberProperty(OSLCConstants.OSLC_QM_V2 + "testCase");
String resultsUrl[] = result.getMembersUrls();
List<String> listMapKey = new ArrayList<String>();
Map<String,String> testCasedetailsMap = readTestCaseDetailsFromExcel(excelFilePath);
for (Map.Entry<String, String> entry : testCasedetailsMap.entrySet()) {
listMapKey.add(entry.getKey());
}
String[] requirementURI = new String[100000];
for(int i=0; i <resultsUrl.length-1; i++) {
response = client.getResource(resultsUrl[i], OSLCConstants.CT_RDF);
ClientResponse tempResponseVar2 = clientTestCase.getResource(resultsUrl[i], OSLCConstants.CT_RDF);
InputStream inputStream = response.getEntity(InputStream.class);
testCase= tempResponseVar2.getEntity(TestCase.class);
InputSource inputSource = new InputSource(inputStream);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document document = dBuilder.parse(inputSource);
NodeList element = document.getElementsByTagName("rqm_qm:shortIdentifier");
String testCaseId = null ;
for (int p = 0; p < element.getLength(); p++) {
testCaseId = element.item(p).getTextContent();
}
response.consumeContent();
tempResponseVar2.consumeContent();
totalTestCases++;
// COMPARISON -------- with list map key /// replace title with getId for TC id
if(listMapKey.contains(testCaseId) ){
OslcQueryParameters queryParamsrequirement = new OslcQueryParameters();
queryParams.setPrefix("dcterms=<http://purl.org/dc/terms/>");
// Iterating for multiple requirement ids
String varMultipleRequirementids;
String[] arrMultipleRequirementids = null;
try{
varMultipleRequirementids = testCasedetailsMap.get(testCaseId);
arrMultipleRequirementids = varMultipleRequirementids.split(",");
}
catch(Exception ex){
logger.info("Please enter a valid ID.");
}
// get service provider url for PA of requirement ids
// String projectAreaRequirement = "Tools (RM)";
for(int k=0; k<arrMultipleRequirementids.length; k++){
OslcQueryParameters queryParamsReq = new OslcQueryParameters();
queryParamsReq .setPrefix("dcterms=<http://purl.org/dc/terms/>");
queryParamsReq.setWhere("dcterms:identifier="+ arrMultipleRequirementids[k]);
queryParamsReq.setSelect("dcterms:title");
rootServicesHelperReq = new JazzRootServicesHelper(serverUrlReq, OSLCConstants.OSLC_RM_V2);
clientReq = rootServicesHelperReq.initFormClient(username, password);
clientReq.formLogin();
String serviceProviderUrlReq = clientReq.lookupServiceProviderUrl(rootServicesHelperReq.getCatalogUrl(), projectAreaRequirement);
String queryCapabilityReq = clientReq.lookupQueryCapability(serviceProviderUrlReq,OSLCConstants.OSLC_RM_V2, OSLCConstants.RM_REQUIREMENT_TYPE);
String requirementFactoryReq = clientReq.lookupCreationFactory(serviceProviderUrlReq, "http://open-services.net/ns/rm#", "http://open-services.net/ns/rm#Requirement");
OslcQuery queryRequirementReq = new OslcQuery(clientReq, queryCapabilityReq, queryParamsReq);
OslcQueryResult resultRequirement = queryRequirementReq.submit();
Requirement requirement = resultRequirement.getRawResponse().getEntity(Requirement.class);
URI uris = requirement.getAbout();
// ------------- Getting the result in requirement object to persist the reverse link ------------------------
rootServicesHelperReverseLink = new JazzRootServicesHelper(serverUrl, OSLCConstants.OSLC_QM_V2);
clientReverseLink = rootServicesHelperReverseLink.initFormClient(username, password);
clientReverseLink.formLogin();
String serviceProviderUrlReverseLink = clientReverseLink.lookupServiceProviderUrl(rootServicesHelperReverseLink.getCatalogUrl(), projectArea);
String queryCapabilityReverseLink = clientReverseLink.lookupQueryCapability(serviceProviderUrlReverseLink,OSLCConstants.OSLC_QM_V2, OSLCConstants.QM_TEST_CASE_QUERY);
OslcQueryParameters queryParamsReverse = new OslcQueryParameters();
queryParamsReverse.setWhere("rqm_qm:shortIdentifier=" + testCaseId);
OslcQuery queryReverse = new OslcQuery(clientReverseLink, queryCapabilityReverseLink, Integer.MAX_VALUE, queryParamsReverse);
OslcQueryResult resultReverse = queryReverse.submit();
resultReverse.setMemberProperty(OSLCConstants.OSLC_QM_V2 + "testCase");
String[] resultReverseURI = resultReverse.getMembersUrls();
// Link[] link = resultReverseURI[0];
// requirement.setValidatedBy(new Link(resultReverseURI[0]));
requirement.addValidatedBy(new Link(new URI(resultReverseURI[0])));
// requirement.addValidatedBy(new Link(new URI(resultReverseURI[1])));
ClientResponse clientResponse = clientReq.updateResource(requirementFactoryReq , (Object) requirement, "application/rdf+xml");
System.out.println( requirement.getValidatedBy() + "-----");
if ( clientResponse.getStatusCode() == 200 || clientResponse.getStatusCode() == 201) {
System.out.println("Requirement Updated");
}
else {
System.out.println("Requirement Not Updateed");
}
// ---------------------------------------
try{
testCase.addValidatesRequirement(new Link(uris));
ClientResponse getResult = client.updateResource(testCase.getIdentifier(), testCase, OSLCConstants.CT_RDF);
testCasesUpdated++;
getResult.consumeContent();
}
catch(Exception ex){
logger.info("Please enter a valid ID");
}
}
}
}
logger.info("Total Test Cases : " + totalTestCases);
logger.info("Total links created : " + testCasesUpdated);
}
public static String[] getArtifactURL(List tcIdList, JazzFormAuthClient client, String queryCapability){
String[] requirementURI = new String[Integer.MAX_VALUE];
for(int i=0; i<tcIdList.size(); i++)
{
OslcQueryParameters queryParams = new OslcQueryParameters();
queryParams.setPrefix("dcterms=<http://purl.org/dc/terms/>");
queryParams.setWhere("dcterms:identifier="+ tcIdList.get(i));
queryParams.setSelect("dcterms:title");
OslcQuery query = new OslcQuery(client, queryCapability, queryParams);
OslcQueryResult result = query.submit();
requirementURI = result.getMembersUrls();
}
return requirementURI;
}
private static void processPagedQueryResults(OslcQueryResult result, OslcClient client, boolean asJavaObjects) {
int page = 1;
do {
// System.out.println("\nPage " + page + ":\n");
processCurrentPage(result,client,asJavaObjects);
if (result.hasNext()) {
result = result.next();
// System.out.println(result+ " /////////////");
page++;
} else {
break;
}
} while(true);
}
private static void processCurrentPage(OslcQueryResult result, OslcClient client, boolean asJavaObjects) {
for (String resultsUrl : result.getMembersUrls()) {
//System.out.println(resultsUrl);
ClientResponse response = null;
try {
//Get a single artifact by its URL
response = client.getResource(resultsUrl, OSLCConstants.CT_RDF);
if (response != null) {
//De-serialize it as a Java object
if (asJavaObjects) {
TestResult tr = response.getEntity(TestResult.class);
// printTestResultInfo(tr); //print a few attributes
} else {
//Just print the raw RDF/XML (or process the XML as desired)
// processRawResponse(response);
}
}
} catch (Exception e) {
// System.out.println(e);
}
}
}
/
private static void printTestResultInfo(TestResult tr) {
//See the OSLC4J TestResult class for a full list of attributes you can access.
if (tr != null) {
System.out.println("ID: " + tr.getIdentifier() + ", Title: " + tr.getTitle() + ", Status: " + tr.getStatus());
}
}/
}
Thanks
Vaibhav