Sign-up our Newsletter  Register on our LinkedIn  Follow us on Twitter  Check out our Facebook  Follow us on Google+
Follow

Interface with XStudio REST API (An exemple)

If you need to interface with XStudio you will want to use the REST API.

 

Here's a simple (Java) Example to show how to authenticate, get and post data.

 

 

package com.xqual.xrest_client;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

public class CClient {

 private final String USER_AGENT = "Mozilla/5.0";

 public HttpURLConnection con = null;
 private CookieManager cookieManager = null;
 private CookieStore cookieStore = null;

 private void start() throws Exception {
        // used to store cookies
  cookieManager = new CookieManager();
  cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        cookieStore = cookieManager.getCookieStore();

        // ------------------
        // FIRST AUTHENTICATE
        // ------------------
  String serverURL = "http://192.168.100.180:8080/xqual/api";
  sendPost(serverURL + "?command=authenticate&username=admin&password=password&userLanguage=en_US", "");

        // Cookie: message --> local store
        Map<String, List<String>> headerFields = con.getHeaderFields();
        List<String> cookiesHeader = headerFields.get("Set-Cookie");

        if (cookieStore != null) {
            if (cookiesHeader != null) {
          if (cookiesHeader.size() > 0) {
              for (String cookieHeader : cookiesHeader) {
            if (cookieHeader != null && cookieHeader.length() > 0) {
                List<HttpCookie> cookiesList = HttpCookie.parse(cookieHeader);
                if (cookiesList != null) {
              if (cookiesList.size() > 0) {
            for (HttpCookie cookie : cookiesList) {
          if (cookie != null) {
              try {
            if (cookie.toString().startsWith("JSESSIONID")) { // we need to store ONLY this one !!!
                System.err.println("<<< saving cookie in the local store: " + cookie.toString());
                cookieStore.add(null, cookie);
            }
              } catch (Exception e) {
            System.err.println("couldn't store cookie!");
              };
          }
            }
              } else {
                  System.err.println("no cookie available in the message");
              }
                } else {
              System.err.println("null cookies list in the message!");
          }
            } else {
                System.err.println("null or empty cookie header in the message!");
            }
              }
          } else {
              System.err.println("no cookie header in the message!");
          }
        } else {
          System.err.println("null cookies header in the message"); // in the next connections, this is normal
      }
        } else {
            System.err.println("null local cookie store!");
  }

        // --------------------------------
        // THEN SEND YOUR GET/POST MESSAGES
        // --------------------------------

        // get the server's settings
  sendGet(serverURL + "?command=getSettings");

  // get the requirements tree
        sendGet(serverURL + "?command=getRequirementsTree");

        // create a new requirement
  StringBuffer bodyContent = new StringBuffer();
  bodyContent.append("{");
  bodyContent.append("    \"form\": {");
  bodyContent.append("  \"formItem\": [{");
  bodyContent.append("      \"id\": 2,"); // name
  bodyContent.append("      \"value\": \"new requirement\"");
  bodyContent.append("  },");
  bodyContent.append("  {");
  bodyContent.append("      \"id\": 3,"); // description
  bodyContent.append("      \"content\": \"CREATE requirement [b]description[/b] 2\"");
  bodyContent.append("  },");
  bodyContent.append("  {");
  bodyContent.append("      \"id\": 5,"); // status
  bodyContent.append("      \"value\": 20");
  bodyContent.append("  },");
  bodyContent.append("  {");
  bodyContent.append("      \"id\": 4,"); // priority
  bodyContent.append("      \"value\": 20");
  bodyContent.append("  },");
  bodyContent.append("  {");
  bodyContent.append("      \"id\": 8,"); // risk
  bodyContent.append("      \"parameters\": \"1;2;3;4\",");
  bodyContent.append("      \"value\": 2345");
  bodyContent.append("  },");
  bodyContent.append("  {");
  bodyContent.append("      \"id\": 6,"); // type
  bodyContent.append("      \"value\": \"Functional\"");
  bodyContent.append("  }]");
  bodyContent.append("    }");
  bodyContent.append("}");
        sendPost(serverURL + "?command=createRequirement&parentFolderId=33", bodyContent.toString());
 }

