<commit_before>/**
 * Copyright (c) 2010-2020 Contributors to the openHAB project
 *
 * See the NOTICE file(s) distributed with this work for additional
 * information.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0
 *
 * SPDX-License-Identifier: EPL-2.0
 */
package org.openhab.binding.amazonechocontrol.internal;

import static org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringEscapeUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.amazonechocontrol.internal.handler.AccountHandler;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates.BluetoothState;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates.PairedDevice;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonDevices.Device;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonMusicProvider;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonNotificationSound;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonPlaylists;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonPlaylists.PlayList;
import org.openhab.core.thing.Thing;
import org.osgi.service.http.HttpService;
import org.osgi.service.http.NamespaceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

/**
 * Provides the following functions
 * --- Login ---
 * Simple http proxy to forward the login dialog from amazon to the user through the binding
 * so the user can enter a captcha or other extended login information
 * --- List of devices ---
 * Used to get the device information of new devices which are currently not known
 * --- List of IDs ---
 * Simple possibility for a user to get the ids needed for writing rules
 *
 * @author <NAME> - Initial Contribution
 */
@NonNullByDefault
public class AccountServlet extends HttpServlet {

    private static final long serialVersionUID = -1453738923337413163L;
    private static final String FORWARD_URI_PART = "/FORWARD/";
    private static final String PROXY_URI_PART = "/PROXY/";

    private final Logger logger = LoggerFactory.getLogger(AccountServlet.class);

    private final HttpService httpService;
    private final String servletUrlWithoutRoot;
    private final String servletUrl;
    private final AccountHandler account;
    private final String id;
    private @Nullable Connection connectionToInitialize;
    private final Gson gson;

    public AccountServlet(HttpService httpService, String id, AccountHandler account, Gson gson) {
        this.httpService = httpService;
        this.account = account;
        this.id = id;
        this.gson = gson;

        try {
            servletUrlWithoutRoot = "amazonechocontrol/" + URLEncoder.encode(id, "UTF8");
            servletUrl = "/" + servletUrlWithoutRoot;

            httpService.registerServlet(servletUrl, this, null, httpService.createDefaultHttpContext());
        } catch (UnsupportedEncodingException | NamespaceException | ServletException e) {
            throw new IllegalStateException(e.getMessage());
        }
    }

    private Connection reCreateConnection() {
        Connection oldConnection = connectionToInitialize;
        if (oldConnection == null) {
            oldConnection = account.findConnection();
        }
        return new Connection(oldConnection, this.gson);
    }

    public void dispose() {
        httpService.unregister(servletUrl);
    }

    @Override
    protected void doPut(@Nullable HttpServletRequest req, @Nullable HttpServletResponse resp)
            throws ServletException, IOException {
        doVerb("PUT", req, resp);
    }

    @Override
    protected void doDelete(@Nullable HttpServletRequest req, @Nullable HttpServletResponse resp)
            throws ServletException, IOException {
        doVerb("DELETE", req, resp);
    }

    @Override
    protected void doPost(@Nullable HttpServletRequest req, @Nullable HttpServletResponse resp)
            throws ServletException, IOException {
        doVerb("POST", req, resp);
    }

