Java Code Examples for org.eclipse.jetty.websocket.client.ClientUpgradeRequest#setSubProtocols()

The following examples show how to use org.eclipse.jetty.websocket.client.ClientUpgradeRequest#setSubProtocols() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BoseSoundTouchHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private synchronized void openConnection() {
    closeConnection();
    try {
        client = new WebSocketClient();
        // we need longer timeouts for web socket.
        client.setMaxIdleTimeout(360 * 1000);
        // Port seems to be hard coded, therefore no user input or discovery is necessary
        String wsUrl = "ws://" + getIPAddress() + ":8080/";
        logger.debug("{}: Connecting to: {}", getDeviceName(), wsUrl);
        ClientUpgradeRequest request = new ClientUpgradeRequest();
        request.setSubProtocols("gabbo");
        client.setStopTimeout(1000);
        client.start();
        client.connect(this, new URI(wsUrl), request);
    } catch (Exception e) {
        onWebSocketError(e);
    }
}
 
Example 2
Source File: JettyWebSocketClient.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public ListenableFuture<WebSocketSession> doHandshakeInternal(WebSocketHandler wsHandler,
		HttpHeaders headers, final URI uri, List<String> protocols,
		List<WebSocketExtension> extensions,  Map<String, Object> attributes) {

	final ClientUpgradeRequest request = new ClientUpgradeRequest();
	request.setSubProtocols(protocols);

	for (WebSocketExtension e : extensions) {
		request.addExtensions(new WebSocketToJettyExtensionConfigAdapter(e));
	}

	headers.forEach(request::setHeader);

	Principal user = getUser();
	final JettyWebSocketSession wsSession = new JettyWebSocketSession(attributes, user);
	final JettyWebSocketHandlerAdapter listener = new JettyWebSocketHandlerAdapter(wsHandler, wsSession);

	Callable<WebSocketSession> connectTask = () -> {
		Future<Session> future = this.client.connect(listener, uri, request);
		future.get();
		return wsSession;
	};

	if (this.taskExecutor != null) {
		return this.taskExecutor.submitListenable(connectTask);
	}
	else {
		ListenableFutureTask<WebSocketSession> task = new ListenableFutureTask<>(connectTask);
		task.run();
		return task;
	}
}
 
Example 3
Source File: JettyWebSocketClient.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public ListenableFuture<WebSocketSession> doHandshakeInternal(WebSocketHandler wsHandler,
		HttpHeaders headers, final URI uri, List<String> protocols,
		List<WebSocketExtension> extensions,  Map<String, Object> attributes) {

	final ClientUpgradeRequest request = new ClientUpgradeRequest();
	request.setSubProtocols(protocols);

	for (WebSocketExtension e : extensions) {
		request.addExtensions(new WebSocketToJettyExtensionConfigAdapter(e));
	}

	headers.forEach(request::setHeader);

	Principal user = getUser();
	final JettyWebSocketSession wsSession = new JettyWebSocketSession(attributes, user);
	final JettyWebSocketHandlerAdapter listener = new JettyWebSocketHandlerAdapter(wsHandler, wsSession);

	Callable<WebSocketSession> connectTask = () -> {
		Future<Session> future = this.client.connect(listener, uri, request);
		future.get();
		return wsSession;
	};

	if (this.taskExecutor != null) {
		return this.taskExecutor.submitListenable(connectTask);
	}
	else {
		ListenableFutureTask<WebSocketSession> task = new ListenableFutureTask<>(connectTask);
		task.run();
		return task;
	}
}
 
