]> git.basschouten.com Git - openhab-addons.git/blob
27229541ae780c7041e4d31ef88f16a72b11463b
[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.homeconnect.internal.servlet;
14
15 import static java.nio.charset.StandardCharsets.UTF_8;
16 import static java.time.ZonedDateTime.now;
17 import static java.time.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME;
18 import static org.openhab.binding.homeconnect.internal.HomeConnectBindingConstants.*;
19
20 import java.io.IOException;
21 import java.time.ZonedDateTime;
22 import java.time.format.DateTimeFormatter;
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Optional;
28 import java.util.Set;
29 import java.util.concurrent.CopyOnWriteArraySet;
30 import java.util.stream.Collectors;
31
32 import javax.servlet.ServletException;
33 import javax.servlet.http.HttpServlet;
34 import javax.servlet.http.HttpServletRequest;
35 import javax.servlet.http.HttpServletResponse;
36 import javax.ws.rs.core.MediaType;
37
38 import org.eclipse.jdt.annotation.NonNullByDefault;
39 import org.eclipse.jdt.annotation.Nullable;
40 import org.eclipse.jetty.http.HttpStatus;
41 import org.openhab.binding.homeconnect.internal.client.exception.ApplianceOfflineException;
42 import org.openhab.binding.homeconnect.internal.client.exception.AuthorizationException;
43 import org.openhab.binding.homeconnect.internal.client.exception.CommunicationException;
44 import org.openhab.binding.homeconnect.internal.client.model.ApiRequest;
45 import org.openhab.binding.homeconnect.internal.handler.AbstractHomeConnectThingHandler;
46 import org.openhab.binding.homeconnect.internal.handler.HomeConnectBridgeHandler;
47 import org.openhab.core.OpenHAB;
48 import org.openhab.core.auth.client.oauth2.AccessTokenResponse;
49 import org.openhab.core.auth.client.oauth2.OAuthException;
50 import org.openhab.core.auth.client.oauth2.OAuthResponseException;
51 import org.osgi.framework.FrameworkUtil;
52 import org.osgi.service.component.annotations.Activate;
53 import org.osgi.service.component.annotations.Component;
54 import org.osgi.service.component.annotations.Deactivate;
55 import org.osgi.service.component.annotations.Reference;
56 import org.osgi.service.component.annotations.ServiceScope;
57 import org.osgi.service.http.HttpService;
58 import org.osgi.service.http.NamespaceException;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61 import org.thymeleaf.TemplateEngine;
62 import org.thymeleaf.context.WebContext;
63 import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect;
64 import org.thymeleaf.templatemode.TemplateMode;
65 import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
66
67 import com.google.gson.Gson;
68 import com.google.gson.GsonBuilder;
69 import com.google.gson.JsonPrimitive;
70 import com.google.gson.JsonSerializer;
71
72 /**
73  *
74  * Home Connect servlet.
75  *
76  * @author Jonas BrĂ¼stel - Initial Contribution
77  */
78 @NonNullByDefault
79 @Component(service = HomeConnectServlet.class, scope = ServiceScope.SINGLETON, immediate = true)
80 public class HomeConnectServlet extends HttpServlet {
81
82     private static final String SLASH = "/";
83     private static final String SERVLET_NAME = "homeconnect";
84     private static final String SERVLET_PATH = SLASH + SERVLET_NAME;
85     private static final String ASSETS_PATH = SERVLET_PATH + "/asset";
86     private static final String ROOT_PATH = SLASH;
87     private static final String APPLIANCES_PATH = "/appliances";
88     private static final String REQUEST_LOG_PATH = "/log/requests";
89     private static final String EVENT_LOG_PATH = "/log/events";
90     private static final String DEFAULT_CONTENT_TYPE = "text/html; charset=UTF-8";
91     private static final String PARAM_CODE = "code";
92     private static final String PARAM_STATE = "state";
93     private static final String PARAM_EXPORT = "export";
94     private static final String PARAM_ACTION = "action";
95     private static final String PARAM_BRIDGE_ID = "bridgeId";
96     private static final String PARAM_THING_ID = "thingId";
97     private static final String PARAM_PATH = "path";
98     private static final String ACTION_AUTHORIZE = "authorize";
99     private static final String ACTION_CLEAR_CREDENTIALS = "clearCredentials";
100     private static final String ACTION_SHOW_DETAILS = "show-details";
101     private static final String ACTION_ALL_PROGRAMS = "all-programs";
102     private static final String ACTION_AVAILABLE_PROGRAMS = "available-programs";
103     private static final String ACTION_SELECTED_PROGRAM = "selected-program";
104     private static final String ACTION_ACTIVE_PROGRAM = "active-program";
105     private static final String ACTION_OPERATION_STATE = "operation-state";
106     private static final String ACTION_POWER_STATE = "power-state";
107     private static final String ACTION_DOOR_STATE = "door-state";
108     private static final String ACTION_REMOTE_START_ALLOWED = "remote-control-start-allowed";
109     private static final String ACTION_REMOTE_CONTROL_ACTIVE = "remote-control-active";
110     private static final String ACTION_PUT_RAW = "put-raw";
111     private static final String ACTION_GET_RAW = "get-raw";
112     private static final DateTimeFormatter FILE_EXPORT_DTF = ISO_OFFSET_DATE_TIME;
113     private static final String EMPTY_RESPONSE = "{}";
114     private static final long serialVersionUID = -2449763690208703307L;
115
116     private final Logger logger = LoggerFactory.getLogger(HomeConnectServlet.class);
117     private final HttpService httpService;
118     private final TemplateEngine templateEngine;
119     private final Set<HomeConnectBridgeHandler> bridgeHandlers;
120     private final Gson gson;
121
122     @Activate
123     public HomeConnectServlet(@Reference HttpService httpService) {
124         bridgeHandlers = new CopyOnWriteArraySet<>();
125         gson = new GsonBuilder().registerTypeAdapter(ZonedDateTime.class, (JsonSerializer<ZonedDateTime>) (src,
126                 typeOfSrc, context) -> new JsonPrimitive(src.format(DateTimeFormatter.ISO_DATE_TIME))).create();
127         this.httpService = httpService;
128
129         // register servlet
130         try {
131             logger.debug("Initialize Home Connect configuration servlet ({})", SERVLET_PATH);
132             httpService.registerServlet(SERVLET_PATH, this, null, httpService.createDefaultHttpContext());
133             httpService.registerResources(ASSETS_PATH, "assets", null);
134         } catch (ServletException | NamespaceException e) {
135             logger.warn("Could not register Home Connect servlet! ({})", SERVLET_PATH, e);
136         }
137
138         // setup template engine
139         ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(getServletContext());
140         templateResolver.setTemplateMode(TemplateMode.HTML);
141         templateResolver.setPrefix("/templates/");
142         templateResolver.setSuffix(".html");
143         templateResolver.setCacheable(true);
144         templateEngine = new TemplateEngine();
145         templateEngine.addDialect(new Java8TimeDialect());
146         templateEngine.setTemplateResolver(templateResolver);
147     }
148
149     @Deactivate
150     protected void dispose() {
151         httpService.unregister(SERVLET_PATH);
152         httpService.unregister(ASSETS_PATH);
153     }
154
155     @Override
156     protected void doGet(@Nullable HttpServletRequest request, @Nullable HttpServletResponse response)
157             throws IOException {
158         if (request == null || response == null) {
159             return;
160         }
161         response.setContentType(DEFAULT_CONTENT_TYPE);
162         response.setCharacterEncoding(UTF_8.name());
163
164         String path = request.getPathInfo();
165         if (path == null || path.isEmpty() || path.equals(ROOT_PATH)) {
166             String code = request.getParameter(PARAM_CODE);
167             String state = request.getParameter(PARAM_STATE);
168             if (code != null && state != null && !code.trim().isEmpty() && !state.trim().isEmpty()) {
169                 getBridgeAuthenticationPage(request, response, code, state);
170             } else {
171                 getBridgesPage(request, response);
172             }
173         } else if (pathMatches(path, APPLIANCES_PATH)) {
174             String action = request.getParameter(PARAM_ACTION);
175             String thingId = request.getParameter(PARAM_THING_ID);
176             if (action != null && thingId != null && !action.trim().isEmpty() && !thingId.trim().isEmpty()) {
177                 processApplianceActions(response, action, thingId);
178             } else {
179                 getAppliancesPage(request, response);
180             }
181         } else if (pathMatches(path, REQUEST_LOG_PATH)) {
182             String export = request.getParameter(PARAM_EXPORT);
183             String bridgeId = request.getParameter(PARAM_BRIDGE_ID);
184             if (export != null && bridgeId != null && !export.trim().isEmpty() && !bridgeId.trim().isEmpty()) {
185                 getRequestLogExport(response, bridgeId);
186             } else {
187                 getRequestLogPage(request, response);
188             }
189         } else if (pathMatches(path, EVENT_LOG_PATH)) {
190             String export = request.getParameter(PARAM_EXPORT);
191             String bridgeId = request.getParameter(PARAM_BRIDGE_ID);
192             if (export != null && bridgeId != null && !export.trim().isEmpty() && !bridgeId.trim().isEmpty()) {
193                 getEventLogExport(response, bridgeId);
194             } else {
195                 getEventLogPage(request, response);
196             }
197         } else {
198             response.sendError(HttpServletResponse.SC_NOT_FOUND);
199         }
200     }
201
202     @Override
203     protected void doPost(@Nullable HttpServletRequest request, @Nullable HttpServletResponse response)
204             throws IOException {
205         if (request == null || response == null) {
206             return;
207         }
208         response.setContentType("text/html; charset=UTF-8");
209         response.setCharacterEncoding("UTF-8");
210
211         String path = request.getPathInfo();
212         if (path == null || path.isEmpty() || path.equals(ROOT_PATH)) {
213             if (request.getParameter(PARAM_ACTION) != null && request.getParameter(PARAM_BRIDGE_ID) != null) {
214                 postBridgesPage(request, response);
215             } else {
216                 response.sendError(HttpServletResponse.SC_NOT_FOUND);
217             }
218         } else if (pathMatches(path, APPLIANCES_PATH)) {
219             String requestPayload = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
220             String action = request.getParameter(PARAM_ACTION);
221             String thingId = request.getParameter(PARAM_THING_ID);
222             String targetPath = request.getParameter(PARAM_PATH);
223
224             if ((ACTION_PUT_RAW.equals(action) || ACTION_GET_RAW.equals(action)) && thingId != null
225                     && targetPath != null && action != null) {
226                 processRawApplianceActions(response, action, thingId, targetPath, requestPayload);
227             } else {
228                 response.sendError(HttpServletResponse.SC_NOT_FOUND);
229             }
230         } else {
231             response.sendError(HttpServletResponse.SC_NOT_FOUND);
232         }
233     }
234
235     /**
236      * Add Home Connect bridge handler to configuration servlet, to allow user to authenticate against Home Connect API.
237      *
238      * @param bridgeHandler bridge handler
239      */
240     public void addBridgeHandler(HomeConnectBridgeHandler bridgeHandler) {
241         bridgeHandlers.add(bridgeHandler);
242     }
243
244     /**
245      * Remove Home Connect bridge handler from configuration servlet.
246      *
247      * @param bridgeHandler bridge handler
248      */
249     public void removeBridgeHandler(HomeConnectBridgeHandler bridgeHandler) {
250         bridgeHandlers.remove(bridgeHandler);
251     }
252
253     private void getAppliancesPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
254         WebContext context = new WebContext(request, response, request.getServletContext());
255         context.setVariable("bridgeHandlers", bridgeHandlers);
256         templateEngine.process("appliances", context, response.getWriter());
257     }
258
259     private void processApplianceActions(HttpServletResponse response, String action, String thingId)
260             throws IOException {
261         Optional<HomeConnectBridgeHandler> bridgeHandler = getBridgeHandlerForThing(thingId);
262         Optional<AbstractHomeConnectThingHandler> thingHandler = getThingHandler(thingId);
263
264         if (bridgeHandler.isPresent() && thingHandler.isPresent()) {
265             try {
266                 response.setContentType(MediaType.APPLICATION_JSON);
267                 String haId = thingHandler.get().getThingHaId();
268
269                 switch (action) {
270                     case ACTION_SHOW_DETAILS: {
271                         String actionResponse = bridgeHandler.get().getApiClient().getRaw(haId,
272                                 "/api/homeappliances/" + haId);
273                         response.getWriter().write(actionResponse != null ? actionResponse : EMPTY_RESPONSE);
274                         break;
275                     }
276                     case ACTION_ALL_PROGRAMS: {
277                         String actionResponse = bridgeHandler.get().getApiClient().getRaw(haId,
278                                 "/api/homeappliances/" + haId + "/programs");
279                         response.getWriter().write(actionResponse != null ? actionResponse : EMPTY_RESPONSE);
280                         break;
281                     }
282                     case ACTION_AVAILABLE_PROGRAMS: {
283                         String actionResponse = bridgeHandler.get().getApiClient().getRaw(haId,
284                                 "/api/homeappliances/" + haId + "/programs/available");
285                         response.getWriter().write(actionResponse != null ? actionResponse : EMPTY_RESPONSE);
286                         break;
287                     }
288                     case ACTION_SELECTED_PROGRAM: {
289                         String actionResponse = bridgeHandler.get().getApiClient().getRaw(haId,
290                                 "/api/homeappliances/" + haId + "/programs/selected");
291                         response.getWriter().write(actionResponse != null ? actionResponse : EMPTY_RESPONSE);
292                         break;
293                     }
294                     case ACTION_ACTIVE_PROGRAM: {
295                         String actionResponse = bridgeHandler.get().getApiClient().getRaw(haId,
296                                 "/api/homeappliances/" + haId + "/programs/active");
297                         response.getWriter().write(actionResponse != null ? actionResponse : EMPTY_RESPONSE);
298                         break;
299                     }
300                     case ACTION_OPERATION_STATE: {
301                         String actionResponse = bridgeHandler.get().getApiClient().getRaw(haId,
302                                 "/api/homeappliances/" + haId + "/status/" + EVENT_OPERATION_STATE);
303                         response.getWriter().write(actionResponse != null ? actionResponse : EMPTY_RESPONSE);
304                         break;
305                     }
306                     case ACTION_POWER_STATE: {
307                         String actionResponse = bridgeHandler.get().getApiClient().getRaw(haId,
308                                 "/api/homeappliances/" + haId + "/settings/" + EVENT_POWER_STATE);
309                         response.getWriter().write(actionResponse != null ? actionResponse : EMPTY_RESPONSE);
310                         break;
311                     }
312                     case ACTION_DOOR_STATE: {
313                         String actionResponse = bridgeHandler.get().getApiClient().getRaw(haId,
314                                 "/api/homeappliances/" + haId + "/status/" + EVENT_DOOR_STATE);
315                         response.getWriter().write(actionResponse != null ? actionResponse : EMPTY_RESPONSE);
316                         break;
317                     }
318                     case ACTION_REMOTE_START_ALLOWED: {
319                         String actionResponse = bridgeHandler.get().getApiClient().getRaw(haId,
320                                 "/api/homeappliances/" + haId + "/status/" + EVENT_REMOTE_CONTROL_START_ALLOWED);
321                         response.getWriter().write(actionResponse != null ? actionResponse : EMPTY_RESPONSE);
322                         break;
323                     }
324                     case ACTION_REMOTE_CONTROL_ACTIVE: {
325                         String actionResponse = bridgeHandler.get().getApiClient().getRaw(haId,
326                                 "/api/homeappliances/" + haId + "/status/" + EVENT_REMOTE_CONTROL_ACTIVE);
327                         response.getWriter().write(actionResponse != null ? actionResponse : EMPTY_RESPONSE);
328                         break;
329                     }
330                     default:
331                         response.sendError(HttpStatus.BAD_REQUEST_400, "Unknown action");
332                         break;
333                 }
334             } catch (CommunicationException | ApplianceOfflineException | AuthorizationException e) {
335                 logger.debug("Could not execute request! thingId={}, action={}, error={}", thingId, action,
336                         e.getMessage());
337                 response.sendError(HttpStatus.INTERNAL_SERVER_ERROR_500, e.getMessage());
338             }
339         } else {
340             response.sendError(HttpStatus.BAD_REQUEST_400, "Thing or bridge not found!");
341         }
342     }
343
344     private void processRawApplianceActions(HttpServletResponse response, String action, String thingId, String path,
345             String body) throws IOException {
346         Optional<HomeConnectBridgeHandler> bridgeHandler = getBridgeHandlerForThing(thingId);
347         Optional<AbstractHomeConnectThingHandler> thingHandler = getThingHandler(thingId);
348
349         if (bridgeHandler.isPresent() && thingHandler.isPresent()) {
350             try {
351                 response.setContentType(MediaType.APPLICATION_JSON);
352                 String haId = thingHandler.get().getThingHaId();
353
354                 if (ACTION_PUT_RAW.equals(action)) {
355                     String actionResponse = bridgeHandler.get().getApiClient().putRaw(haId, path, body);
356                     response.getWriter().write(actionResponse);
357                 } else if (ACTION_GET_RAW.equals(action)) {
358                     String actionResponse = bridgeHandler.get().getApiClient().getRaw(haId, path, true);
359                     if (actionResponse == null) {
360                         response.getWriter().write("{\"status\": \"No response\"}");
361                     } else {
362                         response.getWriter().write(actionResponse);
363                     }
364                 } else {
365                     response.sendError(HttpStatus.BAD_REQUEST_400, "Unknown action");
366                 }
367             } catch (CommunicationException | ApplianceOfflineException | AuthorizationException e) {
368                 logger.debug("Could not execute request! thingId={}, action={}, error={}", thingId, action,
369                         e.getMessage());
370                 response.sendError(HttpStatus.INTERNAL_SERVER_ERROR_500, e.getMessage());
371             }
372         } else {
373             response.sendError(HttpStatus.BAD_REQUEST_400, "Bridge or Thing not found!");
374         }
375     }
376
377     private void getBridgesPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
378         WebContext context = new WebContext(request, response, request.getServletContext());
379         context.setVariable("bridgeHandlers", bridgeHandlers);
380         templateEngine.process("bridges", context, response.getWriter());
381     }
382
383     private void postBridgesPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
384         String action = request.getParameter(PARAM_ACTION);
385         String bridgeId = request.getParameter(PARAM_BRIDGE_ID);
386         Optional<HomeConnectBridgeHandler> bridgeHandlerOptional = bridgeHandlers.stream().filter(
387                 homeConnectBridgeHandler -> homeConnectBridgeHandler.getThing().getUID().toString().equals(bridgeId))
388                 .findFirst();
389
390         if (bridgeHandlerOptional.isPresent()
391                 && (ACTION_AUTHORIZE.equals(action) || ACTION_CLEAR_CREDENTIALS.equals(action))) {
392             HomeConnectBridgeHandler bridgeHandler = bridgeHandlerOptional.get();
393             if (ACTION_AUTHORIZE.equals(action)) {
394                 try {
395                     String authorizationUrl = bridgeHandler.getOAuthClientService().getAuthorizationUrl(null, null,
396                             bridgeHandler.getThing().getUID().getAsString());
397                     logger.debug("Generated authorization url: {}", authorizationUrl);
398
399                     response.sendRedirect(authorizationUrl);
400                 } catch (OAuthException e) {
401                     logger.error("Could not create authorization url!", e);
402                     response.sendError(HttpStatus.INTERNAL_SERVER_ERROR_500, "Could not create authorization url!");
403                 }
404             } else {
405                 logger.info("Remove access token for '{}' bridge.", bridgeHandler.getThing().getLabel());
406                 try {
407                     bridgeHandler.getOAuthClientService().remove();
408                 } catch (OAuthException e) {
409                     logger.debug("Could not clear oAuth credentials. error={}", e.getMessage());
410                 }
411                 bridgeHandler.reinitialize();
412
413                 WebContext context = new WebContext(request, response, request.getServletContext());
414                 context.setVariable("action",
415                         bridgeHandler.getThing().getUID().getAsString() + ACTION_CLEAR_CREDENTIALS);
416                 context.setVariable("bridgeHandlers", bridgeHandlers);
417                 templateEngine.process("bridges", context, response.getWriter());
418             }
419         } else {
420             response.sendError(HttpStatus.BAD_REQUEST_400, "Unknown bridge or action is missing!");
421         }
422     }
423
424     private void getRequestLogPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
425         ArrayList<ApiRequest> requests = new ArrayList<>();
426         bridgeHandlers.forEach(homeConnectBridgeHandler -> requests
427                 .addAll(homeConnectBridgeHandler.getApiClient().getLatestApiRequests()));
428
429         WebContext context = new WebContext(request, response, request.getServletContext());
430         context.setVariable("bridgeHandlers", bridgeHandlers);
431         context.setVariable("requests", gson.toJson(requests));
432         templateEngine.process("log-requests", context, response.getWriter());
433     }
434
435     private void getRequestLogExport(HttpServletResponse response, String bridgeId) throws IOException {
436         Optional<HomeConnectBridgeHandler> bridgeHandler = getBridgeHandler(bridgeId);
437         if (bridgeHandler.isPresent()) {
438             response.setContentType(MediaType.APPLICATION_JSON);
439             String fileName = String.format("%s__%s__requests.json", now().format(FILE_EXPORT_DTF),
440                     bridgeId.replaceAll("[^a-zA-Z0-9]", "_"));
441             response.setHeader("Content-disposition", "attachment; filename=" + fileName);
442
443             HashMap<String, Object> responsePayload = new HashMap<>();
444             responsePayload.put("openHAB", OpenHAB.getVersion());
445             responsePayload.put("bundle", FrameworkUtil.getBundle(this.getClass()).getVersion().toString());
446             List<ApiRequest> apiRequestList = bridgeHandler.get().getApiClient().getLatestApiRequests().stream()
447                     .peek(apiRequest -> {
448                         Map<String, String> headers = apiRequest.getRequest().getHeader();
449                         if (headers.containsKey("authorization")) {
450                             headers.put("authorization", "*replaced*");
451                         } else if (headers.containsKey("Authorization")) {
452                             headers.put("Authorization", "*replaced*");
453                         }
454                     }).collect(Collectors.toList());
455             responsePayload.put("requests", apiRequestList);
456             response.getWriter().write(gson.toJson(responsePayload));
457         } else {
458             response.sendError(HttpStatus.BAD_REQUEST_400, "Unknown bridge");
459         }
460     }
461
462     private void getEventLogPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
463         WebContext context = new WebContext(request, response, request.getServletContext());
464         context.setVariable("bridgeHandlers", bridgeHandlers);
465         templateEngine.process("log-events", context, response.getWriter());
466     }
467
468     private void getEventLogExport(HttpServletResponse response, String bridgeId) throws IOException {
469         Optional<HomeConnectBridgeHandler> bridgeHandler = getBridgeHandler(bridgeId);
470         if (bridgeHandler.isPresent()) {
471             response.setContentType(MediaType.APPLICATION_JSON);
472             String fileName = String.format("%s__%s__events.json", now().format(FILE_EXPORT_DTF),
473                     bridgeId.replaceAll("[^a-zA-Z0-9]", "_"));
474             response.setHeader("Content-disposition", "attachment; filename=" + fileName);
475
476             HashMap<String, Object> responsePayload = new HashMap<>();
477             responsePayload.put("openHAB", OpenHAB.getVersion());
478             responsePayload.put("bundle", FrameworkUtil.getBundle(this.getClass()).getVersion().toString());
479             responsePayload.put("events", bridgeHandler.get().getEventSourceClient().getLatestEvents());
480             response.getWriter().write(gson.toJson(responsePayload));
481         } else {
482             response.sendError(HttpStatus.BAD_REQUEST_400, "Unknown bridge");
483         }
484     }
485
486     private void getBridgeAuthenticationPage(HttpServletRequest request, HttpServletResponse response, String code,
487             String state) throws IOException {
488         // callback handling from authorization server
489         logger.debug("[oAuth] redirect from authorization server (code={}, state={}).", code, state);
490
491         Optional<HomeConnectBridgeHandler> bridgeHandler = getBridgeHandler(state);
492         if (bridgeHandler.isPresent()) {
493             try {
494                 AccessTokenResponse accessTokenResponse = bridgeHandler.get().getOAuthClientService()
495                         .getAccessTokenResponseByAuthorizationCode(code, null);
496
497                 logger.debug("access token response: {}", accessTokenResponse);
498
499                 // inform bridge
500                 bridgeHandler.get().reinitialize();
501
502                 WebContext context = new WebContext(request, response, request.getServletContext());
503                 context.setVariable("action", bridgeHandler.get().getThing().getUID().getAsString() + ACTION_AUTHORIZE);
504                 context.setVariable("bridgeHandlers", bridgeHandlers);
505                 templateEngine.process("bridges", context, response.getWriter());
506             } catch (OAuthException | OAuthResponseException e) {
507                 logger.error("Could not fetch token!", e);
508                 response.sendError(HttpStatus.INTERNAL_SERVER_ERROR_500, "Could not fetch token!");
509             }
510         } else {
511             response.sendError(HttpStatus.BAD_REQUEST_400, "Unknown bridge");
512         }
513     }
514
515     private boolean pathMatches(String path, String targetPath) {
516         return targetPath.equals(path) || (targetPath + SLASH).equals(path);
517     }
518
519     private Optional<HomeConnectBridgeHandler> getBridgeHandler(String bridgeUid) {
520         for (HomeConnectBridgeHandler handler : bridgeHandlers) {
521             if (handler.getThing().getUID().getAsString().equals(bridgeUid)) {
522                 return Optional.of(handler);
523             }
524         }
525         return Optional.empty();
526     }
527
528     private Optional<AbstractHomeConnectThingHandler> getThingHandler(String thingUid) {
529         for (HomeConnectBridgeHandler handler : bridgeHandlers) {
530             for (AbstractHomeConnectThingHandler thingHandler : handler.getThingHandler()) {
531                 if (thingHandler.getThing().getUID().getAsString().equals(thingUid)) {
532                     return Optional.of(thingHandler);
533                 }
534             }
535         }
536         return Optional.empty();
537     }
538
539     private Optional<HomeConnectBridgeHandler> getBridgeHandlerForThing(String thingUid) {
540         for (HomeConnectBridgeHandler handler : bridgeHandlers) {
541             for (AbstractHomeConnectThingHandler thingHandler : handler.getThingHandler()) {
542                 if (thingHandler.getThing().getUID().getAsString().equals(thingUid)) {
543                     return Optional.of(handler);
544                 }
545             }
546         }
547         return Optional.empty();
548     }
549 }