 // +-------------------+
 // |        GET        |
 // +-------------------+
 public void sendGet(String url) throws Exception {
  System.err.println("************* [GET]  " + url);
  URL obj = new URL(url);

  con = (HttpURLConnection) obj.openConnection();

  addCookie();

  con.setRequestMethod("GET");
  con.setRequestProperty("User-Agent", USER_AGENT);

  //displayDetails(con);

  int responseCode = con.getResponseCode();
  //System.out.println("\nSending 'GET' request to URL : " + url);
  System.out.println("Response Code : " + responseCode);

  BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
  String inputLine;
  StringBuffer response = new StringBuffer();
  while ((inputLine = in.readLine()) != null) {
      response.append(inputLine);
  }
  System.out.println("response: " + response.toString() + ".");
  in.close();
  con.disconnect();
 }

 // +-------------------+
 // |      POST        |
 // +-------------------+   
 private void sendPost(String url, String body) throws Exception {
  System.err.println("************* [POST]  " + url);
  URL obj = new URL(url);

  con = (HttpURLConnection) obj.openConnection();

  addCookie();

  con.setRequestMethod("POST");
  con.setRequestProperty("User-Agent", USER_AGENT);

  // body
  byte[] postData = body.getBytes("UTF8");
  int postDataLength = postData.length;
  con.addRequestProperty("Content-Type", "application/json");
  con.setRequestProperty("Content-Length", ""+postDataLength);

  // Send post request
  con.setDoOutput(true);

  DataOutputStream wr = new DataOutputStream(con.getOutputStream());
  wr.write(postData);
  wr.flush();
  wr.close();

  /*
  or...
  con.addRequestProperty("Content-Type", "application/json");
  con.setRequestProperty("Content-Length", Integer.toString(body.length()));
  con.getOutputStream().write(body.getBytes("UTF8"));
  */

  //displayDetails(con);

  int responseCode = con.getResponseCode();
  System.out.println("\nSending 'POST' request to URL : " + url);
  System.out.println("Response Code : " + responseCode);

  BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
  String inputLine;
  StringBuffer response = new StringBuffer();
  while ((inputLine = in.readLine()) != null) {
      response.append(inputLine);
  }
  in.close();
  System.out.println(response.toString());
  con.disconnect();
 }


 private void addCookie() {
        // Cookie: local store --> message
        String storedCookie = null;
        try {
            //System.err.println("local cookie store:" + cookieStore);
      if (cookieStore != null) {
          List<HttpCookie> cookiesList = cookieStore.getCookies();
          //System.err.println("local cookies list:" + cookiesList);
          if (cookiesList != null) {
              //System.err.println("cookies# in the local store:" + cookiesList.size());
              if (cookiesList.size() > 0) {
            HttpCookie firstCookie = cookiesList.get(0);
            if (firstCookie != null) {
                storedCookie = firstCookie.toString();
                //System.err.println(">>> set cookie in the message: " + storedCookie);
                con.setRequestProperty("Cookie", storedCookie);
            } else {
                System.err.println("null cookie in local store!");
            }
              } else {
            System.err.println("no cookie available in local store"); // at the first connection, this is normal
              }
          } else {
              System.err.println("null local cookies list!");
          }
      } else {
          System.err.println("null local cookie store!");
      }
        } catch (Exception e) {
            System.err.println("Exception while parsing cookies: " + e);
        }
 }

 public static void main(String[] args) throws Exception {
  System.out.println("- - - - - - - - NEW CLIENT - - - - - - -");
  CClient client = new CClient();
  client.start();
 }
}

 

Was this article helpful?
0 out of 0 found this helpful
Have more questions? Submit a request

0 Comments

Please sign in to leave a comment.