Skip to content

Commit

Permalink
Updating http connection management.... Broken
Browse files Browse the repository at this point in the history
  • Loading branch information
bwssytems committed Aug 30, 2017
1 parent 2814431 commit 5231eac
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 38 deletions.
91 changes: 80 additions & 11 deletions src/main/java/com/bwssystems/HABridge/plugins/http/HTTPHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import org.apache.http.HttpClientConnection;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.CookieSpecs;
Expand All @@ -13,10 +18,17 @@
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.ConnectionRequest;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -25,13 +37,22 @@

public class HTTPHandler {
private static final Logger log = LoggerFactory.getLogger(HTTPHandler.class);
private CloseableHttpClient httpClient;
private RequestConfig globalConfig;

// private CloseableHttpClient httpClient;
// private RequestConfig globalConfig;
private HttpClientContext context;
private HttpClientConnectionManager connMgr;
private HttpRoute route;
private HttpClientConnection conn;
private HttpHost theHost;

public HTTPHandler() {
globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();
context = HttpClientContext.create();
connMgr = new BasicHttpClientConnectionManager();
route = null;
conn = null;
theHost = null;
// globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
// httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();
}


Expand All @@ -43,6 +64,7 @@ public String doHttpRequest(String url, String httpVerb, String contentType, Str
String theContent = null;
URI theURI = null;
ContentType parsedContentType = null;
ConnectionRequest connRequest = null;
StringEntity requestBody = null;
if (contentType != null && !contentType.trim().isEmpty()) {
parsedContentType = ContentType.parse(contentType);
Expand All @@ -55,6 +77,44 @@ public String doHttpRequest(String url, String httpVerb, String contentType, Str
log.warn("Error creating URI http request: " + url + " with message: " + e1.getMessage());
return null;
}
if(route == null) {
theHost = new HttpHost(theURI.getHost(), theURI.getPort());
route = new HttpRoute(theHost);
}
if(conn == null) {
// Request new connection. This can be a long process
connRequest = connMgr.requestConnection(route, null);
// Wait for connection up to 10 sec
try {
conn = connRequest.get(10, TimeUnit.SECONDS);
} catch (ConnectionPoolTimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// If not open
if (!conn.isOpen()) {
// establish connection based on its route info
try {
connMgr.connect(conn, route, 1000, context);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// and mark it as route complete
try {
connMgr.routeComplete(conn, route, context);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
if (httpVerb == null || httpVerb.trim().isEmpty() || HttpGet.METHOD_NAME.equalsIgnoreCase(httpVerb)) {
request = new HttpGet(theURI);
Expand Down Expand Up @@ -82,14 +142,19 @@ public String doHttpRequest(String url, String httpVerb, String contentType, Str
}
}
HttpResponse response = null;
HttpRequestExecutor exeRequest = new HttpRequestExecutor();
context.setTargetHost(theHost);
for (int retryCount = 0; retryCount < 2; retryCount++) {
try {
response = httpClient.execute(request);
response = exeRequest.execute(request, conn, context);
} catch (ClientProtocolException e) {
log.warn("Client Protocol Exception received, retyring....");
} catch (IOException e) {
log.warn("Error calling out to HA gateway: IOException in log", e);
retryCount = 2;
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
log.debug((httpVerb == null ? "GET" : httpVerb) + " execute (" + retryCount + ") on URL responded: "
+ response.getStatusLine().getStatusCode());
Expand Down Expand Up @@ -130,6 +195,7 @@ public String doHttpRequest(String url, String httpVerb, String contentType, Str
}
}
}
connMgr.releaseConnection(conn, null, 1, TimeUnit.SECONDS);
return theContent;
}

Expand All @@ -138,17 +204,20 @@ public String doHttpRequest(String url, String httpVerb, String contentType, Str
// }


public CloseableHttpClient getHttpClient() {
return httpClient;
}
// public CloseableHttpClient getHttpClient() {
// return httpClient;
// }


public void closeHandler() {
try {
httpClient.close();
// httpClient.close();
conn.close();
connMgr.closeExpiredConnections();
connMgr.shutdown();
} catch (IOException e) {
// noop
}
httpClient = null;
// httpClient = null;
}
}
44 changes: 17 additions & 27 deletions src/main/java/com/bwssystems/HABridge/plugins/hue/HueInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@

public class HueInfo {
private static final Logger log = LoggerFactory.getLogger(HueInfo.class);
private HTTPHandler httpClient;
private HTTPHandler httpHandler;
private NamedIP hueAddress;
private HueHome myHome;
public static final String HUE_REQUEST = "/api";

public HueInfo(NamedIP addressName, HueHome theHome) {
super();
httpClient = new HTTPHandler();
httpHandler = new HTTPHandler();
hueAddress = addressName;
myHome = theHome;
}
Expand Down Expand Up @@ -65,7 +65,7 @@ public HueApiResponse getHueApiResponse() {
}
}
theUrl = "http://" + hueAddress.getIp() + HUE_REQUEST + "/" + hueAddress.getUsername();
theData = httpClient.doHttpRequest(theUrl, null, null, null, null);
theData = httpHandler.doHttpRequest(theUrl, null, null, null, null);
if(theData != null) {
log.debug("GET HueApiResponse - data: " + theData);
if(theData.contains("[{\"error\":")) {
Expand Down Expand Up @@ -98,35 +98,25 @@ public HueApiResponse getHueApiResponse() {
public String registerWithHue() {
UserCreateRequest theLogin = new UserCreateRequest();
theLogin.setDevicetype("HABridge#MyMachine");
HttpPost postRequest = new HttpPost("http://" + hueAddress.getIp() + HUE_REQUEST);
ContentType parsedContentType = ContentType.parse("application/json");
StringEntity requestBody = new StringEntity(new Gson().toJson(theLogin), parsedContentType);
HttpResponse response = null;
postRequest.setEntity(requestBody);
HttpClient anHttpClient = httpClient.getHttpClient();
try {
response = anHttpClient.execute(postRequest);
log.debug("registerWithHue - POST execute on " + hueAddress.getName() + "URL responded: " + response.getStatusLine().getStatusCode());
if(response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300){
String theBody = EntityUtils.toString(response.getEntity());
log.debug("registerWithHue response data: " + theBody);
if(theBody.contains("[{\"error\":")) {
if(theBody.contains("link button not")) {

String aMessage = httpHandler.doHttpRequest("http://" + hueAddress.getIp() + HUE_REQUEST, HttpPost.METHOD_NAME, "application/json", new Gson().toJson(theLogin), null);

log.debug("registerWithHue - POST execute on " + hueAddress.getName() + "URL responded: " + aMessage);
if(!aMessage.isEmpty()){
log.debug("registerWithHue response data: " + aMessage);
if(aMessage.contains("[{\"error\":")) {
if(aMessage.contains("link button not")) {
log.warn("registerWithHue needs link button pressed on HUE bridge: " + hueAddress.getName());
}
else
log.warn("registerWithHue returned an unexpected error: " + theBody);
log.warn("registerWithHue returned an unexpected error: " + aMessage);
}
else {
SuccessUserResponse[] theResponses = new Gson().fromJson(theBody, SuccessUserResponse[].class); //read content for data, SuccessUserResponse[].class);
SuccessUserResponse[] theResponses = new Gson().fromJson(aMessage, SuccessUserResponse[].class); //read content for data, SuccessUserResponse[].class);
hueAddress.setUsername(theResponses[0].getSuccess().getUsername());
myHome.updateHue(hueAddress);
}
}
EntityUtils.consume(response.getEntity()); //close out inputstream ignore content
} catch (IOException e) {
log.warn("Error logging into HUE: IOException in log", e);
}
return hueAddress.getUsername();
}

Expand All @@ -138,7 +128,7 @@ public DeviceResponse getHueDeviceInfo(String hueDeviceId, DeviceDescriptor devi
registerWithHue();
if (hueAddress.getUsername() != null) {
// make call
responseString = httpClient.doHttpRequest(
responseString = httpHandler.doHttpRequest(
"http://" + hueAddress.getIp() + "/api/" + hueAddress.getUsername()
+ "/lights/" + hueDeviceId,
HttpGet.METHOD_NAME, "application/json", null, null);
Expand Down Expand Up @@ -167,7 +157,7 @@ public String changeState(HueDeviceIdentifier deviceId, String lightId, String b
if(hueAddress.getUsername() == null)
registerWithHue();
if (hueAddress.getUsername() != null) {
responseString = httpClient.doHttpRequest(
responseString = httpHandler.doHttpRequest(
"http://" + deviceId.getIpAddress() + "/api/" + hueAddress.getUsername()
+ "/lights/" + deviceId.getDeviceId() + "/state",
HttpPut.METHOD_NAME, "application/json", body, null);
Expand All @@ -188,8 +178,8 @@ public String changeState(HueDeviceIdentifier deviceId, String lightId, String b
}

public void closeHue() {
httpClient.closeHandler();
httpClient = null;
httpHandler.closeHandler();
httpHandler = null;
}

public NamedIP getHueAddress() {
Expand Down

0 comments on commit 5231eac

Please sign in to comment.