Search in sources :

Example 26 with Endpoint

use of javax.websocket.Endpoint in project jetty.project by eclipse.

the class MessageReceivingTest method testWholeTextMessage.

/**
     * Method tests receiving of text messages at once.
     *
     * @throws Exception on exception occur
     */
@Test
@Ignore("flappy test")
public void testWholeTextMessage() throws Exception {
    final TestEndpoint echoer = new TestEndpoint(new WholeStringCaptureHandler());
    Assert.assertThat(echoer, instanceOf(javax.websocket.Endpoint.class));
    // Issue connect using instance of class that extends Endpoint
    final Session session = container.connectToServer(echoer, serverUri);
    if (LOG.isDebugEnabled())
        LOG.debug("Client Connected: {}", session);
    session.getBasicRemote().sendText("");
    session.getBasicRemote().sendText("Echo");
    session.getBasicRemote().sendText(VERY_LONG_STRING);
    session.getBasicRemote().sendText("Echo");
    if (LOG.isDebugEnabled())
        LOG.debug("Client Message Sent");
    echoer.handler.getMessageQueue().awaitMessages(2, 1000, TimeUnit.MILLISECONDS);
}
Also used : Endpoint(javax.websocket.Endpoint) Session(javax.websocket.Session) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 27 with Endpoint

use of javax.websocket.Endpoint in project jetty.project by eclipse.

the class MessageReceivingTest method testWholeBinaryMessage.

/**
     * Method tests receiving of binary messages at once.
     *
     * @throws Exception on exception occur
     */
@Test
public void testWholeBinaryMessage() throws Exception {
    final TestEndpoint echoer = new TestEndpoint(new WholeByteBufferCaptureHandler());
    Assert.assertThat(echoer, instanceOf(javax.websocket.Endpoint.class));
    // Issue connect using instance of class that extends Endpoint
    final Session session = container.connectToServer(echoer, serverUri);
    if (LOG.isDebugEnabled())
        LOG.debug("Client Connected: {}", session);
    sendBinary(session, "");
    sendBinary(session, "Echo");
    if (LOG.isDebugEnabled())
        LOG.debug("Client Message Sent");
    echoer.handler.getMessageQueue().awaitMessages(2, 1000, TimeUnit.MILLISECONDS);
}
Also used : Endpoint(javax.websocket.Endpoint) Session(javax.websocket.Session) Test(org.junit.Test)

Example 28 with Endpoint

use of javax.websocket.Endpoint in project jetty.project by eclipse.

the class MessageReceivingTest method testPartialBinaryMessage.

/**
     * Method tests receiving of binary messages by parts.
     *
     * @throws Exception on exception occur
     */
@Test
public void testPartialBinaryMessage() throws Exception {
    final TestEndpoint echoer = new TestEndpoint(new PartialByteBufferCaptureHandler());
    Assert.assertThat(echoer, instanceOf(javax.websocket.Endpoint.class));
    // Issue connect using instance of class that extends Endpoint
    final Session session = container.connectToServer(echoer, serverUri);
    if (LOG.isDebugEnabled())
        LOG.debug("Client Connected: {}", session);
    sendBinary(session, "");
    sendBinary(session, "Echo");
    if (LOG.isDebugEnabled())
        LOG.debug("Client Message Sent");
    echoer.handler.getMessageQueue().awaitMessages(2, 1000, TimeUnit.MILLISECONDS);
}
Also used : Endpoint(javax.websocket.Endpoint) Session(javax.websocket.Session) Test(org.junit.Test)

Example 29 with Endpoint

use of javax.websocket.Endpoint in project tomcat by apache.

the class WsWebSocketContainer method connectToServer.

