Java 类javax.websocket.WebSocketContainer 实例源码

项目:launcher-backend    文件:MissionControlStatusEndpointIT.java   
/**
 * Ensures that CDI event is relayed over the webSocket status endpoint.
 *
 * @throws Exception when the test has failed
 */
@Test
public void webSocketsStatusTest() throws Exception {
    //given
    UUID uuid = UUID.randomUUID();
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    URI uri = UriBuilder.fromUri(deploymentUrl).scheme("ws").path("status").path(uuid.toString()).build();
    container.connectToServer(endpoint, uri);

    //when
    Thread.sleep(200);
    testEvent.fire(new StatusMessageEvent(uuid, StatusEventType.GITHUB_CREATE,
                                          singletonMap(EXTRA_DATA_KEY, "http://github.com/dummy-project-location")));
    endpoint.getLatch().await(1, TimeUnit.SECONDS);

    //then
    assertNotNull("a status message should have been send", endpoint.getMessage());
    assertTrue(endpoint.getMessage().contains(EXTRA_DATA_KEY));
}
项目:tomcat7    文件:TestWsRemoteEndpointImplServer.java   
@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();
}
项目: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();
}
项目:testee.fi    文件:WebsocketTest.java   
@Test
public void roundtrip_works() throws Exception {
    when(managedBean.getValue()).thenReturn("mocked");

    final URI uri = URI.create("ws://localhost:" + restServer.getPort() + "/websockets/echo");
    final CountDownLatch latch = new CountDownLatch(1);
    final WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    final Client client = new Client(() -> latch.countDown());
    try (final Session session = container.connectToServer(client, uri)) {
        session.getBasicRemote().sendText("Hello");
        assertTrue(latch.await(5, SECONDS));
    } finally {
        ((LifeCycle) container).stop();
    }
    assertEquals("mocked:Hello", client.message);
}
项目:Mastering-Java-EE-Development-with-WildFly    文件:IntroTestCase.java   
@Test
public void testServerFirstCall() throws Exception {
    logger.info("start websocket server first call test");
    reset();

    final WebSocketContainer serverContainer = getWebSocketContainer();
    serverContainer.connectToServer(WebSocketClient.class, url.toURI().resolve("chat"));

    assertEquals("the message is sent at the start of client", "Server received [Hello]", getMessage());
    sleep(30000);
    assertEquals("It comes from the server. First", "Message from server", getMessage());
    assertEquals("It comes from the server. Second", "Message from server", getMessage());
    assertEquals("It comes from the server. Third", "Message from server", getMessage());
    assertNull("no other messages", getMessage());

    assertTrue("PostConstruct method on client endpoint instance not called.", postConstructCalled);
}
项目: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();
}
项目: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));
}
项目:tomcat7    文件:TesterWsClientAutobahn.java   
public static void main(String[] args) throws Exception {

        WebSocketContainer wsc = ContainerProvider.getWebSocketContainer();

        int testCaseCount = getTestCaseCount(wsc);
        System.out.println("There are " + testCaseCount + " test cases");
        for (int testCase = 1; testCase <= testCaseCount; testCase++) {
            if (testCase % 50 == 0) {
                System.out.println(testCase);
            } else {
                System.out.print('.');
            }
            try {
                executeTestCase(wsc, testCase);
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
                t.printStackTrace();
            }

        }
        System.out.println("Testing complete");
        updateReports(wsc);
    }
项目: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();
}
项目:apache-tomcat-7.0.73-with-comment    文件:TestWsRemoteEndpointImplServer.java   
@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();
}
项目: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));
}
项目:apache-tomcat-7.0.73-with-comment    文件:TesterWsClientAutobahn.java   
public static void main(String[] args) throws Exception {

        WebSocketContainer wsc = ContainerProvider.getWebSocketContainer();

        int testCaseCount = getTestCaseCount(wsc);
        System.out.println("There are " + testCaseCount + " test cases");
        for (int testCase = 1; testCase <= testCaseCount; testCase++) {
            if (testCase % 50 == 0) {
                System.out.println(testCase);
            } else {
                System.out.print('.');
            }
            try {
                executeTestCase(wsc, testCase);
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
                t.printStackTrace();
            }

        }
        System.out.println("Testing complete");
        updateReports(wsc);
    }
