javax.websocket.EncodeException Java Examples

The following examples show how to use javax.websocket.EncodeException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PojoMessageHandlerBase.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
protected final void processResult(Object result) {
    if (result == null) {
        return;
    }

    RemoteEndpoint.Basic remoteEndpoint = session.getBasicRemote();
    try {
        if (result instanceof String) {
            remoteEndpoint.sendText((String) result);
        } else if (result instanceof ByteBuffer) {
            remoteEndpoint.sendBinary((ByteBuffer) result);
        } else if (result instanceof byte[]) {
            remoteEndpoint.sendBinary(ByteBuffer.wrap((byte[]) result));
        } else {
            remoteEndpoint.sendObject(result);
        }
    } catch (IOException ioe) {
        throw new IllegalStateException(ioe);
    } catch (EncodeException ee) {
        throw new IllegalStateException(ee);
    }
}
 
Example #2
Source File: WsRemoteEndpointImplBase.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
private void handleSendFailureWithEncode(Throwable t) throws IOException, EncodeException {
    // First, unwrap any execution exception
    if (t instanceof ExecutionException) {
        t = t.getCause();
    }

    // Close the session
    wsSession.doClose(new CloseReason(CloseCodes.GOING_AWAY, t.getMessage()),
            new CloseReason(CloseCodes.CLOSED_ABNORMALLY, t.getMessage()));

    // Rethrow the exception
    if (t instanceof EncodeException) {
        throw (EncodeException) t;
    }
    if (t instanceof IOException) {
        throw (IOException) t;
    }
    throw new IOException(t);
}
 
Example #3
Source File: WebSocketSessionRemoteEndpoint.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
private void sendObjectImpl(final Object o) throws IOException, EncodeException {
    if (o instanceof String) {
        sendText((String) o);
    } else if (o instanceof byte[]) {
        sendBinary(ByteBuffer.wrap((byte[]) o));
    } else if (o instanceof ByteBuffer) {
        sendBinary((ByteBuffer) o);
    } else if (encoding.canEncodeText(o.getClass())) {
        sendText(encoding.encodeText(o));
    } else if (encoding.canEncodeBinary(o.getClass())) {
        sendBinary(encoding.encodeBinary(o));
    } else {
        // TODO: Replace on bug is fixed
        // https://issues.jboss.org/browse/LOGTOOL-64
        throw new EncodeException(o, "No suitable encoder found");
    }
}
 
Example #4
Source File: WebSocketSessionRemoteEndpoint.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
private void sendObjectImpl(final Object o, final SendHandler callback) {
    try {
        if (o instanceof String) {
            sendText((String) o, callback);
        } else if (o instanceof byte[]) {
            sendBinary(ByteBuffer.wrap((byte[]) o), callback);
        } else if (o instanceof ByteBuffer) {
            sendBinary((ByteBuffer) o, callback);
        } else if (encoding.canEncodeText(o.getClass())) {
            sendText(encoding.encodeText(o), callback);
        } else if (encoding.canEncodeBinary(o.getClass())) {
            sendBinary(encoding.encodeBinary(o), callback);
        } else {
            // TODO: Replace on bug is fixed
            // https://issues.jboss.org/browse/LOGTOOL-64
            throw new EncodeException(o, "No suitable encoder found");
        }
    } catch (Exception e) {
        callback.onResult(new SendResult(e));
    }
}
 
Example #5
Source File: TestWSService.java    From grain with MIT License 5 votes vote down vote up
public void onTestC(WsPacket wsPacket) throws IOException, EncodeException {
	TestC testc = (TestC) wsPacket.getData();
	wsPacket.putMonitor("接到客户端发来的消息:" + testc.getMsg());
	TestS.Builder tests = TestS.newBuilder();
	tests.setWsOpCode("tests");
	tests.setMsg("你好客户端,我是服务器");
	WsPacket pt = new WsPacket("tests", tests.build());
	Session session = (Session) wsPacket.session;
	session.getBasicRemote().sendObject(pt);
}
 