// socketChannel is closed
@SuppressWarnings("resource")
@Override
public Session connectToServer(Endpoint endpoint, ClientEndpointConfig clientEndpointConfiguration, URI path) throws DeploymentException {
    boolean secure = false;
    ByteBuffer proxyConnect = null;
    URI proxyPath;
    // Validate scheme (and build proxyPath)
    String scheme = path.getScheme();
    if ("ws".equalsIgnoreCase(scheme)) {
        proxyPath = URI.create("http" + path.toString().substring(2));
    } else if ("wss".equalsIgnoreCase(scheme)) {
        proxyPath = URI.create("https" + path.toString().substring(3));
        secure = true;
    } else {
        throw new DeploymentException(sm.getString("wsWebSocketContainer.pathWrongScheme", scheme));
    }
    // Validate host
    String host = path.getHost();
    if (host == null) {
        throw new DeploymentException(sm.getString("wsWebSocketContainer.pathNoHost"));
    }
    int port = path.getPort();
    SocketAddress sa = null;
    // Check to see if a proxy is configured. Javadoc indicates return value
    // will never be null
    List<Proxy> proxies = ProxySelector.getDefault().select(proxyPath);
    Proxy selectedProxy = null;
    for (Proxy proxy : proxies) {
        if (proxy.type().equals(Proxy.Type.HTTP)) {
            sa = proxy.address();
            if (sa instanceof InetSocketAddress) {
                InetSocketAddress inet = (InetSocketAddress) sa;
                if (inet.isUnresolved()) {
                    sa = new InetSocketAddress(inet.getHostName(), inet.getPort());
                }
            }
            selectedProxy = proxy;
            break;
        }
    }
    // scheme
    if (port == -1) {
        if ("ws".equalsIgnoreCase(scheme)) {
            port = 80;
        } else {
            // Must be wss due to scheme validation above
            port = 443;
        }
    }
    // If sa is null, no proxy is configured so need to create sa
    if (sa == null) {
        sa = new InetSocketAddress(host, port);
    } else {
        proxyConnect = createProxyRequest(host, port);
    }
    // Create the initial HTTP request to open the WebSocket connection
    Map<String, List<String>> reqHeaders = createRequestHeaders(host, port, clientEndpointConfiguration.getPreferredSubprotocols(), clientEndpointConfiguration.getExtensions());
    clientEndpointConfiguration.getConfigurator().beforeRequest(reqHeaders);
    if (Constants.DEFAULT_ORIGIN_HEADER_VALUE != null && !reqHeaders.containsKey(Constants.ORIGIN_HEADER_NAME)) {
        List<String> originValues = new ArrayList<>(1);
        originValues.add(Constants.DEFAULT_ORIGIN_HEADER_VALUE);
        reqHeaders.put(Constants.ORIGIN_HEADER_NAME, originValues);
    }
    ByteBuffer request = createRequest(path, reqHeaders);
    AsynchronousSocketChannel socketChannel;
    try {
        socketChannel = AsynchronousSocketChannel.open(getAsynchronousChannelGroup());
    } catch (IOException ioe) {
        throw new DeploymentException(sm.getString("wsWebSocketContainer.asynchronousSocketChannelFail"), ioe);
    }
    // Get the connection timeout
    long timeout = Constants.IO_TIMEOUT_MS_DEFAULT;
    String timeoutValue = (String) clientEndpointConfiguration.getUserProperties().get(Constants.IO_TIMEOUT_MS_PROPERTY);
    if (timeoutValue != null) {
        timeout = Long.valueOf(timeoutValue).intValue();
    }
    // Set-up
    // Same size as the WsFrame input buffer
    ByteBuffer response = ByteBuffer.allocate(maxBinaryMessageBufferSize);
    String subProtocol;
    boolean success = false;
    List<Extension> extensionsAgreed = new ArrayList<>();
    Transformation transformation = null;
    // Open the connection
    Future<Void> fConnect = socketChannel.connect(sa);
    AsyncChannelWrapper channel = null;
    if (proxyConnect != null) {
        try {
            fConnect.get(timeout, TimeUnit.MILLISECONDS);
            // Proxy CONNECT is clear text
            channel = new AsyncChannelWrapperNonSecure(socketChannel);
            writeRequest(channel, proxyConnect, timeout);
            HttpResponse httpResponse = processResponse(response, channel, timeout);
            if (httpResponse.getStatus() != 200) {
                throw new DeploymentException(sm.getString("wsWebSocketContainer.proxyConnectFail", selectedProxy, Integer.toString(httpResponse.getStatus())));
            }
        } catch (TimeoutException | InterruptedException | ExecutionException | EOFException e) {
            if (channel != null) {
                channel.close();
            }
            throw new DeploymentException(sm.getString("wsWebSocketContainer.httpRequestFailed"), e);
        }
    }
    if (secure) {
        // Regardless of whether a non-secure wrapper was created for a
        // proxy CONNECT, need to use TLS from this point on so wrap the
        // original AsynchronousSocketChannel
        SSLEngine sslEngine = createSSLEngine(clientEndpointConfiguration.getUserProperties());
        channel = new AsyncChannelWrapperSecure(socketChannel, sslEngine);
    } else if (channel == null) {
        // Only need to wrap as this point if it wasn't wrapped to process a
        // proxy CONNECT
        channel = new AsyncChannelWrapperNonSecure(socketChannel);
    }
    try {
        fConnect.get(timeout, TimeUnit.MILLISECONDS);
        Future<Void> fHandshake = channel.handshake();
        fHandshake.get(timeout, TimeUnit.MILLISECONDS);
        writeRequest(channel, request, timeout);
        HttpResponse httpResponse = processResponse(response, channel, timeout);
        // TODO: Handle redirects
        if (httpResponse.status != 101) {
            throw new DeploymentException(sm.getString("wsWebSocketContainer.invalidStatus", Integer.toString(httpResponse.status)));
        }
        HandshakeResponse handshakeResponse = httpResponse.getHandshakeResponse();
        clientEndpointConfiguration.getConfigurator().afterResponse(handshakeResponse);
        // Sub-protocol
        List<String> protocolHeaders = handshakeResponse.getHeaders().get(Constants.WS_PROTOCOL_HEADER_NAME);
        if (protocolHeaders == null || protocolHeaders.size() == 0) {
            subProtocol = null;
        } else if (protocolHeaders.size() == 1) {
            subProtocol = protocolHeaders.get(0);
        } else {
            throw new DeploymentException(sm.getString("wsWebSocketContainer.invalidSubProtocol"));
        }
        // Extensions
        // Should normally only be one header but handle the case of
        // multiple headers
        List<String> extHeaders = handshakeResponse.getHeaders().get(Constants.WS_EXTENSIONS_HEADER_NAME);
        if (extHeaders != null) {
            for (String extHeader : extHeaders) {
                Util.parseExtensionHeader(extensionsAgreed, extHeader);
            }
        }
        // Build the transformations
        TransformationFactory factory = TransformationFactory.getInstance();
        for (Extension extension : extensionsAgreed) {
            List<List<Extension.Parameter>> wrapper = new ArrayList<>(1);
            wrapper.add(extension.getParameters());
            Transformation t = factory.create(extension.getName(), wrapper, false);
            if (t == null) {
                throw new DeploymentException(sm.getString("wsWebSocketContainer.invalidExtensionParameters"));
            }
            if (transformation == null) {
                transformation = t;
            } else {
                transformation.setNext(t);
            }
        }
        success = true;
    } catch (ExecutionException | InterruptedException | SSLException | EOFException | TimeoutException e) {
        throw new DeploymentException(sm.getString("wsWebSocketContainer.httpRequestFailed"), e);
    } finally {
        if (!success) {
            channel.close();
        }
    }
    // Switch to WebSocket
    WsRemoteEndpointImplClient wsRemoteEndpointClient = new WsRemoteEndpointImplClient(channel);
    WsSession wsSession = new WsSession(endpoint, wsRemoteEndpointClient, this, null, null, null, null, null, extensionsAgreed, subProtocol, Collections.<String, String>emptyMap(), secure, clientEndpointConfiguration);
    WsFrameClient wsFrameClient = new WsFrameClient(response, channel, wsSession, transformation);
    // WsFrame adds the necessary final transformations. Copy the
    // completed transformation chain to the remote end point.
    wsRemoteEndpointClient.setTransformation(wsFrameClient.getTransformation());
    endpoint.onOpen(wsSession, clientEndpointConfiguration);
    registerSession(endpoint, wsSession);
    /* It is possible that the server sent one or more messages as soon as
         * the WebSocket connection was established. Depending on the exact
         * timing of when those messages were sent they could be sat in the
         * input buffer waiting to be read and will not trigger a "data
         * available to read" event. Therefore, it is necessary to process the
         * input buffer here. Note that this happens on the current thread which
         * means that this thread will be used for any onMessage notifications.
         * This is a special case. Subsequent "data available to read" events
         * will be handled by threads from the AsyncChannelGroup's executor.
         */
    wsFrameClient.startInputProcessing();
    return wsSession;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) SSLEngine(javax.net.ssl.SSLEngine) ArrayList(java.util.ArrayList) URI(java.net.URI) SSLException(javax.net.ssl.SSLException) HandshakeResponse(javax.websocket.HandshakeResponse) Proxy(java.net.Proxy) EOFException(java.io.EOFException) List(java.util.List) ArrayList(java.util.ArrayList) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) Endpoint(javax.websocket.Endpoint) ClientEndpoint(javax.websocket.ClientEndpoint) Extension(javax.websocket.Extension) AsynchronousSocketChannel(java.nio.channels.AsynchronousSocketChannel) DeploymentException(javax.websocket.DeploymentException)

