2015年4月6日 星期一

[ RTC Client Lib ] SC - Retrieve change set based on given IBuildResult object

Question 
How do I retrieve the change set (diff from previous build result) from a given build result object? From the RTC web page, There is a link "Show Change": 
 
when click on it, I can have the corresponding change set diffed from the previous build result. That way, I can analyze the change set to narrow down the problem space while the test cases broken. 

Sample Code: 
Below sample code will do actions: 
* Login RTC
* Retrieve IBuildDefinition implemented object with given ID.
* Retrieve IBuildResult list from above build definition.
* Retrieve IBaseline from build result
* Diff two baseline to have IChangeHistorySyncReport
* List and print IChangeSet list
* Logout RTC

  1. package test.pub;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Arrays;  
  5. import java.util.Date;  
  6. import java.util.List;  
  7.   
  8. import org.eclipse.core.runtime.IProgressMonitor;  
  9. import org.eclipse.core.runtime.NullProgressMonitor;  
  10.   
  11. import com.ibm.team.build.client.ITeamBuildClient;  
  12. import com.ibm.team.build.common.ScmConstants;  
  13. import com.ibm.team.build.common.model.BuildState;  
  14. import com.ibm.team.build.common.model.BuildStatus;  
  15. import com.ibm.team.build.common.model.IBuildDefinition;  
  16. import com.ibm.team.build.common.model.IBuildResult;  
  17. import com.ibm.team.build.common.model.IBuildResultContribution;  
  18. import com.ibm.team.build.common.model.IBuildResultHandle;  
  19. import com.ibm.team.build.common.model.query.IBaseBuildResultQueryModel.IBuildResultQueryModel;  
  20. import com.ibm.team.links.client.ILinkManager;  
  21. import com.ibm.team.links.common.ILink;  
  22. import com.ibm.team.links.common.ILinkHandle;  
  23. import com.ibm.team.process.client.IProcessClientService;  
  24. import com.ibm.team.repository.client.IItemManager;  
  25. import com.ibm.team.repository.client.ITeamRepository;  
  26. import com.ibm.team.repository.client.TeamPlatform;  
  27. import com.ibm.team.repository.client.ITeamRepository.ILoginHandler;  
  28. import com.ibm.team.repository.client.ITeamRepository.ILoginHandler.ILoginInfo;  
  29. import com.ibm.team.repository.common.IItemHandle;  
  30. import com.ibm.team.repository.common.TeamRepositoryException;  
  31. import com.ibm.team.repository.common.UUID;  
  32. import com.ibm.team.repository.common.model.FetchResult;  
  33. import com.ibm.team.repository.common.query.IItemQuery;  
  34. import com.ibm.team.repository.common.query.IItemQueryPage;  
  35. import com.ibm.team.repository.common.query.ast.IPredicate;  
  36. import com.ibm.team.repository.common.service.IQueryService;  
  37. import com.ibm.team.scm.client.IBaselineConnection;  
  38. import com.ibm.team.scm.client.IWorkspaceManager;  
  39. import com.ibm.team.scm.client.SCMPlatform;  
  40. import com.ibm.team.scm.common.IBaseline;  
  41. import com.ibm.team.scm.common.IBaselineHandle;  
  42. import com.ibm.team.scm.common.IBaselineSet;  
  43. import com.ibm.team.scm.common.IBaselineSetHandle;  
  44. import com.ibm.team.scm.common.IChangeSet;  
  45. import com.ibm.team.scm.common.IChangeSetHandle;  
  46. import com.ibm.team.scm.common.dto.IChangeHistorySyncReport;  
  47. import com.ibm.team.scm.common.dto.IChangeSetLinkSummary;  
  48. import com.ibm.team.scm.common.links.ChangeSetLinks;  
  49. import com.ibm.team.scm.common.links.ILinkConstants;  
  50. import com.ibm.team.scm.common.providers.ProviderFactory;  
  51. import com.ibm.team.workitem.client.IAuditableClient;  
  52. import com.ibm.team.workitem.client.IWorkItemClient;  
  53. import com.ibm.team.workitem.common.model.IWorkItem;  
  54. import com.ibm.team.workitem.common.model.IWorkItemHandle;  
  55.   
  56. public class RetrieveChangeSetFromBuildResult{  
  57.     public static IProgressMonitor MyProgressMonitor = new NullProgressMonitor();  
  58.     public static ITeamRepository TeamRepository = null;  
  59.       
  60.     public static String BuildDefinitionID="xxx";  
  61.       
  62.     public static String repositoryURI = "xxx";  
  63.     public static String userId = "xxx";  
  64.     public static String password = "xxx";  
  65.     public static String CHANGE_SET_TYPE = "com.ibm.team.filesystem.workitems.change_set";  
  66.       
  67.     private static class LoginHandler implements ILoginHandler, ILoginInfo {  
  68.   
  69.         private String fUserId;  
  70.         private String fPassword;  
  71.   
  72.         private LoginHandler(String userId, String password) {  
  73.             fUserId = userId;  
  74.             fPassword = password;  
  75.         }  
  76.   
  77.         public String getUserId() {  
  78.             return fUserId;  
  79.         }  
  80.   
  81.         public String getPassword() {  
  82.             return fPassword;  
  83.         }  
  84.   
  85.         public ILoginInfo challenge(ITeamRepository repository) {  
  86.             return this;  
  87.         }  
  88.     }  
  89.               
  90.     public static void Start(String buildDftID) throws Exception  
  91.     {  
  92.         IProcessClientService processClient = (IProcessClientService) TeamRepository  
  93.                 .getClientLibrary(IProcessClientService.class);  
  94.         IAuditableClient auditableClient = (IAuditableClient) TeamRepository  
  95.                 .getClientLibrary(IAuditableClient.class);  
  96.         IWorkItemClient workItemClient = (IWorkItemClient) TeamRepository  
  97.                 .getClientLibrary(IWorkItemClient.class);  
  98.         ITeamBuildClient buildClient = (ITeamBuildClient) TeamRepository.getClientLibrary(ITeamBuildClient.class);        
  99.         ILinkManager linkManager = (ILinkManager) TeamRepository  
  100.                 .getClientLibrary(ILinkManager.class);  
  101.           
  102.         // 1) Fetch Build Definition  
  103.         IBuildResultHandle handle = (IBuildResultHandle) IBuildResult.ITEM_TYPE  
  104.                 .createItemHandle(UUID.valueOf(buildDftID), null);  
  105.         ArrayList handleList = new ArrayList();  
  106.         handleList.add(handle);  
  107.         FetchResult fetchResult = (FetchResult) TeamRepository.itemManager()  
  108.                 .fetchCompleteItemsPermissionAware(handleList,  
  109.                         IItemManager.REFRESH, null);  
  110.           
  111.         IBuildDefinition definition = null;  
  112.         if (fetchResult.hasNotFoundItems()) {  
  113.             System.err.printf("\t[Error] Fail in retrieving build definition...");  
  114.             return;  
  115.         } else {  
  116.             for (Object result : fetchResult.getRetrievedItems()) {  
  117.                 // System.out.printf("\t[Test] Retrieved item:\n%s\n", result);  
  118.                 if (result instanceof IBuildResult) {  
  119.                     IBuildResult buildResult = (IBuildResult) result;  
  120.                     //System.out.printf("\t\tBuild Result=%s\n", buildResult);  
  121.                 } else if (result instanceof IBuildDefinition) {  
  122.                     //System.out.printf("\t\tBuild Definition=%s\n", result);  
  123.                     definition = (IBuildDefinition) result;  
  124.                 }  
  125.             }  
  126.         }  
  127.         if (definition == null) {  
  128.             System.err.printf("\t[Error] Fail in retrieving build definition!\n");  
  129.             return;  
  130.         }  
  131.           
  132.         // 2) Query Build Result          
  133.         IBuildResultQueryModel buildResultQueryModel = IBuildResultQueryModel.ROOT;  
  134.         IItemQuery query = IItemQuery.FACTORY  
  135.                 .newInstance(buildResultQueryModel);  
  136.           
  137.         IPredicate predicate = (buildResultQueryModel.buildDefinition()  
  138.                 ._eq(query.newItemHandleArg()))._and(  
  139.                 buildResultQueryModel.personalBuild()._isFalse())._and(  
  140.                 buildResultQueryModel.buildState()._eq(  
  141.                         BuildState.COMPLETED.name()));  
  142.   
  143.         query.filter(predicate);  
  144.         query.orderByAsc(buildResultQueryModel.buildStartTime());  
  145.   
  146.         IItemQueryPage queryPage = buildClient.queryItems(query,  
  147.                 new Object[] { definition.getItemId() },  
  148.                 IQueryService.ITEM_QUERY_MAX_PAGE_SIZE, MyProgressMonitor);  
  149.   
  150.         // print out the labels of the retrieved builds  
  151.         String[] properties = new String[] { IBuildResult.PROPERTY_LABEL,  
  152.                                                          IBuildResult.PROPERTY_BUILD_STATUS,  
  153.                                                          IBuildResult.PROPERTY_BUILD_REQUESTS,  
  154.                                                          IBuildResult.PROPERTY_SUMMARY,  
  155.                                                          IBuildResult.PROPERTY_BUILD_RESULT_CONTRIBUTIONS};  
  156.         List buildResults = TeamRepository.itemManager().fetchPartialItems(  
  157.                 queryPage.getItemHandles(), IItemManager.DEFAULT,  
  158.                 Arrays.asList(properties), MyProgressMonitor);  
  159.           
  160.         IBaselineConnection pbaseLineConnection=null;  
  161.         Date preBaselineDate=null;  
  162.         if(buildResults.size()==0) System.err.printf("\t[Warn] No build result exist!\n");  
  163.         for (Object result : buildResults) {  
  164.             IBuildResult buildResult = (IBuildResult) result;  
  165.             if (buildResult.getStatus().equals(BuildStatus.ERROR)  
  166.                     || buildResult.getStatus().equals(BuildStatus.OK)) {  
  167.                 System.out.printf("\t[Info] Build Result='%s'...\n",  
  168.                         buildResult.getLabel());  
  169.                 IBuildResultContribution[] contribs = buildClient  
  170.                         .getBuildResultContributions(  
  171.                                 buildResult,  
  172.                                 ScmConstants.EXTENDED_DATA_TYPE_ID_BUILD_SNAPSHOT,  
  173.                                 null);  
  174.   
  175.                 for (IBuildResultContribution c : contribs) {                     
  176.                     IItemHandle item = c.getExtendedContribution();  
  177.                     IBaselineSetHandle baseLineHandle = (IBaselineSetHandle) item;  
  178.                     IBaselineSet snapshot = (IBaselineSet) TeamRepository  
  179.                             .itemManager().fetchCompleteItem(baseLineHandle,  
  180.                                     IItemManager.DEFAULT, null);  
  181.                     List baseLines = snapshot.getBaselines();  
  182.                     Date latestDate = null;  
  183.                     IBaseline latestLine = null;  
  184.                     for (IBaselineHandle lineHandle : baseLines) {  
  185.                         IBaseline line = (IBaseline) TeamRepository  
  186.                                 .itemManager().fetchCompleteItem(lineHandle,  
  187.                                         IItemManager.DEFAULT, null);                          
  188.                         if (latestDate == null) {  
  189.                             latestDate = line.getCreationDate();  
  190.                             latestLine = line;  
  191.                         } else {  
  192.                             if (line.getCreationDate().compareTo(latestDate) > 0) {  
  193.                                 latestDate = line.getCreationDate();  
  194.                                 latestLine = line;  
  195.                             }  
  196.                         }  
  197.                     }  
  198.                       
  199.                     System.out.printf("\t%s (%s/%d)\n", latestLine.getComment(), latestLine.getCreationDate(), latestLine.getId());  
  200.                     if (latestLine != null) {  
  201.                          IWorkspaceManager wm = SCMPlatform.getWorkspaceManager(TeamRepository);  
  202.                          IBaselineConnection baseLineConnection = wm.getBaselineConnection(latestLine, null);  
  203.                         if (pbaseLineConnection != null && latestDate.compareTo(preBaselineDate)!=0)   
  204.                         {  
  205.                             IWorkspaceManager workspaceManager = com.ibm.team.scm.client.SCMPlatform.getWorkspaceManager(TeamRepository);  
  206.                             IChangeHistorySyncReport changeHistory = pbaseLineConnection  
  207.                                     .compareTo(  
  208.                                             baseLineConnection.getBaseline(),  
  209.                                             null);  
  210.   
  211.                             List incomingChangeSetHandles = changeHistory.incomingChangeSets();  
  212.                             List changeSetLink = workspaceManager  
  213.                                     .getChangeSetLinkSummary(  
  214.                                             incomingChangeSetHandles, null);  
  215.                             System.out.printf("\t========== Change Set Start (%d) ==========\n", changeSetLink.size());  
  216.                             for (IChangeSetLinkSummary summary : changeSetLink) {  
  217.                                 List linkHandles = summary.getLinks();  
  218.                                 for (ILinkHandle linkHandle : linkHandles) {  
  219.                                     ILink link = (ILink) TeamRepository  
  220.                                             .itemManager().fetchCompleteItem(  
  221.                                                     linkHandle,  
  222.                                                     IItemManager.DEFAULT, null);      
  223.                                   
  224.                                     if (CHANGE_SET_TYPE.equals(link.getLinkTypeId()))   
  225.                                     {  
  226.                                         IChangeSetHandle changeSetHandle = (IChangeSetHandle) link.getSourceRef().resolve();  
  227.                                         IChangeSet changeset = (IChangeSet) TeamRepository.itemManager()  
  228.                                                       .fetchCompleteItem(changeSetHandle, IItemManager.DEFAULT,null);                                        
  229.                                         System.out.printf("\t\t%s (%s)\n", changeset.getComment(), changeset.getItemId().getUuidValue());  
  230.                                           
  231.                                         List links = ChangeSetLinks  
  232.                                                 .findLinks(  
  233.                                                         (ProviderFactory) TeamRepository  
  234.                                                                 .getClientLibrary(ProviderFactory.class),  
  235.                                                         changeSetHandle,  
  236.                                                         new String[] { ILinkConstants.CHANGESET_WORKITEM_LINKTYPE_ID },  
  237.                                                         MyProgressMonitor);  
  238.                                         for (final ILink lk : links) {  
  239.                                             final Object resolved = lk  
  240.                                                     .getTargetRef().resolve();  
  241.                                             if (resolved instanceof IWorkItemHandle) {  
  242.                                                 IWorkItem workItem = (IWorkItem) TeamRepository  
  243.                                                         .itemManager()  
  244.                                                         .fetchCompleteItem(  
  245.                                                                 (IWorkItemHandle)resolved,  
  246.                                                                 IItemManager.DEFAULT,  
  247.                                                                 null);  
  248.                                                 System.out.printf("\t\t\tWorkItemID=%d:%s\n", workItem.getId(), workItem.getHTMLSummary().getPlainText());  
  249.                                             }  
  250.                                         }  
  251.                                     }                     
  252.                                     else  
  253.                                     {  
  254.                                         //System.out.printf("\t\t%s\n", link.getLinkTypeId());  
  255.                                     }  
  256.                                 }  
  257.                             }  
  258.                             System.out.printf("\t========== Change Set End ==========\n");  
  259.                             pbaseLineConnection=baseLineConnection;  
  260.                             preBaselineDate=latestDate;  
  261.                         }  
  262.                          else {  
  263.                              pbaseLineConnection=baseLineConnection;  
  264.                              preBaselineDate=latestDate;  
  265.                          }  
  266.                     }  
  267.                 }  
  268.             }  
  269.         }  
  270.     }  
  271.       
  272.     /** 
  273.      * Login RTC System. 
  274.      * @throws TeamRepositoryException 
  275.      */  
  276.     public static void Login() throws TeamRepositoryException {  
  277.         ITeamRepository teamRepository = TeamPlatform.getTeamRepositoryService().getTeamRepository(repositoryURI);  
  278.         teamRepository.registerLoginHandler(new LoginHandler(userId, password));  
  279.         teamRepository.login(MyProgressMonitor);  
  280.         TeamRepository = teamRepository;  
  281.     }  
  282.   
  283.     /** 
  284.      * Retrieve change set based on given IBuildResult object 
  285.      *  http://www.ibm.com/developerworks/cn/rational/r-cn-rtcbuildwithplainjavaapi/ 
  286.      *  https://github.com/jenkinsci/teamconcert-plugin/blob/master/com.ibm.team.build.hjplugin-rtc/src/test/java/com/ibm/team/build/internal/hjplugin/rtc/tests/BuildConnectionTests.java 
  287.      *  http://stackoverflow.com/questions/24628644/how-to-get-changesetall-files-changes-from-iworkitem-item-by-program 
  288.      *  https://jazz.net/forum/questions/153345/how-to-get-associated-work-items-from-a-change-set-using-rtc-sdk 
  289.      * @param args 
  290.      * @throws Exception 
  291.      */  
  292.     public static void main(String[] args) throws Exception{  
  293.           
  294.         TeamPlatform.startup();  
  295.         try {                         
  296.             Login();  
  297.             Start(BuildDefinitionID);  
  298.         } catch (TeamRepositoryException e) {  
  299.             System.out.println("Unable to login: " + e.getMessage());  
  300.         } finally {  
  301.             TeamPlatform.shutdown();  
  302.         }  
  303.     }  
  304. }  
Supplement 
通过 Plain Java API 增强 Rational Team Concert 的自动化构建 
Stackoverflow - How to get ChangeSet(All files cha...from IWorkItem item by Program 
Jazz forum - How to get Associated Work Items from a Change Set using RTC SDK?

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...