Skip to content

Commit

Permalink
Set explicit timeout for http request (openhab#15505)
Browse files Browse the repository at this point in the history
* Bondhome
* chatgpt
* electroluxair
* energidataservice
* freeboxos
* gardena
* generacmobilelink
* hdpowerview
* icalendar
* juicenet
* kostalinverter
* liquidcheck
* mcd
* meater
* miele
* mercedesme
* mybmw
* myq
* ojelectronics
* plex
* radiothermostat
* renault
* semsportal
* sensibo
* tapocontrol
* tellstick
* verisure
* vizio

---------

Signed-off-by: lsiepel <leosiepel@gmail.com>
Signed-off-by: Leo Siepel <leosiepel@gmail.com>
  • Loading branch information
lsiepel authored Oct 19, 2023
1 parent c7568cb commit 7313415
Show file tree
Hide file tree
Showing 32 changed files with 135 additions and 48 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ private synchronized String request(String uri) throws BondException {
final Request request = httpClient.newRequest(url).method(HttpMethod.GET).header("BOND-Token",
bridgeHandler.getBridgeToken());
ContentResponse response;
response = request.send();
response = request.timeout(BOND_API_TIMEOUT_MS, TimeUnit.MILLISECONDS).send();
String encoding = response.getEncoding() != null ? response.getEncoding().replace("\"", "").trim()
: StandardCharsets.UTF_8.name();
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,13 @@
*/
package org.openhab.binding.chatgpt.internal;

import static org.openhab.binding.chatgpt.internal.ChatGPTBindingConstants.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.eclipse.jdt.annotation.NonNullByDefault;
Expand Down Expand Up @@ -55,6 +58,7 @@
@NonNullByDefault
public class ChatGPTHandler extends BaseThingHandler {

private static final int REQUEST_TIMEOUT_MS = 10_000;
private final Logger logger = LoggerFactory.getLogger(ChatGPTHandler.class);

private HttpClient httpClient;
Expand Down Expand Up @@ -125,8 +129,8 @@ private void processChatResponse(ChannelUID channelUID, @Nullable String respons

String queryJson = gson.toJson(root);
Request request = httpClient.newRequest(apiUrl).method(HttpMethod.POST)
.header("Content-Type", "application/json").header("Authorization", "Bearer " + apiKey)
.content(new StringContentProvider(queryJson));
.timeout(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS).header("Content-Type", "application/json")
.header("Authorization", "Bearer " + apiKey).content(new StringContentProvider(queryJson));
logger.trace("Query '{}'", queryJson);
try {
ContentResponse response = request.send();
Expand Down Expand Up @@ -166,8 +170,8 @@ public void initialize() {

scheduler.execute(() -> {
try {
Request request = httpClient.newRequest(modelUrl).method(HttpMethod.GET).header("Authorization",
"Bearer " + apiKey);
Request request = httpClient.newRequest(modelUrl).timeout(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS)
.method(HttpMethod.GET).header("Authorization", "Bearer " + apiKey);
ContentResponse response = request.send();
if (response.getStatus() == 200) {
updateStatus(ThingStatus.ONLINE);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.eclipse.jdt.annotation.NonNullByDefault;
Expand Down Expand Up @@ -55,6 +56,7 @@ public class ElectroluxDeltaAPI {

private static final String JSON_CONTENT_TYPE = "application/json";
private static final int MAX_RETRIES = 3;
private static final int REQUEST_TIMEOUT_MS = 10_000;

private final Logger logger = LoggerFactory.getLogger(ElectroluxDeltaAPI.class);
private final Gson gson;
Expand Down Expand Up @@ -176,7 +178,7 @@ public boolean setSafetyLock(String applianceId, String safetyLockStatus) {

private Request createRequest(String uri, HttpMethod httpMethod) {
Request request = httpClient.newRequest(uri).method(httpMethod);

request.timeout(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
request.header(HttpHeader.ACCEPT, JSON_CONTENT_TYPE);
request.header(HttpHeader.CONTENT_TYPE, JSON_CONTENT_TYPE);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -76,6 +77,7 @@ public class ApiController {

private static final String HEADER_REMAINING_CALLS = "RemainingCalls";
private static final String HEADER_TOTAL_CALLS = "TotalCalls";
private static final int REQUEST_TIMEOUT_SECONDS = 30;

private final Logger logger = LoggerFactory.getLogger(ApiController.class);
private final Gson gson = new GsonBuilder() //
Expand Down Expand Up @@ -110,6 +112,7 @@ public ElspotpriceRecord[] getSpotPrices(String priceArea, Currency currency, Da
}

Request request = httpClient.newRequest(ENDPOINT + DATASET_PATH + DATASET_NAME_SPOT_PRICES)
.timeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.param("start", start.toString()) //
.param("filter", "{\"" + FILTER_KEY_PRICE_AREA + "\":\"" + priceArea + "\"}") //
.param("columns", "HourUTC,SpotPrice" + currency) //
Expand Down Expand Up @@ -198,6 +201,7 @@ public Collection<DatahubPricelistRecord> getDatahubPriceLists(GlobalLocationNum
}

Request request = httpClient.newRequest(ENDPOINT + DATASET_PATH + DATASET_NAME_DATAHUB_PRICELIST)
.timeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.param("filter", mapToFilter(filterMap)) //
.param("columns", columns) //
.agent(userAgent) //
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import javax.ws.rs.core.UriBuilder;
Expand Down Expand Up @@ -51,6 +52,7 @@
public class FreeboxOsIconProvider extends AbstractResourceIconProvider {

private final Logger logger = LoggerFactory.getLogger(FreeboxOsIconProvider.class);
private static final int REQUEST_TIMEOUT_MS = 8000;

private final HttpClient httpClient;
private final UriBuilder uriBuilder;
Expand All @@ -77,7 +79,8 @@ protected Integer getPriority() {
@Override
protected @Nullable InputStream getResource(String iconSetId, String resourceName) {
URI uri = uriBuilder.clone().path(resourceName).build();
Request request = httpClient.newRequest(uri).method(HttpMethod.GET);
Request request = httpClient.newRequest(uri).method(HttpMethod.GET).timeout(REQUEST_TIMEOUT_MS,
TimeUnit.MILLISECONDS);

try {
ContentResponse response = request.send();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
@NonNullByDefault
public class GardenaSmartImpl implements GardenaSmart, GardenaSmartWebSocketListener {
private final Logger logger = LoggerFactory.getLogger(GardenaSmartImpl.class);
private static final int REQUEST_TIMEOUT_MS = 10_000;

private Gson gson = new GsonBuilder().registerTypeAdapter(DataItem.class, new DataItemDeserializer()).create();

Expand Down Expand Up @@ -212,6 +213,7 @@ private <T> T executeRequest(HttpMethod method, String url, @Nullable Object con
}

Request request = httpClient.newRequest(url).method(method).header(HttpHeader.CONTENT_TYPE, contentType)
.timeout(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS)
.header(HttpHeader.ACCEPT, "application/vnd.api+json").header(HttpHeader.ACCEPT_ENCODING, "gzip");

if (!URL_API_TOKEN.equals(url)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
@NonNullByDefault
public class GeneracMobileLinkAccountHandler extends BaseBridgeHandler {
private final Logger logger = LoggerFactory.getLogger(GeneracMobileLinkAccountHandler.class);
private static final int REQUEST_TIMEOUT_MS = 10_000;

private static final String API_BASE = "https://app.mobilelinkgen.com/api";
private static final String LOGIN_BASE = "https://generacconnectivity.b2clogin.com/generacconnectivity.onmicrosoft.com/B2C_1A_MobileLink_SignIn";
Expand Down Expand Up @@ -286,8 +287,9 @@ private synchronized void login() throws IOException, InvalidCredentialsExceptio
fields.put("password", config.password);

Request selfAssertedRequest = httpClient.POST(LOGIN_BASE + "/SelfAsserted")
.header("X-Csrf-Token", signInConfig.csrf).param("tx", "StateProperties=" + signInConfig.transId)
.param("p", "B2C_1A_SignUpOrSigninOnline").content(new FormContentProvider(fields));
.timeout(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS).header("X-Csrf-Token", signInConfig.csrf)
.param("tx", "StateProperties=" + signInConfig.transId).param("p", "B2C_1A_SignUpOrSigninOnline")
.content(new FormContentProvider(fields));

ContentResponse selfAssertedResponse = selfAssertedRequest.send();

Expand All @@ -309,8 +311,8 @@ private synchronized void login() throws IOException, InvalidCredentialsExceptio
}

Request confirmedRequest = httpClient.newRequest(LOGIN_BASE + "/api/CombinedSigninAndSignup/confirmed")
.param("csrf_token", signInConfig.csrf).param("tx", "StateProperties=" + signInConfig.transId)
.param("p", "B2C_1A_SignUpOrSigninOnline");
.timeout(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS).param("csrf_token", signInConfig.csrf)
.param("tx", "StateProperties=" + signInConfig.transId).param("p", "B2C_1A_SignUpOrSigninOnline");

ContentResponse confirmedResponse = confirmedRequest.send();

Expand Down Expand Up @@ -362,7 +364,8 @@ private boolean submitPage(String loginString)
fields.put("state", loginState.attr("value"));
fields.put("code", loginCode.attr("value"));

Request loginRequest = httpClient.POST(action).content(new FormContentProvider(fields));
Request loginRequest = httpClient.POST(action).timeout(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS)
.content(new FormContentProvider(fields));

ContentResponse loginResponse = loginRequest.send();
if (logger.isTraceEnabled()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ public class GatewayWebTargets implements Closeable, HostnameVerifier {
private static final String IDS = "ids";
private static final int SLEEP_SECONDS = 360;
private static final Set<Integer> HTTP_OK_CODES = Set.of(HttpStatus.OK_200, HttpStatus.NO_CONTENT_204);
private static final int REQUEST_TIMEOUT_MS = 10_000;

private final Logger logger = LoggerFactory.getLogger(GatewayWebTargets.class);
private final Gson jsonParser = new Gson();
Expand Down Expand Up @@ -248,7 +249,8 @@ protected synchronized String invoke(HttpMethod method, String url, @Nullable Qu
logger.trace("invoke() request JSON:{}", jsonCommand);
}
}
Request request = httpClient.newRequest(url).method(method).header("Connection", "close").accept("*/*");
Request request = httpClient.newRequest(url).method(method).header("Connection", "close").accept("*/*")
.timeout(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
if (query != null) {
request.param(query.getKey(), query.getValue());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import java.time.Instant;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.eclipse.jdt.annotation.NonNullByDefault;
Expand Down Expand Up @@ -75,6 +76,7 @@
*/
@NonNullByDefault
public class HDPowerViewWebTargets {
private static final int REQUEST_TIMEOUT_MS = 30_000;

private final Logger logger = LoggerFactory.getLogger(HDPowerViewWebTargets.class);

Expand Down Expand Up @@ -581,7 +583,8 @@ private synchronized String invoke(HttpMethod method, String url, @Nullable Quer
logger.trace("JSON command = {}", jsonCommand);
}
}
Request request = httpClient.newRequest(url).method(method).header("Connection", "close").accept("*/*");
Request request = httpClient.newRequest(url).method(method).header("Connection", "close").accept("*/*")
.timeout(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
if (query != null) {
request.param(query.getKey(), query.getValue());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,8 @@ public PullJob(HttpClient httpClient, URI sourceURI, @Nullable String username,

@Override
public void run() {
final Request request = httpClient.newRequest(sourceURI).followRedirects(true).method(HttpMethod.GET);
final Request request = httpClient.newRequest(sourceURI).followRedirects(true).method(HttpMethod.GET)
.timeout(HTTP_TIMEOUT_SECS, TimeUnit.SECONDS);
final Authentication.Result currentAuthentication = authentication;
if (currentAuthentication != null) {
currentAuthentication.apply(request);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.eclipse.jdt.annotation.NonNullByDefault;
Expand Down Expand Up @@ -54,6 +55,7 @@ public class JuiceNetApi {
private static final String API_HOST = "https://jbv1-api.emotorwerks.com/";
private static final String API_ACCOUNT = API_HOST + "box_pin";
private static final String API_DEVICE = API_HOST + "box_api_secure";
private static final int REQUEST_TIMEOUT_MS = 10_000;

private String apiToken = "";
private HttpClient httpClient;
Expand Down Expand Up @@ -180,6 +182,7 @@ public JsonObject postApiCommand(ApiCommand cmd, @Nullable String token)
public JsonObject postApiCommand(ApiCommand cmd, @Nullable String token, Map<String, Object> params)
throws InterruptedException, JuiceNetApiException {
Request request = httpClient.POST(cmd.uri);
request.timeout(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
request.header(HttpHeader.CONTENT_TYPE, "application/json");

// Add required params
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.eclipse.jdt.annotation.NonNullByDefault;
Expand All @@ -42,6 +43,8 @@
@NonNullByDefault
public class SecondGenerationConfigurationHandler {

private static final int REQUEST_TIMEOUT_MS = 5000;

public static void executeConfigurationChanges(HttpClient httpClient, String url, String username, String password,
String dxsId, String value)
throws InterruptedException, ExecutionException, TimeoutException, NoSuchAlgorithmException {
Expand Down Expand Up @@ -75,7 +78,8 @@ public static void executeConfigurationChanges(HttpClient httpClient, String url
String loginPostJsonData = "{\"mode\":1,\"userId\":\"" + username + "\",\"pwh\":\"" + saltedmDigestedPwd
+ "\"}";

Request loginPostJsonResponse = httpClient.POST(urlLogin + "?sessionId=" + sessionId);
Request loginPostJsonResponse = httpClient.POST(urlLogin + "?sessionId=" + sessionId)
.timeout(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
loginPostJsonResponse.header(HttpHeader.CONTENT_TYPE, "application/json");
loginPostJsonResponse.content(new StringContentProvider(loginPostJsonData));
ContentResponse loginPostJsonDataContentResponse = loginPostJsonResponse.send();
Expand All @@ -91,7 +95,8 @@ public static void executeConfigurationChanges(HttpClient httpClient, String url
// Part for sending data to Inverter
String postJsonData = "{\"dxsEntries\":[{\"dxsId\":" + dxsId + ",\"value\":" + value + "}]}";

Request postJsonDataRequest = httpClient.POST(url + "/api/dxs.json?sessionId=" + sessionId);
Request postJsonDataRequest = httpClient.POST(url + "/api/dxs.json?sessionId=" + sessionId)
.timeout(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
postJsonDataRequest.header(HttpHeader.CONTENT_TYPE, "application/json");
postJsonDataRequest.content(new StringContentProvider(postJsonData));
postJsonDataRequest.send();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.eclipse.jdt.annotation.NonNullByDefault;
Expand Down Expand Up @@ -58,6 +59,7 @@
public class LiquidCheckDiscoveryService extends AbstractDiscoveryService {

private static final int DISCOVER_TIMEOUT_SECONDS = 300;
private static final int REQUEST_TIMEOUT_MS = 10_000;

private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final HttpClient httpClient;
Expand Down Expand Up @@ -97,7 +99,8 @@ protected Runnable liquidCheckDiscoveryRunnable() {
List<InetAddress> hosts = findActiveHosts(addresses);
for (InetAddress host : hosts) {
Request request = httpClient.newRequest("http://" + host.getHostAddress() + "/infos.json")
.method(HttpMethod.GET).followRedirects(false);
.timeout(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS).method(HttpMethod.GET)
.followRedirects(false);
try {
ContentResponse response = request.send();
if (response.getStatus() == 200) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
*/
@NonNullByDefault
public class LiquidCheckHttpClient {

private final Logger logger = LoggerFactory.getLogger(LiquidCheckHttpClient.class);
private final HttpClient client;
private final LiquidCheckConfiguration config;
Expand Down Expand Up @@ -78,7 +77,7 @@ public String pollData() throws InterruptedException, TimeoutException, Executio
*/
public String measureCommand() throws InterruptedException, TimeoutException, ExecutionException {
String uri = "http://" + config.hostname + "/command";
Request request = client.newRequest(uri);
Request request = client.newRequest(uri).timeout(config.connectionTimeout, TimeUnit.SECONDS);
request.method(HttpMethod.POST);
request.header(HttpHeader.CONTENT_TYPE, "applicaton/json");
request.content(new StringContentProvider(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
@NonNullByDefault
public class McdBridgeHandler extends BaseBridgeHandler {

private static final int REQUEST_TIMEOUT_MS = 10_000;
private final Logger logger = LoggerFactory.getLogger(McdBridgeHandler.class);

private @Nullable McdBridgeConfiguration config;
Expand Down Expand Up @@ -107,7 +108,9 @@ protected void logMeIn() {
Request request = httpClient.newRequest("https://cunds-syncapi.azurewebsites.net/token")
.method(HttpMethod.POST).header(HttpHeader.CONTENT_TYPE, "application/x-www-form-urlencoded")
.header(HttpHeader.HOST, "cunds-syncapi.azurewebsites.net")
.header(HttpHeader.ACCEPT, "application/json");
.header(HttpHeader.ACCEPT, "application/json")
.timeout(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);

String content = "grant_type=password&username=" + localConfig.getUserEmail() + "&password="
+ localConfig.getUserPassword();
request.content(new StringContentProvider(content), "application/x-www-form-urlencoded");
Expand Down
Loading

0 comments on commit 7313415

Please sign in to comment.