1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package Torello.Browser;

import static Torello.Java.C.BYELLOW;
import static Torello.Java.C.RESET;

import Torello.HTML.Scrape;

import java.net.URL;
import java.net.MalformedURLException;
import java.io.StringReader;
import javax.json.Json;
import javax.json.JsonObject;

final class BCBuilder
{
    static BrowserConn getBrowserConn(Integer port, final boolean quiet)
    {
        if (port == null) port = 9222;

        final String    urlStr ="http://127.0.0.1:" + port + "/json/version";
        final URL       url;

        try 
            { url = new URL(urlStr); }

        catch (MalformedURLException e)
        {
            throw new RDPException(
                "An Internal Error has occurred.  Unable to instantiate URL.\n" +
                "    URL: " + urlStr + "\n" +
                "    Exception: " + e.getClass().getSimpleName() + " - " + e.getMessage() + '\n' +
                "Please see cause-exception for details.",
                e
            );
        }

        if (!quiet) System.out.println(
            "\nQuerying Browser-Level WebSocket URL:\n\t" +
            BYELLOW + urlStr + RESET
        );

        final String json;

        try
            { json = Scrape.scrapePage(url); }

        catch (Exception e)
        {
            throw new RDPException(
                "Problem while querying browser-level WebSocket URL:\n" +
                "    URL: " + url + "\n" +
                "    Exception: " + e.getClass().getSimpleName() + " - " + e.getMessage() + '\n' +
                "Please see cause-exception for details.",
                e
            );
        }

        if (!quiet) System.out.println("Browser-Level JSON Response:\n" + json);

        final JsonObject obj;

        try 
            { obj = Json.createReader(new StringReader(json)).readObject(); }

        catch (Exception e)
        {
            throw new RDPException(
                "Failed to parse JSON object from Chrome's /json/version response:\n" +
                "    Exception: " + e.getClass().getSimpleName() + " - " + e.getMessage() + '\n' +
                "Please see cause-exception for details.",
                e
            );
        }

        try
            { return new BrowserConn(obj); }

        catch (Exception e)
        {
            throw new RDPException(
                "Failed to construct BrowserConn from parsed JSON object:\n" +
                "    Exception: " + e.getClass().getSimpleName() + " - " + e.getMessage() + '\n' +
                "Raw JSON was:\n" + json,
                e
            );
        }
    }
}