Example #6
Source File: ConvertingEncoderDecoderSupport.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Encode an object to a message.
 * @see javax.websocket.Encoder.Text#encode(Object)
 * @see javax.websocket.Encoder.Binary#encode(Object)
 */
@SuppressWarnings("unchecked")
@Nullable
public M encode(T object) throws EncodeException {
	try {
		return (M) getConversionService().convert(object, getType(), getMessageType());
	}
	catch (ConversionException ex) {
		throw new EncodeException(object, "Unable to encode websocket message using ConversionService", ex);
	}
}
 
Example #7
Source File: MessageEncoder.java    From Hands-On-Cloud-Native-Applications-with-Java-and-Quarkus with MIT License 5 votes vote down vote up
@Override
public String encode(List<Customer> list) throws EncodeException {
    JsonArrayBuilder jsonArray = Json.createArrayBuilder();
    for(Customer c : list) {
        jsonArray.add(Json.createObjectBuilder()
                .add("Name", c.getName())
                .add("Surname", c.getSurname()));
    }
    JsonArray array = jsonArray.build();
    StringWriter buffer = new StringWriter();
    Json.createWriter(buffer).writeArray(array);
    return buffer.toString();
}
 
Example #8
Source File: TestEncodingDecoding.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public String encode(List<String> str) throws EncodeException {
    StringBuffer sbuf = new StringBuffer();
    sbuf.append("[");
    for (String s: str){
        sbuf.append(s).append(",");
    }
    sbuf.deleteCharAt(sbuf.lastIndexOf(",")).append("]");
    return sbuf.toString();
}
 
Example #9
Source File: ConvertingEncoderDecoderSupportTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void encodeToBinaryCannotConvert() throws Exception {
	setup(NoConvertersConfig.class);
	thown.expect(EncodeException.class);
	thown.expectCause(isA(ConverterNotFoundException.class));
	new MyBinaryEncoder().encode(myType);
}
 
