It's all about the answers!

Ask a question

AssertionFailedException problem with getting the values of attributes


0
1
Robert Siara (821014) | asked Nov 23 '12, 4:34 p.m.
edited Nov 23 '12, 6:56 p.m.
I have a problem with getting the values of attributes ​​(built in and custom).

I use this code to get the built-in attributes and their values.

List<IAttributeHandle> builtInAttributeHandles = service.findBuiltInAttributes(projectArea, monitor);
IFetchResult builtIn = repository.itemManager().fetchCompleteItemsPermissionAware(builtInAttributeHandles,IItemManager.REFRESH, monitor);
for (Iterator it = builtIn.getRetrievedItems().iterator(); it.hasNext();) {
com.ibm.team.workitem.common.model.IAttributeHandle handle = (IAttributeHandle) it.next();
com.ibm.team.workitem.common.model.IAttribute attribute = (IAttribute) repository.itemManager().fetchCompleteItem(handle, IItemManager.DEFAULT,new NullProgressMonitor());
System.out.println("  Built In Attribute: "+ attribute.getDisplayName());
System.out.println(" Type: " + attribute.getAttributeType());
try {
     System.out.println("  Value "+ resolved.getItem().getValue(attribute));
    } catch (AssertionFailedException e) {
     System.out.println(e.toString());
     }
 }

But i always get AssertionFailedException ( i know that i need use different method for enumeration but even for other atributtes i get this exception)



This code I use for enumeration (borrowed from this forum)
 System.out.println(" type"+"="+attribute.getAttributeType());
 System.out.println(" value"+"="+item.getValue(attribute));
 IEnumeration<ILiteral> enumeration = (IEnumeration<ILiteral>)workItemClient.resolveEnumeration(attribute, null);
 IAuditableClient iac = (IAuditableClient) repository.getClientLibrary(IAuditableClient.class);
 if(enumeration!=null){
 IAuditableClient auditableClient = (IAuditableClient )repository.getClientLibrary(IAuditableClient.class);
 String[] iaval = attribute.getValue(auditableClient, item, null).toString().split(":");
 if(iaval.length>1 && iaval[1]!=null){                                                       
 List<ILiteral> enumerationLiterals = enumeration.getEnumerationLiterals();
 for (ILiteral literal : enumerationLiterals){
 if(literal.getIdentifier2().getStringIdentifier().equalsIgnoreCase(iaval[1])){
 System.out.println("attribute name="+attribute.getIdentifier() +", type"+"="+attribute.getAttributeType()+" literal="+literal.getIdentifier2().getStringIdentifier()+" literal name="+literal.getName());                                       
  break;
 }
 }
 }
 }

I will be very grateful for help

edit:
Also i have problem with format code in this post, I do not know that anyone will want to read it :/

Accepted answer


permanent link
sam detweiler (12.5k6195201) | answered Nov 24 '12, 9:35 a.m.
edited Jul 14 '14, 5:30 p.m.
I modified one of my clients, this will list all the attributes for each workitem in a project
it does not completely resolve all values

| edit Dec 30,2013, add function to list references, and attachment details.
| using Ralph's Blog content
| edit July 14, 2014, add function to use the password decryption support.
| see the second answer here https://jazz.net/forum/questions/156705/is-there-support-for-password-files-in-the-plain-java-client-api
| for info on encrypting the password

for example
=======
5 Define team members
            processing for variable=Archived attrib type=boolean kind=
                attribute name=archived, type=boolean value=false
            processing for variable=Filed Against attrib type=category kind=
                attribute name=category, type=category value=com.ibm.team.workitem.common.internal.model.impl.CategoryHandleImpl@24c22b (stateId: [UUID _IvGqIDRPEeKg4Lm936jbng], itemId: [UUID _IvAjgjRPEeKg4Lm936jbng], origin: com.ibm.team.repository.client.internal.TeamRepository@3aef16, immutable: true)
            processing for variable=Restricted Access attrib type=uuid kind=
                attribute name=contextId, type=uuid value=[UUID _GX9MkDRPEeK9D7Bj0AW-VQ]
            processing for variable=Corrected Estimate attrib type=duration kind=
                attribute name=correctedEstimate, type=duration value=-1
            processing for variable=Creation Date attrib type=timestamp kind=
                attribute name=creationDate, type=timestamp value=2012-11-21 20:48:55.826
======