Example 4
Source File: WebSocketClient.java    From aliyun-cupid-sdk with Apache License 2.0 5 votes vote down vote up
public void connect(boolean isReconnect) {
    if (client == null) {
        client = new org.eclipse.jetty.websocket.client.WebSocketClient();
    }
    // For debug usage
    // client.setConnectTimeout(SDKConstants.ONE_HOUR);
    try {
        if (!client.isStarted()) {
            client.start();
        }
        ClientUpgradeRequest request = new ClientUpgradeRequest();
        request.setSubProtocols(subProtocol);
        setLoadBalanceKey(request);
        if (token != null) {
            request.setHeader(SDKConstants.CUPID_INTERACTION_HEADER_TOKEN, token);
        }
        if (isReconnect) {
            request.setHeader(SDKConstants.CUPID_INTERACTION_HEADER_RECONNECT,
                    String.valueOf(System.currentTimeMillis()));
        }
        LOG.info(subProtocol + " - Connecting to : " + destUri);
        Future<Session> future = client.connect(interactionSocket, destUri, request);
        Session session = future.get(5l, TimeUnit.SECONDS);
        if (!isReconnect && SDKConstants.CUPID_INTERACTION_SUB_PROTOCOL_CLIENT.equals(subProtocol)) {
            // will be used for reconnect
            token = session.getUpgradeResponse().getHeader(SDKConstants.CUPID_INTERACTION_HEADER_TOKEN);
            routeInfo =
                    session.getUpgradeResponse()
                            .getHeader(SDKConstants.CUPID_INTERACTION_HEADER_ROUTE_INFO);
        }
        extractLoadBalanceKey(session);
        LOG.info(subProtocol + " - Connected!");
    } catch (Throwable t) {
        String errMsg = subProtocol + " - Websocket connect failed";
        LOG.error(errMsg, t);
        close();
    }
}
 
Example 5
Source File: TestReflectionJob.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private void prepareWebSocket() throws Exception {
  client.start();
  URI socketUri = new URI(getAPIv2().path("socket").getUri().toString().replace("http://", "ws://"));
  ClientUpgradeRequest request = new ClientUpgradeRequest();
  request.setSubProtocols(Lists.newArrayList(getAuthHeaderValue()));
  this.socket = new TestWebSocket.TestSocket();
  client.connect(socket, socketUri, request);
  socket.awaitConnection(2);
  assertEquals(getAuthHeaderValue(), socket.getSession().getUpgradeResponse().getAcceptedSubProtocol());
}
 
Example 6
Source File: TestWebSocket.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  client.start();
  URI socketUri = new URI(getAPIv2().path("socket").getUri().toString().replace("http://", "ws://"));
  ClientUpgradeRequest request = new ClientUpgradeRequest();
  request.setSubProtocols(Lists.newArrayList(getAuthHeaderValue()));
  this.socket = new TestSocket();
  client.connect(socket, socketUri, request);
  socket.awaitConnection(2);
  assertEquals(getAuthHeaderValue(), socket.session.getUpgradeResponse().getAcceptedSubProtocol());
}
 
Example 7
Source File: JettyWebSocketClient.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<WebSocketSession> doHandshakeInternal(WebSocketHandler wsHandler,
		HttpHeaders headers, final URI uri, List<String> protocols,
		List<WebSocketExtension> extensions,  Map<String, Object> attributes) {

	final ClientUpgradeRequest request = new ClientUpgradeRequest();
	request.setSubProtocols(protocols);

	for (WebSocketExtension e : extensions) {
		request.addExtensions(new WebSocketToJettyExtensionConfigAdapter(e));
	}

	for (String header : headers.keySet()) {
		request.setHeader(header, headers.get(header));
	}

	Principal user = getUser();
	final JettyWebSocketSession wsSession = new JettyWebSocketSession(attributes, user);
	final JettyWebSocketHandlerAdapter listener = new JettyWebSocketHandlerAdapter(wsHandler, wsSession);

	Callable<WebSocketSession> connectTask = new Callable<WebSocketSession>() {
		@Override
		public WebSocketSession call() throws Exception {
			Future<Session> future = client.connect(listener, uri, request);
			future.get();
			return wsSession;
		}
	};

	if (this.taskExecutor != null) {
		return this.taskExecutor.submitListenable(connectTask);
	}
	else {
		ListenableFutureTask<WebSocketSession> task = new ListenableFutureTask<WebSocketSession>(connectTask);
		task.run();
		return task;
	}
}
 
