org.springframework.core.convert.ConverterNotFoundException#javax.websocket.EncodeException源码实例Demo

下面列出了org.springframework.core.convert.ConverterNotFoundException#javax.websocket.EncodeException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。


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));
    }
}
 

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");
    }
}
 

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);
}
 

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);
    }
}
 
源代码5 项目: openwebbeans-meecrowave   文件: ChatWS.java

@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();
	}

}
 

@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();
}
 

@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();
    }
}
 

@Override
public void run() {
    try {
        // Breakpoint B required on following line
        session.getBasicRemote().sendObject("test");
    } catch (IOException | EncodeException e) {
        e.printStackTrace();
    }
}
 

@Test
public void encodeToTextCannotConvert() throws Exception {
	setup(NoConvertersConfig.class);
	thown.expect(EncodeException.class);
	thown.expectCause(isA(ConverterNotFoundException.class));
	new MyTextEncoder().encode(myType);
}
 

@Test
public void encodeToBinaryCannotConvert() throws Exception {
	setup(NoConvertersConfig.class);
	thown.expect(EncodeException.class);
	thown.expectCause(isA(ConverterNotFoundException.class));
	new MyBinaryEncoder().encode(myType);
}
 

/**
 * @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);
	}
}
 

@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();
}
 

/**
 * 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);
	}
}
 

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);
    }
}
 

@Test
public void encodeToBinaryCannotConvert() throws Exception {
	setup(NoConvertersConfig.class);
	assertThatExceptionOfType(EncodeException.class).isThrownBy(() ->
			new MyBinaryEncoder().encode(myType))
		.withCauseInstanceOf(ConverterNotFoundException.class);
}
 
源代码16 项目: quarkus-http   文件: Encoding.java

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");
}
 
源代码17 项目: quarkus-http   文件: Encoding.java

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");
}
 

@Override
public void sendObject(final Object data) throws IOException, EncodeException {
    if (data == null) {
        throw JsrWebSocketMessages.MESSAGES.messageInNull();
    }
    sendObjectImpl(data);
}
 
源代码19 项目: apicurio-studio   文件: MessageEncoder.java

@Override
public String encode(JsonNode msg) throws EncodeException {
    try {
        return mapper.writeValueAsString(msg);
    } catch (JsonProcessingException e) {
        throw new EncodeException(msg, e.getMessage());
    }
}
 

/**
 * 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);
	}
}
 

@Test
public void encodeToTextCannotConvert() throws Exception {
	setup(NoConvertersConfig.class);
	thown.expect(EncodeException.class);
	thown.expectCause(isA(ConverterNotFoundException.class));
	new MyTextEncoder().encode(myType);
}
 
源代码22 项目: tomcatsrc   文件: TestEncodingDecoding.java

@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();
    }
}
 
源代码23 项目: tomcatsrc   文件: TestEncodingDecoding.java

@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;
}
 
源代码24 项目: tomcatsrc   文件: TestEncodingDecoding.java

@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();
}
 
源代码25 项目: grain   文件: TestWSService.java

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);
}
 
源代码26 项目: grain   文件: TestWSService.java

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);
}
 
源代码27 项目: openwebbeans-meecrowave   文件: WSTest.java

@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());
	}
}
 
源代码28 项目: lsp4j   文件: MockSession.java

@Override
public void sendObject(Object data) throws IOException, EncodeException {
}
 

@Override
public void sendObject(Object o) throws IOException, EncodeException {
    base.sendObject(o);
}
 

@Override
public String encode(SecurityRulesProgressMessage message) throws EncodeException {
    return message.toJson();
}