Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
/*
* Copyright 2016 Mohamed Kiswani.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.rhkiswani.javaff.httpclient;

import io.github.rhkiswani.javaff.exceptions.SmartException;
import io.github.rhkiswani.javaff.httpclient.exceptions.HttpClientException;
import io.github.rhkiswani.javaff.httpclient.util.IOUtil;
import io.github.rhkiswani.javaff.json.JsonHandlerFactory;
import io.github.rhkiswani.javaff.reflection.ReflectionUtil;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author Mohamed Kiswani
* @since 0.0.20
*
*/
public class ApacheHttpClient2 implements HttpClient{

@Override
public String postJson(String url, String json, Map<String, String> headers) throws HttpClientException {
return doJsonRequest(new HttpPost(url), json, headers);
}

@Override
public String putJson(String url, String json, Map<String, String> headers) throws HttpClientException {
return doJsonRequest(new HttpPut(url), json, headers);
}

private String doJsonRequest(HttpRequestBase method, String json, Map<String, String> headers) {
try {
if (json == null){
throw new HttpClientException(SmartException.NULL_VAL, "Json Object");
}
CloseableHttpClient c = HttpClientBuilder.create().build();
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recommendation generated by Amazon CodeGuru Reviewer

Problem
This line of code might contain a resource leak. Resource leaks can cause your system to slow down or crash.

Fix
Consider closing the following resource: c. Currently, there are execution paths that do not contain closure statements. Either a) close c in a try-finally block or b) close the resource by declaring c in a try-with-resources block.

More info
View resource management guidelines at oracle.com (external link).

((HttpEntityEnclosingRequestBase) method).setEntity(new StringEntity(json));
method.setHeader("Accept", "application/json");
method.setHeader("Content-type", "application/json");
setHeaders(method, headers);
return handleResponse(method, c);
} catch (Exception e) {
throw new HttpClientException(e.getMessage());
}
}

private String handleResponse(HttpRequestBase method, CloseableHttpClient c) {
HashMap<String, Object> hashMap = new HashMap<>();
try {
HttpResponse response = c.execute(method);
hashMap.put("response", IOUtil.inputStreamToString(response.getEntity().getContent()));
hashMap.put("status", response.getStatusLine().getStatusCode());
hashMap.put("headers", IOUtil.headersToMap(response.getAllHeaders()));
} catch (Exception ex) {
hashMap.put("status", HttpStatus.SC_BAD_REQUEST );
hashMap.put("errors", ReflectionUtil.getErrorsAsArray(ex));
}
return JsonHandlerFactory.getJsonHandler(HashMap.class).toJson(hashMap);
}

@Override
public String post(String url, Map<String, String> params, Map<String, String> headers) throws HttpClientException {
return doRequest(new HttpPost(url), params, headers);
}

@Override
public String put(String url, Map<String, String> params, Map<String, String> headers) throws HttpClientException {
return doRequest(new HttpPut(url), params, headers);
}

private String doRequest(HttpRequestBase method, Map<String, String> params, Map<String, String> headers) {
try {
CloseableHttpClient c = prepareRequest(method, params);
setHeaders(method, headers);
return handleResponse(method, c);
} catch (Exception e) {
throw new HttpClientException(e.getMessage());
}
}

private CloseableHttpClient prepareRequest(HttpRequestBase method, Map<String, String> params) throws UnsupportedEncodingException {
CloseableHttpClient c = HttpClientBuilder.create().build();
Copy link
Owner Author

@rhkiswani rhkiswani Dec 13, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Problem
This line of code contains a resource that might not be closed properly. Resource leaks can cause your system to slow down or crash.

Fix
Consider closing the following resource: c. The resource is returned at line: 119. There are other execution paths that neither close the resource nor return it, e.g., when exception is thrown by BasicNameValuePair constructor, and if-branch is taken at line 109. Either a) close c in a try-finally block or b) close the resource by declaring c in a try-with-resources block.

More info
View resource management guidelines at oracle.com (external link).

if(params != null){
List<NameValuePair> urlParameters = new ArrayList<>();
for (String key : params.keySet()) {

urlParameters.add(new BasicNameValuePair(key, params.get(key)));
}
if (method instanceof HttpEntityEnclosingRequestBase){
((HttpEntityEnclosingRequestBase) method).setEntity(new UrlEncodedFormEntity(urlParameters));
}
}
return c;
}

private void setHeaders(HttpRequestBase method, Map<String, String> headers) {
if(headers != null){
for (String header : headers.keySet()) {
method.setHeader(header, headers.get(header));
}
}
}

@Override
public String get(String url, Map<String, String> params, Map<String, String> headers) throws HttpClientException {
String urlWithParams = paramsToString(url, params);
return doRequest(new HttpGet(urlWithParams), params, headers);
}

private String paramsToString(String url, Map<String, String> params) {
String urlWithParams = url;
if(params != null){
urlWithParams += "?";
for (String key : params.keySet()) {
urlWithParams += key + "=" + params.get(key) +"&";
}
}
return urlWithParams;
}

@Override
public Map<String, String> head(String url, Map<String, String> params, Map<String, String> headers) throws HttpClientException {
try {
HttpHead method = new HttpHead(url);
CloseableHttpClient client = prepareRequest(method, params);
setHeaders(method, headers);
HttpResponse response = client.execute(method);
Header[] s = response.getAllHeaders();
Map<String, String> returnedHeaders = new HashMap<>();
for (Header header : s) {
returnedHeaders.put(header.getName(), header.getValue());
}
return returnedHeaders;
} catch (Exception e) {
throw new HttpClientException(e.getMessage());
}
}

@Override
public String delete(String url, Map<String, String> params, Map<String, String> headers) throws HttpClientException {
String urlWithParams = paramsToString(url, params);
return doRequest(new HttpDelete(urlWithParams), params, headers);
}

@Override
public Map<String, String> options(String url, Map<String, String> params, Map<String, String> headers) throws HttpClientException {
return head(url, params, headers);
}


@Override
public String patchJson(String url, String json, Map<String, String> headers) throws HttpClientException {
return doJsonRequest(new HttpPatch(url), json, headers);
}
}