Example 8
Source File: WebSocketClient.java    From icure-backend with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args)
{
	URI uri = URI.create("ws://127.0.0.1:16043/ws/be_kmehr/generateSumehr");

	org.eclipse.jetty.websocket.client.WebSocketClient client = new org.eclipse.jetty.websocket.client.WebSocketClient();
	try
	{
		try
		{
			client.start();
			// The socket that receives events
			WebSocketClient socket = new WebSocketClient();
			// Attempt Connect
			ClientUpgradeRequest request = new ClientUpgradeRequest();
			request.setSubProtocols("xsCrossfire");
			String basicAuthHeader = org.apache.commons.codec.binary.Base64.encodeBase64String("abaudoux:lambda".getBytes("UTF8"));
			request.setHeader("Authorization", "Basic " + basicAuthHeader);

			Future<Session> fut = client.connect(socket,uri,request);
			// Wait for Connect
			Session session = fut.get();
			// Send a message

			System.out.println(">>> Sending message: Hello");
			session.getRemote().sendString("{\"parameters\":{\"language\":\"fr\",\"info\":{\"comment\":\"\",\"recipient\":{\"name\":\"Abrumet\",\"nihii\":\"1990000728\",\"specialityCodes\":[{\"type\":\"CD-HCPARTY\",\"code\":\"hub\"}]},\"secretForeignKeys\":[\"44eccc69-11d5-4c89-accc-6911d5dc8942\"]},\"patientId\":\"29e6fafd-05be-4f2b-a6fa-fd05beef2bbc\"}}");
			Thread.sleep(1000);
			session.getRemote().sendString("{\"parameters\":{\"language\":\"fr\",\"info\":{\"comment\":\"\",\"recipient\":{\"name\":\"Abrumet\",\"nihii\":\"1990000728\",\"specialityCodes\":[{\"type\":\"CD-HCPARTY\",\"code\":\"hub\"}]},\"secretForeignKeys\":[\"44eccc69-11d5-4c89-accc-6911d5dc8942\"]},\"patientId\":\"29e6fafd-05be-4f2b-a6fa-fd05beef2bbc\"}}");
			Thread.sleep(1000);
			session.getRemote().sendString("{\"parameters\":{\"language\":\"fr\",\"info\":{\"comment\":\"\",\"recipient\":{\"name\":\"Abrumet\",\"nihii\":\"1990000728\",\"specialityCodes\":[{\"type\":\"CD-HCPARTY\",\"code\":\"hub\"}]},\"secretForeignKeys\":[\"44eccc69-11d5-4c89-accc-6911d5dc8942\"]},\"patientId\":\"29e6fafd-05be-4f2b-a6fa-fd05beef2bbc\"}}");
			Thread.sleep(1000);
			session.getRemote().sendString("{\"parameters\":{\"language\":\"fr\",\"info\":{\"comment\":\"\",\"recipient\":{\"name\":\"Abrumet\",\"nihii\":\"1990000728\",\"specialityCodes\":[{\"type\":\"CD-HCPARTY\",\"code\":\"hub\"}]},\"secretForeignKeys\":[\"44eccc69-11d5-4c89-accc-6911d5dc8942\"]},\"patientId\":\"29e6fafd-05be-4f2b-a6fa-fd05beef2bbc\"}}");
			Thread.sleep(1000);
			session.getRemote().sendString("{\"parameters\":{\"language\":\"fr\",\"info\":{\"comment\":\"\",\"recipient\":{\"name\":\"Abrumet\",\"nihii\":\"1990000728\",\"specialityCodes\":[{\"type\":\"CD-HCPARTY\",\"code\":\"hub\"}]},\"secretForeignKeys\":[\"44eccc69-11d5-4c89-accc-6911d5dc8942\"]},\"patientId\":\"29e6fafd-05be-4f2b-a6fa-fd05beef2bbc\"}}");
			Thread.sleep(1000);
			session.getRemote().sendString("{\"parameters\":{\"language\":\"fr\",\"info\":{\"comment\":\"\",\"recipient\":{\"name\":\"Abrumet\",\"nihii\":\"1990000728\",\"specialityCodes\":[{\"type\":\"CD-HCPARTY\",\"code\":\"hub\"}]},\"secretForeignKeys\":[\"44eccc69-11d5-4c89-accc-6911d5dc8942\"]},\"patientId\":\"29e6fafd-05be-4f2b-a6fa-fd05beef2bbc\"}}");
			Thread.sleep(1000);

			Thread.sleep(10000);

			session.close();

		}
		finally
		{
			client.stop();
		}
	}
	catch (Throwable t)
	{
		t.printStackTrace(System.err);
	}
}