Search in sources :

Example 11 with WebSocketException

use of org.eclipse.jetty.websocket.api.WebSocketException in project joynr by bmwcarit.

the class WebSocketJettyServer method writeBytes.

@Override
public synchronized void writeBytes(Address toAddress, byte[] message, long timeout, TimeUnit unit, final SuccessAction successAction, final FailureAction failureAction) {
    if (!(toAddress instanceof WebSocketClientAddress)) {
        throw new JoynrIllegalStateException("Web Socket Server can only send to WebSocketClientAddresses");
    }
    WebSocketClientAddress toClientAddress = (WebSocketClientAddress) toAddress;
    Session session = sessionMap.get(toClientAddress.getId());
    if (session == null) {
        // TODO We need a delay with invalidation of the stub
        throw new JoynrDelayMessageException("no active session for WebSocketClientAddress: " + toClientAddress.getId());
    }
    try {
        session.getRemote().sendBytes(ByteBuffer.wrap(message), new WriteCallback() {

            @Override
            public void writeSuccess() {
                successAction.execute();
            }

            @Override
            public void writeFailed(Throwable error) {
                if (shutdown) {
                    return;
                }
                failureAction.execute(error);
            }
        });
    } catch (WebSocketException e) {
        // Jetty throws WebSocketException when expecting [OPEN or CONNECTED] but found a different state
        // The client must reconnect, but the message can be queued in the mean time.
        sessionMap.remove(toClientAddress.getId());
        // TODO We need a delay with invalidation of the stub
        throw new JoynrDelayMessageException(e.getMessage(), e);
    }
}
Also used : WebSocketException(org.eclipse.jetty.websocket.api.WebSocketException) JoynrDelayMessageException(io.joynr.exceptions.JoynrDelayMessageException) WebSocketClientAddress(joynr.system.RoutingTypes.WebSocketClientAddress) WriteCallback(org.eclipse.jetty.websocket.api.WriteCallback) JoynrIllegalStateException(io.joynr.exceptions.JoynrIllegalStateException) Session(org.eclipse.jetty.websocket.api.Session)

Example 12 with WebSocketException

use of org.eclipse.jetty.websocket.api.WebSocketException in project elastic-core-maven by OrdinaryDude.

the class PeerWebSocket method sendResponse.

/**
 * Send POST response
 *
 * This method is used by the connection acceptor to return the POST response
 *
 * @param   requestId           Request identifier
 * @param   response            Response message
 * @throws  IOException         I/O error occurred
 */
