Downloading Attachments from Work Items


I published how to upload attachments to work items some time ago. The missing piece was how to download them. I was able to figure that out now and want to share it.

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.

To keep it simple this example is, as many others in this blog, based on the Jazz Team Wiki entry on Programmatic Work Item Creation and the Plain Java Client Library Snippets. The example in this blog shows RTC Client and Common API.

Download the code here

Solution Overview

The example below is based on the wiki entry on Programmatic Work Item Creation. I basically use the main() and run() operation for the parameter handling. The code below is inserted at the end of the run() operation. The WorkItemOperation part is not used in this case.

The code below shows how to get to the attachments resolving the work item references and using the endpoint to narrow down to the attachments. See the post about manipulation references using the Plain Java Client Library for more details on references.

Once the IAttachment is resolved it is passed to the saveAttachment() method which does the download and saving part.

IWorkItem workItem = workItemClient.findWorkItemById(id, IWorkItem.FULL_PROFILE, null);

IWorkItemCommon common = (IWorkItemCommon) teamRepository.getClientLibrary(IWorkItemCommon.class);
IWorkItemReferences workitemReferences = common.resolveWorkItemReferences(workItem, null);
List references = workitemReferences.getReferences(WorkItemEndPoints.ATTACHMENT);
for (IReference iReference : references) {
	IAttachmentHandle attachHandle = (IAttachmentHandle) iReference.resolve();
	IAuditableClient auditableClient = (IAuditableClient) teamRepository.getClientLibrary(IAuditableClient.class);
	IAttachment attachment = (IAttachment) auditableClient.resolveAuditable((IAttachmentHandle) attachHandle,
		IAttachment.DEFAULT_PROFILE, null);
	saveAttachment(teamRepository, attachment);
}

The saveAttachment() method basically creates a new file with the name stored in the attachment and uses the ITeamRepository.contentManager() to get the content into the file. The code below uses the file name stored in the attachment for simplicity, but you can provide a different name and location.

/**
 * Save the attachment
 */
public static void saveAttachment(ITeamRepository teamRepository,IAttachment attachment) throws TeamRepositoryException {
	try {
		File save = new File(attachment.getName());

		OutputStream out = new FileOutputStream(save);
		try {
			teamRepository.contentManager().retrieveContent(attachment.getContent(), out, null);
		} finally {
			out.close();
		}
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
	} catch (IOException e) {
		// TODO Auto-generated catch block
	}
}

As usual the exception handling is very basic and you might want to improve that if using this code. I hope this is helpful and saves some cycles searching through the RTC SDK.