    void doVerb(String verb, @Nullable HttpServletRequest req, @Nullable HttpServletResponse resp) throws IOException {
        if (req == null) {
            return;
        }
        if (resp == null) {
            return;
        }
        String requestUri = req.getRequestURI();
        if (requestUri == null) {
            return;
        }
        String baseUrl = requestUri.substring(servletUrl.length());
        String uri = baseUrl;
        String queryString = req.getQueryString();
        if (queryString != null && queryString.length() > 0) {
            uri += "?" + queryString;
        }

        Connection connection = this.account.findConnection();
        if (connection != null && uri.equals("/changedomain")) {
            Map<String, String[]> map = req.getParameterMap();
            String[] domainArray = map.get("domain");
            if (domainArray == null) {
                logger.warn("Could not determine domain");
                return;
            }
            String domain = domainArray[0];
            String loginData = connection.serializeLoginData();
            Connection newConnection = new Connection(null, this.gson);
            if (newConnection.tryRestoreLogin(loginData, domain)) {
                account.setConnection(newConnection);
            }
            resp.sendRedirect(servletUrl);
            return;
        }
        if (uri.startsWith(PROXY_URI_PART)) {
            // handle proxy request

            if (connection == null) {
                returnError(resp, "Account not online");
                return;
            }
            String getUrl = "https://alexa." + connection.getAmazonSite() + "/"
                    + uri.substring(PROXY_URI_PART.length());

            String postData = null;
            if (verb == "POST" || verb == "PUT") {
                postData = req.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
            }

            this.handleProxyRequest(connection, resp, verb, getUrl, null, postData, true, connection.getAmazonSite());
            return;
        }

        // handle post of login page
        connection = this.connectionToInitialize;
        if (connection == null) {
            returnError(resp, "Connection not in initialize mode.");
            return;
        }

        resp.addHeader("content-type", "text/html;charset=UTF-8");

        Map<String, String[]> map = req.getParameterMap();
        StringBuilder postDataBuilder = new StringBuilder();
        for (String name : map.keySet()) {
            if (postDataBuilder.length() > 0) {
                postDataBuilder.append('&');
            }

            postDataBuilder.append(name);
            postDataBuilder.append('=');
            String value = "";
            if (name.equals("failedSignInCount")) {
                value = "ape:AA==";
            } else {
                String[] strings = map.get(name);
                if (strings != null && strings.length > 0 && strings[0] != null) {
                    value = strings[0];
                }
            }
            postDataBuilder.append(URLEncoder.encode(value, StandardCharsets.UTF_8.name()));
        }

        uri = req.getRequestURI();
        if (uri == null || !uri.startsWith(servletUrl)) {
            returnError(resp, "Invalid request uri '" + uri + "'");
            return;
        }
        String relativeUrl = uri.substring(servletUrl.length()).replace(FORWARD_URI_PART, "/");

        String site = connection.getAmazonSite();
        if (relativeUrl.startsWith("/ap/signin")) {
            site = "amazon.com";
        }
        String postUrl = "https://www." + site + relativeUrl;
        queryString = req.getQueryString();
        if (queryString != null && queryString.length() > 0) {
            postUrl += "?" + queryString;
        }
        String referer = "https://www." + site;
        String postData = postDataBuilder.toString();
        handleProxyRequest(connection, resp, "POST", postUrl, referer, postData, false, site);
    }

    @Override
    protected void doGet(@Nullable HttpServletRequest req, @Nullable HttpServletResponse resp) throws IOException {
        if (req == null) {
            return;
        }
        if (resp == null) {
            return;
        }
        String requestUri = req.getRequestURI();
        if (requestUri == null) {
            return;
        }
        String baseUrl = requestUri.substring(servletUrl.length());
        String uri = baseUrl;
        String queryString = req.getQueryString();
        if (queryString != null && queryString.length() > 0) {
            uri += "?" + queryString;
        }
        logger.debug("doGet {}", uri);
        try {
            Connection connection = this.connectionToInitialize;
            if (uri.startsWith(FORWARD_URI_PART) && connection != null) {
                String getUrl = "https://www." + connection.getAmazonSite() + "/"
                        + uri.substring(FORWARD_URI_PART.length());

                this.handleProxyRequest(connection, resp, "GET", getUrl, null, null, false, connection.getAmazonSite());
                return;
            }

            connection = this.account.findConnection();
            if (uri.startsWith(PROXY_URI_PART)) {
                // handle proxy request

                if (connection == null) {
                    returnError(resp, "Account not online");
                    return;
                }
                String getUrl = "https://alexa." + connection.getAmazonSite() + "/"
                        + uri.substring(PROXY_URI_PART.length());

                this.handleProxyRequest(connection, resp, "GET", getUrl, null, null, false, connection.getAmazonSite());
                return;
            }

            if (connection != null && connection.verifyLogin()) {
                // handle commands
                if (baseUrl.equals("/logout") || baseUrl.equals("/logout/")) {
                    this.connectionToInitialize = reCreateConnection();
                    this.account.setConnection(null);
                    resp.sendRedirect(this.servletUrl);
                    return;
                }
                // handle commands
                if (baseUrl.equals("/newdevice") || baseUrl.equals("/newdevice/")) {
                    this.connectionToInitialize = new Connection(null, this.gson);
                    this.account.setConnection(null);
                    resp.sendRedirect(this.servletUrl);
                    return;
                }

                if (baseUrl.equals("/devices") || baseUrl.equals("/devices/")) {
                    handleDevices(resp, connection);
                    return;
                }
                if (baseUrl.equals("/changeDomain") || baseUrl.equals("/changeDomain/")) {
                    handleChangeDomain(resp, connection);
                    return;
                }
                if (baseUrl.equals("/ids") || baseUrl.equals("/ids/")) {
                    String serialNumber = getQueryMap(queryString).get("serialNumber");
                    Device device = account.findDeviceJson(serialNumber);
                    if (device != null) {
                        Thing thing = account.findThingBySerialNumber(device.serialNumber);
                        handleIds(resp, connection, device, thing);
                        return;
                    }
                }
                // return hint that everything is ok
                handleDefaultPageResult(resp, "The Account is logged in.", connection);
                return;
            }
            connection = this.connectionToInitialize;
            if (connection == null) {
                connection = this.reCreateConnection();
                this.connectionToInitialize = connection;
            }

            if (!uri.equals("/")) {
                String newUri = req.getServletPath() + "/";
                resp.sendRedirect(newUri);
                return;
            }

            String html = connection.getLoginPage();
            returnHtml(connection, resp, html, "amazon.com");
        } catch (URISyntaxException | InterruptedException e) {
            logger.warn("get failed with uri syntax error", e);
        }
    }

