Java 类javax.websocket.ClientEndpointConfig 实例源码

项目:tomcat7    文件:TestWebSocketFrameClient.java   
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");

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
    Assert.assertTrue(latchResult);

    Queue<String> messages = handler.getMessages();
    Assert.assertEquals(1, messages.size());
    for (String message : messages) {
        Assert.assertEquals("Hello", message);
    }
    wsSession.close();
}
项目:Mastering-Java-EE-Development-with-WildFly    文件:SessionSecureTestCase.java   
private void connect() throws Exception {
    while (sessionServer != null && !sessionServer.isOpen()) {
        break;
    }
    SSLContext context = createSSLContext();
    SecureSocketClient endpoint = new SecureSocketClient();

    Configurator configurator = new Configurator() {

        @Override
        public void beforeRequest(Map<String, List<String>> headers) {
            headers.put(SEC_WEB_SOCKET_PROTOCOL_STRING, singletonList("configured-proto"));
        }

    };
    ClientEndpointConfig clientEndpointConfig = create().configurator(configurator)
            .preferredSubprotocols(asList(new String[] { "foo", "bar", "configured-proto" })).build();
    clientEndpointConfig.getUserProperties().put(SSL_CONTEXT, context);

    final WebSocketContainer serverContainer = getWebSocketContainer();
    URI uri = new URI("wss://127.0.0.1:8443/secure-test/session");
    serverContainer.connectToServer(endpoint, clientEndpointConfig, uri);
    awake();
}
项目:cf-java-client-sap    文件:CloudControllerClientImpl.java   
private StreamingLogToken streamLoggregatorLogs(String appName, ApplicationLogListener listener, boolean recent) {
    ClientEndpointConfig.Configurator configurator = new ClientEndpointConfig.Configurator() {
        @Override
        public void beforeRequest(Map<String, List<String>> headers) {
            String authorizationHeader = oauthClient.getAuthorizationHeader();
            if (authorizationHeader != null) {
                headers.put(AUTHORIZATION_HEADER_KEY, Arrays.asList(authorizationHeader));
            }
        }
    };

    String endpoint = getInfo().getLoggregatorEndpoint();
    String mode = recent ? "dump" : "tail";
    UUID appId = getAppId(appName);
    return loggregatorClient.connectToLoggregator(endpoint, mode, appId, listener, configurator);
}
项目:tomcat7    文件:TestWsWebSocketContainer.java   
@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));
}
项目:lams    文件:WebsocketClient.java   
public WebsocketClient(String uri, final String sessionID, MessageHandler.Whole<String> messageHandler)
    throws IOException {

// add session ID so the request gets through LAMS security
Builder configBuilder = ClientEndpointConfig.Builder.create();
configBuilder.configurator(new Configurator() {
    @Override
    public void beforeRequest(Map<String, List<String>> headers) {
    headers.put("Cookie", Arrays.asList("JSESSIONID=" + sessionID));
    }
});
ClientEndpointConfig clientConfig = configBuilder.build();
this.websocketEndpoint = new WebsocketEndpoint(messageHandler);
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
try {
    container.connectToServer(websocketEndpoint, clientConfig, new URI(uri));
} catch (DeploymentException | URISyntaxException e) {
    throw new IOException("Error while connecting to websocket server", e);
}
   }
