mirror of
https://github.com/bwssytems/ha-bridge.git
synced 2025-12-16 18:24:36 +00:00
Updating http connection management.... Broken
This commit is contained in:
@@ -4,7 +4,12 @@ import java.io.IOException;
|
||||
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;
|
||||
@@ -13,10 +18,17 @@ import org.apache.http.client.methods.HttpGet;
|
||||
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;
|
||||
@@ -25,13 +37,22 @@ import com.bwssystems.HABridge.api.NameValue;
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
|
||||
@@ -43,6 +64,7 @@ public class HTTPHandler {
|
||||
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);
|
||||
@@ -55,6 +77,44 @@ public class HTTPHandler {
|
||||
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);
|
||||
@@ -82,14 +142,19 @@ public class HTTPHandler {
|
||||
}
|
||||
}
|
||||
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());
|
||||
@@ -130,6 +195,7 @@ public class HTTPHandler {
|
||||
}
|
||||
}
|
||||
}
|
||||
connMgr.releaseConnection(conn, null, 1, TimeUnit.SECONDS);
|
||||
return theContent;
|
||||
}
|
||||
|
||||
@@ -138,17 +204,20 @@ public class HTTPHandler {
|
||||
// }
|
||||
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,14 +25,14 @@ import com.google.gson.Gson;
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -65,7 +65,7 @@ public class HueInfo {
|
||||
}
|
||||
}
|
||||
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\":")) {
|
||||
@@ -98,35 +98,25 @@ public class HueInfo {
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -138,7 +128,7 @@ public class HueInfo {
|
||||
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);
|
||||
@@ -167,7 +157,7 @@ public class HueInfo {
|
||||
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);
|
||||
@@ -188,8 +178,8 @@ public class HueInfo {
|
||||
}
|
||||
|
||||
public void closeHue() {
|
||||
httpClient.closeHandler();
|
||||
httpClient = null;
|
||||
httpHandler.closeHandler();
|
||||
httpHandler = null;
|
||||
}
|
||||
|
||||
public NamedIP getHueAddress() {
|
||||
|
||||
Reference in New Issue
Block a user