this executes a query in the project to get the list of workitems. (this was built to test performance

package xxxxxxxxxxxxxx;

/*******************************************************************************
 * Licensed Materials - Property of IBM
 * (c) Copyright IBM Corporation 2008. All Rights Reserved.
 *
 * Note to U.S. Government Users Restricted Rights:  Use, duplication or
 * disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
 *******************************************************************************/

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.eclipse.core.runtime.IProgressMonitor;

import com.ibm.team.apt.common.IIterationPlanRecord;
import com.ibm.team.apt.common.IIterationPlanRecordHandle;
import com.ibm.team.apt.internal.client.IIterationPlanClient;
import com.ibm.team.apt.internal.client.IterationPlanClient;
import com.ibm.team.build.common.model.IBuildResultHandle;
import com.ibm.team.links.common.IItemReference;
import com.ibm.team.links.common.IReference;
import com.ibm.team.links.common.factory.IReferenceFactory;
import com.ibm.team.links.common.registry.IEndPointDescriptor;
import com.ibm.team.links.common.registry.ILinkTypeRegistry;
import com.ibm.team.process.client.IProcessClientService;
import com.ibm.team.process.common.IDevelopmentLine;
import com.ibm.team.process.common.IDevelopmentLineHandle;
import com.ibm.team.process.common.IIterationHandle;
import com.ibm.team.process.common.IProjectArea;
import com.ibm.team.repository.client.IContentManager;
import com.ibm.team.repository.client.IItemManager;
import com.ibm.team.repository.client.ITeamRepository;
import com.ibm.team.repository.client.ITeamRepository.ILoginHandler;
import com.ibm.team.repository.client.ITeamRepository.ILoginHandler.ILoginInfo;
import com.ibm.team.repository.client.TeamPlatform;
import com.ibm.team.repository.common.IAuditable;
import com.ibm.team.repository.common.IAuditableHandle;
import com.ibm.team.repository.common.IContent;
import com.ibm.team.repository.common.IContributor;
import com.ibm.team.repository.common.Location;
import com.ibm.team.repository.common.TeamRepositoryException;
import com.ibm.team.repository.common.util.ObfuscationHelper;
import com.ibm.team.workitem.client.IAuditableClient;
import com.ibm.team.workitem.client.IQueryClient;
import com.ibm.team.workitem.client.IWorkItemClient;
import com.ibm.team.workitem.client.WorkItemOperation;
import com.ibm.team.workitem.client.WorkItemWorkingCopy;
import com.ibm.team.workitem.common.IWorkItemCommon;
import com.ibm.team.workitem.common.internal.WorkItemCommon;
import com.ibm.team.workitem.common.model.IAttachment;
import com.ibm.team.workitem.common.model.IAttachmentHandle;
import com.ibm.team.workitem.common.model.IAttribute;
import com.ibm.team.workitem.common.model.ICategory;
import com.ibm.team.workitem.common.model.ICategoryHandle;
import com.ibm.team.workitem.common.model.IEnumeration;
import com.ibm.team.workitem.common.model.ILiteral;
import com.ibm.team.workitem.common.model.IWorkItem;
import com.ibm.team.workitem.common.model.WorkItemEndPoints;
import com.ibm.team.workitem.common.model.WorkItemLinkTypes;

import com.ibm.team.workitem.common.model.IWorkItemHandle;
import com.ibm.team.workitem.common.model.IWorkItemReferences;
import com.ibm.team.workitem.common.model.Identifier;
import com.ibm.team.workitem.common.model.ItemProfile;
import com.ibm.team.workitem.common.query.IQueryDescriptor;
import com.ibm.team.workitem.common.query.IQueryResult;
import com.ibm.team.workitem.common.query.IResolvedResult;
import com.ibm.team.workitem.common.query.IResult;
import com.ibm.team.workitem.common.query.QueryTypes;
import com.ibm.team.workitem.common.query.ResultSize;

/**
 * Example code, see
 * https://jazz.net/wiki/bin/view/Main/ProgrammaticWorkItemCreation.
 */
public class RunQuery
{
    /*
     * public class SysoutProgressMonitor implements IProgressMonitor {
     *
     * public void beginTask(String name, int totalWork) { //print(name); }
     *
     * public void done() { }
     *
     * public void internalWorked(double work) { }
     *
     * public boolean isCanceled() { return false; }
     *
     * public void setCanceled(boolean value) { }
     *
     * public void setTaskName(String name) { print(name); }
     *
     * public void subTask(String name) { print(name); }
     *
     * public void worked(int work) { }
     *
     * private void print(String name) { //if(name != null && ! "".equals(name))
     * // System.out.println(name); } }
     */
    private static boolean debug = false;
    static IContentManager icm = null;

    private static class LoginHandler implements ILoginHandler, ILoginInfo
    {

        private String fUserId;
        private String fPassword;

        private LoginHandler(String userId, String password)
        {
            fUserId = userId;
            fPassword = password;
        }

        public String getUserId()
        {
            return fUserId;
        }

        public String getPassword()
        {
            return fPassword;
        }

        public ILoginInfo challenge(ITeamRepository repository)
        {
            return this;
        }
    }

    public static void main(String[] args)
    {

        boolean result;
        if (debug)
            System.out.println("starting up\n");
        TeamPlatform.startup();
        if (debug)
            System.out.println("platform started\n");

        try
        {
            result = run(args);
        }
        catch (Exception x)
        {
            x.printStackTrace();
            result = false;
        }
        finally
        {
            TeamPlatform.shutdown();
        }

        if (!result)
            System.exit(1);
    }

    private static boolean run(String[] args) throws TeamRepositoryException
    {
        final class mylog implements org.eclipse.core.runtime.IProgressMonitor
        {

            public void beginTask(String arg0, int arg1)
            {
                // TODO Auto-generated method stub

            }

            public void done()
            {
                // TODO Auto-generated method stub

            }

            public void internalWorked(double arg0)
            {
                // TODO Auto-generated method stub

            }

            public boolean isCanceled()
            {
                // TODO Auto-generated method stub
                return false;
            }

            public void setCanceled(boolean arg0)
            {
                // TODO Auto-generated method stub

            }

            public void setTaskName(String arg0)
            {
                // TODO Auto-generated method stub

            }

            public void subTask(String arg0)
            {
                // TODO Auto-generated method stub

            }

            public void worked(int arg0)
            {
                // TODO Auto-generated method stub

            }

        }

        mylog mine = new mylog();

        if (debug)
            System.out.println("run started\n");
        if (args.length != 5)
        {
            System.out
                    .println("Usage: QueryWorkItems <repositoryURI> <userId> <password> <projectArea> <queryname>");
            return false;
        }

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

        ITeamRepository teamRepository = TeamPlatform
                .getTeamRepositoryService().getTeamRepository(repositoryURI);
        if (debug)
            System.out.println("logging in\n");
        try
        {
            // decrypt the user password, if encrypted
            password = ObfuscationHelper.decryptString(password);
        }
        catch(Exception ex)
        {
            // nothin to do, variable not overlayed on error
        }
        teamRepository.registerLoginHandler(new LoginHandler(userId, password));

        teamRepository.login(null);

        if (debug)
            System.out.println("logged in\n");
        icm = teamRepository.contentManager();
        IProcessClientService processClient = (IProcessClientService) teamRepository
                .getClientLibrary(IProcessClientService.class);

        IAuditableClient auditableClient = (IAuditableClient) teamRepository
                .getClientLibrary(IAuditableClient.class);

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

        IIterationPlanClient planClient = (IIterationPlanClient) teamRepository
                .getClientLibrary(IIterationPlanClient.class);

        URI uri = URI.create(projectAreaName.replaceAll(" ", "%20"));

        IProjectArea iprja = (IProjectArea) processClient.findProcessArea(uri, null, null);

        if (iprja == null)
        {
            System.out.println("Project area not found.");
            return false;
        }

        //long start = System.currentTimeMillis();
        IDevelopmentLineHandle[] dlh = iprja.getDevelopmentLines();
        IDevelopmentLine dl = (IDevelopmentLine) auditableClient
                .fetchCurrentAuditable(dlh[0], ItemProfile
                        .createFullProfile(IDevelopmentLine.ITEM_TYPE), null);

        IIterationHandle cih = dl.getCurrentIteration();

        List<IIterationPlanRecordHandle> phandles = ((IterationPlanClient) planClient)
                .fetchAllIterationPlans(ItemProfile.ITERATION_DEFAULT, null);
        List<IAuditable> itall = auditableClient.fetchCurrentAuditables(
                phandles,
                ItemProfile.createFullProfile(IIterationPlanRecord.ITEM_TYPE),
                null);
        System.out.println(" there are " + phandles.size()
                + " plans available and " + itall.size() + " records");

        /*
         * int i; for (i = itall.size() - 1; i >= 0; i--) { IIterationPlanRecord
         * ipr = (IIterationPlanRecord) itall.get(i); IProcessArea ipa =
         * (IProcessArea) auditableClient.resolveAuditable( ipr.getOwner(),
         * ItemProfile .createFullProfile(IProcessArea.ITEM_TYPE), null); // if
         * the plan iteration matches the project timeline current // iteration
         * if (ipr.getIteration().sameItemId(cih)) { // assume the top level
         * team area is the same as the project // name // IProgressInformation
         * iiii = // planClient.fetchPlanProgress(phandles.get(i), null); //
         * ResolvedIterationPlan kkk = //
         * planClient.fetchIterationPlan(phandles.get(i), mine);
         *
         * if (ipa.getName().equalsIgnoreCase(iprja.getName())) { //
         * System.out.println("can save="+kkk.canSavePlan());
         * System.out.println("process name = " + ipa.getName());
         * System.out.println("plan name=" + ipr.getName());
         * System.out.println("\tproject area = " + iprja.getName()); break; } }
         *
         * }
         */
        IContributor loggedIn = teamRepository.loggedInContributor();

        IQueryClient queryClient = workItemClient.getQueryClient();
        String queryType = QueryTypes.WORK_ITEM_QUERY;
        ItemProfile<IQueryDescriptor> profile = IQueryDescriptor.FULL_PROFILE;
        IQueryDescriptor queryToRun = null;
        List<IQueryDescriptor> personalQueries = null;

        personalQueries = queryClient.findPersonalQueries(
                iprja.getProjectArea(), loggedIn, queryType, profile, null);
        for (Iterator<IQueryDescriptor> iterator = personalQueries.iterator(); iterator
                .hasNext();)
        {
            IQueryDescriptor iQueryDescriptor = iterator.next();
            if (iQueryDescriptor.getName().equals(queryName))
            {
                queryToRun = iQueryDescriptor;
                break;
            }
        }
        if (null == queryToRun)
        {
            // If we know which team they are shared with
            List<IAuditableHandle> sharingTargets = new ArrayList<IAuditableHandle>();
            List<IQueryDescriptor> sharedQueries = null;

            sharedQueries = queryClient.findSharedQueries(
                    iprja.getProjectArea(), sharingTargets,
                    QueryTypes.WORK_ITEM_QUERY, IQueryDescriptor.FULL_PROFILE,
                    null);

            for (Iterator<IQueryDescriptor> iterator = sharedQueries.iterator(); iterator
                    .hasNext();)
            {
                IQueryDescriptor iQueryDescriptor = iterator.next();
                if (iQueryDescriptor.getName().equals(queryName))
                {
                    queryToRun = iQueryDescriptor;
                    break;
                }
            }
        }
        if (null == queryToRun)
        {
            System.out.println("Query not found: [" + queryName + "].");
            return false;
        }
        // printUnresolved(auditableClient, queryClient, queryToRun);

        printResolved(queryClient, queryToRun, iprja, auditableClient, mine,
                teamRepository);

        //long stop = System.currentTimeMillis();

        // System.out.println(" elapsed =" + (stop - start));

        teamRepository.logout();

        return true;
    }

    private static void printUnresolved(IAuditableClient auditableClient,
            IQueryClient queryClient, IQueryDescriptor queryToRun,
            ITeamRepository teamRepository) throws TeamRepositoryException
    {
        IQueryResult<IResult> results = queryClient.getQueryResults(queryToRun);

        ((IQueryResult<IResult>) results).setLimit(Integer.MAX_VALUE);
        int count = 0;
        while (results.hasNext(null))
        {
            count++;
            IResult result = results.next(null);
            IWorkItem workItem = (IWorkItem) auditableClient.resolveAuditable(
                    (IAuditableHandle) result.getItem(),
                    IWorkItem.FULL_PROFILE, null);
            int id = workItem.getId();
            String summary = workItem.getHTMLSummary().toString();
            System.out.println("\t" + count + "\t" + id + " " + summary);
        }
        System.out.println("Results:" + count);
    }

    private static void printResolved(IQueryClient queryClient,
            IQueryDescriptor queryToRun, IProjectArea pa,
            IAuditableClient auditableClient,
            IProgressMonitor mine,
            ITeamRepository teamRepository) throws TeamRepositoryException
    {
        // get the xml source for the project, in case there is a multi-select
        // stored in a string field
        IContent pxml = (IContent) pa.getProcessData().get(
                "com.ibm.team.internal.process.compiled.xml");
        String XML = getXMLSource(pa, pxml, icm, mine);

        IQueryResult<IResolvedResult<IWorkItem>> resolvedResults = queryClient
                .getResolvedQueryResults(queryToRun, IWorkItem.FULL_PROFILE);
        resolvedResults.setLimit(Integer.MAX_VALUE - 1); // First thing to do!!!!!!

        ResultSize rSize = resolvedResults.getResultSize(null);
        int total = rSize.getTotal();
        int estimatedTotal = rSize.getEstimatedTotal();
        int totalAvailable = rSize.getTotalAvailable();
        boolean isAccurate = rSize.isAccurate();
        boolean isInitialized = rSize.isInitialized();
        System.out.println("Query result initialized: " + isInitialized
                + " accurate: " + isAccurate + " estimated: " + estimatedTotal
                + " available: " + totalAvailable + " total: " + total);

        int count = 0;
        while (resolvedResults.hasNext(null))
        {
            IResolvedResult<IWorkItem> result = resolvedResults.next(null);
            IWorkItem workItem = result.getItem();
            if (workItem != null)
            {
                count++;
                int id = workItem.getId();
                String summary = workItem.getHTMLSummary().toString();
                System.out.println("\t" + count + "\t" + id + " " + summary);

                printAttributes(workItem, auditableClient, pa, mine,
                        teamRepository, XML);
            }
        }
    }

    @SuppressWarnings("unchecked")
    static void printAttributes(IWorkItem workItem,
            IAuditableClient auditableClient, IProjectArea projectArea,
            IProgressMonitor monitor,
            ITeamRepository repository, String XML)
            throws TeamRepositoryException
    {

        IWorkItemCommon workItemCommon = (IWorkItemCommon) repository
                .getClientLibrary(IWorkItemCommon.class);

        // List<IAttributeHandle> wi_attribs = workItem.getCustomAttributes();
        IAttribute ii = workItemCommon.findAttribute(projectArea,
                "internalComments", monitor);
        if (ii == null)
        {
            System.out.println("unable to find comments in projectarea="
                    + projectArea.getName());
            return;
        }

        try
        {
            // loop thru all the workitem attributes
            for (IAttribute ia : workItemCommon.findAttributes(projectArea,
                    monitor))
            {

                // if this workitem has this attribute and
                // its nOT an internal use attribute
                if (workItem.hasAttribute(ia) && !ia.isInternal())
                {
                    // say we are going to dump it
                    System.out.println("\t\t\tprocessing for variable="
                            + ia.getDisplayName() + " attrib type="
                            + ia.getAttributeType() + " kind="
                            + ia.getFullTextKind()
                            + (ia.isBuiltIn() ? " " : " custom attribute"));

                    try
                    {
                        // if this is a category attribute
                        if (ia.getAttributeType().equals("category"))
                        {
                            // get the handle
                            ICategoryHandle ich = (ICategoryHandle) (ia
                                    .getValue(auditableClient, workItem, null));
                            // and its full value
                            ICategory ic = (ICategory) repository.itemManager()
                                    .fetchCompleteItem(ich,
                                            IItemManager.REFRESH, monitor); // .fetchCompleteItem(ich,
                                                                            // IItemManager.DEFAULT,
                                                                            // null);
                            System.out.println("\t\t\t\tCategory name="
                                    + ic.getName());
                        }
                        else if (ia.getAttributeType().toString()
                                .startsWith("enumerationList"))
                        {
                            List<ILiteral> enumerationLiterals = (List<ILiteral>) workItemCommon
                                    .resolveEnumeration(ia, monitor)
                                    .getEnumerationLiterals();
                            System.out
                                    .println("\t\t\t\thave an enumeration list (V4 and up)");
                            List<Identifier> ial = (List<Identifier>) ia
                                    .getValue(auditableClient, workItem,
                                            monitor);
                            System.out.println("\t\t\t\t there are "
                                    + ial.size() + " entries selected");
                            for (int r = 0; r < ial.size(); r++)
                            {
                                for (ILiteral literal : enumerationLiterals)
                                {
                                    if (literal
                                            .getIdentifier2()
                                            .getStringIdentifier()
                                            .equalsIgnoreCase(
                                                    ial.get(r)
                                                            .getStringIdentifier()))
                                    {
                                        System.out.println("\t\t\t\t entry "
                                                + (r + 1)
                                                + " --> "
                                                + " literal="
                                                + literal.getIdentifier2()
                                                        .getStringIdentifier()
                                                + " literal value="
                                                + literal.getName());
                                        break;
                                    }
                                }
                            }
                        }
                        else
                        {
                            // this will throw exception if not enumeration
                            IEnumeration<ILiteral> enumeration = (IEnumeration<ILiteral>) workItemCommon
                                    .resolveEnumeration(ia, monitor);
                            if (enumeration != null)
                            {
                                String[] iaval = ia
                                        .getValue(auditableClient, workItem,
                                                monitor).toString().split(":");
                                if (iaval.length > 1 && iaval[1] != null)
                                {
                                    List<ILiteral> enumerationLiterals = enumeration
                                            .getEnumerationLiterals();
                                    for (ILiteral literal : enumerationLiterals)
                                    {
                                        if (literal.getIdentifier2()
                                                .getStringIdentifier()
                                                .equalsIgnoreCase(iaval[1]))
                                        {
                                            System.out
                                                    .println("\t\t\t\t --> attribute id="
                                                            + ia.getIdentifier()
                                                            + ", type"
                                                            + "="
                                                            + ia.getAttributeType()
                                                            + " literal="
                                                            + literal
                                                                    .getIdentifier2()
                                                                    .getStringIdentifier()
                                                            + " literal name="
                                                            + literal.getName());
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        System.out.println("\t\t\t\tattribute id="
                                + ia.getIdentifier()
                                + ", type"
                                + "="
                                + ia.getAttributeType()
                                + " value="
                                + ia.getValue(auditableClient, workItem,
                                        monitor));
                        if (ia.getAttributeType().toString().toLowerCase()
                                .endsWith("string"))
                        {
                            // if this is a string type, it MIGHT be
                            // multi-select
                            // so, find the attribute definition in the project
                            // area
                            // then check to see if there is a related
                            // enumeration,
                            // if not its just a string.. bummer

                            // try to find the attribute in the presentation
                            // definition as a list type
                            // data looks like this, numbers for reference
                            // 1 <presentation attributeId="field name"
                            // kind="com.ibm.team.workitem.kind.list">
                            // 2 <property key="enumeration"
                            // value="enumeration name"/>
                            // 3 </presentation>
                            String typeString = "<presentation attributeId=\""
                                    + ia.getIdentifier()
                                    + "\" kind=\"com.ibm.team.workitem.kind.list\">";
                            String endString = "</presentation>";
                            // find the xml string that starts the presentation
                            // definition for this field
                            // could use xpath, but this is faster
                            // find line 1 if it exists
                            int typeIndex = XML.indexOf(typeString);
                            // if we found the string type as a list
                            if (typeIndex >= 0)
                            {
                                System.out
                                        .println("\t\t\t\t have an enumeration list (V3)");
                                // parse the defined enum
                                // get the xml offset of the end of line 1
                                // we don't need this data anymore
                                int fieldOffset = typeIndex
                                        + typeString.length();
                                // use substring to extract just line 2
                                // use split to get the quoted enum name
                                String[] result = XML.substring(fieldOffset,
                                        XML.indexOf(endString, fieldOffset))
                                        .split("\"");
                                // report what we found
                                System.out.println("\t\t\t\t enumeration="
                                        + result[result.length - 2]);
                                // get the Enum object from its name
                                IEnumeration enumeration = (IEnumeration) ((WorkItemCommon) workItemCommon)
                                        .internalResolveEnumeration(
                                                projectArea,
                                                result[result.length - 2],
                                                monitor);
                                // get the data literals (selected values) from
                                // the field, comma separated
                                String[] Literals = workItem.getValue(ia)
                                        .toString().split(",");
                                // loop thru the selected value literals
                                if (Literals[0].length() > 0)
                                    System.out.println("\t\t\t\t there are "
                                            + Literals.length
                                            + " entries selected");
                                else
                                    System.out.println("\t\t\t\t there are "
                                            + 0 + " entries selected");
                                for (int r = 0; r < Literals.length; r++)
                                // for(String literal: Literals)
                                {
                                    String literal = Literals[r];
                                    if (literal.length() > 0)
                                    {
                                        // print out the literal name and the
                                        // human readable value
                                        System.out
                                                .println("\t\t\t\t entry "
                                                        + (r + 1)
                                                        + " --> "
                                                        + " literal="
                                                        + literal
                                                        + " literal value="
                                                        + enumeration
                                                                .findEnumerationLiteral(
                                                                        Identifier
                                                                                .create(ILiteral.class,
                                                                                        literal))
                                                                .getName());
                                    }
                                }
                            }
                        }
                    }
                }
            }
            // handle all the workitem references/links/attachments
            analyzeReferences(workItemCommon.resolveWorkItemReferences(
                    workItem, null));
            System.out.println(" ");
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            System.out.println("outer Exception=" + e.toString());
        }
    }

    private static void analyzeReferences(IWorkItemReferences iReferences)
    {
        List<IEndPointDescriptor> endpoints = iReferences.getTypes();
        for (IEndPointDescriptor iEndPointDescriptor : endpoints)
        {
            System.out.println("Endpoint type: "
                    + iEndPointDescriptor.getDisplayName() + " ID: "
                    + iEndPointDescriptor.getLinkType().getLinkTypeId());
            List<IReference> typedReferences = iReferences
                    .getReferences(iEndPointDescriptor);
            for (IReference iReference : typedReferences)
            {
                analyzeReference(iReference);
            }
        }
    }

    /**
     * Analyze a reference
     */
    public static void analyzeReference(IReference iReference)
    {
        if (iReference.isItemReference())
        {
            Object resolvedRef = iReference.resolve();
            analyzeItem(resolvedRef);
        }
        if (iReference.isURIReference())
        {
            analyzeReferenceTarget(iReference);
        }
    }

    /**
     * Analyze an Item
     */
    private static void analyzeItem(Object resolvedRef)
    {
        // System.out.println(" Resolved item: "
        // + resolvedRef.toString());
        if (resolvedRef instanceof IWorkItemHandle)
        {
            IWorkItemHandle handle = (IWorkItemHandle) resolvedRef;
            analyzeresolvedWorkitem(handle);
        }
        if (resolvedRef instanceof IBuildResultHandle)
        {
            System.out.println(" Resolved attachment: "
                    + resolvedRef.toString());
            IBuildResultHandle handle = (IBuildResultHandle) resolvedRef;
        }
        if (resolvedRef instanceof IAttachmentHandle)
        {

            IAttachmentHandle handle = (IAttachmentHandle) resolvedRef;
            analyzeresolvedAttachment(handle);
        }
    }

    /**
     * Further analyze an item referenced by an URI
     *
     * @param iReference
     */
    public static void analyzeReferenceTarget(IReference iReference)
    {
        URI uri = iReference.createURI();
        try
        {
            System.out.println("   Resolving URI: " + uri.toString());
            ITeamRepository teamRepo = (ITeamRepository) iReference.getLink()
                    .getOrigin();
            IAuditableClient auditableClient = (IAuditableClient) teamRepo
                    .getClientLibrary(IAuditableClient.class);

            // get the location from the URI
            Location location = Location.location(uri);
            // resolve the item by location
            if (location.getItemType() != null)
            {
                IAuditable referenced = auditableClient
                        .resolveAuditableByLocation(location, ItemProfile
                                .createFullProfile(location.getItemType()),
                                null);
                // look for a referenced work item
                if (referenced != null && referenced instanceof IWorkItem)
                {
                    IWorkItem referencedWI = (IWorkItem) referenced;
                    System.out.println("   Resolved URI (resolve): "
                            + uri.toString() + " to: " + referencedWI.getId()
                            + " " + referencedWI.getState2().toString());
                }
            }
            else
                System.out.println("   Resolved URI "
                        + uri.toString() + "\n\t\t\t comment="+iReference.getComment());
            //System.out.println("   Resolved URI: " + uri.toString());
        }
        catch (TeamRepositoryException e)
        {
            e.printStackTrace();
        }

    }

    private static void analyzeresolvedAttachment(IAttachmentHandle athandle)
    {
        // ITeamRepository teamRepo = (ITeamRepository) handle.getOrigin();
        IAuditableClient auditableClient = (IAuditableClient) ((ITeamRepository) athandle
                .getOrigin()).getClientLibrary(IAuditableClient.class);
        try
        {
            IAttachment iattachment = (IAttachment) auditableClient
                    .fetchCurrentAuditable(athandle, ItemProfile
                            .createFullProfile(IAttachment.ITEM_TYPE), null);
            System.out.println(" Resolved item: ID=" + iattachment.getId()
                    + " name=" + iattachment.getName() + " description="
                    + iattachment.getDescription() + " size="
                    + iattachment.getContent().getEstimatedConvertedLength());
           
            if(debug==true)
            {
                // make an output stream for the content manager
                OutputStream os = new ByteArrayOutputStream();
                // get the content manager service
                IContentManager icm=((ITeamRepository) athandle.getOrigin()).contentManager();
                // get the content into the stream
                icm.retrieveContent(iattachment.getContent(), os, null);
                // print the content if text..           
                if(iattachment.getContent().getContentType().startsWith("text"))
                   System.out.println(" content="+os.toString());
            }
        }
        catch (Exception ex)
        {
            System.out.println("exception=" + ex.getMessage());
        }
    }

    private static void analyzeresolvedWorkitem(IWorkItemHandle wihandle)
    {
        // ITeamRepository teamRepo = (ITeamRepository) handle.getOrigin();
        IAuditableClient auditableClient = (IAuditableClient) ((ITeamRepository) wihandle
                .getOrigin()).getClientLibrary(IAuditableClient.class);
        try
        {
            IWorkItem workitem = (IWorkItem) auditableClient
                    .fetchCurrentAuditable(wihandle,
                            ItemProfile.createFullProfile(IWorkItem.ITEM_TYPE),
                            null);
            System.out.println(" Resolved item: ID=" + workitem.getId()
                    + " summary=" + workitem.getHTMLSummary());
        }
        catch (Exception ex)
        {
            System.out.println("exception=" + ex.getMessage());
        }
    }

    private static String getXMLSource(IProjectArea ip, IContent ic,
            IContentManager icm, org.eclipse.core.runtime.IProgressMonitor sPm)
    {
        // make an output stream for the content manager
        OutputStream os = new ByteArrayOutputStream();
        // get the content of the content object.
        try
        {
            icm.retrieveContent(ic, os, sPm);
            return os.toString();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Inner class to do the modification
     *
     */
    private static class WorkItemReferencesModification extends
            WorkItemOperation
    {

        private IWorkItemHandle fOpposite;

        public WorkItemReferencesModification(IWorkItemHandle opposite)
        {
            super("Modifying Work Item References", IWorkItem.FULL_PROFILE);
            fOpposite = opposite;
        }

        @Override
        protected void execute(WorkItemWorkingCopy workingCopy,
                IProgressMonitor monitor) throws TeamRepositoryException
        {
            // Create a new reference to the opposite item
            IItemReference reference = IReferenceFactory.INSTANCE
                    .createReferenceToItem(fOpposite);
            // Create a new end point
            IEndPointDescriptor endpoint = ILinkTypeRegistry.INSTANCE
                    .getLinkType(WorkItemLinkTypes.BLOCKS_WORK_ITEM)
                    .getTargetEndPointDescriptor();
            // Add the new reference using a specific work item end point
            workingCopy.getReferences().add(endpoint, reference);
        }
    }

    /**
     * Inner class to do the modification
     *
     */
    private static class WorkItemReferencesModification2 extends
            WorkItemOperation
    {
        private IWorkItemHandle fOpposite;

        public WorkItemReferencesModification2(IWorkItemHandle opposite)
        {
            super("Modifying Work Item References", IWorkItem.FULL_PROFILE);
            fOpposite = opposite;
        }

        @Override
        protected void execute(WorkItemWorkingCopy workingCopy,
                IProgressMonitor monitor) throws TeamRepositoryException
        {
            // Create a new reference to the opposite item
            IItemReference reference = IReferenceFactory.INSTANCE
                    .createReferenceToItem(fOpposite);
            // Add the new reference using a specific work item end point
            workingCopy.getReferences().add(WorkItemEndPoints.BLOCKS_WORK_ITEM,
                    reference);
        }
    }
}

Robert Siara selected this answer as the correct answer

14 other answers



permanent link
Robert Siara (821014) | answered Nov 26 '12, 8:10 a.m.
edited Nov 26 '12, 9:08 a.m.
I tried to use your function "static void printAttributes()" in my code , but for this line, the compiler returns:
 "The method getPeer(Class<IWorkItemCommon>) from the type IAuditableCommon is deprecated
"
so i tried replace this line to "IWorkItemCommon workItemCommon = (IWorkItemCommon) repository.getClientLibrary(IWorkItemCommon.class);"
but for both solutions i dont get any result:

In addition, I send my code:

public class mRTC2 {

    static String repository_address = "xxxxx";
    static String userId = "xxxx";
    static String password = "xxxx";
    static String projectAreaName = "xxxxxx";

    public static void main(String[] args) throws TeamRepositoryException {

        System.out.println("Main runned");
        TeamPlatform.startup();
        ITeamRepository repository = TeamPlatform.getTeamRepositoryService()
                .getTeamRepository(repository_address);

        repository.registerLoginHandler(new ITeamRepository.ILoginHandler() {
            public ILoginInfo challenge(ITeamRepository repository) {
                return new ILoginInfo() {
                    public String getUserId() {
                        return userId;
                    }

                    public String getPassword() {
                        return password;
                    }
                };
            }
        });

        // IProgressMonitor monitor = new SysoutProgressMonitor();
        IProgressMonitor monitor = null;
        try {
            repository.login(null);
        } catch (TeamRepositoryException e) {
            e.printStackTrace();
        }
        if (repository.getState() == 1) {
            System.out.println("CONNECTED to: " + repository_address);
        }

        // --------------
        IWorkItemClient service = (IWorkItemClient) repository
                .getClientLibrary(IWorkItemClient.class);
        IQueryClient queryClient = (IQueryClient) repository
                .getClientLibrary(IQueryClient.class);
        IProcessClientService processClient = (IProcessClientService) repository
                .getClientLibrary(IProcessClientService.class);
        URI uri = URI.create(projectAreaName.replaceAll(" ", "%20"));
        IProjectArea projectArea = (IProjectArea) processClient
                .findProcessArea(uri, null, null);
        IAuditableClient iac = (IAuditableClient) repository.getClientLibrary(IAuditableClient.class);
       
        // getting workitems
        Term term = new Term(Operator.AND);
        IQueryResult<IResolvedResult<IWorkItem>> result = queryClient
                .getResolvedExpressionResults(projectArea, term,
                        IWorkItem.FULL_PROFILE);

        for (int k = 0; result.hasNext(null); k++) {
            System.out.println("WORKITEM------------------------------------------------");

            IResolvedResult<IWorkItem> resolved = result.next(null);
            //Custom attributes
            WorkItem wi = new WorkItem();
            if (!resolved.getItem().getCustomAttributes().isEmpty()) {
                for (int i = 0; i < resolved.getItem().getCustomAttributes()
                        .size(); i++) {
                    com.ibm.team.workitem.common.model.IAttributeHandle handle = resolved
                            .getItem().getCustomAttributes().get(i);
                    com.ibm.team.workitem.common.model.IAttribute attribute = (IAttribute) repository
                            .itemManager().fetchCompleteItem(handle,
                                    IItemManager.DEFAULT,
                                    new NullProgressMonitor()); //
                    System.out.println("The attribute id: "
                            + attribute.getIdentifier());
                    System.out.println("The attribute name: "
                            + attribute.getDisplayName());
                    System.out.println("The value of the custom attribute: "
                            + resolved.getItem().getValue(attribute));
                            printAttributes(resolved.getItem(), repository, iac, projectArea, monitor);
                    try {
                       
                    } catch (Exception e) {
                        System.out.println("ASSERTION FAILED!!!!");
                    }
                }
            }
            //Builtin attributtes
           
            List<IAttributeHandle> builtInAttributeHandles = service
                    .findBuiltInAttributes(projectArea, monitor);
            IFetchResult builtIn = repository.itemManager()
                    .fetchCompleteItemsPermissionAware(builtInAttributeHandles,
                            IItemManager.REFRESH, monitor);
           
            for (Iterator it = builtIn.getRetrievedItems().iterator(); it
                    .hasNext();) {
                com.ibm.team.workitem.common.model.IAttributeHandle handle = (IAttributeHandle) it
                        .next();
                com.ibm.team.workitem.common.model.IAttribute attribute = (IAttribute) repository
                        .itemManager()
                        .fetchCompleteItem(handle, IItemManager.DEFAULT,
                                new NullProgressMonitor());
                System.out.println("  Built In Attribute: "
                        + attribute.getDisplayName());
                System.out.println(" Type: " + attribute.getAttributeType());
                try {
                    // wi.getAttributeValue(attribute, resolved.getItem());
                    System.out.println("  Value "
                            + resolved.getItem().getValue(attribute));

                } catch (AssertionFailedException e) {
                    System.out.println(e.toString());
                }
            }
           
        }
       
       
    }

    static void printAttributes(IWorkItem workItem,ITeamRepository repository,
            IAuditableClient auditableClient, IProjectArea projectArea,
            org.eclipse.core.runtime.IProgressMonitor monitor) {
       
        IWorkItemCommon workItemCommon = (IWorkItemCommon) repository.getClientLibrary(IWorkItemCommon.class);
       
        try {
            for (IAttribute ia : workItemCommon.findAttributes(projectArea,
                    monitor)) {

                if (workItem.hasAttribute(ia)) {
                    System.out.println("\t\t\tprocessing for variable="
                            + ia.getDisplayName() + " attrib type="
                            + ia.getAttributeType() + " kind="
                            + ia.getFullTextKind());
                    try {
                        // this will throw exception if not enumeration
                        IEnumeration<ILiteral> enumeration = (IEnumeration<ILiteral>) workItemCommon
                                .resolveEnumeration(ia, monitor);
                        if (enumeration != null) {
                            String[] iaval = ia
                                    .getValue(auditableClient, workItem,
                                            monitor).toString().split(":");
                            if (iaval.length > 1 && iaval[1] != null) {
                                List<ILiteral> enumerationLiterals = enumeration
                                        .getEnumerationLiterals();
                                for (ILiteral literal : enumerationLiterals) {
                                    if (literal.getIdentifier2()
                                            .getStringIdentifier()
                                            .equalsIgnoreCase(iaval[1])) {
                                        System.out
                                                .println("\t\t\t\t --> attribute name="
                                                        + ia.getIdentifier()
                                                        + ", type"
                                                        + "="
                                                        + ia.getAttributeType()
                                                        + " literal="
                                                        + literal
                                                                .getIdentifier2()
                                                                .getStringIdentifier()
                                                        + " literal name="
                                                        + literal.getName());
                                        break;
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        System.out.println("\t\t\t\tattribute name="
                                + ia.getIdentifier()
                                + ", type"
                                + "="
                                + ia.getAttributeType()
                                + " value="
                                + ia.getValue(auditableClient, workItem,
                                        monitor));
                    }
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("outer Exception=" + e.toString());
        }
    }

}// Main END


And this is snippet of result for custom atributtes:
WORKITEM------------------------------------------------
The attribute id: com.ibm.team.apt.attribute.planitem.priority._pm7NmRYUEd6L1tNIGdz5qQ
The attribute name: Ranking (w odniesieniu do null)
The value of the custom attribute: priority.literal.l01 O0000:
WORKITEM------------------------------------------------
The attribute id: com.ibm.team.apt.attribute.planitem.priority._pm7NmRYUEd6L1tNIGdz5qQ
The attribute name: Ranking (w odniesieniu do null)
The value of the custom attribute: priority.literal.l01 O0000;
WORKITEM------------------------------------------------
The attribute id: com.ibm.team.apt.attribute.planitem.priority._pm7NmRYUEd6L1tNIGdz5qQ
The attribute name: Ranking (w odniesieniu do null)
The value of the custom attribute: priority.literal.l01 O0000;
WORKITEM------------------------------------------------
The attribute id: com.ibm.team.apt.attribute.planitem.priority._pm7NmRYUEd6L1tNIGdz5qQ
The attribute name: Ranking (w odniesieniu do null)
The value of the custom attribute: priority.literal.l01 O0000=
WORKITEM------------------------------------------------
The attribute id: com.ibm.team.apt.attribute.planitem.priority._pm7NmRYUEd6L1tNIGdz5qQ
The attribute name: Ranking (w odniesieniu do null)
The value of the custom attribute: priority.literal.l01 O0000>
WORKITEM------------------------------------------------
The attribute id: com.ibm.team.apt.attribute.acceptance
The attribute name: Acceptance Test
The value of the custom attribute:
The attribute id: com.ibm.team.apt.attribute.complexity
The attribute name: Story Points
The value of the custom attribute: com.ibm.team.workitem.common.model.ILiteral:20
WORKITEM------------------------------------------------
The attribute id: com.ibm.team.apt.attribute.acceptance
The attribute name: Acceptance Test
The value of the custom attribute:
The attribute id: com.ibm.team.apt.attribute.complexity
The attribute name: Story Points
The value of the custom attribute: com.ibm.team.workitem.common.model.ILiteral:20

result when i run also code for builtIn attributes:

WORKITEM------------------------------------------------
The attribute id: com.ibm.team.apt.attribute.planitem.priority._pm7NmRYUEd6L1tNIGdz5qQ
The attribute name: Ranking (w odniesieniu do Priorytet)
The value of the custom attribute: priority.literal.l3 O00001
  Built In Attribute: Archived
 Type: boolean
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Filed Against
 Type: category
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Restricted Access
 Type: uuid
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Corrected Estimate
 Type: duration
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Creation Date
 Type: timestamp
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Created By
 Type: contributor
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Custom Attributes
 Type: customAttribute
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Description
 Type: html
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Due Date
 Type: timestamp
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Estimate
 Type: duration
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Found In
 Type: deliverable
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Id
 Type: integer
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Approval Descriptors
 Type: approvalDescriptors
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Approvals
 Type: approvals
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Comments
 Type: comments
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Priority
 Type: priority
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Resolution
 Type: smallString
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Sequence Value
 Type: smallString
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Severity
 Type: severity
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Status
 Type: smallString
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: State Transitions
 Type: stateTransitions
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Subscribed By
 Type: subscriptions
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Tags
 Type: tags
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Modified Date
 Type: timestamp
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Modified By
 Type: contributor
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Owned By
 Type: contributor
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Project Area
 Type: projectArea
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Resolution Date
 Type: timestamp
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Resolved By
 Type: contributor
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Start Date
 Type: timestamp
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Summary
 Type: mediumHtml
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Planned For
 Type: interval
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Time Spent
 Type: duration
org.eclipse.core.runtime.AssertionFailedException: assertion failed:
  Built In Attribute: Type
 Type: type
org.eclipse.core.runtime.AssertionFailedException: assertion failed:


I have a problem with getting the values ​​displayed on the RTC webservice, what is wrong? or what I forget?


permanent link
Robert Siara (821014) | answered Nov 24 '12, 4:52 a.m.
this code don't resolve My problem with AssertionFailedException.

permanent link
sam detweiler (12.5k6195201) | answered Nov 23 '12, 8:12 p.m.
see my code in the third post here https://jazz.net/forum/questions/76276/how-to-get-the-value-selected-by-user-from-a-drop-down-list

I don't care if the attribute is builtin or not

permanent link
sam detweiler (12.5k6195201) | answered Nov 26 '12, 9:15 a.m.
note that my CATCH prints the values for where the assertion fails..

Your answer


Register or to post your answer.


Dashboards and work items are no longer publicly available, so some links may be invalid. We now provide similar information through other means. Learn more here.