]> git.basschouten.com Git - openhab-addons.git/blob
3cc7a51862a124c0658cf21060ce140b87f56728
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.siemensrds.internal;
14
15 import static org.openhab.binding.siemensrds.internal.RdsBindingConstants.*;
16
17 import java.io.BufferedReader;
18 import java.io.DataOutputStream;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.InputStreamReader;
22 import java.io.OutputStream;
23 import java.net.HttpURLConnection;
24 import java.net.URL;
25 import java.nio.charset.StandardCharsets;
26 import java.text.ParseException;
27 import java.text.SimpleDateFormat;
28 import java.util.Calendar;
29 import java.util.Date;
30
31 import javax.net.ssl.HttpsURLConnection;
32
33 import org.eclipse.jdt.annotation.NonNullByDefault;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 import com.google.gson.Gson;
39 import com.google.gson.annotations.SerializedName;
40
41 /**
42  * Interface to the Access Token for a particular User
43  *
44  * @author Andrew Fiddian-Green - Initial contribution
45  *
46  */
47 @NonNullByDefault
48 public class RdsAccessToken {
49
50     /*
51      * NOTE: requires a static logger because the class has static methods
52      */
53     protected final Logger logger = LoggerFactory.getLogger(RdsAccessToken.class);
54
55     private static final Gson GSON = new Gson();
56
57     @SerializedName("access_token")
58     private @Nullable String accessToken;
59     @SerializedName(".expires")
60     private @Nullable String expires;
61
62     private @Nullable Date expDate = null;
63
64     /*
65      * public static method: execute the HTTP POST on the server
66      */
67     public static String httpGetTokenJson(String apiKey, String payload) throws RdsCloudException, IOException {
68         /*
69          * NOTE: this class uses JAVAX HttpsURLConnection library instead of the
70          * preferred JETTY library; the reason is that JETTY does not allow sending the
71          * square brackets characters "[]" verbatim over HTTP connections
72          */
73         URL url = new URL(URL_TOKEN);
74
75         HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
76
77         https.setRequestMethod(HTTP_POST);
78
79         https.setRequestProperty(USER_AGENT, MOZILLA);
80         https.setRequestProperty(ACCEPT, TEXT_PLAIN);
81         https.setRequestProperty(CONTENT_TYPE, TEXT_PLAIN);
82         https.setRequestProperty(SUBSCRIPTION_KEY, apiKey);
83
84         https.setDoOutput(true);
85
86         try (OutputStream outputStream = https.getOutputStream();
87                 DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) {
88             dataOutputStream.writeBytes(payload);
89             dataOutputStream.flush();
90         }
91
92         if (https.getResponseCode() != HttpURLConnection.HTTP_OK) {
93             throw new IOException(https.getResponseMessage());
94         }
95
96         try (InputStream inputStream = https.getInputStream();
97                 InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
98                 BufferedReader reader = new BufferedReader(inputStreamReader)) {
99             String inputString;
100             StringBuffer response = new StringBuffer();
101             while ((inputString = reader.readLine()) != null) {
102                 response.append(inputString);
103             }
104             return response.toString();
105         }
106     }
107
108     /*
109      * public method: parse the JSON, and create a class that encapsulates the data
110      */
111     public static @Nullable RdsAccessToken createFromJson(String json) {
112         return GSON.fromJson(json, RdsAccessToken.class);
113     }
114
115     /*
116      * public method: return the access token
117      */
118     public String getToken() throws RdsCloudException {
119         String accessToken = this.accessToken;
120         if (accessToken != null) {
121             return accessToken;
122         }
123         throw new RdsCloudException("no access token");
124     }
125
126     /*
127      * public method: check if the token has expired
128      */
129     public boolean isExpired() {
130         Date expDate = this.expDate;
131         if (expDate == null) {
132             try {
133                 expDate = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z").parse(expires);
134             } catch (ParseException e) {
135                 logger.debug("isExpired: expiry date parsing exception");
136
137                 Calendar calendar = Calendar.getInstance();
138                 calendar.setTime(new Date());
139                 calendar.add(Calendar.DAY_OF_YEAR, 1);
140                 expDate = calendar.getTime();
141             }
142         }
143         return (expDate == null || expDate.before(new Date()));
144     }
145 }