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