Example #10
Source File: TestEncodingDecoding.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testUnsupportedObject() throws Exception{
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(ProgramaticServerEndpointConfig.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");

    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();

    tomcat.start();

    Client client = new Client();
    URI uri = new URI("ws://localhost:" + getPort() + PATH_PROGRAMMATIC_EP);
    Session session = wsContainer.connectToServer(client, uri);

    // This should fail
    Object msg1 = new Object();
    try {
        session.getBasicRemote().sendObject(msg1);
        Assert.fail("No exception thrown ");
    } catch (EncodeException e) {
        // Expected
    } catch (Throwable t) {
        Assert.fail("Wrong exception type");
    } finally {
        session.close();
    }
}
 
Example #11
Source File: TestWsRemoteEndpointImplServer.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void run() {
    try {
        // Breakpoint B required on following line
        session.getBasicRemote().sendObject("test");
    } catch (IOException | EncodeException e) {
        e.printStackTrace();
    }
}
 
Example #12
Source File: ChatWS.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
@OnMessage
public void message(Session session, JsonObject msg) {		
	try {
		if (!"ping".equals(msg.getString("chat"))) {
			session.close(new CloseReason(CloseCodes.UNEXPECTED_CONDITION, String.format("unexpected chat value %s", msg.getString("chat"))));
		}
		JsonObject pong = Json.createObjectBuilder().add("chat", "pong " + chatCounter.incrementAndGet()).build();
		session.getBasicRemote().sendObject(pong);
	} catch (IOException | EncodeException e) {
		e.printStackTrace();
	}

}
 
Example #13
Source File: ConvertingEncoderDecoderSupportTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void encodeToTextCannotConvert() throws Exception {
	setup(NoConvertersConfig.class);
	thown.expect(EncodeException.class);
	thown.expectCause(isA(ConverterNotFoundException.class));
	new MyTextEncoder().encode(myType);
}
 
Example #14
Source File: ConvertingEncoderDecoderSupport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * @see javax.websocket.Encoder.Text#encode(Object)
 * @see javax.websocket.Encoder.Binary#encode(Object)
 */
@SuppressWarnings("unchecked")
public M encode(T object) throws EncodeException {
	try {
		return (M) getConversionService().convert(object, getType(), getMessageType());
	}
	catch (ConversionException ex) {
		throw new EncodeException(object, "Unable to encode websocket message using ConversionService", ex);
	}
}
 
Example #15
Source File: WsRemoteEndpointImplBase.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
private void handleSendFailure(Throwable t) throws IOException {
    try {
        handleSendFailureWithEncode(t);
    } catch (EncodeException e) {
        // Should never happen. But in case it does...
        throw new IOException(e);
    }
}
 
Example #16
Source File: ConvertingEncoderDecoderSupportTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void encodeToBinaryCannotConvert() throws Exception {
	setup(NoConvertersConfig.class);
	assertThatExceptionOfType(EncodeException.class).isThrownBy(() ->
			new MyBinaryEncoder().encode(myType))
		.withCauseInstanceOf(ConverterNotFoundException.class);
}
 
Example #17
Source File: Encoding.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public String encodeText(final Object o) throws EncodeException {
    List<InstanceHandle<? extends Encoder>> encoders = textEncoders.get(o.getClass());
    if(encoders == null) {
        for(Map.Entry<Class<?>, List<InstanceHandle<? extends Encoder>>> entry : textEncoders.entrySet()) {
            if(entry.getKey().isAssignableFrom(o.getClass())) {
                encoders = entry.getValue();
                break;
            }
        }
    }
    if (encoders != null) {
        for (InstanceHandle<? extends Encoder> decoderHandle : encoders) {
            Encoder decoder = decoderHandle.getInstance();
            if (decoder instanceof Encoder.Text) {
                return ((Encoder.Text) decoder).encode(o);
            } else {
                try {
                    StringWriter out = new StringWriter();
                    ((Encoder.TextStream) decoder).encode(o, out);
                    return out.toString();
                } catch (IOException e) {
                    throw new EncodeException(o, "Could not encode text", e);
                }
            }
        }
    }

    if (EncodingFactory.isPrimitiveOrBoxed(o.getClass())) {
        return o.toString();
    }
    throw new EncodeException(o, "Could not encode text");
}
 
Example #18
Source File: Encoding.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public ByteBuffer encodeBinary(final Object o) throws EncodeException {
    List<InstanceHandle<? extends Encoder>> encoders = binaryEncoders.get(o.getClass());

    if(encoders == null) {
        for(Map.Entry<Class<?>, List<InstanceHandle<? extends Encoder>>> entry : binaryEncoders.entrySet()) {
            if(entry.getKey().isAssignableFrom(o.getClass())) {
                encoders = entry.getValue();
                break;
            }
        }
    }
    if (encoders != null) {
        for (InstanceHandle<? extends Encoder> decoderHandle : encoders) {
            Encoder decoder = decoderHandle.getInstance();
            if (decoder instanceof Encoder.Binary) {
                return ((Encoder.Binary) decoder).encode(o);
            } else {
                try {
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    ((Encoder.BinaryStream) decoder).encode(o, out);
                    return ByteBuffer.wrap(out.toByteArray());
                } catch (IOException e) {
                    throw new EncodeException(o, "Could not encode binary", e);
                }
            }
        }
    }
    throw new EncodeException(o, "Could not encode binary");
}
 
Example #19
Source File: WebSocketSessionRemoteEndpoint.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void sendObject(final Object data) throws IOException, EncodeException {
    if (data == null) {
        throw JsrWebSocketMessages.MESSAGES.messageInNull();
    }
    sendObjectImpl(data);
}
 
Example #20
Source File: ConvertingEncoderDecoderSupport.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Encode an object to a message.
 * @see javax.websocket.Encoder.Text#encode(Object)
 * @see javax.websocket.Encoder.Binary#encode(Object)
 */
@SuppressWarnings("unchecked")
@Nullable
public M encode(T object) throws EncodeException {
	try {
		return (M) getConversionService().convert(object, getType(), getMessageType());
	}
	catch (ConversionException ex) {
		throw new EncodeException(object, "Unable to encode websocket message using ConversionService", ex);
	}
}
 
Example #21
Source File: ConvertingEncoderDecoderSupportTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void encodeToTextCannotConvert() throws Exception {
	setup(NoConvertersConfig.class);
	thown.expect(EncodeException.class);
	thown.expectCause(isA(ConverterNotFoundException.class));
	new MyTextEncoder().encode(myType);
}
 
Example #22
Source File: TestEncodingDecoding.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnsupportedObject() throws Exception{
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(ProgramaticServerEndpointConfig.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();

    tomcat.start();

    Client client = new Client();
    URI uri = new URI("ws://localhost:" + getPort() + PATH_PROGRAMMATIC_EP);
    Session session = wsContainer.connectToServer(client, uri);

    // This should fail
    Object msg1 = new Object();
    try {
        session.getBasicRemote().sendObject(msg1);
        Assert.fail("No exception thrown ");
    } catch (EncodeException e) {
        // Expected
    } catch (Throwable t) {
        Assert.fail("Wrong exception type");
    } finally {
        session.close();
    }
}
 
Example #23
Source File: WSTest.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
@OnOpen
public void onOpen(Session session) {
	try {
		JsonObject ping = Json.createObjectBuilder().add("chat", "ping").build();
		session.getBasicRemote().sendObject(ping);
	} catch (IOException | EncodeException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}
}
 
Example #24
Source File: TestEncodingDecoding.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public ByteBuffer encode(MsgByte msg) throws EncodeException {
    byte[] data = msg.getData();
    ByteBuffer reply = ByteBuffer.allocate(2 + data.length);
    reply.put((byte) 0x12);
    reply.put((byte) 0x34);
    reply.put(data);
    reply.flip();
    return reply;
}
 
Example #25
Source File: TestEncodingDecoding.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public String encode(List<String> str) throws EncodeException {
    StringBuffer sbuf = new StringBuffer();
    sbuf.append("[");
    for (String s: str){
        sbuf.append(s).append(",");
    }
    sbuf.deleteCharAt(sbuf.lastIndexOf(",")).append("]");
    return sbuf.toString();
}
 
Example #26
Source File: TestWSService.java    From grain with MIT License 5 votes vote down vote up
public void onTestC(WsPacket wsPacket) throws IOException, EncodeException {
	TestC testc = (TestC) wsPacket.getData();
	wsPacket.putMonitor("接到客户端发来的消息:" + testc.getMsg());
	TestS.Builder tests = TestS.newBuilder();
	tests.setWsOpCode("tests");
	tests.setMsg("你好客户端,我是服务器");
	WsPacket pt = new WsPacket("tests", tests.build());
	Session session = (Session) wsPacket.session;
	session.getBasicRemote().sendObject(pt);
}
 
Example #27
Source File: MessageEncoder.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
@Override
public String encode(JsonNode msg) throws EncodeException {
    try {
        return mapper.writeValueAsString(msg);
    } catch (JsonProcessingException e) {
        throw new EncodeException(msg, e.getMessage());
    }
}
 
Example #28
Source File: RunningMessageEncoder.java    From ipst with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public String encode(RunningMessage message) throws EncodeException {
    return message.toJson();
}
 
Example #29
Source File: WcaRunningMessageEncoder.java    From ipst with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public String encode(WcaRunningMessage message) throws EncodeException {
    return message.toJson();
}
 
Example #30
Source File: ConnectionMessageEncoder.java    From ipst with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public String encode(ConnectionMessage message) throws EncodeException {
    return message.toJson();
}