2 * Copyright (c) 2010-2022 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.homeconnect.internal.client;
15 import static io.github.bucket4j.Bandwidth.classic;
16 import static io.github.bucket4j.Refill.intervally;
18 import java.io.IOException;
19 import java.time.Duration;
20 import java.time.LocalDateTime;
21 import java.time.format.DateTimeFormatter;
22 import java.util.HashMap;
24 import java.util.concurrent.ExecutionException;
25 import java.util.concurrent.TimeoutException;
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.eclipse.jetty.client.api.ContentResponse;
30 import org.eclipse.jetty.client.api.Request;
31 import org.eclipse.jetty.http.HttpMethod;
32 import org.openhab.binding.homeconnect.internal.client.exception.AuthorizationException;
33 import org.openhab.binding.homeconnect.internal.client.exception.CommunicationException;
34 import org.openhab.core.auth.client.oauth2.AccessTokenResponse;
35 import org.openhab.core.auth.client.oauth2.OAuthClientService;
36 import org.openhab.core.auth.client.oauth2.OAuthException;
37 import org.openhab.core.auth.client.oauth2.OAuthResponseException;
38 import org.slf4j.LoggerFactory;
40 import com.google.gson.Gson;
41 import com.google.gson.GsonBuilder;
42 import com.google.gson.JsonElement;
43 import com.google.gson.JsonObject;
44 import com.google.gson.JsonParser;
46 import io.github.bucket4j.Bucket;
47 import io.github.bucket4j.Bucket4j;
52 * @author Jonas BrĂ¼stel - Initial contribution
53 * @author Laurent Garnier - Removed okhttp
57 public class HttpHelper {
58 private static final String BEARER = "Bearer ";
59 private static final int OAUTH_EXPIRE_BUFFER = 10;
60 private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
61 private static final JsonParser JSON_PARSER = new JsonParser();
62 private static final Map<String, Bucket> BUCKET_MAP = new HashMap<>();
63 private static final Object AUTHORIZATION_HEADER_MONITOR = new Object();
64 private static final Object BUCKET_MONITOR = new Object();
66 private static @Nullable String lastAccessToken = null;
68 public static ContentResponse sendRequest(Request request, String clientId)
69 throws InterruptedException, TimeoutException, ExecutionException {
70 if (HttpMethod.GET.name().equals(request.getMethod())) {
72 getBucket(clientId).asScheduler().consume(1);
73 } catch (InterruptedException e) {
74 LoggerFactory.getLogger(HttpHelper.class).debug("Could not consume from bucket! clientId={}, error={}",
75 clientId, e.getMessage());
78 return request.send();
81 public static String formatJsonBody(@Nullable String jsonString) {
82 if (jsonString == null) {
86 JsonObject json = parseString(jsonString).getAsJsonObject();
87 return GSON.toJson(json);
88 } catch (Exception e) {
93 public static String getAuthorizationHeader(OAuthClientService oAuthClientService)
94 throws AuthorizationException, CommunicationException {
95 synchronized (AUTHORIZATION_HEADER_MONITOR) {
97 AccessTokenResponse accessTokenResponse = oAuthClientService.getAccessTokenResponse();
98 // refresh the token if it's about to expire
99 if (accessTokenResponse != null
100 && accessTokenResponse.isExpired(LocalDateTime.now(), OAUTH_EXPIRE_BUFFER)) {
101 LoggerFactory.getLogger(HttpHelper.class).debug("Requesting a refresh of the access token.");
102 accessTokenResponse = oAuthClientService.refreshToken();
105 if (accessTokenResponse != null) {
106 String lastToken = lastAccessToken;
107 if (lastToken == null) {
108 LoggerFactory.getLogger(HttpHelper.class).debug("The used access token was created at {}",
109 accessTokenResponse.getCreatedOn().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
110 } else if (!lastToken.equals(accessTokenResponse.getAccessToken())) {
111 LoggerFactory.getLogger(HttpHelper.class).debug(
112 "The access token changed. New one created at {}",
113 accessTokenResponse.getCreatedOn().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
115 lastAccessToken = accessTokenResponse.getAccessToken();
117 LoggerFactory.getLogger(HttpHelper.class).debug("Current access token: {}",
118 accessTokenResponse.getAccessToken());
119 return BEARER + accessTokenResponse.getAccessToken();
121 LoggerFactory.getLogger(HttpHelper.class).error("No access token available! Fatal error.");
122 throw new AuthorizationException("No access token available!");
124 } catch (IOException e) {
125 String errorMessage = e.getMessage();
126 throw new CommunicationException(errorMessage != null ? errorMessage : "IOException", e);
127 } catch (OAuthException | OAuthResponseException e) {
128 String errorMessage = e.getMessage();
129 throw new AuthorizationException(errorMessage != null ? errorMessage : "oAuth exception", e);
134 public static JsonElement parseString(String json) {
135 return JSON_PARSER.parse(json);
138 private static Bucket getBucket(String clientId) {
139 synchronized (BUCKET_MONITOR) {
140 Bucket bucket = null;
141 if (BUCKET_MAP.containsKey(clientId)) {
142 bucket = BUCKET_MAP.get(clientId);
145 if (bucket == null) {
146 bucket = Bucket4j.builder()
147 // allows 50 tokens per minute (added 10 second buffer)
148 .addLimit(classic(50, intervally(50, Duration.ofSeconds(70))).withInitialTokens(40))
149 // but not often then 50 tokens per second
150 .addLimit(classic(10, intervally(10, Duration.ofSeconds(1)))).build();
151 BUCKET_MAP.put(clientId, bucket);