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

The following examples show how to use org.eclipse.jetty.websocket.client.ClientUpgradeRequest#setHeader() . 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: 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 2
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 3
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 4
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 5
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 6
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 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: 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 9
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);
	}
}
 
Example 10
Source File: TestWebSocketServerPushSource.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Test
public void testSource() throws Exception {
  WebSocketConfigs webSocketConfigs = new WebSocketConfigs();
  webSocketConfigs.appId = () -> "appId";
  webSocketConfigs.port = NetworkUtils.getRandomPort();
  webSocketConfigs.maxConcurrentRequests = 1;
  webSocketConfigs.tlsConfigBean.tlsEnabled = false;
  WebSocketServerPushSource source = new WebSocketServerPushSource(
      webSocketConfigs,
      DataFormat.JSON,
      new DataParserFormatConfig(),
      new ResponseConfigBean()
  );
  final PushSourceRunner runner =
      new PushSourceRunner.Builder(WebSocketServerDPushSource.class, source).addOutputLane("a").build();
  runner.runInit();
  try {
    final List<Record> records = new ArrayList<>();
    runner.runProduce(Collections.<String, String>emptyMap(), 1, new PushSourceRunner.Callback() {
      @Override
      public void processBatch(StageRunner.Output output) {
        records.clear();
        runner.getSourceResponseSink().getResponseRecords().clear();
        records.addAll(output.getRecords().get("a"));
        records.forEach(record -> {
          runner.getSourceResponseSink().addResponse(record);
        });
        runner.setStop();
      }
    });

    // wait for the HTTP server up and running
    WebSocketReceiverServer httpServer = (WebSocketReceiverServer) Whitebox.getInternalState(source, "server");
    await().atMost(Duration.TEN_SECONDS).until(isServerRunning(httpServer));

    WebSocketClient client = new WebSocketClient();
    SimpleEchoSocket socket = new SimpleEchoSocket();
    try {
      client.start();
      URI echoUri = new URI("ws://localhost:" + webSocketConfigs.getPort());
      ClientUpgradeRequest request = new ClientUpgradeRequest();
      request.setHeader(HttpConstants.X_SDC_APPLICATION_ID_HEADER, "appId");
      Future<Session> future = client.connect(socket, echoUri, request);
      future.get();
      // wait for closed socket connection.
      socket.awaitClose(5, TimeUnit.SECONDS);
    } catch (Throwable t) {
      t.printStackTrace();
    } finally {
      try {
        client.stop();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    runner.waitOnProduce();

    Assert.assertEquals(1, records.size());
    Assert.assertEquals("value", records.get(0).get("/field1").getValue());

    // check response from WebSocket Server
    Assert.assertNotNull(socket.receivedMessage);
    Assert.assertEquals(
        "{\"httpStatusCode\":200,\"data\":[{\"field1\":\"value\"}],\"error\":[]}",
        socket.receivedMessage
    );
  } finally {
    runner.runDestroy();
  }
}