]> git.basschouten.com Git - openhab-addons.git/blob
655aa225f428a34cc3d8034e0977cbd15e403782
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.ihc.internal.ws.http;
14
15 import java.io.IOException;
16 import java.net.SocketTimeoutException;
17 import java.nio.charset.StandardCharsets;
18 import java.time.Duration;
19 import java.time.LocalDateTime;
20 import java.util.Map;
21 import java.util.concurrent.atomic.AtomicInteger;
22
23 import org.apache.http.HttpResponse;
24 import org.apache.http.NoHttpResponseException;
25 import org.apache.http.client.ClientProtocolException;
26 import org.apache.http.client.HttpClient;
27 import org.apache.http.client.config.RequestConfig;
28 import org.apache.http.client.methods.HttpPost;
29 import org.apache.http.entity.StringEntity;
30 import org.apache.http.util.EntityUtils;
31 import org.openhab.binding.ihc.internal.ws.exeptions.IhcExecption;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 /**
36  * Simple HTTP Client for IHC / ELKO LS Controller connection purposes.
37  *
38  * @author Pauli Anttila - Initial contribution
39  */
40 public abstract class IhcHttpsClient {
41
42     private final Logger logger = LoggerFactory.getLogger(IhcHttpsClient.class);
43
44     private IhcConnectionPool ihcConnectionPool;
45     private HttpClient client;
46     private HttpPost postReq;
47     private AtomicInteger counter = new AtomicInteger();
48
49     public IhcHttpsClient(IhcConnectionPool ihcConnectionPool) {
50         this.ihcConnectionPool = ihcConnectionPool;
51     }
52
53     /**
54      * Init HTTP connection.
55      *
56      * @param url Url to connect.
57      */
58     private void initConnection(String url) throws IhcExecption {
59         if (client == null) {
60             client = ihcConnectionPool.getHttpClient();
61         }
62         postReq = new HttpPost(url);
63     }
64
65     /**
66      * Send HTTP request and wait response from the server.
67      *
68      */
69     public String sendQuery(String url, Map<String, String> requestProperties, String query, int timeout)
70             throws IhcExecption {
71         initConnection(url);
72         setRequestProperty(requestProperties);
73         try {
74             return sendQ(query, timeout);
75         } catch (NoHttpResponseException | SocketTimeoutException e) {
76             try {
77                 logger.debug("No response received, resend query");
78                 return sendQ(query, timeout);
79             } catch (IOException ee) {
80                 throw new IhcExecption(ee);
81             }
82         } catch (IOException e) {
83             throw new IhcExecption(e);
84         }
85     }
86
87     private String sendQ(String query, int timeout)
88             throws ClientProtocolException, IOException, NoHttpResponseException {
89         postReq.setEntity(new StringEntity(query, StandardCharsets.UTF_8.name()));
90         postReq.addHeader("content-type", "text/xml");
91
92         int requestId = 0;
93
94         if (logger.isTraceEnabled()) {
95             requestId = counter.getAndIncrement();
96             logger.trace("Send query (url={}, connectionPool={}, clientId={} requestId={}, timeout={}, headers={}): {}",
97                     postReq.getURI(), ihcConnectionPool.hashCode(), client.hashCode(), requestId, timeout,
98                     postReq.getAllHeaders(), query);
99         }
100
101         final RequestConfig params = RequestConfig.custom().setConnectTimeout(timeout)
102                 .setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
103         postReq.setConfig(params);
104
105         // Execute POST
106         LocalDateTime start = LocalDateTime.now();
107         try {
108             HttpResponse response = client.execute(postReq, ihcConnectionPool.getHttpContext());
109             String resp = EntityUtils.toString(response.getEntity());
110             if (logger.isTraceEnabled()) {
111                 logger.trace("Received response (connectionPool={}, clientId={} requestId={}, in {}, headers={}): {}",
112                         ihcConnectionPool.hashCode(), client.hashCode(), requestId,
113                         Duration.between(start, LocalDateTime.now()), response.getAllHeaders(), resp);
114             }
115             return resp;
116         } catch (Exception e) {
117             if (logger.isTraceEnabled()) {
118                 logger.trace("Exception occured (connectionPool={}, clientId={} requestId={}, in {}): {}",
119                         ihcConnectionPool.hashCode(), client.hashCode(), requestId,
120                         Duration.between(start, LocalDateTime.now()), e.getMessage());
121             }
122             throw (e);
123         }
124     }
125
126     /**
127      * Set request properties.
128      *
129      */
130     private void setRequestProperty(Map<String, String> requestProperties) {
131         if (postReq != null && requestProperties != null) {
132             requestProperties.forEach((k, v) -> postReq.setHeader(k, v));
133         }
134     }
135 }