javax.websocket.WebSocketContainer Java Examples

The following examples show how to use javax.websocket.WebSocketContainer. 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: AnnotatedServerTest.java    From wildfly-samples with MIT License 6 votes vote down vote up
@Test
    public void testEndpoint() throws IOException, ServletException, DeploymentException, InterruptedException {
        AnnotatedWebSocketServer server = new AnnotatedWebSocketServer();
        server.start();

        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        String uri = "ws://localhost:8080/server";
        System.out.println("Connecting to " + uri);
        container.connectToServer(MyClient.class, URI.create(uri));

//        WebClient webClient = new WebClient();
//        TextPage page = webClient.getPage("http://localhost:8080/myapp/server");
//        assertEquals("Hello World", page.getContent());
        assertTrue(AnnotatedWebSocketServer.LATCH.await(3, TimeUnit.SECONDS));
        server.stop();
    }
 
Example #2
Source File: MessageFailureTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 8000)
public void testMessageTooBig() throws Exception {
  final String bigMessage = RandomStringUtils.randomAscii(66001);

  WebSocketContainer container = ContainerProvider.getWebSocketContainer();

  WebsocketClient client = new WebsocketClient();
  javax.websocket.Session session = container.connectToServer(client,
      proxyUri);
  session.getBasicRemote().sendText(bigMessage);

  client.awaitClose(CloseReason.CloseCodes.TOO_BIG.getCode(), 1000,
      TimeUnit.MILLISECONDS);

  Assert.assertThat(client.close.getCloseCode().getCode(), CoreMatchers.is(CloseReason.CloseCodes.TOO_BIG.getCode()));
}
 
Example #3
Source File: BadBackendTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 8000)
public void testBadBackEnd() throws IOException, Exception {
  final String message = "Echo";

  WebSocketContainer container = ContainerProvider.getWebSocketContainer();

  WebsocketClient client = new WebsocketClient();
  javax.websocket.Session session = container.connectToServer(client,
      proxyUri);
  session.getBasicRemote().sendText(message);

  client.awaitClose(CloseReason.CloseCodes.UNEXPECTED_CONDITION.getCode(), 1000,
      TimeUnit.MILLISECONDS);

  Assert.assertThat(client.close.getCloseCode().getCode(), CoreMatchers.is(CloseReason.CloseCodes.UNEXPECTED_CONDITION.getCode()));
}
 
Example #4
Source File: DaemonMessagesClientEndpoint.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
public DaemonMessagesClientEndpoint( String host, int port, boolean ssl,
                                     MessageEventService messageEventService ) throws KettleException {
  try {
    setAuthProperties();

    String url = String.format( URL_TEMPLATE, ( ssl ? PRFX_WS_SSL : PRFX_WS ), host, port );
    URI uri = new URI( url );
    this.messageEventService = messageEventService;

    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    container.connectToServer( this, ClientEndpointConfig.Builder.create()
      .encoders( Collections.singletonList( MessageEncoder.class ) )
      .decoders( Collections.singletonList( MessageDecoder.class ) )
      .configurator( new SessionConfigurator( uri, keytab, principal ) )
      .build(), uri );

  } catch ( Exception e ) {
    throw new KettleException( e );
  }
}
 
Example #5
Source File: AbstractTyrusRequestUpgradeStrategy.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public Object createdEndpoint(ServerEndpointRegistration registration, ComponentProviderService provider,
		WebSocketContainer container, TyrusWebSocketEngine engine) throws DeploymentException {

	DirectFieldAccessor accessor = new DirectFieldAccessor(engine);
	Object sessionListener = accessor.getPropertyValue("sessionListener");
	Object clusterContext = accessor.getPropertyValue("clusterContext");
	try {
		if (constructorWithBooleanArgument) {
			// Tyrus 1.11+
			return constructor.newInstance(registration.getEndpoint(), registration, provider, container,
					"/", registration.getConfigurator(), sessionListener, clusterContext, null, Boolean.TRUE);
		}
		else {
			return constructor.newInstance(registration.getEndpoint(), registration, provider, container,
					"/", registration.getConfigurator(), sessionListener, clusterContext, null);
		}
	}
	catch (Exception ex) {
		throw new HandshakeFailureException("Failed to register " + registration, ex);
	}
}
 
