]> git.basschouten.com Git - openhab-addons.git/blob
f147b0a26ca1714e698fa1aa66c8de4af39f42a3
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.weathercompany.internal.handler;
14
15 import java.io.IOException;
16 import java.util.concurrent.Future;
17 import java.util.concurrent.TimeUnit;
18
19 import org.apache.commons.lang3.exception.ExceptionUtils;
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.eclipse.jetty.client.HttpResponseException;
23 import org.openhab.binding.weathercompany.internal.config.WeatherCompanyBridgeConfig;
24 import org.openhab.core.io.net.http.HttpUtil;
25 import org.openhab.core.thing.Bridge;
26 import org.openhab.core.thing.ChannelUID;
27 import org.openhab.core.thing.ThingStatus;
28 import org.openhab.core.thing.ThingStatusDetail;
29 import org.openhab.core.thing.binding.BaseBridgeHandler;
30 import org.openhab.core.types.Command;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 /**
35  * The {@link WeatherCompanyBridgeHandler} is responsible for validating the API key
36  * used to access the Weather Company API.
37  *
38  * @author Mark Hilbush - Initial contribution
39  */
40 @NonNullByDefault
41 public class WeatherCompanyBridgeHandler extends BaseBridgeHandler {
42     private static final long KEY_VALIDATION_FREQ_SECONDS = 120L;
43     private static final String BASE_URL = "https://api.weather.com/v3/location/search?query=chicago&locationType=locid&language=en-US&format=json&apiKey=";
44
45     private final Logger logger = LoggerFactory.getLogger(WeatherCompanyBridgeHandler.class);
46
47     private @Nullable Future<?> validateApiKeyJob;
48
49     private final Runnable validateApiKeyRunnable = new Runnable() {
50         @Override
51         public void run() {
52             logger.debug("Bridge: Attempting to validate API key");
53             try {
54                 String url = BASE_URL + getConfigAs(WeatherCompanyBridgeConfig.class).apiKey;
55                 String response = HttpUtil.executeUrl("GET", url, 10000);
56                 // If we get a response, we know the API key is valid
57                 logger.debug("Bridge: Got a successful response to key validation: '{}'", response);
58                 updateStatus(ThingStatus.ONLINE);
59                 cancelValidateApiKeyJob();
60             } catch (IOException e) {
61                 Throwable rootcause = ExceptionUtils.getRootCause(e);
62                 if (rootcause instanceof HttpResponseException
63                         && rootcause.getMessage().contains("Authentication challenge without")) {
64                     logger.debug("Bridge: HttpResponseException: API key is not valid");
65                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "API key is invalid");
66                 } else {
67                     logger.debug("Bridge: IOException trying to validate Api key: {}", e.getMessage());
68                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, e.getMessage());
69                 }
70             }
71         }
72     };
73
74     public WeatherCompanyBridgeHandler(Bridge thing) {
75         super(thing);
76     }
77
78     @Override
79     public void initialize() {
80         scheduleValidateApiKeyJob();
81     }
82
83     @Override
84     public void dispose() {
85         cancelValidateApiKeyJob();
86     }
87
88     @Override
89     public void handleCommand(ChannelUID channelUID, Command command) {
90         // Bridge doesn't handle any commands
91     }
92
93     public @Nullable String getApiKey() {
94         return getConfigAs(WeatherCompanyBridgeConfig.class).apiKey;
95     }
96
97     private void scheduleValidateApiKeyJob() {
98         cancelValidateApiKeyJob();
99         validateApiKeyJob = scheduler.scheduleWithFixedDelay(validateApiKeyRunnable, 0L, KEY_VALIDATION_FREQ_SECONDS,
100                 TimeUnit.SECONDS);
101         logger.debug("Bridge: Scheduling job to validate API key");
102     }
103
104     private void cancelValidateApiKeyJob() {
105         if (validateApiKeyJob != null) {
106             validateApiKeyJob.cancel(true);
107             validateApiKeyJob = null;
108             logger.debug("Bridge: Canceling job to validate API key");
109         }
110     }
111 }