]> git.basschouten.com Git - openhab-addons.git/blob
e57676727406592f139abe0ec9195ede2e768380
[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.squeezebox.internal.utils;
14
15 import java.util.concurrent.ExecutionException;
16 import java.util.concurrent.TimeUnit;
17 import java.util.concurrent.TimeoutException;
18
19 import org.eclipse.jetty.client.HttpClient;
20 import org.eclipse.jetty.client.api.ContentResponse;
21 import org.eclipse.jetty.client.util.StringContentProvider;
22 import org.eclipse.jetty.http.HttpMethod;
23 import org.eclipse.jetty.http.HttpStatus;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 import com.google.gson.JsonElement;
28 import com.google.gson.JsonParser;
29
30 /**
31  * Collection of methods to help retrieve HTTP data from a SqueezeServer
32  *
33  * @author Dan Cunningham - Initial contribution
34  * @author Svilen Valkanov - replaced Apache HttpClient with Jetty
35  * @author Mark Hilbush - Add support for LMS authentication
36  * @author Mark Hilbush - Rework exception handling
37  */
38 public class HttpUtils {
39     private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
40
41     private static final int TIMEOUT = 5000;
42     private static HttpClient client = new HttpClient();
43     /**
44      * JSON request to get the CLI port from a Squeeze Server
45      */
46     private static final String JSON_REQ = "{\"params\": [\"\", [\"pref\" ,\"plugin.cli:cliport\",\"?\"]], \"id\": 1, \"method\": \"slim.request\"}";
47
48     /**
49      * Simple logic to perform a post request
50      *
51      * @param url URL to be sent to LMS server
52      * @param postData Data to be sent to LMS server
53      * @return Content received from LMS
54      * @throws SqueezeBoxCommunicationException
55      * @throws SqueezeBoxNotAuthorizedException
56      */
57     public static String post(String url, String postData)
58             throws SqueezeBoxNotAuthorizedException, SqueezeBoxCommunicationException {
59         if (!client.isStarted()) {
60             try {
61                 client.start();
62             } catch (Exception e) {
63                 throw new SqueezeBoxCommunicationException("Jetty http client exception: " + e.getMessage());
64             }
65         }
66
67         ContentResponse response;
68         try {
69             response = client.newRequest(url).method(HttpMethod.POST).content(new StringContentProvider(postData))
70                     .timeout(TIMEOUT, TimeUnit.MILLISECONDS).send();
71         } catch (InterruptedException | TimeoutException | ExecutionException e) {
72             throw new SqueezeBoxCommunicationException("Jetty http client exception: " + e.getMessage());
73         }
74
75         int statusCode = response.getStatus();
76
77         if (statusCode == HttpStatus.UNAUTHORIZED_401) {
78             String statusLine = response.getStatus() + " " + response.getReason();
79             logger.error("Received '{}' from squeeze server", statusLine);
80             throw new SqueezeBoxNotAuthorizedException("Unauthorized: " + statusLine);
81         }
82
83         if (statusCode != HttpStatus.OK_200) {
84             String statusLine = response.getStatus() + " " + response.getReason();
85             logger.error("HTTP POST method failed: {}", statusLine);
86             throw new SqueezeBoxCommunicationException("Http post to server failed: " + statusLine);
87         }
88
89         return response.getContentAsString();
90     }
91
92     /**
93      * Retrieves the command line port (cli) from a SqueezeServer
94      *
95      * @param ip
96      * @param webPort
97      * @return Command Line Interpreter (CLI) port number
98      * @throws SqueezeBoxNotAuthorizedException
99      * @throws SqueezeBoxCommunicationException
100      * @throws NumberFormatException
101      */
102     public static int getCliPort(String ip, int webPort)
103             throws SqueezeBoxNotAuthorizedException, SqueezeBoxCommunicationException {
104         String url = "http://" + ip + ":" + webPort + "/jsonrpc.js";
105         String json = HttpUtils.post(url, JSON_REQ);
106         logger.trace("Recieved json from server {}", json);
107         JsonElement resp = JsonParser.parseString(json);
108         String cliPort = resp.getAsJsonObject().get("result").getAsJsonObject().get("_p2").getAsString();
109         return Integer.parseInt(cliPort);
110     }
111 }