2 * Copyright (c) 2010-2023 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.wundergroundupdatereceiver.internal;
15 import static java.util.stream.Collectors.toMap;
16 import static java.util.stream.Collectors.toSet;
17 import static org.openhab.binding.wundergroundupdatereceiver.internal.WundergroundUpdateReceiverBindingConstants.*;
19 import java.io.IOException;
20 import java.io.PrintWriter;
21 import java.time.Instant;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.HashSet;
26 import java.util.Optional;
28 import java.util.regex.Pattern;
30 import javax.servlet.Servlet;
31 import javax.servlet.http.HttpServlet;
32 import javax.servlet.http.HttpServletRequest;
33 import javax.servlet.http.HttpServletResponse;
35 import org.eclipse.jdt.annotation.NonNullByDefault;
36 import org.eclipse.jdt.annotation.Nullable;
37 import org.osgi.service.component.annotations.Activate;
38 import org.osgi.service.component.annotations.Component;
39 import org.osgi.service.component.annotations.Deactivate;
40 import org.osgi.service.component.annotations.Reference;
41 import org.osgi.service.http.whiteboard.propertytypes.HttpWhiteboardServletName;
42 import org.osgi.service.http.whiteboard.propertytypes.HttpWhiteboardServletPattern;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
47 * The {@link WundergroundUpdateReceiverServlet} is responsible for receiving updates,and
48 * updating the matching channels.
50 * @author Daniel Demus - Initial contribution
53 @HttpWhiteboardServletName(WundergroundUpdateReceiverServlet.SERVLET_URL)
54 @HttpWhiteboardServletPattern(WundergroundUpdateReceiverServlet.SERVLET_URL)
55 @Component(immediate = true, service = { Servlet.class, WundergroundUpdateReceiverServlet.class })
56 public class WundergroundUpdateReceiverServlet extends HttpServlet
57 implements WundergroundUpdateReceiverServletControls {
59 public static final String SERVLET_URL = "/weatherstation/updateweatherstation.php";
60 private static final long serialVersionUID = -5296703727081438023L;
61 private static final Pattern CLEANER = Pattern.compile("[^\\w-]");
63 private final Logger logger = LoggerFactory.getLogger(WundergroundUpdateReceiverServlet.class);
64 private final Map<String, WundergroundUpdateReceiverHandler> handlers = new HashMap<>();
66 private static final Object LOCK = new Object();
67 private final WundergroundUpdateReceiverDiscoveryService discoveryService;
69 private boolean active = false;
70 private String errorDetail = "";
73 public WundergroundUpdateReceiverServlet(
74 final @Reference WundergroundUpdateReceiverDiscoveryService discoveryService) {
75 this.discoveryService = discoveryService;
77 active = discoveryService.isBackgroundDiscoveryEnabled();
81 public boolean isActive() {
87 public String getErrorDetail() {
89 return this.errorDetail;
93 public Set<String> getStationIds() {
94 return this.handlers.keySet();
97 public void addHandler(WundergroundUpdateReceiverHandler handler) {
98 synchronized (this.handlers) {
99 if (this.handlers.containsKey(handler.getStationId())) {
100 errorDetail = "Handler handling request for stationId " + handler.getStationId() + " is already added";
101 logger.warn("Error during handler registration - StationId {} already being handled",
102 handler.getStationId());
105 this.handlers.put(handler.getStationId(), handler);
113 public void removeHandler(String stationId) {
114 synchronized (this.handlers) {
115 WundergroundUpdateReceiverHandler handler = this.handlers.get(stationId);
116 if (handler != null) {
117 this.handlers.remove(stationId);
119 if (this.handlers.isEmpty() && !this.discoveryService.isBackgroundDiscoveryEnabled()) {
126 public void enable() {
132 public void disable() {
137 public void handlerConfigUpdated(WundergroundUpdateReceiverHandler handler) {
138 synchronized (this.handlers) {
139 final Set<Map.Entry<String, WundergroundUpdateReceiverHandler>> changedStationIds = this.handlers.entrySet()
140 .stream().filter(entry -> handler.getThing().getUID().equals(entry.getValue().getThing().getUID()))
142 changedStationIds.forEach(entry -> {
143 logger.debug("Re-assigning listener from station id {} to station id {}", entry.getKey(),
144 handler.getStationId());
145 this.removeHandler(entry.getKey());
146 this.addHandler(handler);
151 public void dispose() {
152 synchronized (this.handlers) {
153 Set<String> stationIds = new HashSet<>(getStationIds());
154 stationIds.forEach(this::removeHandler);
159 protected Map<String, String> normalizeParameterMap(Map<String, String[]> parameterMap) {
160 return parameterMap.entrySet().stream()
161 .collect(toMap(e -> makeUidSafeString(e.getKey()), e -> String.join("", e.getValue())));
165 protected void doGet(@Nullable HttpServletRequest req, @Nullable HttpServletResponse resp) throws IOException {
175 if (req.getRequestURI() == null) {
178 logger.trace("doGet {}", req.getQueryString());
180 String stationId = req.getParameter(STATION_ID_PARAMETER);
181 Map<String, String> states = normalizeParameterMap(req.getParameterMap());
182 Optional.ofNullable(this.handlers.get(stationId)).ifPresentOrElse(handler -> {
183 String queryString = req.getQueryString();
184 if (queryString != null && queryString.length() > 0) {
185 states.put(LAST_QUERY, queryString);
187 handler.updateChannelStates(states);
189 this.discoveryService.addUnhandledStationId(stationId, states);
192 resp.setStatus(HttpServletResponse.SC_OK);
193 resp.setContentType("text/html;charset=utf-8");
194 resp.setContentLength(7);
195 resp.setDateHeader("Date", Instant.now().toEpochMilli());
196 resp.setHeader("Connection", "close");
197 PrintWriter writer = resp.getWriter();
198 writer.write("success");
203 protected Map<String, WundergroundUpdateReceiverHandler> getHandlers() {
204 return Collections.unmodifiableMap(this.handlers);
207 private String makeUidSafeString(String key) {
208 return CLEANER.matcher(key).replaceAll("-");