Example #6
Source File: TestConnectionLimit.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void run() {
    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();

    int count = 0;

    try {
        while (true) {
            wsContainer.connectToServer(TesterProgrammaticEndpoint.class,
                    Builder.create().build(), uri);
            count = counter.incrementAndGet();
            if (count % 100 == 0) {
                System.out.println(count + " and counting...");
            }
        }
    } catch (IOException | DeploymentException ioe) {
        // Let thread die
    }
}
 
Example #7
Source File: ClientStarter.java    From jetty-web-sockets-jsr356 with Apache License 2.0 6 votes vote down vote up
public static void main( final String[] args ) throws Exception {
	final String client = UUID.randomUUID().toString().substring( 0, 8 );
	
	final WebSocketContainer container = ContainerProvider.getWebSocketContainer();				
	final String uri = "ws://localhost:8080/broadcast";		
	
	try( Session session = container.connectToServer( BroadcastClientEndpoint.class, URI.create( uri ) ) ) {
		for( int i = 1; i <= 10; ++i ) {
			session.getBasicRemote().sendObject( new Message( client, "Message #" + i ) );
			Thread.sleep( 1000 );
		}
	}
	
	// JSR-356 has no concept of Container lifecycle.
	// (This is an oversight on the spec's part)
	// This stops the lifecycle of the Client WebSocketContainer
	if( container instanceof LifeCycle ) {
	    ( ( LifeCycle )container ).stop();
	}
}
 
Example #8
Source File: TestWebSocketFrameClient.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
public void echoTester(String path) throws Exception {
    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    ClientEndpointConfig clientEndpointConfig =
            ClientEndpointConfig.Builder.create().build();
    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            clientEndpointConfig,
            new URI("ws://localhost:" + getPort() + path));
    CountDownLatch latch =
            new CountDownLatch(1);
    BasicText handler = new BasicText(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendText("Hello");

    handler.getLatch().await(100, TimeUnit.MILLISECONDS);

    Queue<String> messages = handler.getMessages();
    Assert.assertEquals(1, messages.size());
    for (String message : messages) {
        Assert.assertEquals("Hello", message);
    }
    wsSession.close();
}
 
Example #9
Source File: TestWsRemoteEndpointImplServer.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Test
public void testClientDropsConnection() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(Bug58624Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();

    tomcat.start();

    SimpleClient client = new SimpleClient();
    URI uri = new URI("ws://localhost:" + getPort() + Bug58624Config.PATH);

    Session session = wsContainer.connectToServer(client, uri);
    // Break point A required on following line
    session.close();
}
 
Example #10
Source File: WebsocketClientEndpoint.java    From ZStreamingQuote with MIT License 6 votes vote down vote up
/**
 * constructor
 * 
 * @param endpointURI
 */
public WebsocketClientEndpoint(URI endpointURI, IwsSessionNotifier sessionNotifier) {
	try {
		this.sessionNotifier = sessionNotifier;
		System.out.println("WebsocketClientEndpoint.WebsocketClientEndpoint(): creating WebSocketContainer...");
		WebSocketContainer container = ContainerProvider.getWebSocketContainer();
		container.connectToServer(this, endpointURI);
	} catch (Exception e) {
		System.out.println(
				"WebsocketClientEndpoint.WebsocketClientEndpoint(): ERROR: Exception on container connectToServer, reason: "
						+ e.getMessage());
		//throw new RuntimeException(e);
       	//notify initiate failed
       	this.sessionNotifier.notifyWsInitiateFailed();
	}
}
 
