Search in sources :

Example 6 with SendResult

use of jakarta.websocket.SendResult 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(jakarta.websocket.EncodeException) ByteBuffer(java.nio.ByteBuffer) EncodeException(jakarta.websocket.EncodeException) NamingException(javax.naming.NamingException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) DeploymentException(jakarta.websocket.DeploymentException) Utf8Encoder(org.apache.tomcat.util.buf.Utf8Encoder) Encoder(jakarta.websocket.Encoder) CharsetEncoder(java.nio.charset.CharsetEncoder) SendResult(jakarta.websocket.SendResult) Writer(java.io.Writer)

Example 7 with SendResult

use of jakarta.websocket.SendResult in project atmosphere by Atmosphere.

the class JSR356WebSocketTest method test_semaphore_is_released_in_case_of_successful_write.

@Test(timeOut = 1000)
public void test_semaphore_is_released_in_case_of_successful_write() throws Exception {
    mockWriteResult(new SendResult());
    webSocket.write("Hello");
    webSocket.write("Hello");
    verify(asyncRemoteEndpoint, times(2)).sendText(eq("Hello"), any(SendHandler.class));
}
Also used : SendHandler(jakarta.websocket.SendHandler) SendResult(jakarta.websocket.SendResult) Test(org.testng.annotations.Test)

Example 8 with SendResult

use of jakarta.websocket.SendResult in project tomcat by apache.

the class WsRemoteEndpointImplBase method startMessage.

void startMessage(byte opCode, ByteBuffer payload, boolean last, SendHandler handler) {
    wsSession.updateLastActiveWrite();
    List<MessagePart> messageParts = new ArrayList<>();
    messageParts.add(new MessagePart(last, 0, opCode, payload, intermediateMessageHandler, new EndMessageHandler(this, handler), -1));
    try {
        messageParts = transformation.sendMessagePart(messageParts);
    } catch (IOException ioe) {
        handler.onResult(new SendResult(ioe));
        return;
    }
    // trigger the supplied SendHandler
    if (messageParts.size() == 0) {
        handler.onResult(new SendResult());
        return;
    }
    MessagePart mp = messageParts.remove(0);
    boolean doWrite = false;
    synchronized (messagePartLock) {
        if (Constants.OPCODE_CLOSE == mp.getOpCode() && getBatchingAllowed()) {
            // Should not happen. To late to send batched messages now since
            // the session has been closed. Complain loudly.
            log.warn(sm.getString("wsRemoteEndpoint.flushOnCloseFailed"));
        }
        if (messagePartInProgress.tryAcquire()) {
            doWrite = true;
        } else {
            // When a control message is sent while another message is being
            // sent, the control message is queued. Chances are the
            // subsequent data message part will end up queued while the
            // control message is sent. The logic in this class (state
            // machine, EndMessageHandler, TextMessageSendHandler) ensures
            // that there will only ever be one data message part in the
            // queue. There could be multiple control messages in the queue.
            // Add it to the queue
            messagePartQueue.add(mp);
        }
        // Add any remaining messages to the queue
        messagePartQueue.addAll(messageParts);
    }
    if (doWrite) {
        // Actual write has to be outside sync block to avoid possible
        // deadlock between messagePartLock and writeLock in
        // o.a.coyote.http11.upgrade.AbstractServletOutputStream
        writeMessagePart(mp);
    }
}
Also used : SendResult(jakarta.websocket.SendResult) ArrayList(java.util.ArrayList) IOException(java.io.IOException)

Example 9 with SendResult

use of jakarta.websocket.SendResult in project tomcat by apache.

the class WsRemoteEndpointImplClient method doWrite.

@Override
protected void doWrite(SendHandler handler, long blockingWriteTimeoutExpiry, ByteBuffer... data) {
    long timeout;
    for (ByteBuffer byteBuffer : data) {
        if (blockingWriteTimeoutExpiry == -1) {
            timeout = getSendTimeout();
            if (timeout < 1) {
                timeout = Long.MAX_VALUE;
            }
        } else {
            timeout = blockingWriteTimeoutExpiry - System.currentTimeMillis();
            if (timeout < 0) {
                SendResult sr = new SendResult(new IOException(sm.getString("wsRemoteEndpoint.writeTimeout")));
                handler.onResult(sr);
            }
        }
        try {
            channel.write(byteBuffer).get(timeout, TimeUnit.MILLISECONDS);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            handler.onResult(new SendResult(e));
            return;
        }
    }
    handler.onResult(SENDRESULT_OK);
}
Also used : SendResult(jakarta.websocket.SendResult) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ByteBuffer(java.nio.ByteBuffer) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

SendResult (jakarta.websocket.SendResult)9 IOException (java.io.IOException)6 SendHandler (jakarta.websocket.SendHandler)3 ByteBuffer (java.nio.ByteBuffer)3 SocketTimeoutException (java.net.SocketTimeoutException)2 Test (org.testng.annotations.Test)2 DeploymentException (jakarta.websocket.DeploymentException)1 EncodeException (jakarta.websocket.EncodeException)1 Encoder (jakarta.websocket.Encoder)1 OutputStream (java.io.OutputStream)1 Writer (java.io.Writer)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 CharsetEncoder (java.nio.charset.CharsetEncoder)1 ArrayList (java.util.ArrayList)1 ExecutionException (java.util.concurrent.ExecutionException)1 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)1 TimeoutException (java.util.concurrent.TimeoutException)1 NamingException (javax.naming.NamingException)1 Utf8Encoder (org.apache.tomcat.util.buf.Utf8Encoder)1