bishnucy

Use Java to access Clarity PPM REST API

Discussion created by bishnucy on Aug 16, 2017
Latest reply on Aug 25, 2017 by Suman Pramanik

The following is a simple example to access project data from Clarity using Java. This example demonstrates how to use a Java build-in HTTP client library to implement a simple Clarity REST API client. We will use “java.net.URL” and “java.net.HttpURLConnection” to send a “GET” request to Clarity to access project data using project’s internal ID. The Response received from Clarity REST API in JSON format will be processed to display the key-value pairs.

 

package com.clarity.rest.api;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.IOException;
import java.util.stream.Collectors;
import com.niku.union.utility.Base64;
import org.json.*;

public class ReadProjectData {
     //Use a Clarity User Account having access to the project with project internal ID = 5020001
     private static String username = "******";
    private static String password = "******";
    //Clarity REST API URL to get single project data
    private static String urlREST = "https://clarity_url/ppm/rest/v1/projects/5020001";
    
    public static void main(String[] args) {
         
          try {
               // Construct Base 64 Authenticate String
               String b64 = username + ":" + password;
               String basicAuth = "Basic " + Base64.encode(b64);
               System.out.println ("basicAuth=" + basicAuth);
               // Connection URL
               URL url = new URL(urlREST);
               HttpURLConnection conn = (HttpURLConnection) url.openConnection();
               //HTTP Request Header
               conn.setDoInput(true);
               conn.setRequestMethod("GET");
               conn.setRequestProperty("Content-type", "application/json");
               conn.setRequestProperty("Accept", "application/json");
               conn.setRequestProperty("cache-control", "no-cache");
               conn.setRequestProperty("Authorization", basicAuth);
               //Send HTTP GET Request
               conn.connect();
               //Check HTTP Response Code for success
               if (conn.getResponseCode() != 200) {
                    System.out.println("Failed : HTTP error code : " + conn.getHeaderField(0));
               } else {
                    //Process HTTP Response from Clarity REST API
                    BufferedReader br = new BufferedReader(new InputStreamReader(
                         (conn.getInputStream())));
                   
                    String fileData = br.readLine();
                    System.out.println ("fileData=" + fileData);
                    br.close();
                   
                    //Process REST API response data in JSON format
                    JSONObject jsonObj = new JSONObject(fileData);
                   
                    //Extract Name Vaue pairs from JSON object
                    for(int i = 0; i< jsonObj.names().length(); i++){
                         System.out.println ("Key = " + jsonObj.names().getString(i) + " | Value = " + jsonObj.get(jsonObj.names().getString(i)));
                    }
               }
          } catch (MalformedURLException e) {
    
               e.printStackTrace();
         
          } catch (IOException e) {
               e.printStackTrace();
              
          }catch (Exception e){//Catch exception if any
                System.err.println("Error: " + e.getMessage());
    
          }
              
     }

}

 

The following example provides a sample Java code to create a project in Clarity using REST API. 

 

package com.clarity.rest.api;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.IOException;
import java.util.stream.Collectors;
import com.niku.union.utility.Base64;
import org.json.*;

public class WriteProject {
     //Use a Clarity User Account having access to Clarity and rights to create project
     private static String username = "xxxxxxxx";
    private static String password = "xxxxxxx";
    //Clarity REST API URL to get single project data
    private static String urlREST = "https://clarity_url/ppm/rest/v1/projects";
    
