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.nzwateralerts.internal.api;
15 import static org.openhab.binding.nzwateralerts.internal.NZWaterAlertsBindingConstants.*;
17 import java.util.concurrent.ExecutionException;
18 import java.util.concurrent.TimeUnit;
19 import java.util.concurrent.TimeoutException;
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.eclipse.jetty.client.HttpClient;
24 import org.eclipse.jetty.client.api.ContentResponse;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
29 * The {@link WebClient} class contains the logic to get data from a URL.
31 * @author Stewart Cossey - Initial contribution
34 public class WaterAlertWebClient {
35 private final Logger logger = LoggerFactory.getLogger(WaterAlertWebClient.class);
37 private static final int REQUEST_TIMEOUT = 10;
39 private final HttpClient httpClient;
40 private final String webService;
41 private final String region;
42 private final String area;
44 private @Nullable WaterWebService service = null;
46 public WaterAlertWebClient(final HttpClient httpClient, final String location) {
47 this.httpClient = httpClient;
49 final String[] locationSegmented = location.split(":", 3);
50 webService = locationSegmented[0];
51 region = locationSegmented[1];
52 area = locationSegmented[2];
54 for (final WaterWebService srv : WATER_WEB_SERVICES) {
55 logger.trace("Checking service {}", srv.service());
56 if (locationSegmented[0].equalsIgnoreCase(srv.service())) {
57 logger.trace("Found service {}", srv.service());
62 if (service == null) {
63 logger.debug("Service could not be found for {}", locationSegmented[0]);
67 public @Nullable Integer getLevel() {
68 ContentResponse response;
69 final WaterWebService localService = service;
71 if (localService != null) {
72 logger.debug("Getting Water Level from service {} region {} area {}", webService, region, area);
74 final String endpoint = localService.endpoint(region);
75 logger.trace("Getting data from endpoint {} with timeout {}", endpoint, REQUEST_TIMEOUT);
76 response = httpClient.newRequest(endpoint).timeout(REQUEST_TIMEOUT, TimeUnit.SECONDS).send();
78 final int waterLevel = localService.findWaterLevel(response.getContentAsString(), area);
79 logger.debug("Got water level {}", waterLevel);
82 logger.debug("Service, region is null");
85 } catch (InterruptedException | ExecutionException | TimeoutException e) {
86 logger.debug("Error when attempting to get Water Level {}", e.getMessage());