2 * Copyright (c) 2010-2021 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.shelly.internal.manager;
15 import static org.openhab.binding.shelly.internal.manager.ShellyManagerConstants.*;
16 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
18 import java.io.IOException;
19 import java.io.OutputStream;
20 import java.io.PrintWriter;
23 import javax.servlet.ServletException;
24 import javax.servlet.http.HttpServlet;
25 import javax.servlet.http.HttpServletRequest;
26 import javax.servlet.http.HttpServletResponse;
28 import org.eclipse.jdt.annotation.NonNullByDefault;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.openhab.binding.shelly.internal.ShellyHandlerFactory;
31 import org.openhab.binding.shelly.internal.api.ShellyApiException;
32 import org.openhab.binding.shelly.internal.manager.ShellyManagerPage.ShellyMgrResponse;
33 import org.openhab.binding.shelly.internal.provider.ShellyTranslationProvider;
34 import org.openhab.core.io.net.http.HttpClientFactory;
35 import org.openhab.core.net.HttpServiceUtil;
36 import org.openhab.core.net.NetworkAddressService;
37 import org.osgi.service.cm.ConfigurationAdmin;
38 import org.osgi.service.component.ComponentContext;
39 import org.osgi.service.component.annotations.Activate;
40 import org.osgi.service.component.annotations.Component;
41 import org.osgi.service.component.annotations.ConfigurationPolicy;
42 import org.osgi.service.component.annotations.Deactivate;
43 import org.osgi.service.component.annotations.Reference;
44 import org.osgi.service.http.HttpService;
45 import org.osgi.service.http.NamespaceException;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
50 * {@link ShellyManagerServlet} implements the Shelly Manager - a simple device overview/management
52 * @author Markus Michels - Initial contribution
55 @Component(service = HttpServlet.class, configurationPolicy = ConfigurationPolicy.OPTIONAL)
56 public class ShellyManagerServlet extends HttpServlet {
57 private static final long serialVersionUID = 1393403713585449126L;
58 private final Logger logger = LoggerFactory.getLogger(ShellyManagerServlet.class);
60 private static final String SERVLET_URI = SHELLY_MANAGER_URI;
61 private final ShellyManager manager;
62 private final String className;
64 private final HttpService httpService;
67 public ShellyManagerServlet(@Reference ConfigurationAdmin configurationAdmin,
68 @Reference NetworkAddressService networkAddressService, @Reference HttpService httpService,
69 @Reference HttpClientFactory httpClientFactory, @Reference ShellyHandlerFactory handlerFactory,
70 @Reference ShellyTranslationProvider translationProvider, ComponentContext componentContext,
71 Map<String, Object> config) {
72 className = substringAfterLast(getClass().toString(), ".");
73 this.httpService = httpService;
74 String localIp = getString(networkAddressService.getPrimaryIpv4HostAddress());
75 int localPort = HttpServiceUtil.getHttpServicePort(componentContext.getBundleContext());
76 this.manager = new ShellyManager(configurationAdmin, translationProvider,
77 httpClientFactory.getCommonHttpClient(), localIp, localPort, handlerFactory);
80 httpService.registerServlet(SERVLET_URI, this, null, httpService.createDefaultHttpContext());
81 logger.debug("{}: Started at '{}'", className, SERVLET_URI);
82 } catch (NamespaceException | ServletException | IllegalArgumentException e) {
83 logger.warn("{}: Unable to initialize bindingConfig", className, e);
88 protected void deactivate() {
89 httpService.unregister(SERVLET_URI);
90 logger.debug("{} stopped", className);
94 protected void service(@Nullable HttpServletRequest request, @Nullable HttpServletResponse response)
95 throws ServletException, IOException, IllegalArgumentException {
96 if ((request == null) || (response == null)) {
97 logger.debug("request or resp must not be null!");
101 String path = getString(request.getRequestURI()).toLowerCase();
102 String ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
103 ShellyMgrResponse output = new ShellyMgrResponse();
104 PrintWriter print = null;
105 OutputStream bin = null;
107 if (ipAddress == null) {
108 ipAddress = request.getRemoteAddr();
110 Map<String, String[]> parameters = request.getParameterMap();
111 logger.debug("{}: {} Request from {}:{}{}?{}", className, request.getProtocol(), ipAddress,
112 request.getRemotePort(), path, parameters.toString());
113 if (!path.toLowerCase().startsWith(SERVLET_URI)) {
114 logger.warn("{} received unknown request: path = {}", className, path);
118 output = manager.generateContent(path, parameters);
119 response.setContentType(output.mimeType);
120 if (output.mimeType.equals("text/html")) {
121 // Make sure it's UTF-8 encoded
122 response.setCharacterEncoding(UTF_8);
123 print = response.getWriter();
124 print.write((String) output.data);
127 byte[] data = (byte[]) output.data;
129 response.setContentLength(data.length);
130 bin = response.getOutputStream();
131 bin.write(data, 0, data.length);
134 } catch (ShellyApiException | RuntimeException e) {
135 logger.debug("{}: Exception uri={}, parameters={}", className, path, request.getParameterMap().toString(),
137 response.setContentType("text/html");
138 print = response.getWriter();
139 print.write("Exception:" + e.toString() + "<br/>Check openHAB.log for details."
140 + "<p/><a href=\"/shelly/manager\">Return to Overview</a>");
141 logger.debug("{}: {}", className, output);
142 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);