diff --git a/bin/http/RCHeaders.class b/bin/http/RCHeaders.class deleted file mode 100644 index 278b69f..0000000 Binary files a/bin/http/RCHeaders.class and /dev/null differ diff --git a/bin/http/RCRequest.class b/bin/http/RCRequest.class deleted file mode 100644 index 3a8cce9..0000000 Binary files a/bin/http/RCRequest.class and /dev/null differ diff --git a/bin/http/RCResponse.class b/bin/http/RCResponse.class deleted file mode 100644 index a2ed677..0000000 Binary files a/bin/http/RCResponse.class and /dev/null differ diff --git a/bin/platform/Platform$1.class b/bin/platform/Platform$1.class index 181fd01..005c393 100644 Binary files a/bin/platform/Platform$1.class and b/bin/platform/Platform$1.class differ diff --git a/bin/platform/Platform.class b/bin/platform/Platform.class index 487854f..bd280ec 100644 Binary files a/bin/platform/Platform.class and b/bin/platform/Platform.class differ 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(); - // } }