Commit ae92bfbd by Eli Ben Baruch

## 1.2.3:

 - add "mavenLocal", for local repository. enables to check this dependency locally
 - Handle correctly Exceptions in http requsts/responses
 - support Encoding type (other than utf8) in http responses
parent 6f707c20
### general utils
## 1.2.3:
- add "mavenLocal", for local repository. enables to check this dependency locally
- Handle correctly Exceptions in http requsts/responses
- support Encoding type (other than utf8) in http responses
group 'com.ipgallery.common'
version '1.1.2'
version '1.1.3'
apply plugin: 'java'
apply plugin: 'maven-publish'
//for mavenLocal
//apply plugin: 'maven'
sourceCompatibility = 1.8
repositories {
//mavenCentral()
//use mavenLocal in cases you want to create this jar on your local machine
//or to be able to use one
//mavenLocal()
maven { url "http://172.16.1.132:8081/repository/internal" }
maven { url "http://mandubian-mvn.googlecode.com/svn/trunk/mandubian-mvn/repository" }
}
......@@ -27,6 +33,18 @@ dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'
}
//1. use this install task (under "other" section)to create this jar localy on your machine.
// version will be extended with the Postfix "-LOCAL"
//2. in order to use this jar in a project:
// in the build.gradle add "mavenLocal()" as first repository
//and the dependency with correct version number ended with "-LOCAL"
//install {
// repositories.mavenInstaller {
// pom.version = version + '-LOCAL'
// }
//}
publishing {
publications {
......
......@@ -49,13 +49,13 @@ public class SimpleHttpClient {
public void shutdown() throws Throwable
{
defaulthttpClient.getConnectionManager().shutdown();
}
}
public SimpleHttpResponse processRequest(SimpleHttpRequest request) throws UnsupportedEncodingException {
HttpUriRequest uriRequest = request.build();
org.apache.http.HttpResponse resultResp = null;
SimpleHttpResponse response = null;
SimpleHttpResponse response = null;
try {
// add cookies
if (request.getCookies().size() > 0) {
......@@ -63,19 +63,22 @@ public class SimpleHttpClient {
cookieStore.addCookie(cookie);
}
}
defaulthttpClient.setCookieStore(cookieStore);
defaulthttpClient.setCookieStore(cookieStore);
// send the request
resultResp = defaulthttpClient.execute(uriRequest);
if (resultResp != null) {
response = ParseResponseAndCookies(resultResp, defaulthttpClient.getCookieStore());
return response;
}
} catch (Exception e) {
}else
{
return new SimpleHttpResponse(500, "request execution failed");
}
} catch (Exception e) {
return new SimpleHttpResponse(500, e.toString());
}
return null;
}
public SimpleHttpResponse ParseResponseAndCookies(org.apache.http.HttpResponse response, CookieStore cookieStore) {
......@@ -99,7 +102,17 @@ public class SimpleHttpClient {
try {
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
BufferedReader rd;
Header contentEncoding = response.getEntity().getContentEncoding();
String contentEncodingValue = null;
if (contentEncoding != null)
contentEncodingValue = contentEncoding.getValue();
if (contentEncodingValue!= null)
rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),
contentEncodingValue));
else
rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
......
......@@ -178,7 +178,7 @@ public class SimpleHttpRequest {
return getRequest;
}
protected HttpUriRequest buildPostRequest() {
protected HttpUriRequest buildPostRequest() throws UnsupportedEncodingException {
// build URI
StringBuilder sb = new StringBuilder();
......@@ -206,19 +206,15 @@ public class SimpleHttpRequest {
// add content
if (content != null) {
try {
StringEntity contentEntity = new StringEntity(content,"UTF-8");
contentEntity.setContentType(contentType);
postRequest.setEntity(contentEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
StringEntity contentEntity = new StringEntity(content,"UTF-8");
contentEntity.setContentType(contentType);
postRequest.setEntity(contentEntity);
}
return postRequest;
}
protected HttpUriRequest buildPutRequest() {
protected HttpUriRequest buildPutRequest() throws UnsupportedEncodingException {
// build URI
StringBuilder sb = new StringBuilder();
......@@ -246,15 +242,11 @@ public class SimpleHttpRequest {
// add content
if (content != null) {
try {
StringEntity contentEntity = new StringEntity(content);
//contentEntity.setContentType("application/json");
contentEntity.setContentType(contentType);
putRequest.setEntity(contentEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
return putRequest;
}
......
......@@ -26,5 +26,24 @@ public class SimpleHttpResponse {
public Map<String, String> getHeaders() { return headers; }
public void setHeaders(Map<String, String> headers) { this.headers = headers; }
public String getContent() { return content; }
public void setContent(String content) { this.content = content; }
public void setContent(String content) { this.content = content; }
@Override
public String toString() {
StringBuilder respString;
try {
respString = new StringBuilder("statusCode=").append(statusCode).append(" content=");
if (content == null)
respString.append("null");
else
respString.append(content);
}
catch (Exception e){
return super.toString();
}
return respString.toString();
}
}
......@@ -18,24 +18,24 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonParser;
import com.google.gdata.util.common.base.PercentEscaper;
public class SimpleRestClient extends SimpleHttpClient {
public class SimpleRestClient extends SimpleHttpClient {
private static final String EMPTY_RESPONSE = "Empty response";
protected String domain = null;
protected String app = null;
protected int port = 0;
protected ObjectMapper objMapper = new ObjectMapper();
protected Map<String,String> headers = null;
public SimpleRestClient(String app, String ip, int port) {
super();
super();
this.app = app;
this.domain = ip;
this.port = port;
this.port = port;
}
public SimpleRestClient(String app, String IpPort) {
super();
this.app = app;
......@@ -43,40 +43,40 @@ import com.google.gdata.util.common.base.PercentEscaper;
this.domain = parts[0];
this.port = Integer.parseInt(parts[1]);
}
public void setCustomHeader(String headerName, String headerValue) {
if (this.headers == null)
this.headers = new HashMap<String, String>();
this.headers.put(headerName, headerValue);
}
public String getDomain() {
return domain;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public int getPort() {
return port;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public void setPort(int port) {
this.port = port;
}
/******************************************************************************
*
/******************************************************************************
*
* HTTP get methods
*
*****************************************************************************/
public SimpleRestResponse get(String entity, String[] params, String requestParams) {
String paramPath = "";
if (params != null) {
for (int i=0; i<params.length; i++) {
for (int i=0; i<params.length; i++) {
paramPath += "/" +params[i];
}
return get(entity, paramPath, requestParams);
......@@ -86,23 +86,26 @@ import com.google.gdata.util.common.base.PercentEscaper;
}
public SimpleRestResponse get(String entity, String params, String requestParams) {
SimpleHttpRequest request = buildGetRequest(entity, params, requestParams);
try {
SimpleHttpResponse httpResp = processRequest(request);
if(httpResp.getStatusCode() == 200)
return getResponseHandler(httpResp.getContent());
else
return new SimpleRestResponse(false, httpResp.getContent(),null);
return buildResp(httpResp);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
return new SimpleRestResponse(false, e.toString(),null);
}
}
private SimpleRestResponse buildResp(SimpleHttpResponse httpResp) {
if(httpResp.getStatusCode() == 200)
return getResponseHandler(httpResp.getContent());
else
return new SimpleRestResponse(false, httpResp.toString(),null);
}
public StringResponse getAsString(String entity, String[] params, String requestParams) {
String paramPath = "";
if (params != null) {
for (int i=0; i<params.length; i++) {
......@@ -115,27 +118,26 @@ import com.google.gdata.util.common.base.PercentEscaper;
}
public StringResponse getAsString(String entity, String params, String requestParams) {
SimpleHttpRequest request = buildGetRequest(entity, params, requestParams);
try {
SimpleHttpResponse resp = processRequest(request);
if (resp != null)
return new StringResponse(resp.getStatusCode(), resp.getContent());
if (resp != null)
return new StringResponse(resp.getStatusCode(), resp.getContent());
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
return new StringResponse(500, "Failed to process request(GET). Exception: "+e.toString());
}
return new StringResponse(500, "Failed to process the request(GET)");
}
/******************************************************************************
*
*
* HTTP post methods
*
*****************************************************************************/
public SimpleRestResponse post(String entity, String[] params, String requestParams, String content) {
String paramPath = "";
if (params != null) {
for (int i=0; i<params.length; i++) {
......@@ -146,25 +148,20 @@ import com.google.gdata.util.common.base.PercentEscaper;
else
return post(entity, (String)null, requestParams, content);
}
public SimpleRestResponse post(String entity, String params, String requestParams, String content) {
SimpleHttpRequest request = buildPostRequest(entity, params, requestParams, content);
try {
SimpleHttpResponse httpResp = processRequest(request);
if(httpResp.getStatusCode() == 200)
return getResponseHandler(httpResp.getContent());
else
return new SimpleRestResponse(false, httpResp.getContent(),null);
return buildResp(httpResp);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
return new SimpleRestResponse(false, e.toString(),null);
}
}
public String postAsString(String entity, String[] params, String requestParams, String content) {
String paramPath = "";
if (params != null) {
for (int i=0; i<params.length; i++) {
......@@ -175,29 +172,29 @@ import com.google.gdata.util.common.base.PercentEscaper;
else
return postAsString(entity, (String[])null, requestParams, content);
}
public String postAsString(String entity, String params, String requestParams, String content) {
SimpleHttpRequest request = buildPostRequest(entity, params, requestParams, content);
try {
SimpleHttpResponse resp = processRequest(request);
if (resp != null)
return resp.getContent();
return resp.getContent();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
/******************************************************************************
*
*
* HTTP put methods
*
*****************************************************************************/
public SimpleRestResponse put(String entity, String[] params, String requestParams, String content) {
String paramPath = "";
if (params != null) {
for (int i=0; i<params.length; i++) {
......@@ -208,30 +205,25 @@ import com.google.gdata.util.common.base.PercentEscaper;
else
return put(entity, (String)null, requestParams, content);
}
public SimpleRestResponse put(String entity, String params, String requestParams, String content) {
SimpleHttpRequest request = buildPutRequest(entity, params, requestParams, content);
try {
SimpleHttpResponse httpResp = processRequest(request);
if(httpResp.getStatusCode() == 200)
return getResponseHandler(httpResp.getContent());
else
return new SimpleRestResponse(false, httpResp.getContent(),null);
return buildResp(httpResp);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
return new SimpleRestResponse(false, e.toString(),null);
}
}
/******************************************************************************
*
*
* HTTP delete methods
*
*****************************************************************************/
public SimpleRestResponse delete(String entity, String[] params, String requestParams) {
String paramPath = "";
if (params != null) {
for (int i=0; i<params.length; i++)
......@@ -241,25 +233,20 @@ import com.google.gdata.util.common.base.PercentEscaper;
else
return delete(entity, (String)null, requestParams);
}
public SimpleRestResponse delete(String entity, String params, String requestParams) {
SimpleHttpRequest request = buildDeleteRequest(entity, params, requestParams);
SimpleHttpRequest request = buildDeleteRequest(entity, params, requestParams);
try {
SimpleHttpResponse httpResp = processRequest(request);
if(httpResp.getStatusCode() == 200)
return getResponseHandler(httpResp.getContent());
else
return new SimpleRestResponse(false, httpResp.getContent(),null);
return buildResp(httpResp);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
return new SimpleRestResponse(false, e.toString(),null);
}
}
public String deleteAsString(String entity, String[] params, String requestParams) {
String paramPath = "";
if (params != null) {
for (int i=0; i<params.length; i++) {
......@@ -272,25 +259,25 @@ import com.google.gdata.util.common.base.PercentEscaper;
}
public String deleteAsString(String entity, String params, String requestParams) {
SimpleHttpRequest request = buildDeleteRequest(entity, params, requestParams);
try {
SimpleHttpResponse resp = processRequest(request);
if (resp != null)
return resp.getContent();
if (resp != null)
return resp.getContent();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
/******************************************************************************
*
*
* helper methods
*
*****************************************************************************/
protected SimpleRestResponse getResponseHandler(String respString)
{
SimpleRestResponse rr = null;
......@@ -298,7 +285,7 @@ import com.google.gdata.util.common.base.PercentEscaper;
{
try
{
rr = objMapper.readValue(respString, SimpleRestResponse.class);
rr = objMapper.readValue(respString, SimpleRestResponse.class);
if (rr != null)
rr.prepare(objMapper);
} catch (Exception e)
......@@ -313,11 +300,11 @@ import com.google.gdata.util.common.base.PercentEscaper;
}
return rr;
}
protected SimpleHttpRequest buildGetRequest(String entity, String params, String requestParams) {
SimpleHttpRequest request = new SimpleHttpRequest();
request.setMethod(SimpleHttpRequest.Method.GET);
request.setDomain(this.domain);
request.setPort(this.port);
......@@ -328,13 +315,13 @@ import com.google.gdata.util.common.base.PercentEscaper;
request.setQueryString(requestParams);
buildHeaders(request);
//request.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
return request;
return request;
}
protected SimpleHttpRequest buildPostRequest(String entity, String params, String requestParams, String content) {
SimpleHttpRequest request = new SimpleHttpRequest();
request.setMethod(SimpleHttpRequest.Method.POST);
request.setDomain(this.domain);
request.setPort(this.port);
......@@ -352,9 +339,9 @@ import com.google.gdata.util.common.base.PercentEscaper;
}
protected SimpleHttpRequest buildPutRequest(String entity, String params, String requestParams, String content) {
SimpleHttpRequest request = new SimpleHttpRequest();
request.setMethod(SimpleHttpRequest.Method.PUT);
request.setDomain(this.domain);
request.setPort(this.port);
......@@ -372,9 +359,9 @@ import com.google.gdata.util.common.base.PercentEscaper;
}
protected SimpleHttpRequest buildDeleteRequest(String entity, String params, String requestParams) {
SimpleHttpRequest request = new SimpleHttpRequest();
request.setMethod(SimpleHttpRequest.Method.DELETE);
request.setDomain(this.domain);
request.setPort(this.port);
......@@ -387,20 +374,20 @@ import com.google.gdata.util.common.base.PercentEscaper;
// request.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
return request;
}
protected void buildHeaders(SimpleHttpRequest request) {
if (headers == null) {
// set default headers
if (request.getMethod() == SimpleHttpRequest.Method.GET) {
request.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
}
request.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
}
else if (request.getMethod() == SimpleHttpRequest.Method.POST) {
request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
request.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
request.addHeader(HttpHeaders.ACCEPT_ENCODING, "gzip, deflate");
} else if (request.getMethod() == SimpleHttpRequest.Method.DELETE) {
request.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
}
}
else {
......@@ -412,13 +399,13 @@ import com.google.gdata.util.common.base.PercentEscaper;
}
}
protected String buildPath(String entity, String params, String requestParams) {
// build path
StringBuilder sb = new StringBuilder();
if (this.app != null)
sb.append(this.app);
StringBuilder sb = new StringBuilder();
if (this.app != null)
sb.append(this.app);
if (entity != null) {
if (entity.charAt(0) != '/')
sb.append("/" + entity);
......@@ -426,11 +413,11 @@ import com.google.gdata.util.common.base.PercentEscaper;
sb.append(entity);
}
if (params != null) {
if (params.charAt(0) != '/')
if (params.charAt(0) != '/')
sb.append("/" + params);
else
sb.append(params);
sb.append(params);
}
return sb.toString();
}
}
}
import http.simpleRestClient.SimpleRestClient;
import http.simpleRestClient.SimpleRestResponse;
import org.junit.Test;
/**
* Created by eli on 7/26/16.
*/
public class TestSimpleRestClient {
@Test
public void testSimpleRestClient(){
SimpleRestClient restClient = new SimpleRestClient("mde", "172.16.1.56:50040");
SimpleRestResponse resp;
restClient.Initialize(100);
//wrong params to get 404
resp = restClient.get("\"/api/v1/\"", "chicago/transportation/routes", "key=gT2nciTKwRv6Jy5njqm8fe7LW");
System.out.println("resp for get is: "+resp.toString());
resp = restClient.post("\"/api/v1/\"", "chicago/transportation/routes", "key=gT2nciTKwRv6Jy5njqm8fe7LW",null);
System.out.println("resp for post is: "+resp.toString());
resp = restClient.get("/api/v1/", "chicago/transportation/routes", "key=gT2nciTKwRv6Jy5njqm8fe7LW");
System.out.println("resp for get is: "+resp.toString());
//domain for http tests http://httpbin.org/post
restClient = new SimpleRestClient("post", "httpbin.org:80");
restClient.Initialize(100);
resp = restClient.post(null, (String)null, null,null);
System.out.println("resp for get is: "+resp.toString());
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment