@Override protected Object decode(ByteBuffer message) throws DecodeException { for (Decoder decoder : decoders) { if (decoder instanceof Binary) { if (((Binary<?>) decoder).willDecode(message)) { return ((Binary<?>) decoder).decode(message); } } else { byte[] array = new byte[message.limit() - message.position()]; message.get(array); ByteArrayInputStream bais = new ByteArrayInputStream(array); try { return ((BinaryStream<?>) decoder).decode(bais); } catch (IOException ioe) { throw new DecodeException(message, sm.getString( "pojoMessageHandlerWhole.decodeIoFail"), ioe); } } } return null; }
@Override protected Object decode(String message) throws DecodeException { // Handle primitives if (primitiveType != null) { return Util.coerceToType(primitiveType, message); } // Handle full decoders for (Decoder decoder : decoders) { if (decoder instanceof Text) { if (((Text<?>) decoder).willDecode(message)) { return ((Text<?>) decoder).decode(message); } } else { StringReader r = new StringReader(message); try { return ((TextStream<?>) decoder).decode(r); } catch (IOException ioe) { throw new DecodeException(message, sm.getString( "pojoMessageHandlerWhole.decodeIoFail"), ioe); } } } return null; }
@Override protected Object decode(ByteBuffer message) throws DecodeException { for (Decoder decoder : decoders) { if (decoder instanceof Binary) { if (((Binary<?>) decoder).willDecode(message)) { return ((Binary<?>) decoder).decode(message); } } else { byte[] array = new byte[message.limit() - message.position()]; message.get(array); ByteArrayInputStream bais = new ByteArrayInputStream(array); try { return ((BinaryStream<?>) decoder).decode(bais); } catch (IOException ioe) { throw new DecodeException(message, sm.getString("pojoMessageHandlerWhole.decodeIoFail"), ioe); } } } return null; }
@Override protected Object decode(String message) throws DecodeException { // Handle primitives if (primitiveType != null) { return Util.coerceToType(primitiveType, message); } // Handle full decoders for (Decoder decoder : decoders) { if (decoder instanceof Text) { if (((Text<?>) decoder).willDecode(message)) { return ((Text<?>) decoder).decode(message); } } else { StringReader r = new StringReader(message); try { return ((TextStream<?>) decoder).decode(r); } catch (IOException ioe) { throw new DecodeException(message, sm.getString("pojoMessageHandlerWhole.decodeIoFail"), ioe); } } } return null; }
private static Object[] buildArgs(PojoPathParam[] pathParams, Map<String, String> pathParameters, Session session, EndpointConfig config, Throwable throwable, CloseReason closeReason) throws DecodeException { Object[] result = new Object[pathParams.length]; for (int i = 0; i < pathParams.length; i++) { Class<?> type = pathParams[i].getType(); if (type.equals(Session.class)) { result[i] = session; } else if (type.equals(EndpointConfig.class)) { result[i] = config; } else if (type.equals(Throwable.class)) { result[i] = throwable; } else if (type.equals(CloseReason.class)) { result[i] = closeReason; } else { String name = pathParams[i].getName(); String value = pathParameters.get(name); try { result[i] = Util.coerceToType(type, value); } catch (Exception e) { throw new DecodeException(value, sm.getString("pojoMethodMapping.decodePathParamFail", value, type), e); } } } return result; }
@Test public void from_byteBuffer() throws IOException, DecodeException { final String input = "MESSAGE\ndestination:wonderland\nsubscription:a\ncontent-length:4\n\nbody\u0000"; final Frame frame; try (InputStream is = new ByteArrayInputStream(input.getBytes())) { frame = Encoding.from(ByteBuffer.wrap(input.getBytes(UTF_8))); } assertEquals(Command.MESSAGE, frame.command()); assertEquals(4, frame.headers().size()); // ensure header order is maintained final Iterator<Entry<Header, List<String>>> itr = frame.headers().entrySet().iterator(); final Entry<Header, List<String>> header2 = itr.next(); assertEquals("destination", header2.getKey().value()); assertEquals(1, header2.getValue().size()); assertEquals("wonderland", header2.getValue().get(0)); final Entry<Header, List<String>> header1 = itr.next(); assertEquals("subscription", header1.getKey().value()); assertEquals(1, header1.getValue().size()); assertEquals("a", header1.getValue().get(0)); assertEquals(ByteBuffer.wrap("body".getBytes(StandardCharsets.UTF_8)), frame.body().get()); }
/** * @see javax.websocket.Decoder.Text#decode(String) * @see javax.websocket.Decoder.Binary#decode(ByteBuffer) */ @SuppressWarnings("unchecked") public T decode(M message) throws DecodeException { try { return (T) getConversionService().convert(message, getMessageType(), getType()); } catch (ConversionException ex) { if (message instanceof String) { throw new DecodeException((String) message, "Unable to decode websocket message using ConversionService", ex); } if (message instanceof ByteBuffer) { throw new DecodeException((ByteBuffer) message, "Unable to decode websocket message using ConversionService", ex); } throw ex; } }
@Override public Message decode(String textMessage) throws DecodeException { Message msg = null; JsonObject obj = Json.createReader(new StringReader(textMessage)). readObject(); try { DecoderHelper helper = new DecoderHelper(obj); msg = helper.getMessage(); msg.init(obj); } catch (ApplicationException e) { logger.log(Level.SEVERE, e.getMessage(), e); } return msg; }
/** * Decodes the message * @param message * @return * @throws DecodeException */ @Override public AbstractCommand decode(String message) throws DecodeException { logger.log(Level.INFO, "Decoding: {0}", message); JsonObject struct; try (JsonReader rdr = Json.createReader(new StringReader(message))) { struct = rdr.readObject(); } String type = struct.getString("type"); CommandTypes cmdType = CommandTypes.valueOf(type); try { AbstractCommand cmd = (AbstractCommand)cmdType.getCommandClass().newInstance(); cmd.decode(struct); return cmd; } catch (InstantiationException | IllegalAccessException ex) { Logger.getLogger(CommandMessageDecoder.class.getName()).log(Level.SEVERE, null, ex); throw new DecodeException(message,"Could not be decoded - invalid type."); } }
@Test public void testReadyNoSavedRoom(@Mocked RoomMediator room) throws DecodeException { ClientMediator mediator = new ClientMediator(nexus, drain, userId, signedJwt); String msgTxt = "ready,{}"; RoutedMessage message = new RoutedMessage(msgTxt); System.out.println(message); new Expectations() {{ nexus.join(mediator, null, ""); }}; mediator.ready(message); new Verifications() {{ nexus.join(mediator, null, ""); times = 1; drain.send((RoutedMessage) any); times = 0; }}; }
@Test public void testReadyUserName(@Mocked RoomMediator room) throws DecodeException { ClientMediator mediator = new ClientMediator(nexus, drain, userId, signedJwt); String msgTxt = "ready,{\"username\":\"TinyJamFilledMuffin\"}"; RoutedMessage message = new RoutedMessage(msgTxt); System.out.println(message); new Expectations() {{ nexus.join(mediator, null, ""); }}; mediator.ready(message); new Verifications() {{ nexus.join(mediator, null, ""); times = 1; drain.send((RoutedMessage) any); times = 0; }}; }
@Test public void testReadyZeroBookmark(@Mocked RoomMediator room) throws DecodeException { ClientMediator mediator = new ClientMediator(nexus, drain, userId, signedJwt); String msgTxt = "ready,{\"bookmark\":0}"; RoutedMessage message = new RoutedMessage(msgTxt); System.out.println(message); new Expectations() {{ nexus.join(mediator, null, "0"); }}; mediator.ready(message); new Verifications() {{ nexus.join(mediator, null, "0"); times = 1; drain.send((RoutedMessage) any); times = 0; }}; }
@Test public void testReadySavedRoom(@Mocked RoomMediator room) throws DecodeException { ClientMediator mediator = new ClientMediator(nexus, drain, userId, signedJwt); String msgTxt = "ready,{\"roomId\": \"roomId\",\"bookmark\": \"id\"}"; RoutedMessage message = new RoutedMessage(msgTxt); System.out.println(message); new Expectations() {{ nexus.join(mediator, roomId, "id"); }}; mediator.ready(message); new Verifications() {{ nexus.join(mediator, roomId, "id"); times = 1; drain.send((RoutedMessage) any); times = 0; }}; }
@Override public WebSocketMessage decode(ByteBuffer buffer) throws DecodeException { try { MessageProtos.Message decMsg = MessageProtos.Message.parseFrom(buffer.array()); WebSocketMessage msg = new WebSocketMessage() .withEvent(decMsg.getEvent()) .withChannel(decMsg.getChannel()) .withFrom(decMsg.getFrom()) .withId(decMsg.getId()) .withPayload(decMsg.getData().toByteArray()); return msg; } catch (IOException e) { throw new DecodeException(buffer, "Error parsing buffer.", e); } }
@Test public void shouldParseBasicObject() throws DecodeException { // given String validJson = "{'from' : 'Alice',"// + "'to' : 'Bob',"// + "'signal' : 'join',"// + "'content' : 'something'}"; // when Message result = decoder.decode(validJson); // then assertNotNull(result); assertThat(result.getFrom(), is("Alice")); assertThat(result.getTo(), is("Bob")); assertThat(result.getSignal(), is("join")); assertThat(result.getContent(), is("something")); }
@Test public void shouldParseAlmostEmptyObject() throws DecodeException { // given String validJson = "{'signal' : 'join',"// + "'content' : 'something'}"; // when Message result = decoder.decode(validJson); // then assertNotNull(result); assertThat(result.getFrom(), is(EMPTY)); assertThat(result.getTo(), is(EMPTY)); assertThat(result.getSignal(), is("join")); assertThat(result.getContent(), is("something")); }
@Test public void shouldParseRequestWithDoubleQuotes() throws DecodeException { // given String validJson = "{'from' : 'Alice',"// + "'to' : 'Bob',"// + "'signal' : 'join',"// + "'content' : 'something',"// + "'parameters' : {'param1' : 'value1'}}".replace("'", "\""); // when Message result = decoder.decode(validJson); // then assertNotNull(result); assertThat(result.getFrom(), is("Alice")); assertThat(result.getTo(), is("Bob")); assertThat(result.getSignal(), is("join")); assertThat(result.getContent(), is("something")); }
@Override public Message decode(String string) throws DecodeException { Message msg = null; if (willDecode(string)) { switch (messageMap.get("type")) { case "join": msg = new JoinMessage(messageMap.get("name")); break; case "chat": msg = new ChatMessage(messageMap.get("name"), messageMap.get("target"), messageMap.get("message")); } } else { throw new DecodeException(string, "[Message] Can't decode."); } return msg; }
private static Object[] buildArgs(PojoPathParam[] pathParams, Map<String,String> pathParameters, Session session, EndpointConfig config, Throwable throwable, CloseReason closeReason) throws DecodeException { Object[] result = new Object[pathParams.length]; for (int i = 0; i < pathParams.length; i++) { Class<?> type = pathParams[i].getType(); if (type.equals(Session.class)) { result[i] = session; } else if (type.equals(EndpointConfig.class)) { result[i] = config; } else if (type.equals(Throwable.class)) { result[i] = throwable; } else if (type.equals(CloseReason.class)) { result[i] = closeReason; } else { String name = pathParams[i].getName(); String value = pathParameters.get(name); try { result[i] = Util.coerceToType(type, value); } catch (Exception e) { throw new DecodeException(value, sm.getString( "pojoMethodMapping.decodePathParamFail", value, type), e); } } } return result; }
@Override public MsgByte decode(ByteBuffer bb) throws DecodeException { MsgByte result = new MsgByte(); byte[] data = new byte[bb.limit() - bb.position()]; bb.get(data); result.setData(data); return result; }
@Override public List<String> decode(String str) throws DecodeException { List<String> lst = new ArrayList<String>(1); str = str.substring(1,str.length()-1); String[] strings = str.split(","); for (String t : strings){ lst.add(t); } return lst; }
public Message decode(String incomingMessage) throws DecodeException { System.out.println("\n=============== Check the received string from client ===============\n" + incomingMessage + "\n---------------------------------------------------"); Message message = new Message().setJson(incomingMessage); // message.setJson(incommingMessage); return message; }
@Override public JsonType decode(ByteBuffer bytes) throws DecodeException { try { return objectMapper.readValue(bytes.array(), JsonType.class); } catch (IOException e) { throw new DecodeException(bytes, "Could not parse input string. Expected a Json message.", e); } }
@Override public MeetupRSVP decode(String s) throws DecodeException { MeetupRSVP meetupRSVP = null; try { meetupRSVP = mapper.readValue(s, MeetupRSVP.class); } catch (IOException ex) { Logger.getLogger(MeetupRSVPJSONDecoder.class.getName()).log(Level.SEVERE, null, ex); } return meetupRSVP; }
@Override public Frame decode(ByteBuffer bytes) throws DecodeException { try { return from(bytes); } catch (IOException | AssertionError e) { throw new DecodeException(bytes, e.getMessage(), e); } }
@Override public Frame decode(String s) throws DecodeException { try { return from(UTF_8.encode(s)); } catch (IOException | AssertionError e) { throw new DecodeException(s, "Unable to decode. \"" + s + "\" : " + e.getMessage(), e); } }
@Test public void decode_byteBuffer() throws DecodeException, IOException { final String input = "MESSAGE\ndestination:wonderland\nsubscription:a\ncontent-length:4\n\nbody\u0000"; final Frame frame; try (InputStream is = new ByteArrayInputStream(input.getBytes())) { frame = binary.decode(ByteBuffer.wrap(input.getBytes(UTF_8))); } assertEquals(Command.MESSAGE, frame.command()); }
@Test public void from_byteBuffer_leadingEoL() throws IOException, DecodeException { final String input = "\nMESSAGE\ndestination:wonderland\nsubscription:a\ncontent-length:4\n\nbody\u0000"; final Frame frame; try (InputStream is = new ByteArrayInputStream(input.getBytes())) { frame = Encoding.from(ByteBuffer.wrap(input.getBytes(UTF_8))); } assertEquals(Command.MESSAGE, frame.command()); assertEquals(4, frame.headers().size()); }
@Test public void Encoding_windowsEoL() throws IOException, DecodeException { final String input = "MESSAGE\r\ndestination:wonderland\r\nsubscription:a\r\ncontent-length:4\r\n\r\nbody\u0000"; final Frame frame; try (InputStream is = new ByteArrayInputStream(input.getBytes())) { frame = Encoding.from(ByteBuffer.wrap(input.getBytes(UTF_8))); } assertEquals(Command.MESSAGE, frame.command()); assertEquals(4, frame.headers().size()); }