You are not logged in. Click here to log in.

codebeamer Application Lifecycle Management (ALM)

Search In Project

Search inClear

Tags:  Java Rest API

Example Rest API client based using Java

The purpose of this document to show Rest client Example written in JAVA to be able to inject Work Item data into codebeamer via Rest API.


Minimum requirement: Java SE framework version 1.8


This application was implemented and tested under Windows 10 but is compatible with Linux.

Usage

java -jar importWorkItemsDemo.jar -e [Endpoint] -u [Username] -p [Password] -t [TrackerId] -f [Filename]
     -e [Endpoint]: the codeBeamer endpoint server address (eg. https://codebeamer.com/cb)
     -u [Username]: login user account name
     -p [Password]: login user password
     -pr [ProjectId]: Target project id where the application should inject the input data
     -tr [TrackerId]: Target tacker id where the application should inject the input data
     -f [Filename]: Input file data in csv format


Example:
     java -jar importWorkItemsDemo.jar -e https://codebeamer.com/cb -u cbprojectadmin -p cbpass -pr 12 -tr 1234 -f input.csv

CSV File example

ID name description attachment

Summary of new item Description of new item c:/testAttachment.txt
1234 New summary of existing item 1 New description of existing item 1
5432 New Summary of existing item 2 New description of existing item 2 c:/testAttachment2.txt
  • The values should be separated by a comma.

  • The first row contains the headers. The order can be modified.

  • If the ID is set - the application updates the existing work item.

  • If the ID is not set - the application creates a new work item.

  • If the attachment is set - the file is uploaded to the work item.
    • The attachment should contain the absolute path to the file.

Rest Client code examples

Basic interfaces and classes

CodeBeamerService Rest Interface contains all necessary methods to create or update work items and upload attachments:

    /**
     * Use this method to obtain item schema.
     *
     * @param projectId is the id of the project
     * @param trackerId is the id of the tracker
     * @param config is the necessary data for connection
     * @return item schema
     * @throws ServiceException
     */
    public Map obtainItemSchema(String projectId, String trackerId, RestClientConfig config) throws ServiceException;

    /**
     * Use this method to create new item.
     *
     * @param item is the item object
     * @param config is the necessary data for connection
     * @return response from codeBeamer
     * @throws ServiceException
     */
    public Map createItem(Map<String, Object> item, RestClientConfig config) throws ServiceException;

    /**
     * Use this method to obtain schema of an existing item.
     *
     * @param itemId is the id of the item
     * @param config is the necessary data for connection
     * @return response from codeBeamer
     * @throws ServiceException
     */
    public Map getItem(String itemId, RestClientConfig config) throws ServiceException;

    /**
     * Use this method to update an existing item.
     *
     * @param item is the item object
     * @param config is the necessary data for connection
     * @return response from codeBeamer
     * @throws ServiceException
     */
    public Map updateItem(Map<String, Object> item, RestClientConfig config) throws ServiceException;

    /**
     * Use this method to upload an attachment.
     *
     * @param itemId is the id of the item
     * @param file is the uploaded file
     * @param config is the necessary data for connection
     * @returnresponse from codeBeamer
     * @throws ServiceException
     */
    public Map uploadAttachmentToItem(String itemId, File file, RestClientConfig config) throws ServiceException;

CodeBeamerServiceImpl uses general Rest Client to communicate with codebeamer:

    public Map createItem(Map<String, Object> item, RestClientConfig config) throws ServiceException {
        try {
            Response<Map> response = RestClient.CLIENT.executePost(
                String.format(ITEM_URL_PATTERN, config.getHost()), new StringEntity(mapper.writeValueAsString(item)), config, Map.class);
            if (!checkStatusCode(response.getHttpStatus())) {
                throw new ServiceException(
                    String.format("Error occurred when tried to create item, http status: %s, response: %s", response.getHttpStatus(), response.getContent()));
            }
            return response.getContent();
        } catch (Exception ex) {
            throw new ServiceException(ex);
        }
    }
    

RestClient is a general rest client implementation. It contains methods to send GET, POST, PUT requests:

Example for POST request implementation:

    /**
     * Use this method to send POST request.
     *
     * @param url is the target url
     * @param entity contains the body of the request
     * @param config contains the necessary data for connection
     * @param clazz is the type of the response
     * @return POST request response with http status code
     * @throws RestClientException
     */
    public <T> Response<T> executePost(String url, HttpEntity entity, RestClientConfig config, Class<T> clazz) throws RestClientException {
        Response<T> result = null;
        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(entity);
            response = client.execute(httpPost, createContext(config));
            HttpEntity responseEntity = response.getEntity();
            String content = IOUtils.toString(entity.getContent());
            result = new Response<T>(response.getStatusLine().getStatusCode(), StringUtils.isNotEmpty(content) ? mapper.readValue(responseEntity.getContent(), clazz) : null);
            EntityUtils.consume(responseEntity);
            return result;
        } catch (Exception ex) {
            throw new RestClientException(ex);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException ex) {
                throw new RestClientException(ex);
            }
        }
    }
    