Example 30 with Endpoint

use of javax.websocket.Endpoint in project pinot by linkedin.

the class MeetupRsvpStream method run.

public void run() {
    try {
        final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build();
        final KafkaJSONMessageDecoder decoder = new KafkaJSONMessageDecoder();
        decoder.init(null, schema, null);
        client = ClientManager.createClient();
        client.connectToServer(new Endpoint() {

            @Override
            public void onOpen(Session session, EndpointConfig config) {
                try {
                    session.addMessageHandler(new MessageHandler.Whole<String>() {

                        @Override
                        public void onMessage(String message) {
                            try {
                                JSONObject messageJSON = new JSONObject(message);
                                JSONObject extracted = new JSONObject();
                                if (messageJSON.has("venue")) {
                                    JSONObject venue = messageJSON.getJSONObject("venue");
                                    extracted.put("venue_name", venue.getString("venue_name"));
                                }
                                if (messageJSON.has("event")) {
                                    JSONObject event = messageJSON.getJSONObject("event");
                                    extracted.put("event_name", event.getString("event_name"));
                                    extracted.put("event_id", event.getString("event_id"));
                                    extracted.put("event_time", event.getLong("time"));
                                }
                                if (messageJSON.has("group")) {
                                    JSONObject group = messageJSON.getJSONObject("group");
                                    extracted.put("group_city", group.getString("group_city"));
                                    extracted.put("group_country", group.getString("group_country"));
                                    extracted.put("group_id", group.getLong("group_id"));
                                    extracted.put("group_name", group.getString("group_name"));
                                }
                                extracted.put("mtime", messageJSON.getLong("mtime"));
                                extracted.put("rsvp_count", 1);
                                if (keepPublishing) {
                                    KeyedMessage<String, byte[]> data = new KeyedMessage<String, byte[]>("meetupRSVPEvents", extracted.toString().getBytes("UTF-8"));
                                    producer.send(data);
                                }
                            } catch (Exception e) {
                            //LOGGER.error("error processing raw event ", e);
                            }
                        }
                    });
                    session.getBasicRemote().sendText("");
                } catch (IOException e) {
                //LOGGER.error("found an event where data did not have all the fields, don't care about for quickstart");
                }
            }
        }, cec, new URI("ws://stream.meetup.com/2/rsvps"));
    } catch (Exception e) {
    //e.printStackTrace();
    }
}
Also used : KafkaJSONMessageDecoder(com.linkedin.pinot.core.realtime.impl.kafka.KafkaJSONMessageDecoder) IOException(java.io.IOException) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) Endpoint(javax.websocket.Endpoint) JSONObject(org.json.JSONObject) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) KeyedMessage(kafka.producer.KeyedMessage) EndpointConfig(javax.websocket.EndpointConfig) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) Session(javax.websocket.Session)

