]> git.basschouten.com Git - openhab-addons.git/blob
6feb0f5a859bcbf87e8eae834f435a85a6790938
[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.magentatv.internal.network;
14
15 import static org.openhab.binding.magentatv.internal.MagentaTVBindingConstants.*;
16
17 import java.io.BufferedReader;
18 import java.io.ByteArrayInputStream;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.InputStreamReader;
22 import java.io.OutputStream;
23 import java.io.PrintStream;
24 import java.net.InetSocketAddress;
25 import java.net.Socket;
26 import java.net.UnknownHostException;
27 import java.nio.charset.StandardCharsets;
28 import java.text.MessageFormat;
29 import java.util.Properties;
30
31 import javax.ws.rs.HttpMethod;
32
33 import org.eclipse.jdt.annotation.NonNullByDefault;
34 import org.openhab.binding.magentatv.internal.MagentaTVException;
35 import org.openhab.core.io.net.http.HttpUtil;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 /**
40  * The {@link MagentaTVHttp} supplies network functions.
41  *
42  * @author Markus Michels - Initial contribution
43  */
44 @NonNullByDefault
45 public class MagentaTVHttp {
46     private final Logger logger = LoggerFactory.getLogger(MagentaTVHttp.class);
47
48     public String httpGet(String host, String urlBase, String urlParameters) throws MagentaTVException {
49         String url = "";
50         String response = "";
51         try {
52             url = !urlParameters.isEmpty() ? urlBase + "?" + urlParameters : urlBase;
53             Properties httpHeader = new Properties();
54             httpHeader.setProperty(HEADER_USER_AGENT, USER_AGENT);
55             httpHeader.setProperty(HEADER_HOST, host);
56             httpHeader.setProperty(HEADER_ACCEPT, "*/*");
57             response = HttpUtil.executeUrl(HttpMethod.GET, url, httpHeader, null, null, NETWORK_TIMEOUT_MS);
58             logger.trace("GET {} - Response={}", url, response);
59             return response;
60         } catch (IOException e) {
61             throw new MagentaTVException(e, "HTTP GET {0} failed: {1}", url, response);
62         }
63     }
64
65     /**
66      * Given a URL and a set parameters, send a HTTP POST request to the URL
67      * location created by the URL and parameters.
68      *
69      * @param url The URL to send a POST request to.
70      * @param urlParameters List of parameters to use in the URL for the POST
71      *            request. Null if no parameters.
72      * @param soapAction Header attribute for SOAP ACTION: xxx
73      * @param connection Header attribut for CONNECTION: xxx
74      * @return String contents of the response for the POST request.
75      * @throws MagentaTVException
76      */
77     public String httpPOST(String host, String url, String postData, String soapAction, String connection)
78             throws MagentaTVException {
79         String httpResponse = "";
80         try {
81             Properties httpHeader = new Properties();
82             httpHeader.setProperty(HEADER_CONTENT_TYPE, CONTENT_TYPE_XML);
83             httpHeader.setProperty(HEADER_ACCEPT, "");
84             httpHeader.setProperty(HEADER_USER_AGENT, USER_AGENT);
85             httpHeader.setProperty(HEADER_HOST, host);
86             if (!soapAction.isEmpty()) {
87                 httpHeader.setProperty(HEADER_SOAPACTION, soapAction);
88             }
89             if (!connection.isEmpty()) {
90                 httpHeader.setProperty(HEADER_CONNECTION, connection);
91             }
92
93             logger.trace("POST {} - SoapAction={}, Data = {}", url, postData, soapAction);
94             InputStream dataStream = new ByteArrayInputStream(postData.getBytes(StandardCharsets.UTF_8));
95             httpResponse = HttpUtil.executeUrl(HttpMethod.POST, url, httpHeader, dataStream, null, NETWORK_TIMEOUT_MS);
96             logger.trace("POST {} - Response = {}", url, httpResponse);
97             return httpResponse;
98         } catch (IOException e) {
99             throw new MagentaTVException(e, "HTTP POST {0} failed, response={1}", url, httpResponse);
100         }
101     }
102
103     /**
104      * Send raw TCP data (SUBSCRIBE command)
105      *
106      * @param remoteIp receiver's IP
107      * @param remotePort destination port
108      * @param data data to send
109      * @return received response
110      * @throws IOException
111      */
112     public String sendData(String remoteIp, String remotePort, String data) throws MagentaTVException {
113
114         String errorMessage = "";
115         StringBuffer response = new StringBuffer();
116         try (Socket socket = new Socket()) {
117             socket.setSoTimeout(NETWORK_TIMEOUT_MS); // set read timeout
118             socket.connect(new InetSocketAddress(remoteIp, Integer.parseInt(remotePort)), NETWORK_TIMEOUT_MS);
119
120             OutputStream out = socket.getOutputStream();
121             PrintStream ps = new PrintStream(out, true);
122             ps.println(data);
123
124             InputStream in = socket.getInputStream();
125
126             // wait until somthing to read is available or socket I/O fails (IOException)
127             BufferedReader buff = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
128             do {
129                 String line = buff.readLine();
130                 response.append(line);
131                 response.append("\r\n");
132             } while (buff.ready());
133         } catch (UnknownHostException e) {
134             errorMessage = "Unknown host!";
135         } catch (IOException /* | InterruptedException */ e) {
136             errorMessage = MessageFormat.format("{0} ({1})", e.getMessage(), e.getClass());
137         }
138
139         if (!errorMessage.isEmpty()) {
140             throw new MagentaTVException(
141                     MessageFormat.format("Network I/O failed for {0}:{1}: {2}", remoteIp, remotePort, errorMessage));
142         }
143         return response.toString();
144     }
145 }