项目:websocket-chat    文件:ChatServerTest.java   
@Test
public void newJoineeGetsWelcomeMsg() throws DeploymentException, IOException, InterruptedException {
    controlLatch = new CountDownLatch(2);

    ChatClient newJoinee = new ChatClient();
    String newJoineeName = "abhishek";
    String endpointURL = BASE_SERVER_URL + newJoineeName + "/";
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    container.connectToServer(newJoinee,
            ClientEndpointConfig.Builder.create().build(),
            URI.create(endpointURL));

    assertTrue(controlLatch.await(5, TimeUnit.SECONDS));
    String expectedWelcomeMessage = "Welcome " + newJoineeName;
    assertTrue(newJoinee.getResponse().contains(expectedWelcomeMessage));
    newJoinee.closeConnection();
}
项目:flow-platform    文件:LogEventHandler.java   
private void initWebSocketSession(String url, int wsConnectionTimeout) throws Exception {
    CountDownLatch wsLatch = new CountDownLatch(1);
    ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build();
    ClientManager client = ClientManager.createClient();

    client.connectToServer(new Endpoint() {
        @Override
        public void onOpen(Session session, EndpointConfig endpointConfig) {
            wsSession = session;
            wsLatch.countDown();
        }
    }, cec, new URI(url));

    if (!wsLatch.await(wsConnectionTimeout, TimeUnit.SECONDS)) {
        throw new TimeoutException("Web socket connection timeout");
    }
}
项目:apache-tomcat-7.0.73-with-comment    文件:TestWebSocketFrameClient.java   
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");

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
    Assert.assertTrue(latchResult);

    Queue<String> messages = handler.getMessages();
    Assert.assertEquals(1, messages.size());
    for (String message : messages) {
        Assert.assertEquals("Hello", message);
    }
    wsSession.close();
}
项目:apache-tomcat-7.0.73-with-comment    文件:TestWsWebSocketContainer.java   
@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));
}
项目:spring4-understanding    文件:EndpointConnectionManager.java   
@Override
protected void openConnection() {
    this.taskExecutor.execute(new Runnable() {
        @Override
        public void run() {
            try {
                logger.info("Connecting to WebSocket at " + getUri());
                Endpoint endpointToUse = (endpoint != null) ? endpoint : endpointProvider.getHandler();
                ClientEndpointConfig endpointConfig = configBuilder.build();
                session = getWebSocketContainer().connectToServer(endpointToUse, endpointConfig, getUri());
                logger.info("Successfully connected");
            }
            catch (Throwable ex) {
                logger.error("Failed to connect", ex);
            }
        }
    });
}
项目:gameboot    文件:OtpWebSocketTest.java   
private void createClearChannel() throws Exception {
  ClientEndpointConfig config = ClientEndpointConfig.Builder.create().build();
  config.getUserProperties().put(WsWebSocketContainer.SSL_CONTEXT_PROPERTY, sslContext);
  clearChannel = ContainerProvider.getWebSocketContainer().connectToServer(endpoint,
      config,
      new URI(createClearUriString()));

  assertTrue(clearChannel.isOpen());

  CountDownLatch cdl = new CountDownLatch(1);
  endpoint.setResponseLatch(cdl);

  cdl.await(1, TimeUnit.SECONDS);

  assertNotNull(endpoint.getSystemId());
  assertEquals(clearChannel, endpoint.getSession());
}
项目:gameon-mediator    文件:WebSocketClientConnection.java   
@Override
public void connect() throws DeploymentException, IOException {
    ConnectionDetails details = info.getConnectionDetails();
    Log.log(Level.FINE, drain, "Creating websocket to {0}", details.getTarget());

    URI uriServerEP = URI.create(details.getTarget());

    authConfigurator = new GameOnHeaderAuthConfigurator(details.getToken(), uriServerEP.getRawPath());
    final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create()
            .decoders(Arrays.asList(RoutedMessageDecoder.class)).encoders(Arrays.asList(RoutedMessageEncoder.class))
            .configurator(authConfigurator)
            .build();

    WebSocketContainer c = ContainerProvider.getWebSocketContainer();
    this.session = c.connectToServer(this, cec, uriServerEP);
}
项目:simple-websocket-client    文件:SimpleWebSocketClient.java   
/**
 * Establishes the connection to the given WebSocket Server Address.
 */
