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.amazonechocontrol.internal;
15 import static org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants.*;
17 import java.io.IOException;
18 import java.io.UnsupportedEncodingException;
19 import java.net.URISyntaxException;
20 import java.net.URLDecoder;
21 import java.net.URLEncoder;
22 import java.nio.charset.StandardCharsets;
23 import java.util.HashMap;
24 import java.util.List;
26 import java.util.stream.Collectors;
28 import javax.net.ssl.HttpsURLConnection;
29 import javax.servlet.ServletException;
30 import javax.servlet.http.HttpServlet;
31 import javax.servlet.http.HttpServletRequest;
32 import javax.servlet.http.HttpServletResponse;
34 import org.eclipse.jdt.annotation.NonNullByDefault;
35 import org.eclipse.jdt.annotation.Nullable;
36 import org.openhab.binding.amazonechocontrol.internal.handler.AccountHandler;
37 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates;
38 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates.BluetoothState;
39 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates.PairedDevice;
40 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonDevices.Device;
41 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonMusicProvider;
42 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonNotificationSound;
43 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonPlaylists;
44 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonPlaylists.PlayList;
45 import org.openhab.core.thing.Thing;
46 import org.osgi.service.http.HttpService;
47 import org.osgi.service.http.NamespaceException;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.unbescape.html.HtmlEscape;
52 import com.google.gson.Gson;
53 import com.google.gson.JsonSyntaxException;
56 * Provides the following functions
58 * Simple http proxy to forward the login dialog from amazon to the user through the binding
59 * so the user can enter a captcha or other extended login information
60 * --- List of devices ---
61 * Used to get the device information of new devices which are currently not known
63 * Simple possibility for a user to get the ids needed for writing rules
65 * @author Michael Geramb - Initial Contribution
68 public class AccountServlet extends HttpServlet {
70 private static final long serialVersionUID = -1453738923337413163L;
71 private static final String FORWARD_URI_PART = "/FORWARD/";
72 private static final String PROXY_URI_PART = "/PROXY/";
74 private final Logger logger = LoggerFactory.getLogger(AccountServlet.class);
76 private final HttpService httpService;
77 private final String servletUrlWithoutRoot;
78 private final String servletUrl;
79 private final AccountHandler account;
80 private final String id;
81 private @Nullable Connection connectionToInitialize;
82 private final Gson gson;
84 public AccountServlet(HttpService httpService, String id, AccountHandler account, Gson gson) {
85 this.httpService = httpService;
86 this.account = account;
91 servletUrlWithoutRoot = "amazonechocontrol/" + URLEncoder.encode(id, "UTF8");
92 servletUrl = "/" + servletUrlWithoutRoot;
94 httpService.registerServlet(servletUrl, this, null, httpService.createDefaultHttpContext());
95 } catch (UnsupportedEncodingException | NamespaceException | ServletException e) {
96 throw new IllegalStateException(e.getMessage());
100 private Connection reCreateConnection() {
101 Connection oldConnection = connectionToInitialize;
102 if (oldConnection == null) {
103 oldConnection = account.findConnection();
105 return new Connection(oldConnection, this.gson);
108 public void dispose() {
109 httpService.unregister(servletUrl);
113 protected void doPut(@Nullable HttpServletRequest req, @Nullable HttpServletResponse resp)
114 throws ServletException, IOException {
115 doVerb("PUT", req, resp);
119 protected void doDelete(@Nullable HttpServletRequest req, @Nullable HttpServletResponse resp)
120 throws ServletException, IOException {
121 doVerb("DELETE", req, resp);
125 protected void doPost(@Nullable HttpServletRequest req, @Nullable HttpServletResponse resp)
126 throws ServletException, IOException {
127 doVerb("POST", req, resp);
130 void doVerb(String verb, @Nullable HttpServletRequest req, @Nullable HttpServletResponse resp) throws IOException {
137 String requestUri = req.getRequestURI();
138 if (requestUri == null) {
141 String baseUrl = requestUri.substring(servletUrl.length());
142 String uri = baseUrl;
143 String queryString = req.getQueryString();
144 if (queryString != null && queryString.length() > 0) {
145 uri += "?" + queryString;
148 Connection connection = this.account.findConnection();
149 if (connection != null && uri.equals("/changedomain")) {
150 Map<String, String[]> map = req.getParameterMap();
151 String[] domainArray = map.get("domain");
152 if (domainArray == null) {
153 logger.warn("Could not determine domain");
156 String domain = domainArray[0];
157 String loginData = connection.serializeLoginData();
158 Connection newConnection = new Connection(null, this.gson);
159 if (newConnection.tryRestoreLogin(loginData, domain)) {
160 account.setConnection(newConnection);
162 resp.sendRedirect(servletUrl);
165 if (uri.startsWith(PROXY_URI_PART)) {
166 // handle proxy request
168 if (connection == null) {
169 returnError(resp, "Account not online");
172 String getUrl = "https://alexa." + connection.getAmazonSite() + "/"
173 + uri.substring(PROXY_URI_PART.length());
175 String postData = null;
176 if ("POST".equals(verb) || "PUT".equals(verb)) {
177 postData = req.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
180 this.handleProxyRequest(connection, resp, verb, getUrl, null, postData, true, connection.getAmazonSite());
184 // handle post of login page
185 connection = this.connectionToInitialize;
186 if (connection == null) {
187 returnError(resp, "Connection not in initialize mode.");
191 resp.addHeader("content-type", "text/html;charset=UTF-8");
193 Map<String, String[]> map = req.getParameterMap();
194 StringBuilder postDataBuilder = new StringBuilder();
195 for (String name : map.keySet()) {
196 if (postDataBuilder.length() > 0) {
197 postDataBuilder.append('&');
200 postDataBuilder.append(name);
201 postDataBuilder.append('=');
203 if (name.equals("failedSignInCount")) {
206 String[] strings = map.get(name);
207 if (strings != null && strings.length > 0 && strings[0] != null) {
211 postDataBuilder.append(URLEncoder.encode(value, StandardCharsets.UTF_8.name()));
214 uri = req.getRequestURI();
215 if (uri == null || !uri.startsWith(servletUrl)) {
216 returnError(resp, "Invalid request uri '" + uri + "'");
219 String relativeUrl = uri.substring(servletUrl.length()).replace(FORWARD_URI_PART, "/");
221 String site = connection.getAmazonSite();
222 if (relativeUrl.startsWith("/ap/signin")) {
225 String postUrl = "https://www." + site + relativeUrl;
226 queryString = req.getQueryString();
227 if (queryString != null && queryString.length() > 0) {
228 postUrl += "?" + queryString;
230 String referer = "https://www." + site;
231 String postData = postDataBuilder.toString();
232 handleProxyRequest(connection, resp, "POST", postUrl, referer, postData, false, site);
236 protected void doGet(@Nullable HttpServletRequest req, @Nullable HttpServletResponse resp) throws IOException {
243 String requestUri = req.getRequestURI();
244 if (requestUri == null) {
247 String baseUrl = requestUri.substring(servletUrl.length());
248 String uri = baseUrl;
249 String queryString = req.getQueryString();
250 if (queryString != null && queryString.length() > 0) {
251 uri += "?" + queryString;
253 logger.debug("doGet {}", uri);
255 Connection connection = this.connectionToInitialize;
256 if (uri.startsWith(FORWARD_URI_PART) && connection != null) {
257 String getUrl = "https://www." + connection.getAmazonSite() + "/"
258 + uri.substring(FORWARD_URI_PART.length());
260 this.handleProxyRequest(connection, resp, "GET", getUrl, null, null, false, connection.getAmazonSite());
264 connection = this.account.findConnection();
265 if (uri.startsWith(PROXY_URI_PART)) {
266 // handle proxy request
268 if (connection == null) {
269 returnError(resp, "Account not online");
272 String getUrl = "https://alexa." + connection.getAmazonSite() + "/"
273 + uri.substring(PROXY_URI_PART.length());
275 this.handleProxyRequest(connection, resp, "GET", getUrl, null, null, false, connection.getAmazonSite());
279 if (connection != null && connection.verifyLogin()) {
281 if (baseUrl.equals("/logout") || baseUrl.equals("/logout/")) {
282 this.connectionToInitialize = reCreateConnection();
283 this.account.setConnection(null);
284 resp.sendRedirect(this.servletUrl);
288 if (baseUrl.equals("/newdevice") || baseUrl.equals("/newdevice/")) {
289 this.connectionToInitialize = new Connection(null, this.gson);
290 this.account.setConnection(null);
291 resp.sendRedirect(this.servletUrl);
295 if (baseUrl.equals("/devices") || baseUrl.equals("/devices/")) {
296 handleDevices(resp, connection);
299 if (baseUrl.equals("/changeDomain") || baseUrl.equals("/changeDomain/")) {
300 handleChangeDomain(resp, connection);
303 if (baseUrl.equals("/ids") || baseUrl.equals("/ids/")) {
304 String serialNumber = getQueryMap(queryString).get("serialNumber");
305 Device device = account.findDeviceJson(serialNumber);
306 if (device != null) {
307 Thing thing = account.findThingBySerialNumber(device.serialNumber);
308 handleIds(resp, connection, device, thing);
312 // return hint that everything is ok
313 handleDefaultPageResult(resp, "The Account is logged in.", connection);
316 connection = this.connectionToInitialize;
317 if (connection == null) {
318 connection = this.reCreateConnection();
319 this.connectionToInitialize = connection;
322 if (!uri.equals("/")) {
323 String newUri = req.getServletPath() + "/";
324 resp.sendRedirect(newUri);
328 String html = connection.getLoginPage();
329 returnHtml(connection, resp, html, "amazon.com");
330 } catch (URISyntaxException | InterruptedException e) {
331 logger.warn("get failed with uri syntax error", e);
335 public Map<String, String> getQueryMap(@Nullable String query) {
336 Map<String, String> map = new HashMap<>();
338 String[] params = query.split("&");
339 for (String param : params) {
340 String[] elements = param.split("=");
341 if (elements.length == 2) {
342 String name = elements[0];
345 value = URLDecoder.decode(elements[1], "UTF8");
346 } catch (UnsupportedEncodingException e) {
347 logger.info("Unsupported encoding", e);
349 map.put(name, value);
356 private void handleChangeDomain(HttpServletResponse resp, Connection connection) {
357 StringBuilder html = createPageStart("Change Domain");
358 html.append("<form action='");
359 html.append(servletUrl);
360 html.append("/changedomain' method='post'>\nDomain:\n<input type='text' name='domain' value='");
361 html.append(connection.getAmazonSite());
362 html.append("'>\n<br>\n<input type=\"submit\" value=\"Submit\">\n</form>");
364 createPageEndAndSent(resp, html);
367 private void handleDefaultPageResult(HttpServletResponse resp, String message, Connection connection)
369 StringBuilder html = createPageStart("");
370 html.append(HtmlEscape.escapeHtml4(message));
372 html.append(" <a href='" + servletUrl + "/logout' >");
373 html.append(HtmlEscape.escapeHtml4("Logout"));
376 html.append(" | <a href='" + servletUrl + "/newdevice' >");
377 html.append(HtmlEscape.escapeHtml4("Logout and create new device id"));
380 html.append("<br>Customer Id: ");
381 html.append(HtmlEscape.escapeHtml4(connection.getCustomerId()));
383 html.append("<br>Customer Name: ");
384 html.append(HtmlEscape.escapeHtml4(connection.getCustomerName()));
386 html.append("<br>App name: ");
387 html.append(HtmlEscape.escapeHtml4(connection.getDeviceName()));
389 html.append("<br>Connected to: ");
390 html.append(HtmlEscape.escapeHtml4(connection.getAlexaServer()));
392 html.append(" <a href='");
393 html.append(servletUrl);
394 html.append("/changeDomain'>Change</a>");
397 html.append("<br><a href='/#!/settings/things/" + BINDING_ID + ":"
398 + URLEncoder.encode(THING_TYPE_ACCOUNT.getId(), "UTF8") + ":" + URLEncoder.encode(id, "UTF8") + "'>");
399 html.append(HtmlEscape.escapeHtml4("Check Thing in Main UI"));
400 html.append("</a><br><br>");
404 "<table><tr><th align='left'>Device</th><th align='left'>Serial Number</th><th align='left'>State</th><th align='left'>Thing</th><th align='left'>Family</th><th align='left'>Type</th><th align='left'>Customer Id</th></tr>");
405 for (Device device : this.account.getLastKnownDevices()) {
407 html.append("<tr><td>");
408 html.append(HtmlEscape.escapeHtml4(nullReplacement(device.accountName)));
409 html.append("</td><td>");
410 html.append(HtmlEscape.escapeHtml4(nullReplacement(device.serialNumber)));
411 html.append("</td><td>");
412 html.append(HtmlEscape.escapeHtml4(device.online ? "Online" : "Offline"));
413 html.append("</td><td>");
414 Thing accountHandler = account.findThingBySerialNumber(device.serialNumber);
415 if (accountHandler != null) {
416 html.append("<a href='" + servletUrl + "/ids/?serialNumber="
417 + URLEncoder.encode(device.serialNumber, "UTF8") + "'>"
418 + HtmlEscape.escapeHtml4(accountHandler.getLabel()) + "</a>");
420 html.append("<a href='" + servletUrl + "/ids/?serialNumber="
421 + URLEncoder.encode(device.serialNumber, "UTF8") + "'>" + HtmlEscape.escapeHtml4("Not defined")
424 html.append("</td><td>");
425 html.append(HtmlEscape.escapeHtml4(nullReplacement(device.deviceFamily)));
426 html.append("</td><td>");
427 html.append(HtmlEscape.escapeHtml4(nullReplacement(device.deviceType)));
428 html.append("</td><td>");
429 html.append(HtmlEscape.escapeHtml4(nullReplacement(device.deviceOwnerCustomerId)));
430 html.append("</td>");
431 html.append("</tr>");
433 html.append("</table>");
434 createPageEndAndSent(resp, html);
437 private void handleDevices(HttpServletResponse resp, Connection connection)
438 throws IOException, URISyntaxException, InterruptedException {
439 returnHtml(connection, resp, "<html>" + HtmlEscape.escapeHtml4(connection.getDeviceListJson()) + "</html>");
442 private String nullReplacement(@Nullable String text) {
449 StringBuilder createPageStart(String title) {
450 StringBuilder html = new StringBuilder();
451 html.append("<html><head><title>"
452 + HtmlEscape.escapeHtml4(BINDING_NAME + " - " + this.account.getThing().getLabel()));
453 if (!title.isEmpty()) {
455 html.append(HtmlEscape.escapeHtml4(title));
457 html.append("</title><head><body>");
458 html.append("<h1>" + HtmlEscape.escapeHtml4(BINDING_NAME + " - " + this.account.getThing().getLabel()));
459 if (!title.isEmpty()) {
461 html.append(HtmlEscape.escapeHtml4(title));
463 html.append("</h1>");
467 private void createPageEndAndSent(HttpServletResponse resp, StringBuilder html) {
468 // account overview link
469 html.append("<br><a href='" + servletUrl + "/../' >");
470 html.append(HtmlEscape.escapeHtml4("Account overview"));
471 html.append("</a><br>");
473 html.append("</body></html>");
474 resp.addHeader("content-type", "text/html;charset=UTF-8");
476 resp.getWriter().write(html.toString());
477 } catch (IOException e) {
478 logger.warn("return html failed with IO error", e);
482 private void handleIds(HttpServletResponse resp, Connection connection, Device device, @Nullable Thing thing)
483 throws IOException, URISyntaxException {
486 html = createPageStart("Channel Options - " + thing.getLabel());
488 html = createPageStart("Device Information - No thing defined");
490 renderBluetoothMacChannel(connection, device, html);
491 renderAmazonMusicPlaylistIdChannel(connection, device, html);
492 renderPlayAlarmSoundChannel(connection, device, html);
493 renderMusicProviderIdChannel(connection, html);
494 renderCapabilities(connection, device, html);
495 createPageEndAndSent(resp, html);
498 private void renderCapabilities(Connection connection, Device device, StringBuilder html) {
499 html.append("<h2>Capabilities</h2>");
500 html.append("<table><tr><th align='left'>Name</th></tr>");
501 device.getCapabilities().forEach(
502 capability -> html.append("<tr><td>").append(HtmlEscape.escapeHtml4(capability)).append("</td></tr>"));
503 html.append("</table>");
506 private void renderMusicProviderIdChannel(Connection connection, StringBuilder html) {
507 html.append("<h2>").append(HtmlEscape.escapeHtml4("Channel " + CHANNEL_MUSIC_PROVIDER_ID)).append("</h2>");
508 html.append("<table><tr><th align='left'>Name</th><th align='left'>Value</th></tr>");
509 List<JsonMusicProvider> musicProviders = connection.getMusicProviders();
510 for (JsonMusicProvider musicProvider : musicProviders) {
511 List<String> properties = musicProvider.supportedProperties;
512 String providerId = musicProvider.id;
513 String displayName = musicProvider.displayName;
514 if (properties != null && properties.contains("Alexa.Music.PlaySearchPhrase") && providerId != null
515 && !providerId.isEmpty() && "AVAILABLE".equals(musicProvider.availability) && displayName != null
516 && !displayName.isEmpty()) {
517 html.append("<tr><td>");
518 html.append(HtmlEscape.escapeHtml4(displayName));
519 html.append("</td><td>");
520 html.append(HtmlEscape.escapeHtml4(providerId));
521 html.append("</td></tr>");
524 html.append("</table>");
527 private void renderPlayAlarmSoundChannel(Connection connection, Device device, StringBuilder html) {
528 html.append("<h2>").append(HtmlEscape.escapeHtml4("Channel " + CHANNEL_PLAY_ALARM_SOUND)).append("</h2>");
529 List<JsonNotificationSound> notificationSounds = List.of();
530 String errorMessage = "No notifications sounds found";
532 notificationSounds = connection.getNotificationSounds(device);
533 } catch (IOException | HttpException | URISyntaxException | JsonSyntaxException | ConnectionException
534 | InterruptedException e) {
535 errorMessage = e.getLocalizedMessage();
537 if (!notificationSounds.isEmpty()) {
538 html.append("<table><tr><th align='left'>Name</th><th align='left'>Value</th></tr>");
539 for (JsonNotificationSound notificationSound : notificationSounds) {
540 if (notificationSound.folder == null && notificationSound.providerId != null
541 && notificationSound.id != null && notificationSound.displayName != null) {
542 String providerSoundId = notificationSound.providerId + ":" + notificationSound.id;
544 html.append("<tr><td>");
545 html.append(HtmlEscape.escapeHtml4(notificationSound.displayName));
546 html.append("</td><td>");
547 html.append(HtmlEscape.escapeHtml4(providerSoundId));
548 html.append("</td></tr>");
551 html.append("</table>");
553 html.append(HtmlEscape.escapeHtml4(errorMessage));
557 private void renderAmazonMusicPlaylistIdChannel(Connection connection, Device device, StringBuilder html) {
558 html.append("<h2>").append(HtmlEscape.escapeHtml4("Channel " + CHANNEL_AMAZON_MUSIC_PLAY_LIST_ID))
561 JsonPlaylists playLists = null;
562 String errorMessage = "No playlists found";
564 playLists = connection.getPlaylists(device);
565 } catch (IOException | HttpException | URISyntaxException | JsonSyntaxException | ConnectionException
566 | InterruptedException e) {
567 errorMessage = e.getLocalizedMessage();
570 if (playLists != null) {
571 Map<String, PlayList @Nullable []> playlistMap = playLists.playlists;
572 if (playlistMap != null && !playlistMap.isEmpty()) {
573 html.append("<table><tr><th align='left'>Name</th><th align='left'>Value</th></tr>");
575 for (PlayList[] innerLists : playlistMap.values()) {
577 if (innerLists != null && innerLists.length > 0) {
578 PlayList playList = innerLists[0];
579 if (playList != null && playList.playlistId != null && playList.title != null) {
580 html.append("<tr><td>");
581 html.append(HtmlEscape.escapeHtml4(nullReplacement(playList.title)));
582 html.append("</td><td>");
583 html.append(HtmlEscape.escapeHtml4(nullReplacement(playList.playlistId)));
584 html.append("</td></tr>");
589 html.append("</table>");
591 html.append(HtmlEscape.escapeHtml4(errorMessage));
596 private void renderBluetoothMacChannel(Connection connection, Device device, StringBuilder html) {
597 html.append("<h2>").append(HtmlEscape.escapeHtml4("Channel " + CHANNEL_BLUETOOTH_MAC)).append("</h2>");
598 JsonBluetoothStates bluetoothStates = connection.getBluetoothConnectionStates();
599 if (bluetoothStates == null) {
602 BluetoothState[] innerStates = bluetoothStates.bluetoothStates;
603 if (innerStates == null) {
606 for (BluetoothState state : innerStates) {
610 String stateDeviceSerialNumber = state.deviceSerialNumber;
611 if ((stateDeviceSerialNumber == null && device.serialNumber == null)
612 || (stateDeviceSerialNumber != null && stateDeviceSerialNumber.equals(device.serialNumber))) {
613 List<PairedDevice> pairedDeviceList = state.getPairedDeviceList();
614 if (!pairedDeviceList.isEmpty()) {
615 html.append("<table><tr><th align='left'>Name</th><th align='left'>Value</th></tr>");
616 for (PairedDevice pairedDevice : pairedDeviceList) {
617 html.append("<tr><td>");
618 html.append(HtmlEscape.escapeHtml4(nullReplacement(pairedDevice.friendlyName)));
619 html.append("</td><td>");
620 html.append(HtmlEscape.escapeHtml4(nullReplacement(pairedDevice.address)));
621 html.append("</td></tr>");
623 html.append("</table>");
625 html.append(HtmlEscape.escapeHtml4("No bluetooth devices paired"));
631 void handleProxyRequest(Connection connection, HttpServletResponse resp, String verb, String url,
632 @Nullable String referer, @Nullable String postData, boolean json, String site) throws IOException {
633 HttpsURLConnection urlConnection;
635 Map<String, String> headers = null;
636 if (referer != null) {
637 headers = new HashMap<>();
638 headers.put("Referer", referer);
641 urlConnection = connection.makeRequest(verb, url, postData, json, false, headers, 0);
642 if (urlConnection.getResponseCode() == 302) {
644 String location = urlConnection.getHeaderField("location");
645 if (location.contains("/ap/maplanding")) {
647 connection.registerConnectionAsApp(location);
648 account.setConnection(connection);
649 handleDefaultPageResult(resp, "Login succeeded", connection);
650 this.connectionToInitialize = null;
652 } catch (URISyntaxException | ConnectionException e) {
654 "Login to '" + connection.getAmazonSite() + "' failed: " + e.getLocalizedMessage());
655 this.connectionToInitialize = null;
660 String startString = "https://www." + connection.getAmazonSite() + "/";
661 String newLocation = null;
662 if (location.startsWith(startString) && connection.getIsLoggedIn()) {
663 newLocation = servletUrl + PROXY_URI_PART + location.substring(startString.length());
664 } else if (location.startsWith(startString)) {
665 newLocation = servletUrl + FORWARD_URI_PART + location.substring(startString.length());
668 if (location.startsWith(startString)) {
669 newLocation = servletUrl + FORWARD_URI_PART + location.substring(startString.length());
672 if (newLocation != null) {
673 logger.debug("Redirect mapped from {} to {}", location, newLocation);
675 resp.sendRedirect(newLocation);
678 returnError(resp, "Invalid redirect to '" + location + "'");
682 } catch (URISyntaxException | ConnectionException | InterruptedException e) {
683 returnError(resp, e.getLocalizedMessage());
686 String response = connection.convertStream(urlConnection);
687 returnHtml(connection, resp, response, site);
690 private void returnHtml(Connection connection, HttpServletResponse resp, String html) {
691 returnHtml(connection, resp, html, connection.getAmazonSite());
694 private void returnHtml(Connection connection, HttpServletResponse resp, String html, String amazonSite) {
695 String resultHtml = html.replace("action=\"/", "action=\"" + servletUrl + "/")
696 .replace("action=\"/", "action=\"" + servletUrl + "/")
697 .replace("https://www." + amazonSite + "/", servletUrl + "/")
698 .replace("https://www." + amazonSite + ":443" + "/", servletUrl + "/")
699 .replace("https://www." + amazonSite + "/", servletUrl + "/")
700 .replace("https://www." + amazonSite + ":443" + "/", servletUrl + "/")
701 .replace("http://www." + amazonSite + "/", servletUrl + "/")
702 .replace("http://www." + amazonSite + "/", servletUrl + "/");
704 resp.addHeader("content-type", "text/html;charset=UTF-8");
706 resp.getWriter().write(resultHtml);
707 } catch (IOException e) {
708 logger.warn("return html failed with IO error", e);
712 void returnError(HttpServletResponse resp, @Nullable String errorMessage) {
714 String message = errorMessage != null ? errorMessage : "null";
715 resp.getWriter().write("<html>" + HtmlEscape.escapeHtml4(message) + "<br><a href='" + servletUrl
716 + "'>Try again</a></html>");
717 } catch (IOException e) {
718 logger.info("Returning error message failed", e);