Example #11
Source File: AbstractTyrusRequestUpgradeStrategy.java    From java-technology-stack with MIT License 6 votes vote down vote up
private Object createEndpoint(ServerEndpointRegistration registration, ComponentProviderService provider,
		WebSocketContainer container, TyrusWebSocketEngine engine) throws DeploymentException {

	DirectFieldAccessor accessor = new DirectFieldAccessor(engine);
	Object sessionListener = accessor.getPropertyValue("sessionListener");
	Object clusterContext = accessor.getPropertyValue("clusterContext");
	try {
		if (constructorWithBooleanArgument) {
			// Tyrus 1.11+
			return constructor.newInstance(registration.getEndpoint(), registration, provider, container,
					"/", registration.getConfigurator(), sessionListener, clusterContext, null, Boolean.TRUE);
		}
		else {
			return constructor.newInstance(registration.getEndpoint(), registration, provider, container,
					"/", registration.getConfigurator(), sessionListener, clusterContext, null);
		}
	}
	catch (Exception ex) {
		throw new HandshakeFailureException("Failed to register " + registration, ex);
	}
}
 
Example #12
Source File: SnoopRegistrationClient.java    From snoop with MIT License 6 votes vote down vote up
/**
 * Sends message to the WebSocket server.
 *
 * @param endpoint The server endpoint
 * @param msg The message
 * @return a return message
 */
private String sendMessage(String endpoint, String msg) {

    LOGGER.config(() -> "Sending message: " + msg);

    String returnValue = "-1";
    try {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        String uri = serviceUrl + endpoint;
        Session session = container.connectToServer(this, URI.create(uri));
        session.getBasicRemote().sendText(msg != null ? msg : "");
        returnValue = session.getId();

    } catch (DeploymentException | IOException ex) {
        LOGGER.warning(ex.getMessage());
    }

    return returnValue;
}
 
Example #13
Source File: TestWsWebSocketContainer.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test(expected=javax.websocket.DeploymentException.class)
public void testConnectToServerEndpointInvalidScheme() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    wsContainer.connectToServer(TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ftp://" + getHostName() + ":" + getPort() +
                    TesterEchoServer.Config.PATH_ASYNC));
}
 
Example #14
Source File: TestWsRemoteEndpointImplServer.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Test
public void testClientDropsConnection() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(Bug58624Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();

    tomcat.start();

    SimpleClient client = new SimpleClient();
    URI uri = new URI("ws://localhost:" + getPort() + Bug58624Config.PATH);

    Session session = wsContainer.connectToServer(client, uri);
    // Break point A required on following line
    session.close();
}
 
Example #15
Source File: LibertySessionWrapper.java    From rogue-cloud with Apache License 2.0 6 votes vote down vote up
private void connect(String url) {
	// Don't try to connect if we have already disposed of the session, or the client instance
	if (disposed || LibertyClientInstance.getInstance().isDisposed()) {
		log.interesting("Ignoring connect as instance of wrapper is disposed ["+disposed+","+LibertyClientInstance.getInstance().isDisposed()+"]", parent.getLogContext());
		return;
	}

	log.interesting("Attempting to connect", parent.getLogContext());
	final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build();
	//
	// ClientManager client = ClientManager.createClient();

	WebSocketContainer c = ContainerProvider.getWebSocketContainer();
	c.setDefaultMaxTextMessageBufferSize(1024 * 1024);
	c.setDefaultMaxSessionIdleTimeout(2 * TimeUnit.MILLISECONDS.convert(RCSharedConstants.MAX_ROUND_LENGTH_IN_NANOS, TimeUnit.NANOSECONDS));
	try {
		c.connectToServer(this.hce, cec, new URI(url));
		// Wait for the endpoint to call us on success or failure.
	} catch (DeploymentException | IOException | URISyntaxException e) {
		errorOccurred(null);
	}

}
 