public void connect() {

    readyState = ReadyState.CONNECTING;

    try {
        if (webSocketHandler == null) {
            webSocketHandler = new WebSocketHandlerAdapter();
        }

        container.connectToServer(new SimpleWebSocketClientEndpoint(), ClientEndpointConfig.Builder.create().build(), websocketURI);
    } catch (Exception e) {

        readyState = ReadyState.CLOSED;
        // throws DeploymentException, IOException
        throw new RuntimeException("could not establish connection");

    }
}
项目:class-guard    文件:TestWsWebSocketContainer.java   
@Test(expected=javax.websocket.DeploymentException.class)
public void testConnectToServerEndpointInvalidScheme() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase - just use temp
    Context ctx =
        tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(new ApplicationListener(
            TesterEchoServer.Config.class.getName(), false));

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    wsContainer.connectToServer(TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ftp://localhost:" + getPort() +
                    TesterEchoServer.Config.PATH_ASYNC));
}
项目:class-guard    文件:TestWsWebSocketContainer.java   
@Test(expected=javax.websocket.DeploymentException.class)
public void testConnectToServerEndpointNoHost() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase - just use temp
    Context ctx =
        tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(new ApplicationListener(
            TesterEchoServer.Config.class.getName(), false));

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    wsContainer.connectToServer(TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://" + TesterEchoServer.Config.PATH_ASYNC));
}
项目:JavaIncrementalParser    文件:TestClient.java   
/**
 * Processes requests for both HTTP
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet TestServlet</title>");            
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>");

        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        String uri = "ws://localhost:8080" + request.getContextPath() + "/websocket";
        out.println("Connecting to " + uri);
        container.connectToServer(MyClient.class, 
                ClientEndpointConfig.Builder.create().configurator(new MyConfigurator()).build(),
                URI.create(uri));
        out.println("<br><br>Look in server.log for message exchange between client/server and headers from configurator.");

        out.println("</body>");
        out.println("</html>");
    } catch (DeploymentException ex) {
        Logger.getLogger(TestClient.class.getName()).log(Level.SEVERE, null, ex);
    }
}
项目:apache-tomcat-7.0.57    文件:TestWsWebSocketContainer.java   
@Test(expected=javax.websocket.DeploymentException.class)
public void testConnectToServerEndpointInvalidScheme() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase - just use temp
    Context ctx =
        tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    wsContainer.connectToServer(TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ftp://localhost:" + getPort() +
                    TesterEchoServer.Config.PATH_ASYNC));
}
项目:apache-tomcat-7.0.57    文件:TestWsWebSocketContainer.java   
@Test(expected=javax.websocket.DeploymentException.class)
public void testConnectToServerEndpointNoHost() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase - just use temp
    Context ctx =
        tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    wsContainer.connectToServer(TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://" + TesterEchoServer.Config.PATH_ASYNC));
}
项目:apache-tomcat-7.0.57    文件:TestWsWebSocketContainer.java   
@Test(expected=javax.websocket.DeploymentException.class)
public void testConnectToServerEndpointInvalidScheme() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase - just use temp
    Context ctx =
        tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    wsContainer.connectToServer(TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ftp://localhost:" + getPort() +
                    TesterEchoServer.Config.PATH_ASYNC));
}
项目:apache-tomcat-7.0.57    文件:TestWsWebSocketContainer.java   
@Test(expected=javax.websocket.DeploymentException.class)
public void testConnectToServerEndpointNoHost() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase - just use temp
    Context ctx =
        tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    wsContainer.connectToServer(TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://" + TesterEchoServer.Config.PATH_ASYNC));
}
项目:pentaho-kettle    文件:DaemonMessagesClientEndpoint.java   
public DaemonMessagesClientEndpoint( String host, String 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 );
  }
}
项目:cf-java-client-sap    文件:LoggregatorClient.java   
private ClientEndpointConfig buildClientConfig(ClientEndpointConfig.Configurator configurator) {
    ClientEndpointConfig config = ClientEndpointConfig.Builder.create().configurator(configurator).build();

    if (trustSelfSignedCerts) {
        SSLContext sslContext = buildSslContext();
        Map<String, Object> userProperties = config.getUserProperties();
        userProperties.put(WsWebSocketContainer.SSL_CONTEXT_PROPERTY, sslContext);
    }

    return config;
}
项目:tomcat7    文件:TestWsPingPongMessages.java   
@Test
public void testPingPongMessages() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());

    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    WebSocketContainer wsContainer = ContainerProvider
            .getWebSocketContainer();

    tomcat.start();

    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder
                    .create().build(), new URI("ws://localhost:"
                    + getPort() + TesterEchoServer.Config.PATH_ASYNC));

    CountDownLatch latch = new CountDownLatch(1);
    TesterEndpoint tep = (TesterEndpoint) wsSession.getUserProperties()
            .get("endpoint");
    tep.setLatch(latch);

    PongMessageHandler handler = new PongMessageHandler(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendPing(applicationData);

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
    Assert.assertTrue(latchResult);
    Assert.assertArrayEquals(applicationData.array(),
            (handler.getMessages().peek()).getApplicationData().array());
}
项目:tomcat7    文件:TestWsWebSocketContainer.java   
@Test
public void testConnectToServerEndpoint() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    // Set this artificially small to trigger
    // https://bz.apache.org/bugzilla/show_bug.cgi?id=57054
    wsContainer.setDefaultMaxBinaryMessageBufferSize(64);
    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://" + getHostName() + ":" + getPort() +
                    TesterEchoServer.Config.PATH_ASYNC));
    CountDownLatch latch = new CountDownLatch(1);
    BasicText handler = new BasicText(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendText(MESSAGE_STRING_1);

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);

    Assert.assertTrue(latchResult);

    Queue<String> messages = handler.getMessages();
    Assert.assertEquals(1, messages.size());
    Assert.assertEquals(MESSAGE_STRING_1, messages.peek());

    ((WsWebSocketContainer) wsContainer).destroy();
}
项目:tomcat7    文件:TestWsWebSocketContainer.java   
@Test(expected=javax.websocket.DeploymentException.class)
public void testConnectToServerEndpointNoHost() 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("ws://" + TesterEchoServer.Config.PATH_ASYNC));
}
项目:tomcat7    文件:TestWsWebSocketContainer.java   
private void doTestPerMessageDefalteClient(String msg, int count) throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase - just use temp
    Context ctx =
        tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    Extension perMessageDeflate = new WsExtension(PerMessageDeflate.NAME);
    List<Extension> extensions = new ArrayList<Extension>(1);
    extensions.add(perMessageDeflate);

    ClientEndpointConfig clientConfig =
            ClientEndpointConfig.Builder.create().extensions(extensions).build();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            clientConfig,
            new URI("ws://" + getHostName() + ":" + getPort() +
                    TesterEchoServer.Config.PATH_ASYNC));
    CountDownLatch latch = new CountDownLatch(count);
    BasicText handler = new BasicText(latch, msg);
    wsSession.addMessageHandler(handler);
    for (int i = 0; i < count; i++) {
        wsSession.getBasicRemote().sendText(msg);
    }

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);

    Assert.assertTrue(latchResult);

    ((WsWebSocketContainer) wsContainer).destroy();
}
项目:osc-core    文件:WebSocketClient.java   
private ClientEndpointConfig getClientEndpointConfig() {
    // initializing custom client end point configurator
    this.configurator = new CustomClientEndPointConfigurator(WebSocketClient.this.mgrApi.getHandshakeParameters());
    final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().configurator(this.configurator).build();

    return cec;
}
项目:websocket-chat    文件:ChatServerTest.java   
@Test
public void sessionAutoClosedAfterMaxIdleTimeoutBreach() throws Exception {
    controlLatch = new CountDownLatch(2);
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();

    ChatClient abhi = new ChatClient();
    String chatter = "abhishek";

    String endpointURL = BASE_SERVER_URL + chatter + "/";
    Session session = container.connectToServer(abhi,
            ClientEndpointConfig.Builder.create().build(),
            URI.create(endpointURL));

    session.setMaxIdleTimeout(maxIdleTime); //set the timeout

    String expectedWelcomeMessageForChatter1 = "Welcome " + chatter;
    assertTrue(controlLatch.await(5, TimeUnit.SECONDS));
    assertTrue(abhi.getResponse().contains(expectedWelcomeMessageForChatter1));


    connClosedLatch = new CountDownLatch(1);
    assertTrue(connClosedLatch.await(maxIdleTime + 5000, TimeUnit.MILLISECONDS)); // wait 5 seconds more than the timeout

    String expectedSessionTimeoutCloseReasonPhrase = "\"Session closed by the container because of the idle timeout.\"";
    assertEquals(expectedSessionTimeoutCloseReasonPhrase, abhi.getCloseReason().getReasonPhrase()); //check the exact phrase

    //String expectedSessionTimeoutCloseReasonCode = "CLOSED_ABNORMALLY";
    //assertEquals(expectedSessionTimeoutCloseReasonCode, abhi.getCloseReason().getCloseCode().toString()); //check the exact code
}
项目:apache-tomcat-7.0.73-with-comment    文件:TestWsPingPongMessages.java   
@Test
public void testPingPongMessages() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());

    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    WebSocketContainer wsContainer = ContainerProvider
            .getWebSocketContainer();

    tomcat.start();

    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder
                    .create().build(), new URI("ws://localhost:"
                    + getPort() + TesterEchoServer.Config.PATH_ASYNC));

    CountDownLatch latch = new CountDownLatch(1);
    TesterEndpoint tep = (TesterEndpoint) wsSession.getUserProperties()
            .get("endpoint");
    tep.setLatch(latch);

    PongMessageHandler handler = new PongMessageHandler(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendPing(applicationData);

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
    Assert.assertTrue(latchResult);
    Assert.assertArrayEquals(applicationData.array(),
            (handler.getMessages().peek()).getApplicationData().array());
}
项目:apache-tomcat-7.0.73-with-comment    文件:TestWsWebSocketContainer.java   
@Test
public void testConnectToServerEndpoint() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    // Set this artificially small to trigger
    // https://bz.apache.org/bugzilla/show_bug.cgi?id=57054
    wsContainer.setDefaultMaxBinaryMessageBufferSize(64);
    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://" + getHostName() + ":" + getPort() +
                    TesterEchoServer.Config.PATH_ASYNC));
    CountDownLatch latch = new CountDownLatch(1);
    BasicText handler = new BasicText(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendText(MESSAGE_STRING_1);

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);

    Assert.assertTrue(latchResult);

    Queue<String> messages = handler.getMessages();
    Assert.assertEquals(1, messages.size());
    Assert.assertEquals(MESSAGE_STRING_1, messages.peek());

    ((WsWebSocketContainer) wsContainer).destroy();
}
项目:apache-tomcat-7.0.73-with-comment    文件:TestWsWebSocketContainer.java   
@Test(expected=javax.websocket.DeploymentException.class)
public void testConnectToServerEndpointNoHost() 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("ws://" + TesterEchoServer.Config.PATH_ASYNC));
}
项目:apache-tomcat-7.0.73-with-comment    文件:TestWsWebSocketContainer.java   
private void doTestPerMessageDefalteClient(String msg, int count) throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase - just use temp
    Context ctx =
        tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    Extension perMessageDeflate = new WsExtension(PerMessageDeflate.NAME);
    List<Extension> extensions = new ArrayList<Extension>(1);
    extensions.add(perMessageDeflate);

    ClientEndpointConfig clientConfig =
            ClientEndpointConfig.Builder.create().extensions(extensions).build();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            clientConfig,
            new URI("ws://" + getHostName() + ":" + getPort() +
                    TesterEchoServer.Config.PATH_ASYNC));
    CountDownLatch latch = new CountDownLatch(count);
    BasicText handler = new BasicText(latch, msg);
    wsSession.addMessageHandler(handler);
    for (int i = 0; i < count; i++) {
        wsSession.getBasicRemote().sendText(msg);
    }

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);

    Assert.assertTrue(latchResult);

    ((WsWebSocketContainer) wsContainer).destroy();
}
项目:redis-websocket-javaee    文件:MeetupRSVPsWebSocketClientSession.java   
@PostConstruct
public void init(){
    try {
        WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer();
        List<Class<? extends Decoder>> decoders = new ArrayList<>();
        decoders.add(MeetupRSVPJSONDecoder.class);
        session = webSocketContainer.connectToServer(new MeetupRSVPsWebSocketClient(),
                ClientEndpointConfig.Builder.create().decoders(decoders).build(),
                URI.create("ws://stream.meetup.com/2/rsvps"));
    } catch (DeploymentException | IOException ex) {
        Logger.getLogger(MeetupRSVPsWebSocketClientSession.class.getName()).log(Level.SEVERE, null, ex);
    }

}
项目:spring4-understanding    文件:StandardWebSocketClient.java   
@Override
protected ListenableFuture<WebSocketSession> doHandshakeInternal(WebSocketHandler webSocketHandler,
        HttpHeaders headers, final URI uri, List<String> protocols,
        List<WebSocketExtension> extensions, Map<String, Object> attributes) {

    int port = getPort(uri);
    InetSocketAddress localAddress = new InetSocketAddress(getLocalHost(), port);
    InetSocketAddress remoteAddress = new InetSocketAddress(uri.getHost(), port);

    final StandardWebSocketSession session = new StandardWebSocketSession(headers,
            attributes, localAddress, remoteAddress);

    final ClientEndpointConfig endpointConfig = ClientEndpointConfig.Builder.create()
            .configurator(new StandardWebSocketClientConfigurator(headers))
            .preferredSubprotocols(protocols)
            .extensions(adaptExtensions(extensions)).build();

    endpointConfig.getUserProperties().putAll(getUserProperties());

    final Endpoint endpoint = new StandardWebSocketHandlerAdapter(webSocketHandler, session);

    Callable<WebSocketSession> connectTask = new Callable<WebSocketSession>() {
        @Override
        public WebSocketSession call() throws Exception {
            webSocketContainer.connectToServer(endpoint, endpointConfig, uri);
            return session;
        }
    };

    if (this.taskExecutor != null) {
        return this.taskExecutor.submitListenable(connectTask);
    }
    else {
        ListenableFutureTask<WebSocketSession> task = new ListenableFutureTask<WebSocketSession>(connectTask);
        task.run();
        return task;
    }
}
项目:spring4-understanding    文件:StandardWebSocketClientTests.java   
@Test
public void clientEndpointConfig() throws Exception {

    URI uri = new URI("ws://localhost/abc");
    List<String> protocols = Collections.singletonList("abc");
    this.headers.setSecWebSocketProtocol(protocols);

    this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get();

    ArgumentCaptor<ClientEndpointConfig> captor = ArgumentCaptor.forClass(ClientEndpointConfig.class);
    verify(this.wsContainer).connectToServer(any(Endpoint.class), captor.capture(), any(URI.class));
    ClientEndpointConfig endpointConfig = captor.getValue();

    assertEquals(protocols, endpointConfig.getPreferredSubprotocols());
}
项目:spring4-understanding    文件:StandardWebSocketClientTests.java   
@Test
public void clientEndpointConfigWithUserProperties() throws Exception {

    Map<String,Object> userProperties = Collections.singletonMap("foo", "bar");

    URI uri = new URI("ws://localhost/abc");
    this.wsClient.setUserProperties(userProperties);
    this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get();

    ArgumentCaptor<ClientEndpointConfig> captor = ArgumentCaptor.forClass(ClientEndpointConfig.class);
    verify(this.wsContainer).connectToServer(any(Endpoint.class), captor.capture(), any(URI.class));
    ClientEndpointConfig endpointConfig = captor.getValue();

    assertEquals(userProperties, endpointConfig.getUserProperties());
}
项目:example-restful-project    文件:TeapotSimulator.java   
/**
 * Creates and starts teapot simulator.
 *
 * @param teapot    teapot domain object
 * @param port      port number of the server
 *
 * @throws URISyntaxException
 * @throws DeploymentException
 * @throws IOException
 */
