]> git.basschouten.com Git - openhab-addons.git/blob
9e6e50d95831f89cf60e1f445cc5e53811855aab
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.neeo.internal.net;
14
15 import java.io.IOException;
16 import java.net.URI;
17 import java.net.URISyntaxException;
18 import java.util.Objects;
19 import java.util.concurrent.ExecutionException;
20 import java.util.concurrent.TimeUnit;
21 import java.util.concurrent.TimeoutException;
22
23 import javax.ws.rs.ProcessingException;
24
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jetty.client.HttpClient;
27 import org.eclipse.jetty.client.api.ContentResponse;
28 import org.eclipse.jetty.client.util.StringContentProvider;
29 import org.eclipse.jetty.http.HttpHeader;
30 import org.eclipse.jetty.http.HttpMethod;
31 import org.eclipse.jetty.http.HttpStatus;
32 import org.openhab.binding.neeo.internal.NeeoUtil;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 /**
37  * This class represents an HTTP session with a client
38  *
39  * @author Tim Roberts - Initial contribution
40  */
41 @NonNullByDefault
42 public class HttpRequest implements AutoCloseable {
43
44     /** the logger */
45     private final Logger logger = LoggerFactory.getLogger(HttpRequest.class);
46
47     /** The client to use */
48     private final HttpClient httpClient;
49
50     /**
51      * Instantiates a new request
52      */
53     public HttpRequest(HttpClient httpClient) {
54         this.httpClient = httpClient;
55     }
56
57     /**
58      * Send a get command to the specified uri
59      *
60      * @param uri the non-null uri
61      * @return the {@link HttpResponse}
62      */
63     public HttpResponse sendGetCommand(String uri) {
64         NeeoUtil.requireNotEmpty(uri, "uri cannot be empty");
65         try {
66             final org.eclipse.jetty.client.api.Request request = httpClient.newRequest(uri);
67             request.method(HttpMethod.GET);
68             request.timeout(10, TimeUnit.SECONDS);
69             ContentResponse refreshResponse = request.send();
70             return new HttpResponse(refreshResponse);
71         } catch (IOException | IllegalStateException e) {
72             return new HttpResponse(HttpStatus.SERVICE_UNAVAILABLE_503, e.getMessage());
73         } catch (InterruptedException | TimeoutException | ExecutionException e) {
74             logger.debug("An exception occurred while invoking a HTTP request: '{}'", e.getMessage());
75             String message = e.getMessage();
76             return new HttpResponse(HttpStatus.SERVICE_UNAVAILABLE_503, message != null ? message : "");
77         }
78     }
79
80     /**
81      * Send post JSON command using the body
82      *
83      * @param uriString the non empty uri
84      * @param body the non-null, possibly empty body
85      * @return the {@link HttpResponse}
86      */
87     public HttpResponse sendPostJsonCommand(String uriString, String body) {
88         NeeoUtil.requireNotEmpty(uriString, "uri cannot be empty");
89         Objects.requireNonNull(body, "body cannot be null");
90
91         logger.trace("sendPostJsonCommand: target={}, body={}", uriString, body);
92
93         try {
94             URI targetUri = new URI(uriString);
95             if (!targetUri.isAbsolute()) {
96                 logger.warn("Absolute URI required but provided URI '{}' is non-absolute. ", uriString);
97                 return new HttpResponse(HttpStatus.NOT_ACCEPTABLE_406, "Absolute URI required");
98             }
99             final org.eclipse.jetty.client.api.Request request = httpClient.newRequest(targetUri);
100             request.content(new StringContentProvider(body));
101             request.header(HttpHeader.CONTENT_TYPE, "application/json");
102             request.method(HttpMethod.POST);
103             request.timeout(10, TimeUnit.SECONDS);
104             ContentResponse refreshResponse = request.send();
105             return new HttpResponse(refreshResponse);
106             // IllegalArgumentException/ProcessingException catches issues with the URI being invalid
107             // as well
108         } catch (IOException | IllegalStateException | IllegalArgumentException | ProcessingException e) {
109             return new HttpResponse(HttpStatus.SERVICE_UNAVAILABLE_503, e.getMessage());
110         } catch (URISyntaxException e) {
111             return new HttpResponse(HttpStatus.NOT_ACCEPTABLE_406, e.getMessage());
112         } catch (InterruptedException | TimeoutException | ExecutionException e) {
113             logger.debug("An exception occurred while invoking a HTTP request: '{}'", e.getMessage());
114             String message = e.getMessage();
115             return new HttpResponse(HttpStatus.SERVICE_UNAVAILABLE_503, message != null ? message : "");
116         }
117     }
118
119     @Override
120     public void close() {
121     }
122 }