Search in sources :

Example 1 with Encoder

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

the class WsRemoteEndpointImplBase method sendObjectByCompletion.

@SuppressWarnings({ "unchecked", "rawtypes" })
public void sendObjectByCompletion(Object obj, SendHandler completion) {
    if (obj == null) {
        throw new IllegalArgumentException(sm.getString("wsRemoteEndpoint.nullData"));
    }
    if (completion == null) {
        throw new IllegalArgumentException(sm.getString("wsRemoteEndpoint.nullHandler"));
    }
    /*
         * Note that the implementation will convert primitives and their object
         * equivalents by default but that users are free to specify their own
         * encoders and decoders for this if they wish.
         */
    Encoder encoder = findEncoder(obj);
    if (encoder == null && Util.isPrimitive(obj.getClass())) {
        String msg = obj.toString();
        sendStringByCompletion(msg, completion);
        return;
    }
    if (encoder == null && byte[].class.isAssignableFrom(obj.getClass())) {
        ByteBuffer msg = ByteBuffer.wrap((byte[]) obj);
        sendBytesByCompletion(msg, completion);
        return;
    }
    try {
        if (encoder instanceof Encoder.Text) {
            String msg = ((Encoder.Text) encoder).encode(obj);
            sendStringByCompletion(msg, completion);
        } else if (encoder instanceof Encoder.TextStream) {
            try (Writer w = getSendWriter()) {
                ((Encoder.TextStream) encoder).encode(obj, w);
            }
            completion.onResult(new SendResult());
        } else if (encoder instanceof Encoder.Binary) {
            ByteBuffer msg = ((Encoder.Binary) encoder).encode(obj);
            sendBytesByCompletion(msg, completion);
        } else if (encoder instanceof Encoder.BinaryStream) {
            try (OutputStream os = getSendStream()) {
                ((Encoder.BinaryStream) encoder).encode(obj, os);
            }
            completion.onResult(new SendResult());
        } else {
            throw new EncodeException(obj, sm.getString("wsRemoteEndpoint.noEncoder", obj.getClass()));
        }
    } catch (Exception e) {
        SendResult sr = new SendResult(e);
        completion.onResult(sr);
    }
}
Also used : OutputStream(java.io.OutputStream) EncodeException(javax.websocket.EncodeException) ByteBuffer(java.nio.ByteBuffer) DeploymentException(javax.websocket.DeploymentException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) EncodeException(javax.websocket.EncodeException) Encoder(javax.websocket.Encoder) Utf8Encoder(org.apache.tomcat.util.buf.Utf8Encoder) CharsetEncoder(java.nio.charset.CharsetEncoder) SendResult(javax.websocket.SendResult) Writer(java.io.Writer)

Example 2 with Encoder

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

the class WsRemoteEndpointImplBase method sendObject.

@SuppressWarnings({ "unchecked", "rawtypes" })
public void sendObject(Object obj) throws IOException, EncodeException {
    if (obj == null) {
        throw new IllegalArgumentException(sm.getString("wsRemoteEndpoint.nullData"));
    }
    /*
         * Note that the implementation will convert primitives and their object
         * equivalents by default but that users are free to specify their own
         * encoders and decoders for this if they wish.
         */
    Encoder encoder = findEncoder(obj);
    if (encoder == null && Util.isPrimitive(obj.getClass())) {
        String msg = obj.toString();
        sendString(msg);
        return;
    }
    if (encoder == null && byte[].class.isAssignableFrom(obj.getClass())) {
        ByteBuffer msg = ByteBuffer.wrap((byte[]) obj);
        sendBytes(msg);
        return;
    }
    if (encoder instanceof Encoder.Text) {
        String msg = ((Encoder.Text) encoder).encode(obj);
        sendString(msg);
    } else if (encoder instanceof Encoder.TextStream) {
        try (Writer w = getSendWriter()) {
            ((Encoder.TextStream) encoder).encode(obj, w);
        }
    } else if (encoder instanceof Encoder.Binary) {
        ByteBuffer msg = ((Encoder.Binary) encoder).encode(obj);
        sendBytes(msg);
    } else if (encoder instanceof Encoder.BinaryStream) {
        try (OutputStream os = getSendStream()) {
            ((Encoder.BinaryStream) encoder).encode(obj, os);
        }
    } else {
        throw new EncodeException(obj, sm.getString("wsRemoteEndpoint.noEncoder", obj.getClass()));
    }
}
Also used : Encoder(javax.websocket.Encoder) Utf8Encoder(org.apache.tomcat.util.buf.Utf8Encoder) CharsetEncoder(java.nio.charset.CharsetEncoder) OutputStream(java.io.OutputStream) EncodeException(javax.websocket.EncodeException) ByteBuffer(java.nio.ByteBuffer) Writer(java.io.Writer)