项目:onerepmax    文件:WebSocketClient.java   
public static void main(final String[] args) {
  URI uri = URI.create("ws://localhost:8080/ws/");

  try {
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();

    try {
      Session session = container.connectToServer(EventSocket.class, uri);
      session.getBasicRemote().sendText("Hello");
      session.close();
    } finally {
      if (container instanceof LifeCycle) {
        ((LifeCycle) container).stop();
      }
    }
  } catch (Throwable t) {
    t.printStackTrace(System.err);
  }
}
项目:snoopee    文件:SnoopEERegistrationClient.java   
/**
 * 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();

        session.close();

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

    return returnValue;
}
项目:spring4-understanding    文件:AbstractTyrusRequestUpgradeStrategy.java   
@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);
    }
}
项目:atmosphere-agent    文件:AgentDispatcher.java   
/**
 * Connects the current agent to a server.
 *
 * @param serverAddress
 *        - address of the agent we want to connect to.
 * @param webSocketPort
 *        - the port number, on which the Server is listening
 * @param agentId
 *        - An identifier of the current agent
 * @throws URISyntaxException
 *         - thrown to indicate that a string could not be parsed as a URI reference
 * @throws IOException
 *         - thrown when I/O exception of some sort has occurred
 * @throws DeploymentException
 *         - failure to publish an endpoint on its server, or a failure to connect a client to its server
 */
public void connectToServer(String serverAddress, int webSocketPort, String agentId)
    throws DeploymentException,
        IOException,
        URISyntaxException {
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    container.setDefaultMaxTextMessageBufferSize(Integer.MAX_VALUE);
    String uriAddress = String.format(SERVER_URI, serverAddress, webSocketPort);
    this.session = container.connectToServer(AgentEndpoint.class, new URI(uriAddress));

    List<DeviceInformation> connectedDevicesInformation = deviceManager.getDevicesInformation();
    DeviceInformation[] devicesInformationArray = connectedDevicesInformation.toArray(new DeviceInformation[0]);

    RequestMessage registerAgentRequest = new RequestMessage(MessageAction.REGISTER_AGENT,
                                                             agentId,
                                                             devicesInformationArray);

    String registerAgentJsonRequest = jsonUtil.serialize(registerAgentRequest);
    sendText(registerAgentJsonRequest, session);

    LOGGER.debug("Connected to server address: " + uriAddress);

    agentManager.registerServer();
    LOGGER.info("The Server(" + serverAddress + ":" + webSocketPort
            + ") is registered for the device changed event notifications.");
}
项目:OpenChatAlytics    文件:SlackMessageSpout.java   
@VisibleForTesting
protected void open(SlackConfig slackConfig, IChatApiDAO slackDao,
                    WebSocketContainer webSocketContainer, TopologyContext context,
                    SpoutOutputCollector collector) {
    this.slackDao = slackDao;
    this.collector = collector;

    String startDateNullable = slackConfig.startDate;
    // get end date, if there is one
    if (startDateNullable != null) {
        this.startDate = Optional.of(DateTime.parse(startDateNullable));
    } else {
        this.startDate = Optional.absent();
    }

    openRealtimeConnection(slackConfig, webSocketContainer);
}
项目:launchpad-missioncontrol    文件:MissionControlStatusEndpointIT.java   
/**
 * Ensures that CDI event is relayed over the webSocket status endpoint.
 *
 * @throws Exception when the test has failed
 */
@Test
public void webSocketsStatusTest() throws Exception {
    //given
    UUID uuid = UUID.randomUUID();
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    URI uri = UriBuilder.fromUri(deploymentUrl).scheme("ws").path("status").path(uuid.toString()).build();
    container.connectToServer(endpoint, uri);

    //when
    Thread.sleep(200);
    testEvent.fire(new StatusMessageEvent(uuid, StatusMessage.GITHUB_CREATE,
                                          singletonMap(EXTRA_DATA_KEY, "http://github.com/dummy-project-location")));
    endpoint.getLatch().await(1, TimeUnit.SECONDS);

    //then
    assertNotNull("a status message should have been send", endpoint.getMessage());
    assertTrue(endpoint.getMessage().contains(EXTRA_DATA_KEY));
}
项目:ZStreamingQuote    文件:WebsocketClientEndpoint.java   
/**
 * 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();
    }
}
项目:sample.async.websockets    文件:AnnotatedClientEndpoint.java   
public static void connect(String clientString) throws IOException {
    if (clientString.startsWith(NEW_CLIENT) ) {
        clientString = clientString.substring(NEW_CLIENT.length());

        WebSocketContainer c = ContainerProvider.getWebSocketContainer();
        Hello.log(AnnotatedClientEndpoint.class, "Starting the client for " + clientString);

        URI uriServerEP = URI.create(clientString);
        try {
            Session s = c.connectToServer(AnnotatedClientEndpoint.class, uriServerEP);

            // we're just going to maintain one client at a time, so reading the output
            // can be somewhat sane.. Set the new session, and close the old one.
            s = clientConnection.getAndSet(s);
            if ( s != null )
                s.close();
        } catch (DeploymentException e) {
            e.printStackTrace();
        }
    }
}
项目:snoop    文件:SnoopRegistrationClient.java   
/**
 * 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;
}
项目: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);
}
项目:ocelot    文件:AbstractOcelotTest.java   
/**
 * Create session
 *
 * @param jsessionid
 * @param userpwd
 * @return
 */
