51 {
52
53 URI uri;
54 try {
55 uri = new URI(url);
56 } catch (URISyntaxException e) {
57 throw new IOException("Invalid URL: " + url, e);
58 }
59 String wsScheme = uri.getScheme();
61 throw new IOException("Unsupported URL scheme: " + wsScheme);
62 }
63
64
65 WebSocket webSocket;
66 try {
67 webSocket = new WebSocket(uri);
68 } catch (WebSocketException e) {
69 throw new IOException("Failed to create websocket: " + url, e);
70 }
71 final VmService vmService = new VmService();
72
73
74 webSocket.setEventHandler(new WebSocketEventHandler() {
75 @Override
76 public void onClose() {
77 Logging.getLogger().logInformation("VM connection closed: " + url);
78
79 vmService.connectionClosed();
80 }
81
82 @Override
83 public void onMessage(WebSocketMessage
message) {
84 Logging.getLogger().logInformation(
"VM message: " +
message.getText());
85 try {
86 vmService.processMessage(
message.getText());
87 } catch (Exception e) {
88 Logging.getLogger().logError(
e.getMessage(), e);
89 }
90 }
91
92 @Override
93 public void onOpen() {
94 vmService.connectionOpened();
95
96 Logging.getLogger().logInformation("VM connection open: " + url);
97 }
98
99 @Override
100 public void onPing() {
101 }
102
103 @Override
104 public void onPong() {
105 }
106 });
107
108
109
110 try {
111 webSocket.connect();
112 } catch (WebSocketException e) {
113 throw new IOException("Failed to connect: " + url, e);
114 } catch (ArrayIndexOutOfBoundsException e) {
115
116
117 throw new IOException("Failed to connect: " + url, e);
118 }
119 vmService.requestSink = new WebSocketRequestSink(webSocket);
120
121
122 final CountDownLatch latch = new CountDownLatch(1);
123 final String[] errMsg = new String[1];
124 vmService.getVersion(new VersionConsumer() {
125 @Override
126 public void onError(RPCError
error) {
127 String msg =
"Failed to determine protocol version: " +
error.getCode() +
"\n message: "
128 +
error.getMessage() +
"\n details: " +
error.getDetails();
129 Logging.getLogger().logInformation(msg);
130 errMsg[0] = msg;
131 }
132
133 @Override
134 public void received(
Version version) {
135 vmService.runtimeVersion =
version;
136
137 latch.countDown();
138 }
139 });
140
141 try {
142 if (!latch.await(5, TimeUnit.SECONDS)) {
143 throw new IOException("Failed to determine protocol version");
144 }
145 if (errMsg[0] != null) {
146 throw new IOException(errMsg[0]);
147 }
148 } catch (InterruptedException e) {
149 throw new RuntimeException("Interrupted while waiting for response", e);
150 }
151
152 return vmService;
153 }
static bool equals(T *a, T *b)
const uint8_t uint32_t uint32_t GError ** error