Example #16
Source File: AbstractTyrusRequestUpgradeStrategy.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private Object createEndpoint(ServerEndpointRegistration registration, ComponentProviderService provider,
		WebSocketContainer container, TyrusWebSocketEngine engine) throws DeploymentException {

	DirectFieldAccessor accessor = new DirectFieldAccessor(engine);
	Object sessionListener = accessor.getPropertyValue("sessionListener");
	Object clusterContext = accessor.getPropertyValue("clusterContext");
	try {
		if (constructorWithBooleanArgument) {
			// Tyrus 1.11+
			return constructor.newInstance(registration.getEndpoint(), registration, provider, container,
					"/", registration.getConfigurator(), sessionListener, clusterContext, null, Boolean.TRUE);
		}
		else {
			return constructor.newInstance(registration.getEndpoint(), registration, provider, container,
					"/", registration.getConfigurator(), sessionListener, clusterContext, null);
		}
	}
	catch (Exception ex) {
		throw new HandshakeFailureException("Failed to register " + registration, ex);
	}
}
 
Example #17
Source File: AbstractWebsocketClientEndpoint.java    From alpaca-java with MIT License 5 votes vote down vote up
/**
 * Connect.
 *
 * @throws DeploymentException the deployment exception
 * @throws IOException         Signals that an I/O exception has occurred.
 */
public void connect() throws DeploymentException, IOException {
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();

    LOGGER.info("Connecting to " + endpointURI);

    container.connectToServer(this, endpointURI);
}
 
Example #18
Source File: SecurityActions.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
static void addContainer(final ClassLoader classLoader, final WebSocketContainer webSocketContainer) {
    if (System.getSecurityManager() == null) {
        UndertowContainerProvider.addContainer(classLoader, webSocketContainer);
    } else {
        AccessController.doPrivileged(new PrivilegedAction<Object>() {
            @Override
            public Object run() {
                UndertowContainerProvider.addContainer(classLoader, webSocketContainer);
                return null;
            }
        });
    }
}
 
Example #19
Source File: TestPojoEndpointBase.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testBug54716() throws Exception {
    TestUtil.generateMask();
    // Set up utility classes
    Bug54716 server = new Bug54716();
    SingletonConfigurator.setInstance(server);
    ServerConfigListener.setPojoClazz(Bug54716.class);

    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(ServerConfigListener.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();


    tomcat.start();

    Client client = new Client();
    URI uri = new URI("ws://localhost:" + getPort() + "/");

    wsContainer.connectToServer(client, uri);

    // Server should close the connection after the exception on open.
    boolean closed = client.waitForClose(5);
    Assert.assertTrue("Server failed to close connection", closed);
}
 
Example #20
Source File: AbstractTyrusRequestUpgradeStrategy.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected List<WebSocketExtension> getInstalledExtensions(WebSocketContainer container) {
	try {
		return super.getInstalledExtensions(container);
	}
	catch (UnsupportedOperationException ex) {
		return new ArrayList<>(0);
	}
}
 
Example #21
Source File: AbstractTyrusRequestUpgradeStrategy.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected List<WebSocketExtension> getInstalledExtensions(WebSocketContainer container) {
	try {
		return super.getInstalledExtensions(container);
	}
	catch (UnsupportedOperationException ex) {
		return new ArrayList<>(0);
	}
}
 
Example #22
Source File: MessageFailureTest.java    From knox with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 8000)
public void testMessageOk() throws Exception {
  final String message = "Echo";

  WebSocketContainer container = ContainerProvider.getWebSocketContainer();

  WebsocketClient client = new WebsocketClient();
  javax.websocket.Session session = container.connectToServer(client,
      proxyUri);
  session.getBasicRemote().sendText(message);

  client.messageQueue.awaitMessages(1, 1000, TimeUnit.MILLISECONDS);

  Assert.assertThat(client.messageQueue.get(0), CoreMatchers.is("Echo"));
}
 
Example #23
Source File: WsUpdatesClient.java    From pnc with Apache License 2.0 5 votes vote down vote up
public void subscribeBlocking(String topic, String filter, Consumer<String> onMessage)
        throws IOException, DeploymentException {

    ProgressUpdatesRequest progressUpdatesRequest = ProgressUpdatesRequest.subscribe(topic, filter);

    UpdatesMessageHandler updatesMessageHandler = new UpdatesMessageHandler(onMessage);

    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    String uri = "ws://localhost:8080/pnc-rest-new/" + NotificationsEndpoint.ENDPOINT_PATH;
    Session session = container.connectToServer(updatesMessageHandler, URI.create(uri));

    RemoteEndpoint.Basic asyncRemote = session.getBasicRemote();
    asyncRemote.sendText(toJson(progressUpdatesRequest));
}
 