protected Session createAndGetSession(String jsessionid, String userpwd) {
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    try {
        StringBuilder sb = new StringBuilder("ws://localhost:");
        sb.append(PORT).append(Constants.SLASH).append(CTXPATH).append(Constants.SLASH).append("ocelot-endpoint");
        URI uri = new URI(sb.toString());
        return container.connectToServer(new Endpoint() {
            @Override
            public void onOpen(Session session, EndpointConfig config) {
            }
        }, createClientEndpointConfigWithJsession(jsessionid, userpwd), uri);
    } catch (URISyntaxException | DeploymentException | IOException ex) {
        ex.getCause().printStackTrace();
        fail("CONNEXION FAILED " + ex.getMessage());
    }
    return null;
}
项目:johnzon    文件:MapperCodecTest.java   
@Test
public void codec() throws Exception {
    ClientEndpointImpl.MESSAGES.clear();
    ClientEndpointImpl.SEMAPHORE.acquire(ClientEndpointImpl.SEMAPHORE.availablePermits());

    final WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    final Session session = container.connectToServer(
            ClientEndpointImpl.class,
            new URI("ws://localhost:" + url.getPort() + url.getPath() + "server"));

    session.getBasicRemote().sendObject(new Message("client"));

    ClientEndpointImpl.SEMAPHORE.acquire();

    // it does wait for the server, using same jaxrs provider to match format, it uses jettison which is weird but we don't care for that part of test
    final Message serverMessage = new MapperBuilder().build().readObject(IO.slurp(new URL(url.toExternalForm() + "report/annotation")), Message.class);

    session.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, "bye"));

    assertNotNull(serverMessage);
    assertEquals("client", serverMessage.getValue());
    assertEquals(1, ClientEndpointImpl.MESSAGES.size());
    assertEquals("server", ClientEndpointImpl.MESSAGES.iterator().next().getValue());
}
项目: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));
}
项目:class-guard    文件:TesterWsClientAutobahn.java   
public static void main(String[] args) throws Exception {

        WebSocketContainer wsc = ContainerProvider.getWebSocketContainer();

        int testCaseCount = getTestCaseCount(wsc);
        System.out.println("There are " + testCaseCount + " test cases");
        for (int testCase = 1; testCase <= testCaseCount; testCase++) {
            if (testCase % 50 == 0) {
                System.out.println(testCase);
            } else {
                System.out.print('.');
            }
            try {
                executeTestCase(wsc, testCase);
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
                t.printStackTrace();
            }

        }
        System.out.println("Testing complete");
        updateReports(wsc);
    }
项目: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, URI.create(uri));
        out.println("<br><br>Look in server.log for log messages from message exchange between client/server.");

        out.println("</body>");
        out.println("</html>");
    } catch (DeploymentException ex) {
        Logger.getLogger(TestClient.class.getName()).log(Level.SEVERE, null, ex);
    }
}
项目: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);
    }
}
项目:JavaIncrementalParser    文件:TestRemoteClient.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("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet TestRemoteClient</title>");            
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet TestRemoteClient at " + request.getContextPath() + "</h1>");

        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        String uri = "ws://echo.websocket.org:80/";
        out.println("Connecting to " + uri);
        container.connectToServer(MyClient.class, URI.create(uri));
        out.println("<br><br>Look in server.log for log messages from message exchange between client/server.");

        out.println("</body>");
        out.println("</html>");
    } catch (DeploymentException ex) {
        Logger.getLogger(TestRemoteClient.class.getName()).log(Level.SEVERE, null, ex);
    }
}
项目:JavaIncrementalParser    文件:TestLocalClient.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, URI.create(uri));
        out.println("<br><br>Look in server.log for log messages from message exchange between client/server.");

        out.println("</body>");
        out.println("</html>");
    } catch (DeploymentException ex) {
        Logger.getLogger(TestLocalClient.class.getName()).log(Level.SEVERE, null, ex);
    }
}
项目: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, 
                null,
                URI.create(uri));
        out.println("<br><br>Look in server.log for message exchange between client/server.");

        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    文件:TesterWsClientAutobahn.java   
public static void main(String[] args) throws Exception {

        WebSocketContainer wsc = ContainerProvider.getWebSocketContainer();

        int testCaseCount = getTestCaseCount(wsc);
        System.out.println("There are " + testCaseCount + " test cases");
        for (int testCase = 1; testCase <= testCaseCount; testCase++) {
            if (testCase % 50 == 0) {
                System.out.println(testCase);
            } else {
                System.out.print('.');
            }
            try {
                executeTestCase(wsc, testCase);
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
                t.printStackTrace();
            }

        }
        System.out.println("Testing complete");
        updateReports(wsc);
    }
项目: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));
}