]> git.argeo.org Git - lgpl/argeo-commons.git/blob - client/WebSocketEventClient.java
Prepare next development cycle
[lgpl/argeo-commons.git] / client / WebSocketEventClient.java
1 package org.argeo.cms.client;
2
3 import java.net.URI;
4 import java.net.URL;
5 import java.net.http.HttpClient;
6 import java.net.http.WebSocket;
7 import java.nio.ByteBuffer;
8 import java.util.concurrent.CompletableFuture;
9 import java.util.concurrent.CompletionStage;
10 import java.util.concurrent.ExecutionException;
11
12 import javax.security.auth.login.LoginContext;
13 import javax.security.auth.login.LoginException;
14
15 import org.argeo.cms.auth.RemoteAuthUtils;
16 import org.argeo.util.http.HttpHeader;
17
18 /** Tests connectivity to the web socket server. */
19 public class WebSocketEventClient implements Runnable {
20
21 private final URI uri;
22
23 private WebSocket webSocket;
24
25 public WebSocketEventClient(URI uri) {
26 this.uri = uri;
27 }
28
29 @Override
30 public void run() {
31 try {
32 WebSocket.Listener listener = new WebSocket.Listener() {
33
34 public CompletionStage<?> onText(WebSocket webSocket, CharSequence message, boolean last) {
35 System.out.println(message);
36 CompletionStage<String> res = CompletableFuture.completedStage(message.toString());
37 return res;
38 }
39
40 @Override
41 public CompletionStage<?> onPong(WebSocket webSocket, ByteBuffer message) {
42 // System.out.println("Pong received.");
43 return null;
44 }
45
46 };
47
48 // SPNEGO
49 URL jaasUrl = SpnegoHttpClient.class.getResource("jaas-client-ipa.cfg");
50 System.setProperty("java.security.auth.login.config", jaasUrl.toExternalForm());
51 LoginContext lc = new LoginContext(SpnegoHttpClient.CLIENT_LOGIN_CONTEXT);
52 lc.login();
53 String token = RemoteAuthUtils.createGssToken(lc.getSubject(), "HTTP", uri.getHost());
54
55 HttpClient client = SpnegoHttpClient.openHttpClient(lc.getSubject());
56 CompletableFuture<WebSocket> ws = client.newWebSocketBuilder()
57 .header(HttpHeader.AUTHORIZATION.getHeaderName(), HttpHeader.NEGOTIATE + " " + token)
58 .buildAsync(uri, listener);
59
60 WebSocket webSocket = ws.get();
61 webSocket.request(Long.MAX_VALUE);
62
63 Runtime.getRuntime().addShutdownHook(new Thread(() -> webSocket.sendClose(WebSocket.NORMAL_CLOSURE, "")));
64
65 while (!webSocket.isInputClosed()) {
66 webSocket.sendPing(ByteBuffer.allocate(0));
67 Thread.sleep(10000);
68 }
69 }catch (InterruptedException e) {
70 if (webSocket != null)
71 webSocket.sendClose(WebSocket.NORMAL_CLOSURE, "");
72 } catch (ExecutionException | LoginException e) {
73 throw new RuntimeException("Cannot listent to " + uri, e.getCause());
74 }
75 }
76
77 // public static void main(String[] args) throws Exception {
78 // if (args.length == 0) {
79 // System.err.println("usage: java " + WebSocketEventClient.class.getName() + " <url>");
80 // System.exit(1);
81 // return;
82 // }
83 // URI uri = URI.create(args[0]);
84 // }
85
86 }