Updating execution status by test case ID/schedule ID using REST API - rest

I have Zephyr related Query, how I can update the execution status of a test case to PASS/FAIL/WIP by using test case ID with rest API.
I have referred to the article at below link
https://support.getzephyr.com/hc/en-us/articles/205042055-Sample-REST-API-Update-execution-status-of-a-testcase-JAVA-
In this example they have shown how to update execution status by using Schedule ID, but the implementation is in SOAP and we need to achieve the same using REST API. Is there any direct REST API to get schedule ID ?
Also, is there a direct REST API to update execution status of a test case using test case ID ? If yes, can you provide examples for both the above cases?
Thanks in advance.

There is no direct method in Jira REST API to update the execution status using test case ID. However,you can use the following custom method :
import java.util.HashMap;
import java.util.Map;
import org.apache.http.client.methods.HttpPost;
import org.apache.commons.io.IOUtils;
import org.codehaus.jettison.json.JSONObject;
import java.net.Proxy;
import java.net.HttpURLConnection;
import java.net.URL;
public class JiraAuthHeader {
public static void main(String args[])
{
try {
JiraAuthHeader jiraAuthHeaderObj= new JiraAuthHeader();
System.out.println(" Create Execution method*********");
int executionId= jiraAuthHeaderObj.createExecution(<project id>,<issue id>,<cycle id>);
System.out.println(" Update Execution method*********");
jiraAuthHeaderObj.updateExecution(executionId,"pass");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String updateExecution(int executionId, String status) throws Exception {
System.out.println("Executing execution with executionId " + executionId + " and status = " + status);
String url = "https://jira.company.com/jira/rest/zapi/latest/execution/" + executionId + "/execute";
//String url = "https://jira.company.com/jira/rest/zapi/latest/execution";
String statusInReq = "";
if (status.equalsIgnoreCase("pass")) {
statusInReq = "1";
} else if (status.equalsIgnoreCase("fail")) {
statusInReq = "2";
}
// Create request body
JSONObject obj = new JSONObject();
obj.put("status", statusInReq);
obj.put("comment", "through java");
String requestBody = obj.toString();
System.out.println("Request body: " + requestBody);
HttpURLConnection conn
= httpPut(url, null, null, obj.toString());
System.out.println("HTTP response code: " + conn.getResponseCode());
String response = getResponse(conn);
System.out.println("HTTP response content: " + response);
System.out.println("from HTTP response content fetch the execution id: " + response.substring(6, 12));
return response;
}
public HttpURLConnection httpGet(String url, Map<String, String> requestHeaders, String queryString) throws Exception {
System.out.println("Get request");
if (queryString != null) {
url += "?" + queryString;
}
if (requestHeaders == null) {
requestHeaders = new HashMap<String, String>();
}
requestHeaders.put("Content-Type", "application/json");
return openConnection(url, "GET", requestHeaders, null);
}
public HttpURLConnection httpPut(String url, Map<String, String> requestHeaders, String queryString, String requestContent) throws Exception {
System.out.println("Put request");
if (queryString != null) {
url += "?" + queryString;
}
System.out.println(url);
if (requestHeaders == null) {
requestHeaders = new HashMap<String, String>();
}
requestHeaders.put("Content-Type", "application/json");
return openConnection(url, "PUT", requestHeaders, requestContent);
}
public HttpURLConnection httpPost(String url, Map<String, String> requestHeaders, String queryString, String requestContent) throws Exception {
System.out.println("Post request");
if (queryString != null) {
url += "?" + queryString;
}
System.out.println(url);
if (requestHeaders == null) {
requestHeaders = new HashMap<String, String>();
}
requestHeaders.put("Content-Type", "application/json");
return openConnection(url, "POST", requestHeaders, requestContent);
}
private HttpURLConnection openConnection(String url, String requestMethod, Map<String, String> requestHeaders, String requestContent)
throws Exception {
boolean usingProxy = false;
HttpURLConnection conn = null;
if (usingProxy) {
/*String[] proxyInfo = jiraIntegrationConfig.getProxyServer().split(":");
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyInfo[0], Integer.valueOf(proxyInfo[1])));
conn = (HttpURLConnection) new URL(url).openConnection(proxy);*/
} else {
conn = (HttpURLConnection) new URL(url).openConnection(Proxy.NO_PROXY);
String auth = "ssing621" + ":" + "amex^123";
auth = "Basic " + new String(new sun.misc.BASE64Encoder().encode(auth.getBytes()));
conn.setRequestProperty("Authorization", auth);
conn.setRequestMethod(requestMethod);
if (requestHeaders != null && requestHeaders.size() > 0) {
for (String key : requestHeaders.keySet()) {
conn.setRequestProperty(key, requestHeaders.get(key));
}
}
if (requestContent != null) {
conn.setDoOutput(true);
conn.getOutputStream().write(requestContent.getBytes("UTF-8"));
}
}
return conn;
}
private String getResponse(HttpURLConnection conn) throws Exception {
String response;
if (conn.getResponseCode() == 200 || conn.getResponseCode() == 201) {
response = IOUtils.toString(conn.getInputStream());
return response;
} else {
response = IOUtils.toString(conn.getErrorStream());
throw new Exception(response);
}
}
public int getIssueIdByKey(String issueKey) throws Exception {
System.out.println("Getting issue ID for test: [" + issueKey + "]");
String url = ("https://jira.company.com/jira/rest/api/2/issue/" + issueKey);
HttpURLConnection conn = httpGet(url, null, null);
String response = getResponse(conn);
JSONObject resObj = new JSONObject(response);
if (resObj.has("id")) {
int issueId = resObj.getInt("id");
System.out.println("Found issue ID: " + issueId);
return issueId;
}
System.out.println("Could not find IssueId for test: [" + issueKey + "]");
return 0;
}
public int createExecution(int projectId, int issueId, int cycleId) throws Exception {
System.out.print("Creating execution for project Id " + projectId + " and issueId " + issueId);
String url = ("https://jira.company.com/jira/rest/zapi/latest/execution");
// Create request body
JSONObject reqObj = new JSONObject();
reqObj.put("issueId", issueId);
reqObj.put("projectId", projectId);
reqObj.put("cycleId", cycleId);
String requestBody = reqObj.toString();
System.out.println("Request body: " + requestBody);
HttpURLConnection conn = httpPost(url, null, null, requestBody);
System.out.println("HTTP response code: " + conn.getResponseCode());
String response = getResponse(conn);
System.out.println("HTTP response content: " + response);
// Parse the Execution Id, and return it
JSONObject resObj = new JSONObject(response);
int executionId = Integer.valueOf(resObj.keys().next().toString());
System.out.println("Creation done, execution ID: " + executionId);
return executionId;
}
}

Related

How to get OAuth 2.0 access token using refresh token in scala

How to get OAuth2.0 access token using refresh token in scala .
Sample code using the HttpsURLConnection, without any libraries
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class Sample_OAuth {
public static void main(String[] args) throws Exception {
Sample_OAuth outhDriver = new Sample_OAuth();
outhDriver.sendRefreshTokenRequestWithOnlyHeader(null);
}
/**
* Send refresh token request to 3rd party with client cred either in body or
* request header.
*
* #param conn
* #param mapListTagToMetaDataName
* #return
* #throws Exception
*/
private Map<String, Object> sendRefreshTokenRequestWithOnlyHeader(Map<String, String> mapListTagToMetaDataName)
throws Exception {
String tokenUrl = "https://xyz.snowflakecomputing.com/oauth/token-request";
URL url = new URL(tokenUrl);
StringBuilder stringBuilder = new StringBuilder();
appendURLParam(stringBuilder, "grant_type", "refresh_token", true);
appendURLParam(stringBuilder, "refresh_token", "ver:2-hint:2065896170862-did:1003-ETMsDgAAAYWAOC1cABRBRVMvQ0JDL1BLQ1M1UGFkZGluZwEAABAAEDu3hgX2UvrDbaMif7uC+ygAAADwoZhxL+aOCvvsmNh0wy0FdNGuDRLCtOq7iQTsZPPmfkRZJnkj3nXgKDxTFeFOmty4ej/O6Fsf17HfNvKdLrqfN3V29FkFQ5S+FktFIznTSjtd7+xaMS+sPEAyey2SFfbSyMvrknjq9F+CQZ50H181OO8Ak4v1uW4ON9Q1UBRd9ywM2Yg5g59hPgy90jtAW0DPQ8gvfAwRJCgg2wzV7tXrQ1H2TQhFEkQH418s5pSNB5V6BSW0fFqOUW3O8X4MmHcWcpTbghZ5aga8+dSKSR8jd2KMmfawyXMdkIYdWEsrpcJozuYDAjFwIT1lkqLxqBnuABQIbwjao0KeWXYU3sYanTb0WoR4Ng==",
false);
String clientRequestType = "Basic Auth Header";
return sendOAuthRequestWithHeader(mapListTagToMetaDataName, url, stringBuilder.toString());
}
private static void appendURLParam(StringBuilder stringBuilder, String name, String value, boolean appendAmpersand)
throws UnsupportedEncodingException {
/*
* if (StringUtil.isNullOrEmptyTrim(name) ||
* StringUtil.isNullOrEmptyTrim(value)) { //log.error(String.
* format("Either Auth attr name : %s or value : %s is Null or empty", name,
* value)); return; }
*/
stringBuilder.append(name);
stringBuilder.append("=");
stringBuilder.append(URLEncoder.encode(value, "UTF-8"));
//stringBuilder.append(value);
if (appendAmpersand) {
stringBuilder.append("&");
}
}
private Map<String, Object> sendOAuthRequestWithHeader(Map<String, String> mapListTagToMetaDataName, URL url,
String postBody) throws Exception {
String clientId = "S0RpOorCRUQOqVncoxc8fXUO22A=";
String client_secret = "MHTOaEmQeLB359K+kEAs/+2ow4AcmqD5/ABckC4E2fQ=";
clientId = clientId + ":" + client_secret;
// Should not be MIME-encode since value is used as a HTTP header and MIME adds
// new lines if over 76 characters
String value = java.util.Base64.getEncoder().encodeToString(clientId.getBytes());
return sendOAuthRequest(url, postBody, value);
}
private Map<String, Object> sendOAuthRequest(URL url, String postBody, String authorizationHeader) throws Exception {
HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
urlConn.setRequestMethod("POST");
urlConn.addRequestProperty("Accept", "application/json");
if (notNullOrEmptyTrim(authorizationHeader)) {
urlConn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConn.addRequestProperty("Authorization", "Basic " + authorizationHeader);
}
return sendAccessTokenRequest(urlConn, postBody);
}
public Map<String, Object> getToken(String tokenUrl, String requestBody, String authorizationHeader)
throws Exception {
// LOG.info("Request : getToken "+ tokenUrl);
URL url = new URL(tokenUrl);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.addRequestProperty("Accept", "application/json");
if (null != authorizationHeader && !authorizationHeader.isEmpty()) {
urlConnection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.addRequestProperty("Authorization", "Basic " + authorizationHeader);
}
return sendAccessTokenRequest(urlConnection, requestBody);
}
private Map<String, Object> sendAccessTokenRequest(HttpsURLConnection urlConn, String postBody) throws Exception {
// Write to input stream
try {
//optional
enableAllSSLCert(urlConn);
urlConn.setDoOutput(true);
//optional
urlConn.setHostnameVerifier((name, session) -> true);
DataOutputStream outputStream = new DataOutputStream(urlConn.getOutputStream());
outputStream.writeBytes(postBody);
outputStream.flush();
outputStream.close();
int responseCode = urlConn.getResponseCode();
InputStream is = null;
// LOG.info(" response code is:" + responseCode);
if (responseCode >= 200 && responseCode < 400) {
is = urlConn.getInputStream();
} else {
// LOG.error("Error, sendOAuthRequest response code is:" + responseCode);
is = urlConn.getErrorStream();
}
// Read response
String response = null;
if (null != is) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
StringBuilder stringBuilder = new StringBuilder();
while (true) {
String line = bufferedReader.readLine();
if (line == null) {
break;
} else {
stringBuilder.append(line);
}
}
response = stringBuilder.toString();
bufferedReader.close();
}
// Logging in case of error
if (responseCode != 200) {
// LOG.error("Get Token error response : " + response);
}
System.out.println(response);
Map<String, Object> retValue = new HashMap<>();
retValue.put("errorCode", responseCode);
retValue.put("token", response);
return retValue;
} catch (Exception exp) {
// LOG.info(" Exception while getting Access Token:", exp);
throw exp;
}
}
public static boolean notNullOrEmptyTrim(String str) {
return !isNullOrEmptyTrim(str);
}
public static boolean isNullOrEmptyTrim(String s) {
return s == null || s.trim().isEmpty();
}
/**
* Enable https client for all SSL cert
*
* #param urlConn
* #throws NoSuchAlgorithmException
* #throws KeyManagementException
*/
private void enableAllSSLCert(HttpsURLConnection urlConn) throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAllTrustManager() }, new java.security.SecureRandom());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = (hostname, session) -> true;
urlConn.setHostnameVerifier(allHostsValid);
}
/**
* Override Trust All trust manager
*/
private class TrustAllTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
}