Aggregations

Endpoint (javax.websocket.Endpoint)46 Session (javax.websocket.Session)29 URI (java.net.URI)24 EndpointConfig (javax.websocket.EndpointConfig)24 ServerEndpointConfig (javax.websocket.server.ServerEndpointConfig)20 AtomicReference (java.util.concurrent.atomic.AtomicReference)18 ServerWebSocketContainer (io.undertow.websockets.jsr.ServerWebSocketContainer)14 UndertowSession (io.undertow.websockets.jsr.UndertowSession)14 AnnotatedClientEndpoint (io.undertow.websockets.jsr.test.annotated.AnnotatedClientEndpoint)14 FrameChecker (io.undertow.websockets.utils.FrameChecker)14 WebSocketTestClient (io.undertow.websockets.utils.WebSocketTestClient)14 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)14 FutureResult (org.xnio.FutureResult)14 IOException (java.io.IOException)13 ClientEndpointConfig (javax.websocket.ClientEndpointConfig)12 MessageHandler (javax.websocket.MessageHandler)12 ByteBuffer (java.nio.ByteBuffer)11 ServerEndpoint (javax.websocket.server.ServerEndpoint)11 CountDownLatch (java.util.concurrent.CountDownLatch)10 ClientEndpoint (javax.websocket.ClientEndpoint)10