2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.neeo.internal.net;
15 import java.io.IOException;
16 import java.util.Objects;
18 import javax.ws.rs.ProcessingException;
19 import javax.ws.rs.client.Client;
20 import javax.ws.rs.client.ClientBuilder;
21 import javax.ws.rs.client.Entity;
22 import javax.ws.rs.client.Invocation.Builder;
23 import javax.ws.rs.core.MediaType;
24 import javax.ws.rs.core.Response;
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jetty.http.HttpStatus;
28 import org.glassfish.jersey.filter.LoggingFilter;
29 import org.openhab.binding.neeo.internal.NeeoUtil;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
34 * This class represents an HTTP session with a client
36 * @author Tim Roberts - Initial contribution
39 public class HttpRequest implements AutoCloseable {
42 private final Logger logger = LoggerFactory.getLogger(HttpRequest.class);
44 /** The client to use */
45 private final Client client;
48 * Instantiates a new request
50 public HttpRequest() {
51 client = ClientBuilder.newClient();
53 if (logger.isDebugEnabled()) {
54 client.register(new LoggingFilter(new Slf4LoggingAdapter(logger), true));
59 * Send a get command to the specified uri
61 * @param uri the non-null uri
62 * @return the {@link HttpResponse}
64 public HttpResponse sendGetCommand(String uri) {
65 NeeoUtil.requireNotEmpty(uri, "uri cannot be empty");
67 final Builder request = client.target(uri).request();
69 final Response content = request.get();
72 return new HttpResponse(content);
76 } catch (IOException | IllegalStateException e) {
77 return new HttpResponse(HttpStatus.SERVICE_UNAVAILABLE_503, e.getMessage());
82 * Send post JSON command using the body
84 * @param uri the non empty uri
85 * @param body the non-null, possibly empty body
86 * @return the {@link HttpResponse}
88 public HttpResponse sendPostJsonCommand(String uri, String body) {
89 NeeoUtil.requireNotEmpty(uri, "uri cannot be empty");
90 Objects.requireNonNull(body, "body cannot be null");
93 final Builder request = client.target(uri).request(MediaType.APPLICATION_JSON);
95 final Response content = request.post(Entity.entity(body, MediaType.APPLICATION_JSON));
98 return new HttpResponse(content);
102 // IllegalArgumentException/ProcessingException catches issues with the URI being invalid
104 } catch (IOException | IllegalStateException | IllegalArgumentException | ProcessingException e) {
105 return new HttpResponse(HttpStatus.SERVICE_UNAVAILABLE_503, e.getMessage());
110 public void close() {