31 thoughts on “Downloading Attachments from Work Items

    • I have not tried, but I would assume it does. The Wiki entry for this is based upon is from 2.x, I think.

      Worth trying anyway. Make sure to use the RTC 2.x Plain Java Client Libraries.

  1. I am using the REST API and OSLC via simple HTTP calls from Delphi to get data out of RTC. I am having trouble getting user photos due to the below error. This should be easier than getting attachments and I can get it to work on normal web sites. Can that extra security be turned off or can I pass something with the http command to make it work?

    “You have followed a direct link to content hosted in a Jazz server. This page has been presented to ensure that a malicious website cannot use cleverly crafted content to circumvent security. If you would like to access the content, please use the link below. “

  2. We are having Rational Jazz RTC tool 5.0 version, we would like to download all the attachment related to multiple CSR(100+), could you please mentioned , how we can achieve
    this?

    • You can run an expression or query, iterate all the work items and download the attachments. The work item commandline has code for that alreadystoring the attachments for eac work item in a sub folder.

      • with help of query we are able to download all comments related to SIR, but how we export attachment using QUERY, our requirement is export all attachment out of DB and save it future reference and clean up everything from DB so that it can be use again for new project.

      • There is no built in capability to mass export attachments. You have to create your own code based on my examples or try to use my work item command line from this blog. It should support exporting attachments:

        The command look similar to

        wcl -exportworkitems /ignoreErrors repository=”https://repository:port/ccm” user=user password=userpassword projectArea=”project area name” exportFile=”C:\aaTemp\Export\Test.csv” query=”All” columns=”workItemType,summary,Attachments”

        where the query named All selects all work items to export.

  3. I have rational Team Concert on my machine, to write the command for exporting the document which tool or eclipse tool do i need to use?Or i can use Ration team concert tool.

    • This blog is for people that want to help themselves and want to enable themselves.
      the answer to your question is written in the blog:

      “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.”

      Note there is a link to a blog in the section

      • Thanks For the info, I really appreciate your help.
        Have one more question is there anyway in RTC tool by which we can access DB and run the SQL directly into it?

      • If you want to do that, you will have to create your own application. This is generally discouraged as the database schema is not provided as stable and supported interface. The tool also uses EMF, so you might not find access easy. Writing should only be done using a supported API or the application itself.

    • The Path is your choice in the code or during runtime.

      I am not sure if you have read the article you comment on. I don’t see your question as being relevant in this context.

  4. Hi,
    teamRepository.contentManager().retrieveContent(content, out, null)

    is extremly slow. Is there a way to accelerate the process?

    Kind Regards,

      • Hi,

        Im going through a foreach of WorkItems.
        Then with the example shown here, im downloading the attachments and writing them into the file system. Its taking 3 minutes to retrieve the content of the files.

        My files are around 800mb.
        Isnt there any faster way to do this?

        I tried to do this:

        int bufferSize = 8 * 1024;

        OutputStream out = new BufferedOutputStream(new FileOutputStream(filePath.toFile()), bufferSize);

        but his doesnt have any effect.

        Can I write the files into database? Would this be a faster approach?
        Would it be enough to save the attachment.getContent as BLOB into database?

        Kind Regards,

      • I have exactly what you have – the SDK and Eclipse. I have provided what the Eclipse client uses to do this. That is all I have. If you need more, you will have to search the SDK yourself.

  5. Hi

    I am new to this forum. I am looking for an option to download the attachment from particular work item using work item command line. I am successfully able to create work item and add attachment using WCL. But I couldn’t find the option for downloading an attachment using WCL. Could you please let me know whether it is feasible to download the attachment from one work item using WCL and if possible how to achieve it.

    • Currently only -exportworkitems supports exporting a work item attachment. You would have to provide a query that returns that one work item. It would be possible to create a command that just gets the data for one work item, but none has provided this yet.

    • When I have tried getting the below error,

      Command:
      wcl -exportworkitems /ignoreErrors projectArea=”value” repository=”https://localhost/ccm” user=”username” password=”xxxxxx” exportFile=”path\Test.csv” query=”All” columns=”workItemType,summary,Attachments”

      Error:
      WARNING: Going to buffer response body of large or unknown size. Using getRespon
      seBodyAsStream instead is recommended.
      Exception creating output writer!
      Failed!

  6. Hi,rsjazz!
    I have a question here.How can I transmit parameters such as repositoryURI, projectAreaName and so on via these codes and how can these codes run at our own projects?Which method is the entrance?Can you make an example?Thanks very much.

    private static boolean run(String[] args) throws TeamRepositoryException {

    if (args.length != 5) {
    System.out
    .println(“Usage: ModifyWorkItem “);
    return false;
    }

    String repositoryURI = args[0];
    String userId = args[1];
    String password = args[2];
    String projectAreaName = args[3];
    String idString = args[4];

    ITeamRepository teamRepository = TeamPlatform
    .getTeamRepositoryService().getTeamRepository(repositoryURI);
    teamRepository.registerLoginHandler(new LoginHandler(userId, password));
    teamRepository.login(null);

    IProcessClientService processClient = (IProcessClientService) teamRepository
    .getClientLibrary(IProcessClientService.class);
    IWorkItemClient workItemClient = (IWorkItemClient) teamRepository
    .getClientLibrary(IWorkItemClient.class);

    URI uri = URI.create(projectAreaName.replaceAll(” “, “%20”));
    IProjectArea projectArea = (IProjectArea) processClient
    .findProcessArea(uri, null, null);

    • Sorry to hear. If you have anything specific that can be answered, let me know.

      Where to download and other important information for new users can be found in this blog post in the section “License and how to get started with the RTC API’S” and links to a getting started blog that links to the other relevant information. I always do that in all my API related posts.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.