Search in sources :

Example 81 with WebSocketContainer

use of javax.websocket.WebSocketContainer in project bitfinex-v2-wss-api-java by jnidzwetzki.

the class WebsocketClientEndpoint method connect.

/**
 * Open a new connection and wait until connection is ready
 *
 * @throws DeploymentException
 * @throws IOException
 * @throws InterruptedException
 */
public void connect() throws DeploymentException, IOException, InterruptedException {
    final WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    this.userSession = container.connectToServer(this, endpointURI);
    connectLatch.await();
}
Also used : WebSocketContainer(javax.websocket.WebSocketContainer)

Example 82 with WebSocketContainer

use of javax.websocket.WebSocketContainer in project javaee7-samples by javaee-samples.

the class TestRemoteClient method processRequest.

/**
 * 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);
    }
}
Also used : WebSocketContainer(javax.websocket.WebSocketContainer) DeploymentException(javax.websocket.DeploymentException) PrintWriter(java.io.PrintWriter)

Example 83 with WebSocketContainer

use of javax.websocket.WebSocketContainer in project javaee7-samples by javaee-samples.

the class TestClient method processRequest.

/**
 * 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:" + request.getLocalPort() + 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);
    }
}
Also used : WebSocketContainer(javax.websocket.WebSocketContainer) DeploymentException(javax.websocket.DeploymentException) PrintWriter(java.io.PrintWriter)

Example 84 with WebSocketContainer

use of javax.websocket.WebSocketContainer in project javaee7-samples by javaee-samples.

the class TestLocalClient method processRequest.

/**
 * 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:" + request.getLocalPort() + 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);
    }
}
Also used : WebSocketContainer(javax.websocket.WebSocketContainer) DeploymentException(javax.websocket.DeploymentException) PrintWriter(java.io.PrintWriter)

Example 85 with WebSocketContainer

use of javax.websocket.WebSocketContainer in project component-runtime by Talend.

the class WebsocketClient method read.

public <T> T read(final Class<T> response, final String method, final String uri, final String body, final String type) {
    final WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<String> indexHolder = new AtomicReference<>();
    final ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build();
    clientEndpointConfig.getUserProperties().put("org.apache.tomcat.websocket.IO_TIMEOUT_MS", "60000");
    final Session session;
    try {
        session = container.connectToServer(new Endpoint() {

            @Override
            public void onOpen(final Session session, final EndpointConfig endpointConfig) {
                final StringBuilder builder = new StringBuilder();
                session.addMessageHandler(ByteBuffer.class, new MessageHandler.Partial<ByteBuffer>() {

                    @Override
                    public synchronized void onMessage(final ByteBuffer part, final boolean last) {
                        try {
                            builder.append(new String(part.array()));
                        } finally {
                            if (builder.toString().endsWith("^@")) {
                                indexHolder.set(builder.toString());
                                doClose(session);
                            }
                        }
                    }
                });
            }

            @Override
            public void onClose(final Session session, final CloseReason closeReason) {
                latch.countDown();
            }

            @Override
            public void onError(final Session session, final Throwable throwable) {
                latch.countDown();
                if (session.isOpen()) {
                    doClose(session);
                }
                fail(throwable.getMessage());
            }

            private void doClose(final Session session) {
                try {
                    session.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, "bye bye"));
                } catch (final IOException e) {
                    fail(e.getMessage());
                }
            }
        }, clientEndpointConfig, URI.create("ws://localhost:" + config.getHttpPort() + "/websocket/v1/bus"));
    } catch (final DeploymentException | IOException e) {
        fail(e.getMessage());
        throw new IllegalStateException(e);
    }
    try {
        final RemoteEndpoint.Async asyncRemote = session.getAsyncRemote();
        final String payload = "SEND\r\ndestination:" + uri + "\r\ndestinationMethod:" + method + "\r\nAccept: " + type + "\r\nContent-Type: " + "application/json\r\n\r\n" + body + "^@";
        asyncRemote.sendBinary(ByteBuffer.wrap(payload.getBytes(StandardCharsets.UTF_8)));
        latch.await(1, MINUTES);
    } catch (final InterruptedException e) {
        Thread.interrupted();
        fail(e.getMessage());
    }
    try {
        final String index = indexHolder.get();
        assertTrue(index.startsWith("MESSAGE\r\n"), index);
        assertTrue(index.contains("Content-Type: " + type + "\r\n"), index);
        final int startJson = index.indexOf('{');
        final int endJson = index.indexOf("^@");
        assertTrue(startJson > 0, index);
        assertTrue(endJson > startJson, index);
        if (String.class == response) {
            return response.cast(index.substring(startJson, endJson));
        }
        try (final Jsonb jsonb = JsonbProvider.provider().create().build()) {
            final T ci = jsonb.fromJson(index.substring(startJson, endJson), response);
            assertNotNull(ci);
            return ci;
        } catch (final Exception e) {
            fail(e.getMessage());
            throw new IllegalStateException(e);
        }
    } finally {
        if (session.isOpen()) {
            try {
                session.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, "bye bye"));
            } catch (IOException e) {
                fail(e.getMessage());
            }
        }
    }
}
Also used : MessageHandler(javax.websocket.MessageHandler) Jsonb(javax.json.bind.Jsonb) Endpoint(javax.websocket.Endpoint) RemoteEndpoint(javax.websocket.RemoteEndpoint) CloseReason(javax.websocket.CloseReason) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) WebSocketContainer(javax.websocket.WebSocketContainer) AtomicReference(java.util.concurrent.atomic.AtomicReference) RemoteEndpoint(javax.websocket.RemoteEndpoint) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) Endpoint(javax.websocket.Endpoint) RemoteEndpoint(javax.websocket.RemoteEndpoint) DeploymentException(javax.websocket.DeploymentException) IOException(java.io.IOException) DeploymentException(javax.websocket.DeploymentException) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) EndpointConfig(javax.websocket.EndpointConfig) Session(javax.websocket.Session)

Aggregations

WebSocketContainer (javax.websocket.WebSocketContainer)85 URI (java.net.URI)52 Session (javax.websocket.Session)52 Test (org.junit.Test)51 Context (org.apache.catalina.Context)29 Tomcat (org.apache.catalina.startup.Tomcat)29 DefaultServlet (org.apache.catalina.servlets.DefaultServlet)27 ClientEndpointConfig (javax.websocket.ClientEndpointConfig)20 CountDownLatch (java.util.concurrent.CountDownLatch)16 DeploymentException (javax.websocket.DeploymentException)13 Endpoint (javax.websocket.Endpoint)13 EndpointConfig (javax.websocket.EndpointConfig)13 ServerEndpoint (javax.websocket.server.ServerEndpoint)10 ServerEndpointConfig (javax.websocket.server.ServerEndpointConfig)10 BasicText (org.apache.tomcat.websocket.TesterMessageCountClient.BasicText)10 IOException (java.io.IOException)8 TesterProgrammaticEndpoint (org.apache.tomcat.websocket.TesterMessageCountClient.TesterProgrammaticEndpoint)8 TomcatBaseTest (org.apache.catalina.startup.TomcatBaseTest)7 TesterEndpoint (org.apache.tomcat.websocket.TesterMessageCountClient.TesterEndpoint)7 PrintWriter (java.io.PrintWriter)6