Examples to use CodeBeamerService Rest Interface

Create new items

  1. To create a new item, the item schema is to be obtained first from codebeamer. It can be downloaded with the obtainItemSchema(String projectId, String trackerId, RestClientConfig config) method of CodeBeamerService class.

  2. This schema can be used as a template to create new items on the server by cloning it.

  3. Once the fields are set, call the createItem(Map<String, Object> item, RestClientConfig config) method of CodeBeamerService class.

Example:

// set project id and tracker id to download the schema
Map<String, Object> schema = service.obtainItemSchema(
    String.valueOf(options.get(Option.PROJECT_ID)),
    String.valueOf(options.get(Option.TRACKER_ID)),
    config);

// item schema is under the "item" attribute, so get it
Map<String, Object> itemSchema = (Map<String, Object>) schema.get("item");

// clone it to use this schema as template to create new items
Map<String, Object> itemSchemaClone = cloner.deepClone(itemSchema)

// set new field values ...
// for ex.: itemSchemaClone.put("description", "Test description");

// create new item on server
service.createItem(itemSchemaClone, config);

Update existing items

  1. First of all, the schema of the item is needed. We can get an existing item schema with values by call getItem(String itemId, RestClientConfig config) method of CodeBeamerService class.
    The response is in JSON format and the current values can be found under the item attribute. This attribute contains all fields which are set earlier for this item.

  2. Now, the fields in the item attributes can be updated, added or deleted (the available fields for the item can be found at the type/properties attribute in the schema).

  3. Once the fileds are set, call the updateItem(Map<String, Object> item, RestClientConfig config) method of CodeBeamerService class and the item will be updated on the server.

Example:

// obtain existing item schema with field values
Map<String, Object> itemSchema = (Map<String, Object>) service.getItem(record.get(ID_FIELD), config).get("item");


// update field values ...
// for ex.: itemSchema.put("description", "Test description");


//update item on server
service.updateItem(itemSchemaClone, config);

Upload attachments

To upload files to items, call the uploadAttachmentToItem(id, file, config) method of CodeBeamerService class.

service.uploadAttachmentToItem(id, file, config);

Reading CSV file

  • In the example implementation, items and item field values are read from a CSV file.

  • The first row is the header which contains the fields of the items, other rows contain item fields values.

  • We iterate over CSV records and set field values in the item schema.

  • Code snippet for creating, updating items:
        // clone the item schema template and it will be used if this is a new item
        Map<String, Object> itemSchemaClone = cloner.deepClone(itemSchema)
        if (!newItem) {
             // obtain existing item schema with field values, because the ID field is set for this item
            itemSchemaClone = (Map<String, Object>) service.getItem(record.get(ID_FIELD), config).get("item");
        }
        // read field values
        for (String field : fields) { // iterate over available fields for items
            if (record.isMapped(field)) { // is this field set in CSV file?
                // get the field value
                String value = record.get(field);
                if (StringUtils.isNotEmpty(value)) {
                    itemSchemaClone.put(field, value); // set new field value in the item
                }
            }
        }