Unity occurs a 400 Bad Request when calling a HTTP-Post on an SAP Rest API

I want to call a REST API with an Unity-Script but it occurs me the Error 400 Bad Request. It is maybe because of the http-header. May you can help me. SAP offers a Code Snippet in JAVA which I want to show you first:
DataOutputStream dataOut = null;
BufferedReader in =null;
try {
//API endpoint for API sandbox
String url = "https://sandbox.api.sap.com/mlfs/api/v2/image/scene-text-
recognition";
//Available API Endpoints
//https://mlfproduction-scene-text-
recognition.cfapps.eu10.hana.ondemand.com/api/v2/image
//https://mlfproduction-scene-text-
recognition.cfapps.us10.hana.ondemand.com/api/v2/image
URL urlObj = new URL(url);
HttpURLConnection connection = (HttpURLConnection)
urlObj.openConnection();
//setting request method
connection.setRequestMethod("POST");
//adding headers
connection.setRequestProperty("content-type","multipart/form-data;
boundary=---011000010111000001101001");
//API Key for API Sandbox
connection.setRequestProperty("APIKey","----api-Key---");
//Available Security Schemes for productive API Endpoints
//OAuth 2.0
connection.setDoInput(true);
//sending POST request
connection.setDoOutput(true);
dataOut = new DataOutputStream(connection.getOutputStream());
dataOut.writeBytes("-----011000010111000001101001\r\nContent-
Disposition: form-data; name=\"files\"; filename=\"<file_name>\"\r\nContent-Type: <file_type>\r\n\r\n<file_contents>\r\n-----011000010111000001101001--");
dataOut.flush();
int responseCode = connection.getResponseCode();
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
//printing response
System.out.println(response.toString());
} catch (Exception e) {
//do something with exception
e.printStackTrace();
} finally {
try {
if(dataOut != null) {
dataOut.close();
}
if(in != null) {
in.close();
}
} catch (IOException e) {
//do something with exception
e.printStackTrace();
}
}
My UnityCode looks something like this:
public void ExecutePost()
{
Debug.Log("execute started");
byte[] img =
File.ReadAllBytes(#"C:\Users\InnovationLab\Documents\ECENTA\ECENTA
FSE\Bild1.jpg");
string url = "https://sandbox.api.sap.com/mlfs/api/v2/image/scene-
text-recognition";
coroutine = Post(url, img);
StartCoroutine(coroutine);
}
public IEnumerator Post(string url,byte[] image)
{
WWWForm form = new WWWForm();
form.AddBinaryData("imageField", image, "HoloImg");
var headers = new Dictionary<string, string> {
{"content-type", "multipart/form-data; boundary=---011000010111000001101001" },
{"APIKey", "---here I implemented the key---" }
};
WWW www = new WWW(url, image, headers);
yield return www;
if (www.error != null && www.error != "")
{ // on error, show information and return
Debug.Log("Network Error occured: " + www.error);
yield break;
}
while (!www.isDone)
{
Debug.Log(www.text);
}
}
}
So my question is, how to change the unity code so that it works?
I fixed it by using MultipartFormSections. The problem was that the api expected form-data not a binary Array.
public IEnumerator Upload(string url, byte[] img)
{
List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
MultipartFormFileSection myFormFile = new MultipartFormFileSection("files", img,
"Bild1.jpg", "multipart/form-data");
formData.Add(myFormFile);
Debug.Log(formData.ToString());
UnityWebRequest www = UnityWebRequest.Post(url, formData);
www.SetRequestHeader("APIKey", "<api-key>");
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
throw new Exception(www.downloadHandler.text ?? www.error);
}
else
{
Debug.Log("Done!!!!!");
}
Debug.Log(www.downloadHandler.text);
var ResultObject = JsonUtility.FromJson<TextPrediction>(www.downloadHandler.text);
foreach (var result in ResultObject.texts)
{
}
}