Example 3 with Encoder

use of javax.websocket.Encoder in project che by eclipse.

the class ServerContainerInitializeListener method createWsServerEndpointConfig.

protected ServerEndpointConfig createWsServerEndpointConfig(ServletContext servletContext) {
    final List<Class<? extends Encoder>> encoders = new LinkedList<>();
    final List<Class<? extends Decoder>> decoders = new LinkedList<>();
    encoders.add(OutputMessageEncoder.class);
    decoders.add(InputMessageDecoder.class);
    final ServerEndpointConfig endpointConfig = create(CheWSConnection.class, websocketContext + websocketEndPoint).configurator(createConfigurator()).encoders(encoders).decoders(decoders).build();
    endpointConfig.getUserProperties().put(EVERREST_PROCESSOR_ATTRIBUTE, getEverrestProcessor(servletContext));
    endpointConfig.getUserProperties().put(EVERREST_CONFIG_ATTRIBUTE, getEverrestConfiguration(servletContext));
    endpointConfig.getUserProperties().put(EXECUTOR_ATTRIBUTE, createExecutor(servletContext));
    return endpointConfig;
}
Also used : ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) Encoder(javax.websocket.Encoder) BaseTextEncoder(org.everrest.websockets.message.BaseTextEncoder) Decoder(javax.websocket.Decoder) BaseTextDecoder(org.everrest.websockets.message.BaseTextDecoder) LinkedList(java.util.LinkedList)

Example 4 with Encoder

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

the class EncoderTest method testTwoQuotes.

@Test
public void testTwoQuotes() throws Exception {
    EchoServer eserver = new EchoServer(server);
    try {
        eserver.start();
        QuotesSocket quoter = new QuotesSocket();
        ClientEndpointConfig.Builder builder = ClientEndpointConfig.Builder.create();
        List<Class<? extends Encoder>> encoders = new ArrayList<>();
        encoders.add(QuotesEncoder.class);
        builder.encoders(encoders);
        ClientEndpointConfig cec = builder.build();
        client.connectToServer(quoter, cec, server.getWsUri());
        Quotes ben = getQuotes("quotes-ben.txt");
        Quotes twain = getQuotes("quotes-twain.txt");
        quoter.write(ben);
        quoter.write(twain);
        quoter.messageQueue.awaitEventCount(2, 1000, TimeUnit.MILLISECONDS);
        String result = quoter.messageQueue.poll();
        assertReceivedQuotes(result, ben);
        result = quoter.messageQueue.poll();
        assertReceivedQuotes(result, twain);
    } finally {
        eserver.stop();
    }
}
Also used : Encoder(javax.websocket.Encoder) ArrayList(java.util.ArrayList) ClientEndpointConfig(javax.websocket.ClientEndpointConfig) Matchers.containsString(org.hamcrest.Matchers.containsString) Test(org.junit.Test)

Example 5 with Encoder

use of javax.websocket.Encoder 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>");
        List<Class<? extends Encoder>> encoders = new ArrayList<>();
        encoders.add(MyMessageEncoder.class);
        List<Class<? extends Decoder>> decoders = new ArrayList<>();
        decoders.add(MyMessageDecoder.class);
        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().encoders(encoders).decoders(decoders).build(), 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);
    }
}
Also used : WebSocketContainer(javax.websocket.WebSocketContainer) Encoder(javax.websocket.Encoder) ArrayList(java.util.ArrayList) Class(java.lang.Class) DeploymentException(javax.websocket.DeploymentException) Decoder(javax.websocket.Decoder) PrintWriter(java.io.PrintWriter)

Aggregations

Encoder (javax.websocket.Encoder)13 EncodeException (javax.websocket.EncodeException)6 ByteBuffer (java.nio.ByteBuffer)4 ArrayList (java.util.ArrayList)4 Decoder (javax.websocket.Decoder)4 IOException (java.io.IOException)3 OutputStream (java.io.OutputStream)3 Writer (java.io.Writer)3 CharsetEncoder (java.nio.charset.CharsetEncoder)3 List (java.util.List)3 DeploymentException (javax.websocket.DeploymentException)3 Utf8Encoder (org.apache.tomcat.util.buf.Utf8Encoder)3 InstanceHandle (io.undertow.servlet.api.InstanceHandle)2 LinkedList (java.util.LinkedList)2 Map (java.util.Map)2 ClientEndpointConfig (javax.websocket.ClientEndpointConfig)2 SendResult (javax.websocket.SendResult)2 ServerEndpointConfig (javax.websocket.server.ServerEndpointConfig)2 MessageOutputStream (org.eclipse.jetty.websocket.common.message.MessageOutputStream)2 MessageWriter (org.eclipse.jetty.websocket.common.message.MessageWriter)2