    public static void main(String[] args) {
         
          try {
               // Construct Base 64 Authenticate String
               String b64 = username + ":" + password;
               String basicAuth = "Basic " + Base64.encode(b64);
               System.out.println ("basicAuth=" + basicAuth);
               // Connection URL
               URL url = new URL(urlREST);
               HttpURLConnection conn = (HttpURLConnection) url.openConnection();
               //HTTP Request Header
               conn.setDoOutput(true);
               conn.setRequestMethod("POST");
               conn.setRequestProperty("Content-type", "application/json");
               conn.setRequestProperty("Accept", "application/json");
               conn.setRequestProperty("cache-control", "no-cache");
               conn.setRequestProperty("Authorization", basicAuth);
              
               //Create Project write request in JSON format
               JSONObject jsonObj = new JSONObject();
              
               jsonObj.put("code", "PROJ0001");
               jsonObj.put("name", "Sample Test Project 1 - Created using REST API");
               jsonObj.put("description", "This a Test Project Created using REST API");
               jsonObj.put("scheduleStart", "2017-08-01T08:00:00");
               jsonObj.put("scheduleFinish", "2017-08-31T17:00:00");
              
               //Send HTTP POST Request
               OutputStreamWriter osw = new OutputStreamWriter(
                       (conn.getOutputStream()));
                 
               osw.write(jsonObj.toString());
              
               osw.close();
               //Check HTTP Response Code for success
               if (conn.getResponseCode() != 200) {
                    System.out.println("Failed : HTTP error code : " + conn.getHeaderField(0));
               } else {
                   
                    //Process HTTP Response from Clarity REST API
                   BufferedReader br = new BufferedReader(new InputStreamReader(
                        (conn.getInputStream())));
                  
                   String outputData = br.readLine();
                   System.out.println ("Project Write Output=" + outputData);
                   br.close();
                  
                   //Process REST API response data in JSON format
                   JSONObject jsonOut = new JSONObject(outputData);
                  
                   //Extract Name Vaue pairs from JSON object
                   for(int i = 0; i< jsonObj.names().length(); i++){
                        System.out.println ("Key = " + jsonObj.names().getString(i) + " | Value = " + jsonObj.get(jsonObj.names().getString(i)));
                   }
                   
               }
          } catch (MalformedURLException e) {
    
               e.printStackTrace();
         
          } catch (IOException e) {
               e.printStackTrace();
              
          }catch (Exception e){//Catch exception if any
                System.err.println("Error: " + e.getMessage());
    
          }
              
     }

}

 

The following Java example will edit an existing project record in Clarity using REST API. 

package com.clarity.rest.api;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.IOException;
import java.util.stream.Collectors;
import com.niku.union.utility.Base64;
import org.json.*;

public class UpdateProjectPartial {
     //Use a Clarity User Account having access to Clarity and rights to create project
     private static String username = "******";
    private static String password = "******";
    //Clarity REST API URL to get single project data
    private static String urlREST = "https://clarity_url/ppm/rest/v1/projects/5020005";
    
    public static void main(String[] args) {
         
          try {
               // Construct Base 64 Authenticate String
               String b64 = username + ":" + password;
               String basicAuth = "Basic " + Base64.encode(b64);
               System.out.println ("basicAuth=" + basicAuth);
               // Connection URL
               URL url = new URL(urlREST);
               HttpURLConnection conn = (HttpURLConnection) url.openConnection();
               //HTTP Request Header
               conn.setDoOutput(true);
               conn.setRequestMethod("PUT");
               conn.setRequestProperty("Content-type", "application/json");
               conn.setRequestProperty("Accept", "application/json");
               conn.setRequestProperty("cache-control", "no-cache");
               conn.setRequestProperty("x-api-force-patch", "true");
               conn.setRequestProperty("Authorization", basicAuth);
              
               //Create Project write request in JSON format
               JSONObject jsonObj = new JSONObject();
              
              jsonObj.put("code", "PRJ00001");
               jsonObj.put("name", "Sample Test Project 1 - Created using REST API - Updated");
               jsonObj.put("description", "This a Test Project Created using REST API Updated");
               jsonObj.put("scheduleStart", "2017-09-01T08:00:00");
               jsonObj.put("scheduleFinish", "2018-12-31T17:00:00");
               jsonObj.put("progress", "1");     //Started
               jsonObj.put("percentComplete", "0.1");     //10%
              
               System.out.println("Request : " + jsonObj.toString());
              
               //Send HTTP POST Request
               OutputStreamWriter osw = new OutputStreamWriter(
                       (conn.getOutputStream()));
                 
               osw.write(jsonObj.toString());
              
               osw.close();
               //Check HTTP Response Code for success
               if (conn.getResponseCode() != 200) {
                    System.out.println("Failed : HTTP error code : " + conn.getHeaderField(0));
               } else {
                   
                    //Process HTTP Response from Clarity REST API
                   BufferedReader br = new BufferedReader(new InputStreamReader(
                        (conn.getInputStream())));
                  
                   String outputData = br.readLine();
                   System.out.println ("Project Write Output=" + outputData);
                   br.close();
                  
                   //Process REST API response data in JSON format
                   JSONObject jsonOut = new JSONObject(outputData);
                  
                   //Extract Name Vaue pairs from JSON object
                   for(int i = 0; i< jsonObj.names().length(); i++){
                        System.out.println ("Key = " + jsonObj.names().getString(i) + " | Value = " + jsonObj.get(jsonObj.names().getString(i)));
                   }
                   
               }
          } catch (MalformedURLException e) {
    
               e.printStackTrace();
         
          } catch (IOException e) {
               e.printStackTrace();
              
          }catch (Exception e){//Catch exception if any
                System.err.println("Error: " + e.getMessage());
    
          }
              
     }

}

Outcomes