Android Volley with REST Api - POST will not insert into dB and respons incorrectly

I am using https://github.com/mevdschee/php-crud-api as REST Api to access my MySQL db. To access data from Android application I use Volley lib.
All works fine except POST (creating new item in db). But instead new item created I am getting JSON will all items (look like output from GET) and item is not created in dB.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "APP START");
tv = findViewById(R.id.textView);
buttonPost = findViewById(R.id.buttonPost);
buttonGet = findViewById(R.id.buttonGet);
Calendar cal = Calendar.getInstance();
SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
current_date = sd1.format(new Date(cal.getTimeInMillis()));
Log.d(TAG, "current_date=" + current_date);
cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
mRequestQueue = new RequestQueue(cache, network);
mRequestQueue.start();
buttonGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "ButtonGet pressed");
tv.setText("");
getRest();
}
});
buttonPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "ButtonPost pressed");
tv.setText("");
postRest();
}
});
}
getRest()
tv.append("REST API - reading data via GET " + "\n");
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, endpointUrl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject vancuraLevel1 = response.getJSONObject("restdemo");
JSONArray vancuraLevel2 = vancuraLevel1.getJSONArray("records");
int JSONlenght2 = vancuraLevel2.length();
Log.d("JSON", "JSONlenght2 =" + JSONlenght2 );
for(int n = 0; n < JSONlenght2; n++) {
Log.d("JSON", "looping " + n );
JSONArray vancuraLevel3 = vancuraLevel2.getJSONArray(n);
int JSONlenght3 = vancuraLevel3.length();
String index = vancuraLevel3.getString(0);
String datum = vancuraLevel3.getString(1);
String subjekt = vancuraLevel3.getString(2);
String ovoce = vancuraLevel3.getString(3);
Log.d("JSON", "result datum" + datum + " subjekt=" + subjekt);
tv.append("Data : " + index + "/" + datum + "/" + subjekt + "/" + ovoce + "\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Volley REST error " + error.toString());
tv.append("ERROR " + error.toString() +"\n");
}
});
// fire Volley request
mRequestQueue.add(jsObjRequest);
postRest(){
final String whatToInsert = "foo subjekt " + current_date;
// POST - insert data
tv.append("REST API - inserting data via POST - payload=" + whatToInsert +"\n");
StringRequest postRequest = new StringRequest(Request.Method.POST, endpointUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
// tv.append(current_date + "\n");
tv.append("response = " + response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.e("Error.Response", error.getMessage());
tv.append("ERROR " + error.toString() +"\n");
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
//params.put("index", "NULL");
params.put("datum", "2017-12-30");
params.put("subjekt", whatToInsert);
params.put("ovoce", "2");
return params;
}
};
// fire Volley request
mRequestQueue.add(postRequest);
Result GET - it is OK
Result POST - fault
project is available at https://github.com/fanysoft/AndroidRESTapi
Looking closely at the code the GET method returns a JSONObject response while the POST method return a String response. The string response of the POST Method is very correct and it carries exactly the same result as the GET method result all you have to do is convert the String response to JSON object you ll have same JSONObject as the GET method
JSONObject jsonObject = new JSONObject(response);
Then you can parse the object for your result
Solved by disabling Volley cache
getRequest.setShouldCache(false);
postRequest.setShouldCache(false);

Unable to access REST API’s in Camunda

In our project , we are trying to use camunda BPMN. using camunda standalone distro and deployed and running in Tomcat.
login as a admin user and able to access cockpit and task lists.But,when we try access the APIs using a Java client . we are getting an unauthorized (401) error. Though we are sending JSESSIONID as a “Cookie”
Tried both DefaultHttpClient and HttpURLConnection - It didn’t work out
Note : JSESSIONID is retrieved by calling the login api with admin username and password.
Help me to solve the issue
Attached below is the java client code
public static void main(String[] args) {
CamundaBMPNClient bpmnClient = new CamundaBMPNClient();
Map<Integer, String> cookieHeader = bpmnClient.getCookieHeader();
bpmnClient.getListofTasks(cookieHeader);
}
public Map<Integer, String> getCookieHeader() {
String jSessionID = null;
Map<Integer, String> headerValues = new HashMap<Integer, String>();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(
"http://localhost:8090/camunda-webapp-tomcat-standalone-7.2.0/"
+ "api/admin/auth/user/default/login/cockpit");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.addHeader("Accept", "application/json");
String jsonString = new Gson()
.toJson("username=admin&password=admin#123");
StringEntity params;
try {
params = new StringEntity(jsonString);
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
Header[] cookieheader = response.getHeaders("Set-Cookie");
for (Header s : cookieheader) {
// Do your stuff here
System.out.println(s.getValue());
String[] str = s.getValue().split(";");
int i = 1;
for (String s1 : str) {
headerValues.put(i, s1.trim());
i++;
}
}
System.out.println("jSessionID::" + jSessionID);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return headerValues;
}
public void getListofTasks(Map<Integer, String> cookieHeader) {
int id = 0;
// DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(
"http://localhost:8090/camunda-webapp-tomcat-standalone-7.2.0/api/engine/engine/default/task");
request.addHeader("Content-type", "application/json");
String[] arrJSessionID = cookieHeader.get(1).split("=");
System.out.println("" + arrJSessionID[1]);
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID=",
arrJSessionID[1]);
cookie.setDomain("http://localhost:8090");
cookie.setPath("/camunda-webapp-tomcat-standalone-7.2.0/");
// cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");
cookieStore.addCookie(cookie);
// httpclient.setCookieStore(cookieStore);
HttpClient httpclient = HttpClientBuilder.create()
.setDefaultCookieStore(cookieStore).build();
String jsonString = new Gson().toJson("{}");
StringEntity jsonStr;
try {
jsonStr = new StringEntity(jsonString);
request.setEntity(jsonStr);
HttpResponse response = httpclient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
Header[] header = response.getHeaders("Set-Cookie");
for (Header h : header) {
System.out.println(h.getValue());
}
System.out.println("statusCode::" + statusCode);
} catch (Exception e) {
e.printStackTrace();
}
}

