]> git.basschouten.com Git - openhab-addons.git/blob
29ab82997f268c68010b0e91188db30f2b31ad63
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.shelly.internal.manager;
14
15 import static org.openhab.binding.shelly.internal.manager.ShellyManagerConstants.*;
16 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
17
18 import java.io.IOException;
19 import java.io.OutputStream;
20 import java.io.PrintWriter;
21 import java.util.Map;
22
23 import javax.servlet.ServletException;
24 import javax.servlet.http.HttpServlet;
25 import javax.servlet.http.HttpServletRequest;
26 import javax.servlet.http.HttpServletResponse;
27
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;
48
49 /**
50  * {@link ShellyManagerServlet} implements the Shelly Manager - a simple device overview/management
51  *
52  * @author Markus Michels - Initial contribution
53  */
54 @NonNullByDefault
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);
59
60     private static final String SERVLET_URI = SHELLY_MANAGER_URI;
61     private final ShellyManager manager;
62     private final String className;
63
64     private final HttpService httpService;
65
66     @Activate
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);
78
79         try {
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);
84         }
85     }
86
87     @Deactivate
88     protected void deactivate() {
89         httpService.unregister(SERVLET_URI);
90         logger.debug("{} stopped", className);
91     }
92
93     @Override
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!");
98             return;
99         }
100
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;
106         try {
107             if (ipAddress == null) {
108                 ipAddress = request.getRemoteAddr();
109             }
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);
115                 return;
116             }
117
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);
125             } else {
126                 // binary data
127                 byte[] data = (byte[]) output.data;
128                 if (data != null) {
129                     response.setContentLength(data.length);
130                     bin = response.getOutputStream();
131                     bin.write(data, 0, data.length);
132                 }
133             }
134         } catch (ShellyApiException | RuntimeException e) {
135             logger.debug("{}: Exception uri={}, parameters={}", className, path, request.getParameterMap().toString(),
136                     e);
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);
143         } finally {
144             if (print != null) {
145                 print.close();
146             }
147             if (bin != null) {
148                 bin.close();
149             }
150         }
151     }
152 }