]> git.basschouten.com Git - openhab-addons.git/blob
41d4e1344815d0368df1d0a1f4acec5191f93dce
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.Servlet;
24 import javax.servlet.ServletException;
25 import javax.servlet.http.HttpServlet;
26 import javax.servlet.http.HttpServletRequest;
27 import javax.servlet.http.HttpServletResponse;
28
29 import org.eclipse.jdt.annotation.NonNullByDefault;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.openhab.binding.shelly.internal.ShellyHandlerFactory;
32 import org.openhab.binding.shelly.internal.api.ShellyApiException;
33 import org.openhab.binding.shelly.internal.manager.ShellyManagerPage.ShellyMgrResponse;
34 import org.openhab.binding.shelly.internal.provider.ShellyTranslationProvider;
35 import org.openhab.core.io.net.http.HttpClientFactory;
36 import org.openhab.core.net.HttpServiceUtil;
37 import org.openhab.core.net.NetworkAddressService;
38 import org.osgi.service.cm.ConfigurationAdmin;
39 import org.osgi.service.component.ComponentContext;
40 import org.osgi.service.component.annotations.Activate;
41 import org.osgi.service.component.annotations.Component;
42 import org.osgi.service.component.annotations.ConfigurationPolicy;
43 import org.osgi.service.component.annotations.Deactivate;
44 import org.osgi.service.component.annotations.Reference;
45 import org.osgi.service.http.whiteboard.propertytypes.HttpWhiteboardServletName;
46 import org.osgi.service.http.whiteboard.propertytypes.HttpWhiteboardServletPattern;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 /**
51  * {@link ShellyManagerServlet} implements the Shelly Manager - a simple device overview/management
52  *
53  * @author Markus Michels - Initial contribution
54  */
55 @NonNullByDefault
56 @Component(service = Servlet.class, configurationPolicy = ConfigurationPolicy.OPTIONAL)
57 @HttpWhiteboardServletName(ShellyManagerServlet.SERVLET_URI)
58 @HttpWhiteboardServletPattern(ShellyManagerServlet.SERVLET_URI + "/*")
59 public class ShellyManagerServlet extends HttpServlet {
60     private static final long serialVersionUID = 1393403713585449126L;
61     private final Logger logger = LoggerFactory.getLogger(ShellyManagerServlet.class);
62
63     public static final String SERVLET_URI = SHELLY_MANAGER_URI;
64     private final ShellyManager manager;
65     private final String className;
66
67     @Activate
68     public ShellyManagerServlet(@Reference ConfigurationAdmin configurationAdmin,
69             @Reference NetworkAddressService networkAddressService, @Reference HttpClientFactory httpClientFactory,
70             @Reference ShellyHandlerFactory handlerFactory, @Reference ShellyTranslationProvider translationProvider,
71             ComponentContext componentContext, Map<String, Object> config) {
72         className = substringAfterLast(getClass().toString(), ".");
73         String localIp = getString(networkAddressService.getPrimaryIpv4HostAddress());
74         Integer localPort = HttpServiceUtil.getHttpServicePort(componentContext.getBundleContext());
75         this.manager = new ShellyManager(configurationAdmin, translationProvider,
76                 httpClientFactory.getCommonHttpClient(), localIp, localPort, handlerFactory);
77
78         // Promote Shelly Manager usage
79         logger.info("{}", translationProvider.get("status.managerstarted", localIp, localPort.toString()));
80     }
81
82     @Deactivate
83     protected void deactivate() {
84         logger.debug("{} stopped", className);
85     }
86
87     @Override
88     protected void service(@Nullable HttpServletRequest request, @Nullable HttpServletResponse response)
89             throws ServletException, IOException, IllegalArgumentException {
90         if ((request == null) || (response == null)) {
91             logger.debug("request or resp must not be null!");
92             return;
93         }
94
95         String path = getString(request.getRequestURI()).toLowerCase();
96         String ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
97         ShellyMgrResponse output = new ShellyMgrResponse();
98         PrintWriter print = null;
99         OutputStream bin = null;
100         try {
101             if (ipAddress == null) {
102                 ipAddress = request.getRemoteAddr();
103             }
104             Map<String, String[]> parameters = request.getParameterMap();
105             logger.debug("{}: {} Request from {}:{}{}?{}", className, request.getProtocol(), ipAddress,
106                     request.getRemotePort(), path, parameters.toString());
107             if (!path.toLowerCase().startsWith(SERVLET_URI)) {
108                 logger.warn("{} received unknown request: path = {}", className, path);
109                 return;
110             }
111
112             output = manager.generateContent(path, parameters);
113             response.setContentType(output.mimeType);
114             if ("text/html".equals(output.mimeType)) {
115                 // Make sure it's UTF-8 encoded
116                 response.setCharacterEncoding(UTF_8);
117                 print = response.getWriter();
118                 print.write((String) output.data);
119             } else {
120                 // binary data
121                 byte[] data = (byte[]) output.data;
122                 if (data != null) {
123                     response.setContentLength(data.length);
124                     bin = response.getOutputStream();
125                     bin.write(data, 0, data.length);
126                 }
127             }
128         } catch (ShellyApiException | RuntimeException e) {
129             logger.debug("{}: Exception uri={}, parameters={}", className, path, request.getParameterMap().toString(),
130                     e);
131             response.setContentType("text/html");
132             print = response.getWriter();
133             print.write("Exception:" + e.toString() + "<br/>Check openhab.log for details."
134                     + "<p/><a href=\"/shelly/manager\">Return to Overview</a>");
135             logger.debug("{}: {}", className, output);
136             response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
137         } finally {
138             if (print != null) {
139                 print.close();
140             }
141             if (bin != null) {
142                 bin.close();
143             }
144         }
145     }
146 }