Integration of Market place with Integration bus in websphere

We have a requirement as below
Integration System needs to call our service
Our service needs to call FlipKart service appending the token in the request
Get the response back to Integration system
The above should work seamlessly for both GET and PUT requests.
I had developed a REST-project in eclipse and was able to get the GET and PUT response back to Integration.
However have few problems
In Get Requests, we are explicitly setting the headers and produces annotation to appication/json. How do we set it for all kind of requests?
In Post Response, we do not get the entire response and we are not able to set the application type in the response (Not sure how!)
All these requests are failing if the application type is pdf, img etc.
Can someone please help on the same?
Code implemented so far:
#GET
#Path("{pathvalue : (.+)?}")
#Produces("{application/json;application/octet-stream}")
public String getFlipKartResponse(#Context UriInfo uriInfo, #PathParam("pathvalue") String pathValue, #Context HttpServletRequest request) throws ClassNotFoundException,IOException {
String methodName = "getFlipKartResponse";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, methodName);
}
MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
//if(null == flipkartUrl || flipkartUrl.isEmpty())
flipkartUrl = config.getProperty(ServiceConstants.FLIPKART_URL);
String queryParam = new String();
Iterator<String> iterator = queryParams.keySet().iterator();
while (iterator.hasNext()) {
String parameter = iterator.next();
queryParam = queryParam.concat(parameter + ServiceConstants.EQUALS + queryParams.getFirst(parameter) + ServiceConstants.AMPERSAND);
}
String modifiedflipkartUrl = flipkartUrl.concat(pathValue).concat(ServiceConstants.QUESTION).concat(queryParam);
if (modifiedflipkartUrl.endsWith(ServiceConstants.QUESTION) || modifiedflipkartUrl.endsWith(ServiceConstants.AMPERSAND)) {
modifiedflipkartUrl = modifiedflipkartUrl.substring(0, modifiedflipkartUrl.length()-1);
}
LOGGER.log(Level.INFO, "Flipkart URL framed : "+ modifiedflipkartUrl);
url = new URL(modifiedflipkartUrl);
connection = (HttpsURLConnection) url.openConnection();
setHeadersInConnectionObject(url, connection, request.getMethod());
return handleInvalidToken(connection.getResponseCode(), request);
}
private String handleInvalidToken(int responseCode, HttpServletRequest request){
try {
if (connection.getResponseCode() == 401) {
LOGGER.log(Level.INFO, "ResponseCode " + connection.getResponseCode());
connection.disconnect();
regenerateAccessToken();
connection = (HttpsURLConnection) url.openConnection();
setHeadersInConnectionObject(url, connection, request.getMethod());
inputLine = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} else if (connection.getResponseCode() == 200) {
inputLine = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} else {
inputLine = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}
String responseInputLine;
String responseMessage = "";
while (null != (responseInputLine = inputLine.readLine())) {
responseMessage = responseMessage + responseInputLine;
}
inputLine.close();
connection.disconnect();
return responseMessage;
} catch (Exception e) {
LOGGER.log(Level.SEVERE,"Exception occured while calling service.Please try again after sometime : ", e);
return this.handleErrorResponse("Exception occured while calling service.Please try again after sometime.");
}
}
private void regenerateAccessToken() throws ClassNotFoundException, IOException, SQLException{
TokenGenerator tokenGenerator = new TokenGenerator();
accessToken= tokenGenerator.getAccessToken();
}
#POST
#Path("{pathvalue : (.+)?}")
#Produces({"application/json;application/octet-stream"})
public String getFlipKartPostResponse(#Context UriInfo uriInfo, #PathParam("pathvalue") String pathValue,#Context HttpServletRequest requestBody) throws ClassNotFoundException,IOException, SQLException {
String methodName = "getFlipKartPostResponse";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, methodName);
}
//if(null == flipkartUrl || flipkartUrl.isEmpty())
flipkartUrl = config.getProperty(ServiceConstants.FLIPKART_URL);
String modifiedflipkartUrl = flipkartUrl + pathValue;
url = new URL(modifiedflipkartUrl);
LOGGER.log(Level.INFO, "Flipkart URL framed : "+ flipkartUrl);
connection = (HttpsURLConnection) url.openConnection();
setHeadersInConnectionObject(url, connection, requestBody.getMethod());
InputStream requestInputStream = requestBody.getInputStream();
String reqBody = getStringFromInputStream(requestBody.getInputStream());
OutputStream outputStream = connection.getOutputStream();
outputStream.write(reqBody.getBytes());
outputStream.flush();
if(connection.getResponseCode() == 401) {
connection.disconnect();
regenerateAccessToken();
connection = (HttpsURLConnection) url.openConnection();
setHeadersInConnectionObject(url, connection, requestBody.getMethod());
outputStream = connection.getOutputStream();
outputStream.write(reqBody.getBytes());
outputStream.flush();
}
String output = getStringFromInputStream (connection.getInputStream());
connection.disconnect();
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.exiting(CLASSNAME, methodName);
}
return output;
}
private static String getStringFromInputStream(InputStream is) {
String methodName = "getStringFromInputStream";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, methodName);
}
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.exiting(CLASSNAME, methodName);
}
return sb.toString();
}
/**
* Method to generate the access token
* #return String - Access token
* #throws IOException
*/
private String getAccessToken() throws IOException {
if (null != accessToken) {
return accessToken;
} else {
url = getClass().getResource(ServiceConstants.ACCESS_TOKEN_CONFIG_PATH);
file = new File(url.getPath());
reader = new BufferedReader (new InputStreamReader (new FileInputStream (file), ServiceConstants.UTF_ENCODING));
accessToken = reader.readLine();
reader.close();
return accessToken;
}
}
/**
* Method to construct error response for exception scenario
* #param errorMessage
* #return
*/
private String handleErrorResponse(String errorMessage) {
String methodName = "handleErrorResponse";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, methodName);
}
JSONObject errorResponse = new JSONObject();
JSONArray errorMsg = new JSONArray();
errorResponse.put(ServiceConstants.STATUS, ServiceConstants.STATUS_FAILED);
errorResponse.put(ServiceConstants.ERROR_MESSAGE, errorMessage);
errorMsg.add(errorResponse);
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.exiting(CLASSNAME, methodName);
}
return errorResponse.toString();
}
/**
* Method to form the connection object
* #param url
* #param connection
* #param requestType
* #throws IOException
*/
private void setHeadersInConnectionObject(URL url, HttpsURLConnection connection, String requestType) throws IOException {
String methodName = "setHeadersInConnectionObject";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, methodName);
}
if (null == accessToken) {
getAccessToken();
}
connection.setRequestMethod(requestType);
connection.setRequestProperty(ServiceConstants.AUTHORIZATION, ServiceConstants.BEARER + accessToken);
connection.setDoOutput(true);
if (requestType.equals(ServiceConstants.REQUEST_TYPE_GET)) {
connection.setRequestProperty(ServiceConstants.ACCEPT_HEADER, ServiceConstants.ACCEPT_ALL);
//connection.setRequestProperty(ServiceConstants.ACCEPT_HEADER, ServiceConstants.APPLICATION_JSON);
}
if (requestType.equals(ServiceConstants.REQUEST_TYPE_POST)) {
connection.setRequestProperty(ServiceConstants.ACCEPT_HEADER, ServiceConstants.APPLICATION_JSON);
connection.setRequestProperty(ServiceConstants.CONTENT_TYPE_HEADER, ServiceConstants.APPLICATION_JSON);
//connection.setDoInput(true);
}
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.exiting(CLASSNAME, methodName);
}
}