org.eclipse.jetty.websocket.client.ClientUpgradeRequest Java Examples

The following examples show how to use org.eclipse.jetty.websocket.client.ClientUpgradeRequest. 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: SimpleEchoClient.java    From java_rosbridge with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) {
	String destUri = "ws://echo.websocket.org";
	if (args.length > 0) {
		destUri = args[0];
	}
	WebSocketClient client = new WebSocketClient();
	SimpleEchoSocket socket = new SimpleEchoSocket();
	try {
		client.start();
		URI echoUri = new URI(destUri);
		ClientUpgradeRequest request = new ClientUpgradeRequest();
		client.connect(socket, echoUri, request);
		System.out.printf("Connecting to : %s%n", echoUri);
		socket.awaitClose(15, TimeUnit.SECONDS);
	} catch (Throwable t) {
		t.printStackTrace();
	} finally {
		try {
			client.stop();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
Example #2
Source File: ZeppelinClient.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private Session openNoteSession(String noteId, String principal, String ticket) {
  ClientUpgradeRequest request = new ClientUpgradeRequest();
  request.setHeader(ORIGIN, "*");
  ZeppelinWebsocket socket = new ZeppelinWebsocket(noteId);
  Future<Session> future = null;
  Session session = null;
  try {
    future = wsClient.connect(socket, zeppelinWebsocketUrl, request);
    session = future.get();
  } catch (IOException | InterruptedException | ExecutionException e) {
    LOG.error("Couldn't establish websocket connection to Zeppelin ", e);
    return session;
  }

  if (notesConnection.containsKey(noteId)) {
    session.close();
    session = notesConnection.get(noteId);
  } else {
    String getNote = serialize(zeppelinGetNoteMsg(noteId, principal, ticket));
    session.getRemote().sendStringByFuture(getNote);
    notesConnection.put(noteId, session);
  }
  return session;
}
 
Example #3
Source File: LoggregatorClient.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
public void start(Target target, String loggregatorLocation, LoggregatorListener listener) throws Exception {
	logger.debug(NLS.bind("About to connect: {0}", loggregatorLocation));

	SslContextFactory sslContextFactory = new SslContextFactory(true);
	WebSocketClient client = new WebSocketClient(sslContextFactory);
	LoggregatorSocket socket = new LoggregatorSocket(listener);
	try {
		client.start();
		URI loggregatorUri = new URI(loggregatorLocation);
		ClientUpgradeRequest request = new ClientUpgradeRequest();
		request.setHeader("Authorization", "bearer " + target.getCloud().getAccessToken().getString("access_token"));

		client.connect(socket, loggregatorUri, request);
		logger.debug(NLS.bind("Connecting to: {0}", loggregatorUri));
		socket.awaitClose(25, TimeUnit.SECONDS);
	} finally {
		client.stop();
	}
}
 
Example #4
Source File: WebSocketAbstractSampler.java    From jmeter-bzm-plugins with Apache License 2.0 6 votes vote down vote up
protected void setConnectionHeaders(ClientUpgradeRequest request, HeaderManager headerManager, CacheManager cacheManager) {
    if (headerManager != null) {
        CollectionProperty headers = headerManager.getHeaders();
        PropertyIterator p = headers.iterator();
        if (headers != null) {
        	while (p.hasNext()){
        		JMeterProperty jMeterProperty = p.next();
        		org.apache.jmeter.protocol.http.control.Header header
                = (org.apache.jmeter.protocol.http.control.Header)
                        jMeterProperty.getObjectValue();
                String n = header.getName();
                if (! HTTPConstants.HEADER_CONTENT_LENGTH.equalsIgnoreCase(n)){
                    String v = header.getValue();
            		request.setHeader(n, v);
                }
        	}
        }
    }
    if (cacheManager != null){
    }
}
 
Example #5
Source File: ZeppelinhubClient.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private ZeppelinhubSession connect(String token) {
  if (StringUtils.isBlank(token)) {
    LOG.debug("Can't connect with empty token");
    return ZeppelinhubSession.EMPTY;
  }
  ZeppelinhubSession zeppelinhubSession;
  try {
    ZeppelinhubWebsocket ws = ZeppelinhubWebsocket.newInstance(token);
    ClientUpgradeRequest request = getConnectionRequest(token);
    Future<Session> future = client.connect(ws, zeppelinhubWebsocketUrl, request);
    Session session = future.get();
    zeppelinhubSession = ZeppelinhubSession.createInstance(session, token);
    setSession(token, zeppelinhubSession);
  } catch (IOException | InterruptedException | ExecutionException e) {
    LOG.info("Couldnt connect to zeppelinhub", e);
    zeppelinhubSession = ZeppelinhubSession.EMPTY;
  }
  return zeppelinhubSession;
}
 
Example #6
Source File: WebSocketClientSource.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private Session connectToWebSocket() throws Exception {
  if (destroyed) {
    return null;
  }

  if (!webSocketClient.isRunning()) {
    webSocketClient.start();
  }

  URI webSocketUri = new URI(conf.resourceUrl);
  ClientUpgradeRequest request = new ClientUpgradeRequest();
  for (String key : conf.headers.keySet()) {
    request.setHeader(key, conf.headers.get(key));
  }

  if (conf.authType.equals(AuthenticationType.BASIC)) {
    String basicAuthHeader = WebSocketCommon.generateBasicAuthHeader(
        conf.basicAuth.username.get(),
        conf.basicAuth.password.get()
    );
    request.setHeader("Authorization", basicAuthHeader);
  }

  Future<Session> connectFuture = webSocketClient.connect(this, webSocketUri, request);
  return connectFuture.get();
}
 
Example #7
Source File: ZeppelinClient.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private Session openWatcherSession() {
  ClientUpgradeRequest request = new ClientUpgradeRequest();
  request.setHeader(WatcherSecurityKey.HTTP_HEADER, WatcherSecurityKey.getKey());
  request.setHeader(ORIGIN, "*");
  WatcherWebsocket socket = WatcherWebsocket.createInstace();
  Future<Session> future = null;
  Session session = null;
  try {
    future = wsClient.connect(socket, zeppelinWebsocketUrl, request);
    session = future.get();
  } catch (IOException | InterruptedException | ExecutionException e) {
    LOG.error("Couldn't establish websocket connection to Zeppelin ", e);
    return session;
  }
  return session;
}
 
Example #8
Source File: RosBridge.java    From java_rosbridge with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Connects to the Rosbridge host at the provided URI.
 * @param rosBridgeURI the URI to the ROS Bridge websocket server. Note that ROS Bridge by default uses port 9090. An example URI is: ws://localhost:9090
 * @param waitForConnection if true, then this method will block until the connection is established. If false, then return immediately.
 */
public void connect(String rosBridgeURI, boolean waitForConnection){
	WebSocketClient client = new WebSocketClient();
	try {
		client.start();
		URI echoUri = new URI(rosBridgeURI);
		ClientUpgradeRequest request = new ClientUpgradeRequest();
		client.connect(this, echoUri, request);
		System.out.printf("Connecting to : %s%n", echoUri);
		if(waitForConnection){
			this.waitForConnection();
		}

	} catch (Throwable t) {
		t.printStackTrace();
	}

}
 
Example #9
Source File: JsonWebSocketProtocolHandler.java    From diozero with MIT License 6 votes vote down vote up
public JsonWebSocketProtocolHandler(NativeDeviceFactoryInterface deviceFactory) {
	super(deviceFactory);

	serialiser = GSON::toJson;
	deserialiser = GSON::fromJson;
	
	webSocketClient = new WebSocketClient();
	try {
		webSocketClient.start();

		URI uri = new URI("ws://localhost:8080/diozero");
		Logger.debug("Connecting to: {}...", uri);
		session = webSocketClient.connect(this, uri, new ClientUpgradeRequest()).get();
		Logger.debug("Connected to: {}", uri);
	} catch (Exception e) {
		throw new RuntimeIOException(e);
	}
}
 
Example #10
Source File: CoinbaseSocket.java    From cloud-bigtable-examples with Apache License 2.0 6 votes vote down vote up
@Override
public boolean start() throws IOException {
  String destUri = "wss://ws-feed.exchange.coinbase.com";
  WebSocketClient client = new WebSocketClient(new SslContextFactory());
  try {
    LOG.info("connecting to coinbsae feed");
    client.start();
    URI echoUri = new URI(destUri);
    ClientUpgradeRequest request = new ClientUpgradeRequest();
    client.connect(this, echoUri, request);
    LOG.info("done connecting");
  } catch (Throwable t) {
    t.printStackTrace();
  }
  return advance();
}
 
Example #11
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 #12
Source File: HttpAgentClient.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
@Override
public void openConnection() throws IOException {

	this.logger.info( getId() + " is opening a connection to the DM." );
	try {
		this.client = new WebSocketClient();
		this.socket = new AgentWebSocket( this.messageQueue );
		this.client.start();

		URI dmUri = new URI( "ws://" + this.dmIp + ":" + this.dmPort + HttpConstants.DM_SOCKET_PATH );
		this.logger.fine( "Connecting to " + dmUri );
		ClientUpgradeRequest request = new ClientUpgradeRequest();

		Future<Session> fut = this.client.connect( this.socket, dmUri, request );
		this.clientSession = fut.get();

	} catch( Exception e ) {
		throw new IOException( e );
	}
}
 
Example #13
Source File: ProxyPublishConsumeTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test(timeOut = 10000)
public void emptySubcriptionConsumerTest() throws Exception {

    // Empty subcription name
    final String consumerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get()
            + "/ws/v2/consumer/persistent/my-property/my-ns/my-topic2/?subscriptionType=Exclusive";
    URI consumeUri = URI.create(consumerUri);

    WebSocketClient consumeClient1 = new WebSocketClient();
    SimpleConsumerSocket consumeSocket1 = new SimpleConsumerSocket();

    try {
        consumeClient1.start();
        ClientUpgradeRequest consumeRequest1 = new ClientUpgradeRequest();
        Future<Session> consumerFuture1 = consumeClient1.connect(consumeSocket1, consumeUri, consumeRequest1);
        consumerFuture1.get();
        fail("should fail: empty subscription");
    } catch (Exception e) {
        // Expected
        assertTrue(e.getCause() instanceof UpgradeException);
        assertEquals(((UpgradeException) e.getCause()).getResponseStatusCode(),
                HttpServletResponse.SC_BAD_REQUEST);
    } finally {
        stopWebSocketClient(consumeClient1);
    }
}
 
Example #14
Source File: WebSocketTarget.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
public void write(Batch batch) throws StageException {
  Session wsSession = null;
  try {
    WebSocketTargetSocket webSocketTargetSocket = new WebSocketTargetSocket(
        conf,
        generatorFactory,
        errorRecordHandler,
        batch
    );
    webSocketClient.start();
    URI webSocketUri = new URI(conf.resourceUrl);

    ClientUpgradeRequest request = new ClientUpgradeRequest();
    for (HeaderBean header : conf.headers) {
      request.setHeader(header.key, header.value.get());
    }

    Future<Session> connectFuture = webSocketClient.connect(webSocketTargetSocket, webSocketUri, request);
    wsSession = connectFuture.get();
    if (!webSocketTargetSocket.awaitClose(conf.maxRequestCompletionSecs, TimeUnit.SECONDS)) {
      throw new RuntimeException("Failed to send all records in maximum wait time.");
    }
  } catch (Exception ex) {
    LOG.error(Errors.HTTP_50.getMessage(), ex.toString(), ex);
    errorRecordHandler.onError(Lists.newArrayList(batch.getRecords()), throwStageException(ex));
  } finally {
    if (wsSession != null) {
      wsSession.close();
    }
    try {
      webSocketClient.stop();
    } catch (Exception e) {
      LOG.error(Errors.HTTP_50.getMessage(), e.toString(), e);
    }
  }
}
 
Example #15
Source File: ProxyPublishConsumeTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test(timeOut = 10000)
public void consumeMessagesInPartitionedTopicTest() throws Exception {
    final String namespace = "my-property/my-ns";
    final String topic = namespace + "/" + "my-topic7";
    admin.topics().createPartitionedTopic("persistent://" + topic, 3);

    final String subscription = "my-sub";
    final String consumerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get() + "/ws/v2/consumer/persistent/" + topic + "/" + subscription;
    final String producerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get() + "/ws/v2/producer/persistent/" + topic;

    URI consumeUri = URI.create(consumerUri);
    URI produceUri = URI.create(producerUri);

    WebSocketClient consumeClient = new WebSocketClient();
    WebSocketClient produceClient = new WebSocketClient();

    SimpleConsumerSocket consumeSocket = new SimpleConsumerSocket();
    SimpleProducerSocket produceSocket = new SimpleProducerSocket();

    try {
        produceClient.start();
        ClientUpgradeRequest produceRequest = new ClientUpgradeRequest();
        Future<Session> producerFuture = produceClient.connect(produceSocket, produceUri, produceRequest);
        producerFuture.get();
        produceSocket.sendMessage(100);
    } finally {
        stopWebSocketClient(produceClient);
    }

    Thread.sleep(500);

    try {
        consumeClient.start();
        ClientUpgradeRequest consumeRequest = new ClientUpgradeRequest();
        Future<Session> consumerFuture = consumeClient.connect(consumeSocket, consumeUri, consumeRequest);
        consumerFuture.get();
    } finally {
        stopWebSocketClient(consumeClient);
    }
}
 
Example #16
Source File: ProxyPublishConsumeTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test(timeOut = 10000)
public void conflictingProducerTest() throws Exception {
    final String producerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get()
            + "/ws/v2/producer/persistent/my-property/my-ns/my-topic4?producerName=my-producer";
    URI produceUri = URI.create(producerUri);

    WebSocketClient produceClient1 = new WebSocketClient();
    WebSocketClient produceClient2 = new WebSocketClient();
    SimpleProducerSocket produceSocket1 = new SimpleProducerSocket();
    SimpleProducerSocket produceSocket2 = new SimpleProducerSocket();

    try {
        produceClient1.start();
        ClientUpgradeRequest produceRequest1 = new ClientUpgradeRequest();
        Future<Session> producerFuture1 = produceClient1.connect(produceSocket1, produceUri, produceRequest1);
        producerFuture1.get();

        try {
            produceClient2.start();
            ClientUpgradeRequest produceRequest2 = new ClientUpgradeRequest();
            Future<Session> producerFuture2 = produceClient2.connect(produceSocket2, produceUri, produceRequest2);
            producerFuture2.get();
            fail("should fail: conflicting producer name");
        } catch (Exception e) {
            // Expected
            assertTrue(e.getCause() instanceof UpgradeException);
            assertEquals(((UpgradeException) e.getCause()).getResponseStatusCode(),
                    HttpServletResponse.SC_CONFLICT);
        } finally {
            stopWebSocketClient(produceClient2);
        }
    } finally {
        stopWebSocketClient(produceClient1);
    }
}
 
Example #17
Source File: JettyWebSocketClient.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private Mono<Void> executeInternal(URI url, HttpHeaders headers, WebSocketHandler handler) {
	MonoProcessor<Void> completionMono = MonoProcessor.create();
	return Mono.fromCallable(
			() -> {
				if (logger.isDebugEnabled()) {
					logger.debug("Connecting to " + url);
				}
				Object jettyHandler = createHandler(url, handler, completionMono);
				ClientUpgradeRequest request = new ClientUpgradeRequest();
				request.setSubProtocols(handler.getSubProtocols());
				UpgradeListener upgradeListener = new DefaultUpgradeListener(headers);
				return this.jettyClient.connect(jettyHandler, url, request, upgradeListener);
			})
			.then(completionMono);
}
 
Example #18
Source File: ProxyPublishConsumeTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test(timeOut = 10000)
public void conflictingConsumerTest() throws Exception {
    final String consumerUri = "ws://localhost:" + proxyServer.getListenPortHTTP().get()
            + "/ws/v2/consumer/persistent/my-property/my-ns/my-topic3/sub1?subscriptionType=Exclusive";
    URI consumeUri = URI.create(consumerUri);

    WebSocketClient consumeClient1 = new WebSocketClient();
    WebSocketClient consumeClient2 = new WebSocketClient();
    SimpleConsumerSocket consumeSocket1 = new SimpleConsumerSocket();
    SimpleConsumerSocket consumeSocket2 = new SimpleConsumerSocket();

    try {
        consumeClient1.start();
        ClientUpgradeRequest consumeRequest1 = new ClientUpgradeRequest();
        Future<Session> consumerFuture1 = consumeClient1.connect(consumeSocket1, consumeUri, consumeRequest1);
        consumerFuture1.get();

        try {
            consumeClient2.start();
            ClientUpgradeRequest consumeRequest2 = new ClientUpgradeRequest();
            Future<Session> consumerFuture2 = consumeClient2.connect(consumeSocket2, consumeUri, consumeRequest2);
            consumerFuture2.get();
            fail("should fail: conflicting subscription name");
        } catch (Exception e) {
            // Expected
            assertTrue(e.getCause() instanceof UpgradeException);
            assertEquals(((UpgradeException) e.getCause()).getResponseStatusCode(),
                    HttpServletResponse.SC_CONFLICT);
        } finally {
            stopWebSocketClient(consumeClient2);
        }
    } finally {
        stopWebSocketClient(consumeClient1);
    }
}
 
Example #19
Source File: RosBridge.java    From java_rosbridge with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Connects to the Rosbridge host at the provided URI.
 * @param rosBridgeURI the URI to the ROS Bridge websocket server. Note that ROS Bridge by default uses port 9090. An example URI is: ws://localhost:9090
 */
public void connect(String rosBridgeURI){
	WebSocketClient client = new WebSocketClient();
	try {
		client.start();
		URI echoUri = new URI(rosBridgeURI);
		ClientUpgradeRequest request = new ClientUpgradeRequest();
		client.connect(this, echoUri, request);
		System.out.printf("Connecting to : %s%n", echoUri);

	} catch (Throwable t) {
		t.printStackTrace();
	}
}
 
Example #20
Source File: WebsocketAppenderTest.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
    // install decanter
    System.out.println(executeCommand("feature:repo-add decanter " + System.getProperty("decanter.version")));
    System.out.println(executeCommand("feature:install decanter-appender-websocket-servlet", new RolePrincipal("admin")));

    String httpList = executeCommand("http:list");
    while (!httpList.contains("Deployed")) {
        Thread.sleep(500);
        httpList = executeCommand("http:list");
    }
    System.out.println(httpList);

    // websocket
    WebSocketClient client = new WebSocketClient();
    DecanterSocket decanterSocket = new DecanterSocket();
    client.start();
    URI uri = new URI("ws://localhost:" + getHttpPort() + "/decanter-websocket");
    ClientUpgradeRequest request = new ClientUpgradeRequest();
    client.connect(decanterSocket, uri, request).get();

    // sending event
    EventAdmin eventAdmin = getOsgiService(EventAdmin.class);
    HashMap<String, String> data = new HashMap<>();
    data.put("foo", "bar");
    Event event = new Event("decanter/collect/test", data);
    eventAdmin.sendEvent(event);

    decanterSocket.awaitClose(20, TimeUnit.SECONDS);

    Assert.assertEquals(1, decanterSocket.messages.size());

    Assert.assertTrue(decanterSocket.messages.get(0).contains("\"foo\":\"bar\""));
    Assert.assertTrue(decanterSocket.messages.get(0).contains("\"event_topics\":\"decanter/collect/test\""));

    client.stop();
}
 
Example #21
Source File: MaxWsConnectionsTest.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {

  List<Session> clients = new ArrayList<>();

  while (true) {

    URI wsUri = new URI("ws", null, "localhost", Integer.parseInt(getPort()), "/jsonrpc", null,
        null);

    WebSocketClient jettyClient = new WebSocketClient(new SslContextFactory(true));
    jettyClient.start();
    Session session = jettyClient
        .connect(new WebSocketClientSocket(), wsUri, new ClientUpgradeRequest()).get();

    clients.add(session);

    log.debug("WebSocket client {} connected", clients.size());

    Thread.sleep(100);

    if (!session.isOpen()) {
      if (clients.size() < MAX_WS_CONNECTIONS) {
        fail("WebSocket num " + clients.size() + " disconnected. MAX_WS_CONNECTION="
            + MAX_WS_CONNECTIONS);
      } else {
        log.debug("WebSocket client {} disconnected from server", clients.size());
        break;
      }
    } else {

      if (clients.size() > MAX_WS_CONNECTIONS) {
        fail("Server should close automatically WebSocket connection above " + MAX_WS_CONNECTIONS
            + " but it has " + clients.size() + " open connections");
      }
    }
  }

}
 
Example #22
Source File: Demo_JettyWebSocketClient.java    From haxademic with MIT License 5 votes vote down vote up
protected void firstFrame() {
        try {
        	// web socket
        	HttpClient http = new HttpClient();
        	http.start();
            WebSocketClient websocket = new WebSocketClient(http);
            websocket.start();
        	try {

        		URI uri = new URI("ws://localhost:8787/websocket");
        		P.out("Connecting to: {}...", uri);
        		Session session = websocket.connect(new ToUpper356ClientSocket(), uri, new ClientUpgradeRequest()).get();
        		P.out("Connected to: {}", uri);
        		remote = session.getRemote();
        		remote.sendString("Hello World");
        	} catch (Exception e) {
        		throw new RuntimeIOException(e);
        	}
        	
//        	ClientUpgradeRequest request = new ClientUpgradeRequest();
//        	
//        	HttpClient http = new HttpClient();
//        	http.start();
//            WebSocketClient websocket = new WebSocketClient(http);
//            websocket.start();
//            try
//            {
//                String dest = "ws://localhost:8787/";
//                websocket.connect(new ToUpper356ClientSocket(), new URI(dest), request);
//            }
//            finally
//            {
//                websocket.stop();
//            } 
        } catch (Throwable t) {
            t.printStackTrace();
        }

	}
 
Example #23
Source File: RaftJettyServerTest.java    From barge with Apache License 2.0 5 votes vote down vote up
@Test
public void receives_START_event_through_web_socket_when_connecting_to_events_endpoint() throws Exception {
  URI wsEvents = new URI("ws://" + uri.getHost() + ":" + uri.getPort() + "/events");

  final Queue<String> messages = new LinkedBlockingQueue<>();
  final EventClientSocket socket = new EventClientSocket(messages);

  ClientUpgradeRequest request = new ClientUpgradeRequest();
  wsClient.connect(socket, wsEvents, request);

  client.target(uri).path("/raft/init").request().post(Entity.json(""));

  new Prober(() -> socket.messages.stream().anyMatch(Predicates.contains(Pattern.compile(".*FOLLOWER.*"))::apply)).probe(10000);
}
 
Example #24
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 #25
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 #26
Source File: JettyWebSocketClient.java    From java-technology-stack with MIT License 5 votes vote down vote up
private Mono<Void> executeInternal(URI url, HttpHeaders headers, WebSocketHandler handler) {
	MonoProcessor<Void> completionMono = MonoProcessor.create();
	return Mono.fromCallable(
			() -> {
				if (logger.isDebugEnabled()) {
					logger.debug("Connecting to " + url);
				}
				Object jettyHandler = createHandler(url, handler, completionMono);
				ClientUpgradeRequest request = new ClientUpgradeRequest();
				request.setSubProtocols(handler.getSubProtocols());
				UpgradeListener upgradeListener = new DefaultUpgradeListener(headers);
				return this.jettyClient.connect(jettyHandler, url, request, upgradeListener);
			})
			.then(completionMono);
}
 
Example #27
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 #28
Source File: WsClient.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
public void start() throws Exception {
    client = new WebSocketClient();
    client.start();
    URI echoUri = new URI(destUri);
    ClientUpgradeRequest request = new ClientUpgradeRequest();
    socket = new SimpleWebSocket(sessionListener);
    client.connect(socket, echoUri, request);
    socket.awaitOpen(10, TimeUnit.SECONDS);
}
 
Example #29
Source File: BitmexWebsocketClient.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
@Override
public boolean connect(String apiKey, String apiSecret) {
    try {
        this.apiKey = apiKey;
        this.apiSecret = apiSecret;
        logger.info("Starting connection");
        client.start();
        URI echoUri = new URI(websocketUrl);
        ClientUpgradeRequest request = new ClientUpgradeRequest();
        client.connect(socket, echoUri, request);
        

        logger.info("Connecting to : " + echoUri);
        latch.await(15, TimeUnit.SECONDS);
        isStarted = socket.isConnected();
        connected = socket.isConnected();
        logger.info("Connected: " + connected);
        if (!Strings.isNullOrEmpty(apiKey)) {
            long nonce = System.currentTimeMillis();
            String signature = getApiSignature(apiSecret, nonce);
            authenticate(apiKey, nonce, signature);
        }
        //socket.startPing();
    } catch (Exception ex) {
        throw new SumZeroException(ex);
    } finally {
        return connected;
    }
}
 
Example #30
Source File: BitmexWebsocketClient.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
@Override
public boolean connect(String apiKey, String apiSecret) {
    try {
        this.apiKey = apiKey;
        this.apiSecret = apiSecret;
        logger.info("Starting connection");
        client.start();
        URI echoUri = new URI(websocketUrl);
        ClientUpgradeRequest request = new ClientUpgradeRequest();
        client.connect(socket, echoUri, request);
        

        logger.info("Connecting to : " + echoUri);
        latch.await(15, TimeUnit.SECONDS);
        isStarted = socket.isConnected();
        connected = socket.isConnected();
        logger.info("Connected: " + connected);
        if (!Strings.isNullOrEmpty(apiKey)) {
            long nonce = System.currentTimeMillis();
            String signature = getApiSignature(apiSecret, nonce);
            authenticate(apiKey, nonce, signature);
        }
        //socket.startPing();
    } catch (Exception ex) {
        throw new SumZeroException(ex);
    } finally {
        return connected;
    }
}