public TeapotSimulator(Teapot teapot, int port)
        throws URISyntaxException, DeploymentException, IOException {

    /* Get websocket container */
    final WebSocketContainer container = ContainerProvider
            .getWebSocketContainer();

    /* Configuration of teapot client endpoint */
    final ClientEndpointConfig teapotConfig = ClientEndpointConfig.Builder
            .create()
            .build();

    /* Disable websocket timeout */
    container.setDefaultMaxSessionIdleTimeout(0);

    URI uri = new URI(String.format(REGISTER_URL, port, teapot.getId()));

    /* Create websocket client for the teapot */
    container.connectToServer(
            new TeapotSimulatorEndpoint(this), teapotConfig, uri);

    /* Create the file system */
    fs = new TeapotFs();

    /* Create help.txt file */
    fs.cat("help.txt", createHelpFileContent());

    /* Create license file */
    fs.cat("license", createLicenseFileContent());

    /* Create config.json file */
    fs.cat("config.json", createConfigFileContent(teapot));
}
项目:gameboot    文件:OtpWebSocketTest.java   
private void createEncryptedChannel() throws Exception {
  ClientEndpointConfig config = ClientEndpointConfig.Builder.create().build();
  config.getUserProperties().put(WsWebSocketContainer.SSL_CONTEXT_PROPERTY, sslContext);
  encChannel = ContainerProvider.getWebSocketContainer().connectToServer(endpoint,
      config,
      new URI(createEncUriString()));

  assertTrue(encChannel.isOpen());
}
项目:ocelot    文件:AbstractOcelotTest.java   
private ClientEndpointConfig createClientEndpointConfigWithJsession(final String jsession, final String userpwd) {
    ClientEndpointConfig.Configurator configurator = new ClientEndpointConfig.Configurator() {
        @Override
        public void beforeRequest(Map<String, List<String>> headers) {
            if (null != jsession) {
                headers.put("Cookie", Arrays.asList("JSESSIONID=" + jsession));
            } 
            headers.put("Authorization", Arrays.asList("Basic " + DatatypeConverter.printBase64Binary(userpwd.getBytes())));
        }
    };
    return ClientEndpointConfig.Builder.create().configurator(configurator).build();
}
项目:class-guard    文件:TestWsPingPongMessages.java   
@Test
public void testPingPongMessages() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase - just use temp
    Context ctx = tomcat.addContext("",
            System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(new ApplicationListener(
            TesterEchoServer.Config.class.getName(), false));

    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    WebSocketContainer wsContainer = ContainerProvider
            .getWebSocketContainer();

    tomcat.start();

    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder
                    .create().build(), new URI("ws://localhost:"
                    + getPort() + TesterEchoServer.Config.PATH_ASYNC));

    CountDownLatch latch = new CountDownLatch(1);
    TesterEndpoint tep = (TesterEndpoint) wsSession.getUserProperties()
            .get("endpoint");
    tep.setLatch(latch);

    PongMessageHandler handler = new PongMessageHandler(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendPing(applicationData);

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
    Assert.assertTrue(latchResult);
    Assert.assertArrayEquals(applicationData.array(),
            (handler.getMessages().peek()).getApplicationData().array());
}