public void sendResponse(long requestId, String response) throws IOException {
    lock.lock();
    try {
        if (session != null && session.isOpen()) {
            byte[] responseBytes = response.getBytes("UTF-8");
            int responseLength = responseBytes.length;
            int flags = 0;
            if (Peers.isGzipEnabled && responseLength >= Peers.MIN_COMPRESS_SIZE) {
                flags |= FLAG_COMPRESSED;
                ByteArrayOutputStream outStream = new ByteArrayOutputStream(responseLength);
                try (GZIPOutputStream gzipStream = new GZIPOutputStream(outStream)) {
                    gzipStream.write(responseBytes);
                }
                responseBytes = outStream.toByteArray();
            }
            ByteBuffer buf = ByteBuffer.allocate(responseBytes.length + 20);
            buf.putInt(version).putLong(requestId).putInt(flags).putInt(responseLength).put(responseBytes).flip();
            if (buf.limit() > Peers.MAX_MESSAGE_SIZE) {
                throw new ProtocolException("POST response length exceeds max message size");
            }
            session.getRemote().sendBytes(buf);
        }
    } catch (WebSocketException exc) {
        throw new SocketException(exc.getMessage());
    } finally {
        lock.unlock();
    }
}
Also used : ProtocolException(java.net.ProtocolException) WebSocketException(org.eclipse.jetty.websocket.api.WebSocketException) SocketException(java.net.SocketException) WebSocketException(org.eclipse.jetty.websocket.api.WebSocketException) GZIPOutputStream(java.util.zip.GZIPOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteBuffer(java.nio.ByteBuffer)

Example 13 with WebSocketException

use of org.eclipse.jetty.websocket.api.WebSocketException in project tray by qzind.

the class UsbUtilities method setupUsbStream.

// shared by usb and hid streaming
public static void setupUsbStream(final Session session, String UID, SocketConnection connection, final DeviceOptions dOpts, final StreamEvent.Stream streamType) {
    final DeviceIO usb = connection.getDevice(dOpts);
    if (usb != null) {
        if (!usb.isStreaming()) {
            usb.setStreaming(true);
            new Thread() {

                @Override
                public void run() {
                    int interval = dOpts.getInterval();
                    int size = dOpts.getResponseSize();
                    Byte endpoint = dOpts.getEndpoint();
                    StreamEvent event = new StreamEvent(streamType, StreamEvent.Type.RECEIVE).withData("vendorId", usb.getVendorId()).withData("productId", usb.getProductId());
                    try {
                        while (usb.isOpen() && usb.isStreaming()) {
                            byte[] response = usb.readData(size, endpoint);
                            JSONArray hex = new JSONArray();
                            for (byte b : response) {
                                hex.put(UsbUtil.toHexString(b));
                            }
                            PrintSocketClient.sendStream(session, event.withData("output", hex));
                            try {
                                Thread.sleep(interval);
                            } catch (Exception ignore) {
                            }
                        }
                    } catch (WebSocketException e) {
                        usb.setStreaming(false);
                        log.error("USB stream error", e);
                    } catch (DeviceException e) {
                        usb.setStreaming(false);
                        log.error("USB stream error", e);
                        StreamEvent eventErr = new StreamEvent(streamType, StreamEvent.Type.ERROR).withException(e).withData("vendorId", usb.getVendorId()).withData("productId", usb.getProductId());
                        PrintSocketClient.sendStream(session, eventErr);
                    }
                }
            }.start();
            PrintSocketClient.sendResult(session, UID, null);
        } else {
            PrintSocketClient.sendError(session, UID, String.format("USB Device [v:%s p:%s] is already streaming data.", dOpts.getVendorId(), dOpts.getProductId()));
        }
    } else {
        PrintSocketClient.sendError(session, UID, String.format("USB Device [v:%s p:%s] must be claimed first.", dOpts.getVendorId(), dOpts.getProductId()));
    }
}
Also used : WebSocketException(org.eclipse.jetty.websocket.api.WebSocketException) StreamEvent(qz.ws.StreamEvent) JSONArray(org.codehaus.jettison.json.JSONArray) DeviceIO(qz.communication.DeviceIO) DeviceException(qz.communication.DeviceException) WebSocketException(org.eclipse.jetty.websocket.api.WebSocketException) JSONException(org.codehaus.jettison.json.JSONException) DeviceException(qz.communication.DeviceException)

Aggregations

WebSocketException (org.eclipse.jetty.websocket.api.WebSocketException)13 IOException (java.io.IOException)3 Session (org.eclipse.jetty.websocket.api.Session)3 JoynrDelayMessageException (io.joynr.exceptions.JoynrDelayMessageException)2 JoynrIllegalStateException (io.joynr.exceptions.JoynrIllegalStateException)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 ProtocolException (java.net.ProtocolException)2 SocketException (java.net.SocketException)2 ByteBuffer (java.nio.ByteBuffer)2 GZIPOutputStream (java.util.zip.GZIPOutputStream)2 DecodeException (javax.websocket.DecodeException)2 Decoder (javax.websocket.Decoder)2 WriteCallback (org.eclipse.jetty.websocket.api.WriteCallback)2 DecoderFactory (org.eclipse.jetty.websocket.jsr356.DecoderFactory)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 TimeoutTask (com.serotonin.m2m2.util.timeout.TimeoutTask)1 AnnotatedTextSocket (examples.AnnotatedTextSocket)1 JoynrCommunicationException (io.joynr.exceptions.JoynrCommunicationException)1 JoynrShutdownException (io.joynr.exceptions.JoynrShutdownException)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1