Example #24
Source File: WSTest.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
@Test
public void run() throws InterruptedException, DeploymentException, IOException, URISyntaxException {
	CountDownLatch cdl = new CountDownLatch(5);
	WebSocketContainer container = ContainerProvider.getWebSocketContainer();
	String wsEndpoint = String.format("ws://localhost:%d/ws-chat", CONTAINER.getConfiguration().getHttpPort());
	Session session = container.connectToServer(new ChatClient(cdl), new URI(wsEndpoint));
	assertTrue(cdl.await(20, TimeUnit.SECONDS));
	session.close();

}
 
Example #25
Source File: TesterWsClientAutobahn.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private static int getTestCaseCount(WebSocketContainer wsc)
        throws Exception {

    URI uri = new URI("ws://" + HOST + ":" + PORT + "/getCaseCount");
    CaseCountClient caseCountClient = new CaseCountClient();
    wsc.connectToServer(caseCountClient, uri);
    return caseCountClient.getCaseCount();
}
 
Example #26
Source File: AbstractTyrusRequestUpgradeStrategy.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private Object createTyrusEndpoint(Endpoint endpoint, String endpointPath, String protocol,
		List<Extension> extensions, WebSocketContainer container, TyrusWebSocketEngine engine)
		throws DeploymentException {

	ServerEndpointRegistration endpointConfig = new ServerEndpointRegistration(endpointPath, endpoint);
	endpointConfig.setSubprotocols(Collections.singletonList(protocol));
	endpointConfig.setExtensions(extensions);
	return getEndpointHelper().createdEndpoint(endpointConfig, this.componentProvider, container, engine);
}
 
Example #27
Source File: StandardWebSocketClientTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
	this.headers = new WebSocketHttpHeaders();
	this.wsHandler = new AbstractWebSocketHandler() {
	};
	this.wsContainer = mock(WebSocketContainer.class);
	this.wsClient = new StandardWebSocketClient(this.wsContainer);
}
 
Example #28
Source File: AbstractStandardUpgradeStrategy.java    From spring-analysis-note with MIT License 5 votes vote down vote up
protected List<WebSocketExtension> getInstalledExtensions(WebSocketContainer container) {
	List<WebSocketExtension> result = new ArrayList<>();
	for (Extension extension : container.getInstalledExtensions()) {
		result.add(new StandardToWebSocketExtensionAdapter(extension));
	}
	return result;
}
 
Example #29
Source File: WebsocketServerInitiatedMessageTest.java    From knox with Apache License 2.0 5 votes vote down vote up
@Test
public void testGatewayServerInitiatedEcho() throws Exception {
  WebSocketContainer container = ContainerProvider.getWebSocketContainer();

  WebsocketClient client = new WebsocketClient();
  container.connectToServer(client,
          new URI(serverUri.toString() + "gateway/websocket/123foo456bar/channels"));

  //session.getBasicRemote().sendText("Echo");
  client.messageQueue.awaitMessages(1, 5000, TimeUnit.MILLISECONDS);

  assertThat(client.messageQueue.get(0), is("echo"));
}
 
Example #30
Source File: AbstractTyrusRequestUpgradeStrategy.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private Object createTyrusEndpoint(Endpoint endpoint, String endpointPath, @Nullable String protocol,
		List<Extension> extensions, WebSocketContainer container, TyrusWebSocketEngine engine)
		throws DeploymentException {

	ServerEndpointRegistration endpointConfig = new ServerEndpointRegistration(endpointPath, endpoint);
	endpointConfig.setSubprotocols(Collections.singletonList(protocol));
	endpointConfig.setExtensions(extensions);
	return createEndpoint(endpointConfig, this.componentProvider, container, engine);
}