]> git.basschouten.com Git - openhab-addons.git/blob
9efc135742aeea89eda1b99c597dd22af473860f
[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.livisismarthome.internal.client;
14
15 import java.io.IOException;
16 import java.net.HttpURLConnection;
17 import java.net.URL;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jetty.http.HttpHeader;
21 import org.eclipse.jetty.http.HttpMethod;
22 import org.openhab.core.auth.client.oauth2.AccessTokenResponse;
23
24 /**
25  * The {@link URLConnectionFactory} is responsible for creating requests / connections.
26  * This is useful to avoid real connections in test mode (via replacing it with mocks).
27  *
28  * @author Sven Strohschein - Initial contribution
29  */
30 @NonNullByDefault
31 public class URLConnectionFactory {
32
33     public static final String CONTENT_TYPE = "application/json";
34     public static final int HTTP_REQUEST_TIMEOUT_MILLISECONDS = 10000;
35
36     private static final String BEARER = "Bearer ";
37
38     public HttpURLConnection createRequest(String url) throws IOException {
39         return (HttpURLConnection) new URL(url).openConnection();
40     }
41
42     public HttpURLConnection createBaseRequest(String url, HttpMethod httpMethod,
43             AccessTokenResponse accessTokenResponse) throws IOException {
44         HttpURLConnection urlConnection = createRequest(url);
45         urlConnection.setRequestMethod(httpMethod.asString());
46         urlConnection.setRequestProperty(HttpHeader.ACCEPT.asString(), CONTENT_TYPE);
47         urlConnection.setRequestProperty(HttpHeader.AUTHORIZATION.asString(),
48                 BEARER + accessTokenResponse.getAccessToken());
49         urlConnection.setConnectTimeout(HTTP_REQUEST_TIMEOUT_MILLISECONDS);
50         urlConnection.setReadTimeout(HTTP_REQUEST_TIMEOUT_MILLISECONDS);
51         return urlConnection;
52     }
53 }