    public Map<String, String> getQueryMap(@Nullable String query) {
        Map<String, String> map = new HashMap<>();
        if (query != null) {
            String[] params = query.split("&");
            for (String param : params) {
                String[] elements = param.split("=");
                if (elements.length == 2) {
                    String name = elements[0];
                    String value = "";
                    try {
                        value = URLDecoder.decode(elements[1], "UTF8");
                    } catch (UnsupportedEncodingException e) {
                        logger.info("Unsupported encoding", e);
                    }
                    map.put(name, value);
                }
            }
        }
        return map;
    }

    private void handleChangeDomain(HttpServletResponse resp, Connection connection) {
        StringBuilder html = createPageStart("Change Domain");
        html.append("<form action='");
        html.append(servletUrl);
        html.append("/changedomain' method='post'>\nDomain:\n<input type='text' name='domain' value='");
        html.append(connection.getAmazonSite());
        html.append("'>\n<br>\n<input type=\"submit\" value=\"Submit\">\n</form>");

        createPageEndAndSent(resp, html);
    }

    private void handleDefaultPageResult(HttpServletResponse resp, String message, Connection connection)
            throws IOException {
        StringBuilder html = createPageStart("");
        html.append(StringEscapeUtils.escapeHtml(message));
        // logout link
        html.append(" <a href='" + servletUrl + "/logout' >");
        html.append(StringEscapeUtils.escapeHtml("Logout"));
        html.append("</a>");
        // newdevice link
        html.append(" | <a href='" + servletUrl + "/newdevice' >");
        html.append(StringEscapeUtils.escapeHtml("Logout and create new device id"));
        html.append("</a>");
        // customer id
        html.append("<br>Customer Id: ");
        html.append(StringEscapeUtils.escapeHtml(connection.getCustomerId()));
        // customer name
        html.append("<br>Customer Name: ");
        html.append(StringEscapeUtils.escapeHtml(connection.getCustomerName()));
        // device name
        html.append("<br>App name: ");
        html.append(StringEscapeUtils.escapeHtml(connection.getDeviceName()));
        // connection
        html.append("<br>Connected to: ");
        html.append(StringEscapeUtils.escapeHtml(connection.getAlexaServer()));
        // domain
        html.append(" <a href='");
        html.append(servletUrl);
        html.append("/changeDomain'>Change</a>");

        // paper ui link
        html.append("<br><a href='/paperui/index.html#/configuration/things/view/" + BINDING_ID + ":"
                + URLEncoder.encode(THING_TYPE_ACCOUNT.getId(), "UTF8") + ":" + URLEncoder.encode(id, "UTF8") + "'>");
        html.append(StringEscapeUtils.escapeHtml("Check Thing in Paper UI"));
        html.append("</a><br><br>");

        // device list
        html.append(
                "<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>");
        for (Device device : this.account.getLastKnownDevices()) {

            html.append("<tr><td>");
            html.append(StringEscapeUtils.escapeHtml(nullReplacement(device.accountName)));
            html.append("</td><td>");
            html.append(StringEscapeUtils.escapeHtml(nullReplacement(device.serialNumber)));
            html.append("</td><td>");
            html.append(StringEscapeUtils.escapeHtml(device.online ? "Online" : "Offline"));
            html.append("</td><td>");
            Thing accountHandler = account.findThingBySerialNumber(device.serialNumber);<commit_msg>[amazonechocontrol] Fixed link to UI (#9431)<commit_after>/**
 * Copyright (c) 2010-2020 Contributors to the openHAB project
 *
 * See the NOTICE file(s) distributed with this work for additional
 * information.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0
 *
 * SPDX-License-Identifier: EPL-2.0
 */
package org.openhab.binding.amazonechocontrol.internal;

import static org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringEscapeUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.amazonechocontrol.internal.handler.AccountHandler;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates.BluetoothState;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates.PairedDevice;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonDevices.Device;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonMusicProvider;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonNotificationSound;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonPlaylists;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonPlaylists.PlayList;
import org.openhab.core.thing.Thing;
import org.osgi.service.http.HttpService;
import org.osgi.service.http.NamespaceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

/**
 * Provides the following functions
 * --- Login ---
 * Simple http proxy to forward the login dialog from amazon to the user through the binding
 * so the user can enter a captcha or other extended login information
 * --- List of devices ---
 * Used to get the device information of new devices which are currently not known
 * --- List of IDs ---
 * Simple possibility for a user to get the ids needed for writing rules
 *
 * @author <NAME> - Initial Contribution
 */
@NonNullByDefault
public class AccountServlet extends HttpServlet {

    private static final long serialVersionUID = -1453738923337413163L;
    private static final String FORWARD_URI_PART = "/FORWARD/";
    private static final String PROXY_URI_PART = "/PROXY/";

    private final Logger logger = LoggerFactory.getLogger(AccountServlet.class);

    private final HttpService httpService;
    private final String servletUrlWithoutRoot;
    private final String servletUrl;
    private final AccountHandler account;
    private final String id;
    private @Nullable Connection connectionToInitialize;
    private final Gson gson;

    public AccountServlet(HttpService httpService, String id, AccountHandler account, Gson gson) {
        this.httpService = httpService;
        this.account = account;
        this.id = id;
        this.gson = gson;

        try {
            servletUrlWithoutRoot = "amazonechocontrol/" + URLEncoder.encode(id, "UTF8");
            servletUrl = "/" + servletUrlWithoutRoot;

            httpService.registerServlet(servletUrl, this, null, httpService.createDefaultHttpContext());
        } catch (UnsupportedEncodingException | NamespaceException | ServletException e) {
            throw new IllegalStateException(e.getMessage());
        }
    }

    private Connection reCreateConnection() {
        Connection oldConnection = connectionToInitialize;
        if (oldConnection == null) {
            oldConnection = account.findConnection();
        }
        return new Connection(oldConnection, this.gson);
    }

    public void dispose() {
        httpService.unregister(servletUrl);
    }

    @Override
    protected void doPut(@Nullable HttpServletRequest req, @Nullable HttpServletResponse resp)
            throws ServletException, IOException {
        doVerb("PUT", req, resp);
    }

    @Override
    protected void doDelete(@Nullable HttpServletRequest req, @Nullable HttpServletResponse resp)
            throws ServletException, IOException {
        doVerb("DELETE", req, resp);
    }

    @Override
    protected void doPost(@Nullable HttpServletRequest req, @Nullable HttpServletResponse resp)
            throws ServletException, IOException {
        doVerb("POST", req, resp);
    }

    void doVerb(String verb, @Nullable HttpServletRequest req, @Nullable HttpServletResponse resp) throws IOException {
        if (req == null) {
            return;
        }
        if (resp == null) {
            return;
        }
        String requestUri = req.getRequestURI();
        if (requestUri == null) {
            return;
        }
        String baseUrl = requestUri.substring(servletUrl.length());
        String uri = baseUrl;
        String queryString = req.getQueryString();
        if (queryString != null && queryString.length() > 0) {
            uri += "?" + queryString;
        }

        Connection connection = this.account.findConnection();
        if (connection != null && uri.equals("/changedomain")) {
            Map<String, String[]> map = req.getParameterMap();
            String[] domainArray = map.get("domain");
            if (domainArray == null) {
                logger.warn("Could not determine domain");
                return;
            }
            String domain = domainArray[0];
            String loginData = connection.serializeLoginData();
            Connection newConnection = new Connection(null, this.gson);
            if (newConnection.tryRestoreLogin(loginData, domain)) {
                account.setConnection(newConnection);
            }
            resp.sendRedirect(servletUrl);
            return;
        }
        if (uri.startsWith(PROXY_URI_PART)) {
            // handle proxy request

            if (connection == null) {
                returnError(resp, "Account not online");
                return;
            }
            String getUrl = "https://alexa." + connection.getAmazonSite() + "/"
                    + uri.substring(PROXY_URI_PART.length());

            String postData = null;
            if (verb == "POST" || verb == "PUT") {
                postData = req.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
            }

            this.handleProxyRequest(connection, resp, verb, getUrl, null, postData, true, connection.getAmazonSite());
            return;
        }

        // handle post of login page
        connection = this.connectionToInitialize;
        if (connection == null) {
            returnError(resp, "Connection not in initialize mode.");
            return;
        }

        resp.addHeader("content-type", "text/html;charset=UTF-8");

        Map<String, String[]> map = req.getParameterMap();
        StringBuilder postDataBuilder = new StringBuilder();
        for (String name : map.keySet()) {
            if (postDataBuilder.length() > 0) {
                postDataBuilder.append('&');
            }

            postDataBuilder.append(name);
            postDataBuilder.append('=');
            String value = "";
            if (name.equals("failedSignInCount")) {
                value = "ape:AA==";
            } else {
                String[] strings = map.get(name);
                if (strings != null && strings.length > 0 && strings[0] != null) {
                    value = strings[0];
                }
            }
            postDataBuilder.append(URLEncoder.encode(value, StandardCharsets.UTF_8.name()));
        }

        uri = req.getRequestURI();
        if (uri == null || !uri.startsWith(servletUrl)) {
            returnError(resp, "Invalid request uri '" + uri + "'");
            return;
        }
        String relativeUrl = uri.substring(servletUrl.length()).replace(FORWARD_URI_PART, "/");

        String site = connection.getAmazonSite();
        if (relativeUrl.startsWith("/ap/signin")) {
            site = "amazon.com";
        }
        String postUrl = "https://www." + site + relativeUrl;
        queryString = req.getQueryString();
        if (queryString != null && queryString.length() > 0) {
            postUrl += "?" + queryString;
        }
        String referer = "https://www." + site;
        String postData = postDataBuilder.toString();
        handleProxyRequest(connection, resp, "POST", postUrl, referer, postData, false, site);
    }

    @Override
    protected void doGet(@Nullable HttpServletRequest req, @Nullable HttpServletResponse resp) throws IOException {
        if (req == null) {
            return;
        }
        if (resp == null) {
            return;
        }
        String requestUri = req.getRequestURI();
        if (requestUri == null) {
            return;
        }
        String baseUrl = requestUri.substring(servletUrl.length());
        String uri = baseUrl;
        String queryString = req.getQueryString();
        if (queryString != null && queryString.length() > 0) {
            uri += "?" + queryString;
        }
        logger.debug("doGet {}", uri);
        try {
            Connection connection = this.connectionToInitialize;
            if (uri.startsWith(FORWARD_URI_PART) && connection != null) {
                String getUrl = "https://www." + connection.getAmazonSite() + "/"
                        + uri.substring(FORWARD_URI_PART.length());

                this.handleProxyRequest(connection, resp, "GET", getUrl, null, null, false, connection.getAmazonSite());
                return;
            }

            connection = this.account.findConnection();
            if (uri.startsWith(PROXY_URI_PART)) {
                // handle proxy request

                if (connection == null) {
                    returnError(resp, "Account not online");
                    return;
                }
                String getUrl = "https://alexa." + connection.getAmazonSite() + "/"
                        + uri.substring(PROXY_URI_PART.length());

                this.handleProxyRequest(connection, resp, "GET", getUrl, null, null, false, connection.getAmazonSite());
                return;
            }

            if (connection != null && connection.verifyLogin()) {
                // handle commands
                if (baseUrl.equals("/logout") || baseUrl.equals("/logout/")) {
                    this.connectionToInitialize = reCreateConnection();
                    this.account.setConnection(null);
                    resp.sendRedirect(this.servletUrl);
                    return;
                }
                // handle commands
                if (baseUrl.equals("/newdevice") || baseUrl.equals("/newdevice/")) {
                    this.connectionToInitialize = new Connection(null, this.gson);
                    this.account.setConnection(null);
                    resp.sendRedirect(this.servletUrl);
                    return;
                }

                if (baseUrl.equals("/devices") || baseUrl.equals("/devices/")) {
                    handleDevices(resp, connection);
                    return;
                }
                if (baseUrl.equals("/changeDomain") || baseUrl.equals("/changeDomain/")) {
                    handleChangeDomain(resp, connection);
                    return;
                }
                if (baseUrl.equals("/ids") || baseUrl.equals("/ids/")) {
                    String serialNumber = getQueryMap(queryString).get("serialNumber");
                    Device device = account.findDeviceJson(serialNumber);
                    if (device != null) {
                        Thing thing = account.findThingBySerialNumber(device.serialNumber);
                        handleIds(resp, connection, device, thing);
                        return;
                    }
                }
                // return hint that everything is ok
                handleDefaultPageResult(resp, "The Account is logged in.", connection);
                return;
            }
            connection = this.connectionToInitialize;
            if (connection == null) {
                connection = this.reCreateConnection();
                this.connectionToInitialize = connection;
            }

            if (!uri.equals("/")) {
                String newUri = req.getServletPath() + "/";
                resp.sendRedirect(newUri);
                return;
            }

            String html = connection.getLoginPage();
            returnHtml(connection, resp, html, "amazon.com");
        } catch (URISyntaxException | InterruptedException e) {
            logger.warn("get failed with uri syntax error", e);
        }
    }

    public Map<String, String> getQueryMap(@Nullable String query) {
        Map<String, String> map = new HashMap<>();
        if (query != null) {
            String[] params = query.split("&");
            for (String param : params) {
                String[] elements = param.split("=");
                if (elements.length == 2) {
                    String name = elements[0];
                    String value = "";
                    try {
                        value = URLDecoder.decode(elements[1], "UTF8");
                    } catch (UnsupportedEncodingException e) {
                        logger.info("Unsupported encoding", e);
                    }
                    map.put(name, value);
                }
            }
        }
        return map;
    }

    private void handleChangeDomain(HttpServletResponse resp, Connection connection) {
        StringBuilder html = createPageStart("Change Domain");
        html.append("<form action='");
        html.append(servletUrl);
        html.append("/changedomain' method='post'>\nDomain:\n<input type='text' name='domain' value='");
        html.append(connection.getAmazonSite());
        html.append("'>\n<br>\n<input type=\"submit\" value=\"Submit\">\n</form>");

        createPageEndAndSent(resp, html);
    }

    private void handleDefaultPageResult(HttpServletResponse resp, String message, Connection connection)
            throws IOException {
        StringBuilder html = createPageStart("");
        html.append(StringEscapeUtils.escapeHtml(message));
        // logout link
        html.append(" <a href='" + servletUrl + "/logout' >");
        html.append(StringEscapeUtils.escapeHtml("Logout"));
        html.append("</a>");
        // newdevice link
        html.append(" | <a href='" + servletUrl + "/newdevice' >");
        html.append(StringEscapeUtils.escapeHtml("Logout and create new device id"));
        html.append("</a>");
        // customer id
        html.append("<br>Customer Id: ");
        html.append(StringEscapeUtils.escapeHtml(connection.getCustomerId()));
        // customer name
        html.append("<br>Customer Name: ");
        html.append(StringEscapeUtils.escapeHtml(connection.getCustomerName()));
        // device name
        html.append("<br>App name: ");
        html.append(StringEscapeUtils.escapeHtml(connection.getDeviceName()));
        // connection
        html.append("<br>Connected to: ");
        html.append(StringEscapeUtils.escapeHtml(connection.getAlexaServer()));
        // domain
        html.append(" <a href='");
        html.append(servletUrl);
        html.append("/changeDomain'>Change</a>");

        // Main UI link
        html.append("<br><a href='/#!/settings/things/" + BINDING_ID + ":"
                + URLEncoder.encode(THING_TYPE_ACCOUNT.getId(), "UTF8") + ":" + URLEncoder.encode(id, "UTF8") + "'>");
        html.append(StringEscapeUtils.escapeHtml("Check Thing in Main UI"));
        html.append("</a><br><br>");

        // device list
        html.append(
                "<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>");
        for (Device device : this.account.getLastKnownDevices()) {

            html.append("<tr><td>");
            html.append(StringEscapeUtils.escapeHtml(nullReplacement(device.accountName)));
            html.append("</td><td>");
            html.append(StringEscapeUtils.escapeHtml(nullReplacement(device.serialNumber)));
            html.append("</td><td>");
            html.append(StringEscapeUtils.escapeHtml(device.online ? "Online" : "Offline"));
            html.append("</td><td>");
            Thing accountHandler = account.findThingBySerialNumber(device.serialNumber);
{'fraction_non_alphanumeric': 0.11805109019699538, 'fraction_numerical': 0.00315660256035541, 'mean_word_length': 2.2564004949081564, 'pattern_counts': {'":': 4, '<': 105, '<?xml version=': 0, '>': 115, 'https://': 10, 'lorem ipsum': 0, 'www.': 8, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3116474', 'n_tokens_mistral': 8986, 'n_tokens_neox': 8693, 'n_words': 1904}