From 402283304ef6cc48eae90ec159984b7ddab341ab Mon Sep 17 00:00:00 2001 From: vyshakhbabji Date: Sat, 26 Sep 2015 15:20:40 -0700 Subject: [PATCH] Platfrom ready --- bin/http/RCHeaders.class | Bin 3698 -> 0 bytes bin/http/RCRequest.class | Bin 1262 -> 0 bytes bin/http/RCResponse.class | Bin 265 -> 0 bytes bin/platform/Platform$1.class | Bin 608 -> 636 bytes bin/platform/Platform.class | Bin 7384 -> 10452 bytes build.gradle | 4 +- src/http/APIResponse.java | 147 ++++++++++++++ src/http/RCHeaders.java | 78 ------- src/http/RCRequest.java | 32 --- src/http/RCResponse.java | 5 - src/platform/Platform.java | 370 +++++++++++++++------------------- 11 files changed, 313 insertions(+), 323 deletions(-) delete mode 100644 bin/http/RCHeaders.class delete mode 100644 bin/http/RCRequest.class delete mode 100644 bin/http/RCResponse.class create mode 100644 src/http/APIResponse.java delete mode 100644 src/http/RCHeaders.java delete mode 100644 src/http/RCRequest.java delete mode 100644 src/http/RCResponse.java diff --git a/bin/http/RCHeaders.class b/bin/http/RCHeaders.class deleted file mode 100644 index 278b69fd750ca952db92f817e905a9367e292811..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3698 zcma)8XlkK$w6=7Hw_SxDpk;`5i1D68la`Nr9&KHFihyoM8VeX`@ZkX zN5Aw#SFG*RKJC~3g#L;CgSO|+ya^MM=c#-kGxvS(xyw24edo`Ae*O)>o%kw>8V${J zp10V0I(5P{&YF%JMV*Fq^Tq|EH)q(hy<;=;X4cc7r^eFbgX!_<@u^dT8WJO`TQZ(w z*|Yr`)(>aK($nP|DhGd1s-g z;N(m@n?EZE4RZ@Yy&5(Il@vTH*L%Wn=SGc1meQE9W^KbOIHrdEl{*G1%dfN?B2L3V zHfPzEcSu8RXV;{Lx)d{Lz$WQv-u6t}>lt5OG#jDeMja88XZDKQy#5zlx=_B?grry9k9vI7!ClO_-7 zI0zw{p)`~Q2~JUexFTiZ_VeblhFB>-QqxwfJ91zLP9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YNVuzzD?VccCbuwIyK=_`~sd$ zEF_v3pM3D6)ODsK7Rv)^J3Z^{+uD2W`T6V1Hvk*RYw!ug>W*`m+0F0D_ifp7Gz0{O z_l*xmreRpM%&YRgtT+OJaje_2p7$oWjJkH3T*a!Y;~{P zd_~7Lty;GKCdWJj2hyoGs{-+UyFicxZE^_j=69q~m3E6v3m$#%hDrQwyTMdjre!)g zf#h;OA+P+oE|MjI_65F|B;Q};l7XsjAm6OY2>ck+F@$mUu$(MunE0oT*Ion(jD;aE ztwYCP2;m6ka7Dwsz(}7mIu@|VWHm_vm%QG3RLv%P#@rP;tKr%?{kwXpk~egO5eXrt zz_N~*0#Q|eMMoN|0?|s-atzaIJ(rYe{Gx(yRd7Z}R0ZD_KnQmP^gIKl<*e=<9dZr{ z+|_Xp_t}0+I-X6L{!8lZQnI9yZt4hPKwzj~TJmN4pe*e@qugLjywI!|jgn!T3VW9U zr*8J{kGKA6nd|OyakB*y=R--s3m+^xM&%uSJRB)D+jd1hGgZOZ+1s?HG{GY2`T5EP z-QNI_#*>e|LyeSAsDbdwQDD%;oUV)65Qgd7jTk|kPK(T@^0iW@7)^ae;>{^0JD5tP z<1;6i{f?_0Tqjui3vQ<4$rGeL(%U_CUDl2fPQ`C^u$GRmd*;uWa)I(V!N$rDL{lpr zJUB)uCHVh|WdnG~XO6@`x&bc25I?h|nZyXzN%1j8v5hh8P|DYsfPpDUOk*E2IH0GE zd1M*A&}{=-ctpg8l!P3DI^}rsF%y`>=h;GMwh-^0xVGSLmhx*58s_-rlqaJB`aPx9 GhwVRAwjjR% diff --git a/bin/http/RCResponse.class b/bin/http/RCResponse.class deleted file mode 100644 index a2ed6773b42b8d6f636379b97a510529265f647d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 265 zcmZ8bF>b;@5S%qO4vvYP{2*PR;F@%aXpmA_K_Zd+vvYz&=8Wuf{*?-ef(P&@#2!M5 zL^HE9tKFI7X@3CliZp~rNLJQv#bUNl?Y1_p3gHvdwfvQ$l4dF9#afk?(0|uP+bN;< zGRg`5to~6EdKknA(C0syHtMt66sq}_MWqN&SzXF1myLG%YWjAiTf$>@6Z=MpzUr?- diff --git a/bin/platform/Platform$1.class b/bin/platform/Platform$1.class index 181fd01b4c7d74097f0e4d36d60ce1eb29ee7a60..005c393a295bed99d93db3cfa7b0632d9f36ab3c 100644 GIT binary patch delta 74 zcmaFB@`q)^8b%BD;?xqy(vl2D1_KSBf}F&XwEUu6eUON?PjY^)esN)GVo_>ofqs5= cMoCG5eo$(0L4ICw>f{rQk&HJcD>2yt0R0jhUjP6A delta 46 zcmeyv@_=Q-8b%q8#L|)s=fs>GMh0OGpRB~PME%l|%p856%;J*CPZ%Q^6DQj-*#Q84 Cu@AZc diff --git a/bin/platform/Platform.class b/bin/platform/Platform.class index 487854f22180b1415cc35f895fe44b5716fc41d6..bd280ecd8af7f6a4857345b9a908ad36f9357366 100644 GIT binary patch literal 10452 zcmcIq3wTu3wf6S<5{&AOg;E`fWLIFN*RW6`IBG-aqEH|fimwZ- zXy4$3Q-TqpaM zm@!iMxN$f6aRkQ}+@skW*CQmI3)AFNFzFDaW|))`Q<{94g~FY!$xzr?6mzC)2V1Iuq4#8zA@BYH+1rJ+GUEm zY2DoIv^X)k0R>byW6u@GkoN-t8^6HG2>$Bj-T8d53LSy(JMdcba6iPop1F}kH6i&TB{vDC&g zET^&-uV`*OzqM`UqVpRUG%r7E#hNBT_2CNIhekos#Z|iO3L7i&DHmd#c!btez(mxXMxYIAEu2e(9hlDn8|UHE zoEs(Vgi;A&%eX;vmwNqN;CzHETtJx&ERY?w(T*@(HtuZV?qjkm>Aaa{LHH5Vf&E*D0gN5{4}hbMk=PRh1u|h}%e@oA70nzM_N1k}pjc@eA3x zY9gt4LT4MBKgA0HGgkYMCOc;+I~#3mQg(b~#{>4y($H45E}nI|AD7^B7B0=6Dej~K z34JoQF_2XJxZ{a$@bfeQ~BCsmnlkV#4^RK5VzJO)%{+$Zh--JE-b*MP)+z@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xcEl*m~4omI=)?Vc18Q@kO sGIDK@5%YUkj_|pL|C78&9+21b-)*P)t$!oTi=*4({HKt}v2F410!_EU9RL6T diff --git a/build.gradle b/build.gradle index d17ee1d..b467d6a 100644 --- a/build.gradle +++ b/build.gradle @@ -9,7 +9,9 @@ dependencies { testCompile 'junit:junit:4.11' compile 'org.apache.httpcomponents:httpclient:4.5' compile 'com.fasterxml.jackson.core:jackson-databind:2.6.0' - compile 'com.google.code.gson:gson:2.3.1' + compile 'com.google.code.gson:gson:2.3.1' + compile 'com.squareup.okhttp:okhttp:2.5.0' + compile 'org.json:json:20141113' } \ No newline at end of file diff --git a/src/http/APIResponse.java b/src/http/APIResponse.java new file mode 100644 index 0000000..dcf5db4 --- /dev/null +++ b/src/http/APIResponse.java @@ -0,0 +1,147 @@ +package http; + + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; +import com.squareup.okhttp.ResponseBody; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.HashMap; + + +public class APIResponse { + + protected Response response; + protected Request request; + + public APIResponse(Request request, Response response) { + this.request = request; + this.response = response; + } + + public Request request() { + return this.response.request(); + } + + public Response response() { + return this.response; + } + + public boolean ok() { + int status = this.response.code(); + return (status >= 200 && status < 300); + } + + public Response raw() { + return response(); + } + + public ResponseBody body() { + return this.response.body(); + } + + public String text() { + + String responseAsText = ""; + try { + responseAsText = response.body().string(); + throw new IOException(); + } catch (IOException e) { + System.err.print("IOException occured while converting the HTTP response to string in Class: " + this.getClass().getName() + ": " + e.getMessage()); + } + + return responseAsText; + } + + public JSONObject json_dict() { + + JSONObject jObject = new JSONObject(); + try { + if (isContentType("application/json")) + jObject = new JSONObject(text()); + else { + throw new IOException(); + } + } catch (JSONException e) { + System.err.print("JSONException occured while converting the HTTP response to JSON Dictonary in Class: " + this.getClass().getName() + ": " + e.getMessage()); + } catch (IOException e) { + System.err.print("IOException occured while converting the HTTP response to JSON Dictonary in Class: " + this.getClass().getName() + ": " + e.getMessage()); + } + return jObject; + } + + + public JSONObject json() { + JSONObject object = new JSONObject(); + try { + object = new JSONObject(response.body().string()); + throw new IOException(); + } catch (JSONException e) { + System.err.print("JSONException occured while converting the HTTP response to JSON in Class: " + this.getClass().getName() + ": " + e.getMessage()); + } catch (IOException e) { + System.err.print("IOException occured while converting the HTTP response to JSON in Class: " + this.getClass().getName() + ": " + e.getMessage()); + } + return object; + } + + public HashMap hashMap() throws IOException { + Gson gson = new Gson(); + Type mapType = new TypeToken>() { + }.getType(); + HashMap jsonMap = new HashMap<>(); + try { + jsonMap = gson.fromJson(this.text(), mapType); + throw new IOException(); + } catch (IOException e) { + System.err.print("IOException occured while converting the HTTP response to JSON in Class: " + this.getClass().getName() + ": " + e.getMessage()); + } + return jsonMap; + } + + + public boolean isContentType(String contentType) { + return this.response().body().contentType().toString().equalsIgnoreCase(contentType); + } + + public String getContentType() { + return this.response.headers().get("Content-Type"); + } + + @SuppressWarnings("finally") + public String error() { + if (this.response == null || this.ok()) { + return null; + } + + String message = "HTTP" + this.response().code(); + + JSONObject data; + + + try { + data = this.json_dict(); + if (data.getString("message") != null) message = message + data.getString("message"); + else if (data.getString("error_description") != null) + message = message + data.getString("error_description"); + else if (data.getString("description") != null) + message = message + data.getString("description"); + + } catch (JSONException e) { + message = message + "JSONException occured in Class: " + this.getClass().getName() + ": " + e.getMessage(); + System.err.print("JSONException occured in Class: " + this.getClass().getName() + ": " + e.getMessage()); + } finally { + return message; + } + } + + //todo: multipart def + //todo: break_into_parts + + +} \ No newline at end of file diff --git a/src/http/RCHeaders.java b/src/http/RCHeaders.java deleted file mode 100644 index e140ef8..0000000 --- a/src/http/RCHeaders.java +++ /dev/null @@ -1,78 +0,0 @@ -package http; - -import java.util.HashMap; -import java.util.Map; - -public class RCHeaders { - - public static String CONTENT_TYPE = "Content-Type"; - - public static final String JSON_CONTENT_TYPE = "application/json"; - public static final String MULTIPART_CONTENT_TYPE = "multipart/mixed"; - public static final String URL_ENCODED_CONTENT_TYPE = "application/x-www-form-urlencoded"; - HashMap hmHeader; - - public RCHeaders() { - this.hmHeader = new HashMap<>(); - } - - public RCHeaders(HashMap headers) { - this.hmHeader = headers; - } - - public String getContentType() { - return hasHeader(CONTENT_TYPE) ? getHeader(CONTENT_TYPE) : ""; - } - - public String getHeader(String key) { - return this.hmHeader.get(key); - } - - public HashMap getHeaders() { - return hmHeader; - } - - public String[] getHeadersArray() { - String[] array = new String[this.hmHeader.size()]; - int count = 0; - for (Map.Entry entry : this.hmHeader.entrySet()) { - array[count] = entry.getKey() + ":" + entry.getValue(); - count++; - } - return array; - } - - public boolean hasHeader(String key) { - return this.hmHeader.containsKey(key); - } - - public boolean isContentType(String contentType) { - return (this.hmHeader.get(CONTENT_TYPE).contains(contentType)); - } - - public boolean isJson() { - return isContentType(JSON_CONTENT_TYPE); - } - - public boolean isMultipart() { - return isContentType(MULTIPART_CONTENT_TYPE); - } - - public boolean isURLEncoded() { - return isContentType(URL_ENCODED_CONTENT_TYPE); - } - - public void setContentType(String contentType) { - this.hmHeader.put(CONTENT_TYPE, contentType); - } - - public void setHeader(String key, String val) { - this.hmHeader.put(key, val); - } - - public void setHeaders(HashMap headers) { - for (Map.Entry entry : headers.entrySet()) { - setHeader(entry.getKey(), entry.getValue()); - } - } -} diff --git a/src/http/RCRequest.java b/src/http/RCRequest.java deleted file mode 100644 index e00ffe3..0000000 --- a/src/http/RCRequest.java +++ /dev/null @@ -1,32 +0,0 @@ -package http; - -import java.util.HashMap; - -public class RCRequest { - HashMap body; - String method; - String query; - public RCHeaders RCHeaders; - String url; - - public RCRequest(HashMap body, - HashMap headerMap) { - RCHeaders = new RCHeaders(); - this.method = headerMap.get("method"); - this.url = headerMap.get("url"); - if (headerMap.containsKey("query")) { - this.query = headerMap.get("query"); - } else { - this.query = ""; - } - if (headerMap.containsKey("Content-Type")) { - this.RCHeaders.setContentType(headerMap.get("Content-Type")); - } - if (body != null) { - this.body = body; - } else { - this.body = null; - } - } - -} diff --git a/src/http/RCResponse.java b/src/http/RCResponse.java deleted file mode 100644 index dc0183c..0000000 --- a/src/http/RCResponse.java +++ /dev/null @@ -1,5 +0,0 @@ -package http; - -public class RCResponse { - -} diff --git a/src/platform/Platform.java b/src/platform/Platform.java index 02a8a06..abf59da 100644 --- a/src/platform/Platform.java +++ b/src/platform/Platform.java @@ -1,9 +1,13 @@ package platform; +import http.APIResponse; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; import java.lang.reflect.Type; +import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; @@ -13,6 +17,8 @@ import javax.net.ssl.HttpsURLConnection; import javax.xml.bind.DatatypeConverter; +import okio.Buffer; + import org.apache.http.Consts; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; @@ -22,32 +28,40 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.client.methods.RequestBuilder; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; +import com.squareup.okhttp.Headers; +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Request.Builder; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.Response; +import com.squareup.okhttp.ResponseBody; +import com.squareup.okhttp.internal.http.HeaderParser; public class Platform { public enum ContentTypeSelection { - FORM_TYPE_MARKDOWN("application/x-www-form-urlencoded"), JSON_TYPE_MARKDOWN( - "application/json"), MULTIPART_TYPE_MARKDOWN( - "multipart/mixed; boundary=Boundary_1_14413901_1361871080888"); - - private String value; - + FORM_TYPE_MARKDOWN("application/x-www-form-urlencoded"), + JSON_TYPE_MARKDOWN("application/json"), + MULTIPART_TYPE_MARKDOWN( + "multipart/mixed; boundary=Boundary_1_14413901_1361871080888"); + public MediaType value; private ContentTypeSelection(String contentType) { - this.value = contentType; + this.value = MediaType.parse(contentType); } - } public enum Server { - PRODUCTION( - "https://platform.ringcentral.com"), SANDBOX("https://platform.devtest.ringcentral.com"); + "https://platform.ringcentral.com"), + SANDBOX("https://platform.devtest.ringcentral.com"); private String value; private Server(String url) { @@ -60,8 +74,14 @@ private Server(String url) { public String appSecret; Auth auth; final String authURL = "/restapi/oauth/token"; - + private HeaderParser headers ; public Server server; + Response response; + Request request; + + StackTraceElement l = new Exception().getStackTrace()[0]; + + public Platform(String appKey, String appSecret, Server server) { super(); @@ -71,47 +91,91 @@ public Platform(String appKey, String appSecret, Server server) { this.auth = new Auth(); } - public void authCall(List body) { - - HttpClient client = new DefaultHttpClient(); - HttpPost post = new HttpPost(server.value + authURL); - post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " - + encodeAPICredentialsToBase64()); - post.setHeader(HttpHeaders.CONTENT_TYPE, - ContentTypeSelection.FORM_TYPE_MARKDOWN.value); - post.setEntity(new UrlEncodedFormEntity(body, Consts.UTF_8)); - - HttpResponse response = null; + protected String createBodyString(HashMap body, ContentTypeSelection type) { + String bodyString = ""; + MediaType mediaType = type.value; try { - response = client.execute(post); - if (response.getStatusLine().getStatusCode() == 200) { - BufferedReader rd = new BufferedReader(new InputStreamReader( - response.getEntity().getContent())); - StringBuffer result = new StringBuffer(); - String line = ""; - while ((line = rd.readLine()) != null) { - result.append(line); + StringBuilder data = new StringBuilder(); + int count = 0; + if (!(mediaType == ContentTypeSelection.FORM_TYPE_MARKDOWN.value)) { + data.append("{ "); + } + for (HashMap.Entry entry : body.entrySet()) { + if (mediaType ==ContentTypeSelection.FORM_TYPE_MARKDOWN.value) { + if (count != 0) { + data.append("&"); + } + data.append(entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), "UTF-8")); + count++; + } else { + if (count != 0) { + data.append(", "); + } + data.append(entry.getKey()); + data.append(": "); + data.append(entry.getValue()); + count++; } - // System.out.println(result.toString()); - Gson gson = new Gson(); - Type HashMapType = new TypeToken>() { - }.getType(); - HashMap authData = gson.fromJson( - result.toString(), HashMapType); - setAuth(auth, authData); } - } catch (IOException e1) { - e1.printStackTrace(); + if (!(mediaType ==ContentTypeSelection.FORM_TYPE_MARKDOWN.value)) { + data.append(" }"); + } + bodyString = data.toString(); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return bodyString; + } + + protected String bodyToString(final Request request){ + try { + final Request copy = request.newBuilder().build(); + final Buffer buffer = new Buffer(); + copy.body().writeTo(buffer); + System.out.println(copy.header("Authorization")); + + System.out.println(copy.header("Content-Type")); + return buffer.readUtf8(); + } catch (final IOException e) { + return "did not work"; } } + + public void authCall(HashMap body) { + + String URL = server.value + authURL; + OkHttpClient client = new OkHttpClient(); + Request.Builder requestBuilder = new Request.Builder(); + request = requestBuilder + .url(URL). + addHeader(HttpHeaders.AUTHORIZATION, "Basic "+encodeAPICredentialsToBase64()). + addHeader(HttpHeaders.CONTENT_TYPE,ContentTypeSelection.FORM_TYPE_MARKDOWN.value.toString()). + post(RequestBody.create(ContentTypeSelection.FORM_TYPE_MARKDOWN.value, createBodyString(body, ContentTypeSelection.FORM_TYPE_MARKDOWN))). + build(); + + System.out.println("Check Body of Request: "+bodyToString(request)); + + try { + response = client.newCall(request).execute(); + if (response.isSuccessful()) + setAuth(auth, response); + else + System.out.println("Authorization not successful"); + //throw new IOException(); + } catch (IOException e) { + System.err.print("Failed Authorization. IOException occured in Class: " + this.getClass().getName() + ": " + e.getMessage() +l.getClassName()+"/"+l.getMethodName()+":"+l.getLineNumber()); + } + } + + public void authorize(String username, String extension, String password) { - List body = new ArrayList(); - body.add(new BasicNameValuePair("username", username)); - body.add(new BasicNameValuePair("password", password)); - body.add(new BasicNameValuePair("extension", extension)); - body.add(new BasicNameValuePair("grant_type", "password")); + HashMap body = new HashMap(); + body.put("username", username); + body.put("password", password); + body.put("extension", extension); + body.put("grant_type", "password"); authCall(body); @@ -135,181 +199,73 @@ public Auth getAuth() { return auth; } - public void setAuth(Auth auth, HashMap authData) { - this.auth.setData(authData); - } + public void setAuth(Auth auth, Response response) { + BufferedReader rd; + HashMap data= new HashMap(); + try { + rd = new BufferedReader(new InputStreamReader( + response.body().byteStream())); + StringBuffer result = new StringBuffer(); + String line = ""; + while ((line = rd.readLine()) != null) { + result.append(line); + } + // System.out.println(result.toString()); + Gson gson = new Gson(); + Type HashMapType = new TypeToken>() { + }.getType(); + data= gson.fromJson( + result.toString(), HashMapType); + } catch (IOException e) { + System.err.print("Failed Authorization. IOException occured in Class: " + this.getClass().getName() + ": " + e.getMessage()+l.getClassName()+"/"+l.getMethodName()+":"+l.getLineNumber()); + } + this.auth.setData(data); - //apiCall("post", "/call-log", "{body}", header) + } - //Additionals + public Builder requestBuilder( HashMap hm) { + if(hm==null){ + hm= new HashMap(); + } + hm.put("Authorization", getAuthHeader()); + Builder requestBuilder = new Request.Builder(); + for (Entry entry : hm.entrySet()) { + requestBuilder.addHeader(entry.getKey(), entry.getValue()); + } + return requestBuilder; + } - public HttpResponse apiCall(String method, String apiURL, LinkedHashMap body, HashMap headerMap) throws IOException { + public APIResponse apiCall(String method, String apiURL, RequestBody body, HashMap headerMap) throws IOException { //this.isAuthorized(); - String URL = server.value+apiURL; - - HttpClient client = HttpClientBuilder.create().build(); - HttpResponse response=null; - if(headerMap==null){ - headerMap= new HashMap(); - } - - headerMap.put("Authorization", getAuthHeader()); - if(method.equalsIgnoreCase("get")){ - HttpGet httpget = new HttpGet(URL); - for (Entry entry : headerMap.entrySet()) { - httpget.addHeader(entry.getKey(), entry.getValue()); + OkHttpClient client = new OkHttpClient(); + try{ + System.out.println(getAuthHeader()); + if(method.equalsIgnoreCase("get")){ + request = requestBuilder(headerMap).url(URL).build(); + } + else if (method.equalsIgnoreCase("delete")){ + request = requestBuilder(headerMap).url(URL).delete().build(); + } + else{ + if(method.equalsIgnoreCase("post")){ + request=requestBuilder(headerMap).url(URL).post(body).build(); + } + else if(method.equalsIgnoreCase("put")){ + request = requestBuilder(headerMap).url(URL).put(body).build(); + } } - response = client.execute(httpget); - } - return response; + } catch (Exception e) { + System.err.print("Failed APICall. Exception occured in Class: " + this.getClass().getName() + ": " + e.getMessage()+l.getClassName()+"/"+l.getMethodName()+":"+l.getLineNumber()); + } + response = client.newCall(request).execute(); + return new APIResponse(request,response); } - - - - // - //BufferedReader in = null; - // - //String output = ""; - //try { - // - // StringBuilder data = new StringBuilder(); - // byte[] byteArray = data.toString().getBytes("UTF-8"); - // - // URL requests = new URL(urll); - // httpConn = (HttpsURLConnection) requests.openConnection(); - // httpConn.setRequestMethod("GET"); - // httpConn.setRequestProperty( - // "Authorization", - // "Bearer "+getAccessToken().toString()); - // httpConn.setDoOutput(true); - // System.out.println("Here"); - // InputStreamReader reader = new InputStreamReader( - // httpConn.getInputStream()); - // in = new BufferedReader(reader); - // System.out.println("Done"); - // StringBuffer content = new StringBuffer(); - // String line; - // while ((line = in.readLine()) != null) { - // content.append(line + "\n"); - // } - // in.close(); - // - // String json = content.toString(); - // Date date = new Date(); - // output = "--------------"+date+"-------------------\n"; - // output = output+ json; - // System.out.println("presence : "+ json); - // - //} catch (java.io.IOException e) { - // output = output+ e.getMessage(); - // System.out.println(e.getMessage()); - // - //} finally { - // if (in != null) - // in.close(); - // if (httpConn != null) - // httpConn.disconnect(); - //} - // - //output=output+"\n --------------------------------------------\n\n\n"; - // - // - //} - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - - - - - - - - - - - - // - // - // - // - // OkHttpClient client = new OkHttpClient(); - // //Check if the Platform is authorized, and add the authorization header - // this.isAuthorized(); - // headerMap.put("Authorization", this.getAuthHeader()); - // //Generate the proper url to be passed into the request - // HashMap options = new HashMap<>(); - // options.put("addServer", "true"); - // String apiUrl = apiURL(url, options); - // - // Request.Builder requestBuilder = new Request.Builder(); - // //Add all the headers to the Request.Builder from the headerMap - // for (Map.Entry entry : headerMap.entrySet()) { - // requestBuilder.addHeader(entry.getKey(), entry.getValue()); - // } - // Request request = null; - // if (method.toUpperCase().equals("GET")) { - // request = requestBuilder - // .url(apiUrl) - // .build(); - // } else if (method.toUpperCase().equals("DELETE")) { - // request = requestBuilder - // .url(apiUrl) - // .delete() - // .build(); - // } else { - // //For POST and PUT requests, find and set what MediaType the body is - // MediaType mediaType; - // if (headerMap.containsValue("application/json")) { - // mediaType = MediaType.parse(ContentTypeSelection.JSON_TYPE_MARKDOWN.toString()); - // } else if (headerMap.containsValue("multipart/mixed")) { - // mediaType = MediaType.parse(ContentTypeSelection.MULTIPART_TYPE_MARKDOWN.toString()); - // } else { - // mediaType =MediaType.parse(ContentTypeSelection.FORM_TYPE_MARKDOWN.toString()); - // } - // String bodyString = getBodyString(body, mediaType); - // if (method.toUpperCase().equals("POST")) { - // request = requestBuilder - // .url(apiUrl) - // .post(RequestBody.create(mediaType, bodyString)) - // .build(); - // } else if (method.toUpperCase().equals("PUT")) { - // request = requestBuilder - // .url(apiUrl) - // .put(RequestBody.create(mediaType, bodyString)) - // .build(); - // } - // } - // //Make OKHttp request call, that returns response to the callback - // client.newCall(request).enqueue(callback); - // } catch (Exception e) { - // e.printStackTrace(); - // } }