javax.websocket.DecodeException Java Examples

The following examples show how to use javax.websocket.DecodeException. 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: PojoMessageHandlerWholeBinary.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@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;
}
 
Example #2
Source File: ConvertingEncoderDecoderSupport.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Decode the a message into an object.
 * @see javax.websocket.Decoder.Text#decode(String)
 * @see javax.websocket.Decoder.Binary#decode(ByteBuffer)
 */
@SuppressWarnings("unchecked")
@Nullable
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;
	}
}
 
Example #3
Source File: Encoding.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
public Object decodeBinary(final Class<?> targetType, final byte[] bytes) throws DecodeException {
    List<InstanceHandle<? extends Decoder>> decoders = binaryDecoders.get(targetType);
    if (decoders != null) {
        for (InstanceHandle<? extends Decoder> decoderHandle : decoders) {
            Decoder decoder = decoderHandle.getInstance();
            if (decoder instanceof Decoder.Binary) {
                if (((Decoder.Binary) decoder).willDecode(ByteBuffer.wrap(bytes))) {
                    return ((Decoder.Binary) decoder).decode(ByteBuffer.wrap(bytes));
                }
            } else {
                try {
                    return ((Decoder.BinaryStream) decoder).decode(new ByteArrayInputStream(bytes));
                } catch (IOException e) {
                    throw new DecodeException(ByteBuffer.wrap(bytes), "Could not decode binary", e);
                }
            }
        }
    }
    throw new DecodeException(ByteBuffer.wrap(bytes), "Could not decode binary");
}
 
Example #4
Source File: Encoding.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
private Object decodePrimitive(final Class<?> targetType, final String message) throws DecodeException {
    if (targetType == Boolean.class || targetType == boolean.class) {
        return Boolean.valueOf(message);
    } else if (targetType == Character.class || targetType == char.class) {
        return message.charAt(0);
    } else if (targetType == Byte.class || targetType == byte.class) {
        return Byte.valueOf(message);
    } else if (targetType == Short.class || targetType == short.class) {
        return Short.valueOf(message);
    } else if (targetType == Integer.class || targetType == int.class) {
        return Integer.valueOf(message);
    } else if (targetType == Long.class || targetType == long.class) {
        return Long.valueOf(message);
    } else if (targetType == Float.class || targetType == float.class) {
        return Float.valueOf(message);
    } else if (targetType == Double.class || targetType == double.class) {
        return Double.valueOf(message);
    }
    return null; // impossible
}
 
Example #5
Source File: Encoding.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
public Object decodeText(final Class<?> targetType, final String message) throws DecodeException {
    if (EncodingFactory.isPrimitiveOrBoxed(targetType)) {
        return decodePrimitive(targetType, message);
    }
    List<InstanceHandle<? extends Decoder>> decoders = textDecoders.get(targetType);
    if (decoders != null) {
        for (InstanceHandle<? extends Decoder> decoderHandle : decoders) {
            Decoder decoder = decoderHandle.getInstance();
            if (decoder instanceof Decoder.Text) {
                if (((Decoder.Text) decoder).willDecode(message)) {
                    return ((Decoder.Text) decoder).decode(message);
                }
            } else {
                try {
                    return ((Decoder.TextStream) decoder).decode(new StringReader(message));
                } catch (IOException e) {
                    throw new DecodeException(message, "Could not decode string", e);
                }
            }
        }
    }
    throw new DecodeException(message, "Could not decode string");
}
 
Example #6
Source File: PojoMessageHandlerWholeText.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #7
Source File: PojoMessageHandlerWholeBinary.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #8
Source File: ConvertingEncoderDecoderSupport.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Decode the a message into an object.
 * @see javax.websocket.Decoder.Text#decode(String)
 * @see javax.websocket.Decoder.Binary#decode(ByteBuffer)
 */
@SuppressWarnings("unchecked")
@Nullable
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;
	}
}
 
Example #9
Source File: JsonQueryMessageDecoder.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Override
public QueryMessage decode(String s) throws DecodeException {
    MultivaluedMapImpl<String,String> map = new MultivaluedMapImpl<>();
    try (JsonParser parser = Json.createParser(new StringReader(s))) {
        while (parser.hasNext()) {
            if (parser.next() == JsonParser.Event.KEY_NAME) {
                String key = parser.getString();
                addValueToMap(key, parser, map);
            }
        }
    }
    if (map.size() == 1 && map.containsKey("cancel"))
        return new CancelMessage();
    else
        return new CreateQueryMessage(map);
}
 
Example #10
Source File: PojoMessageHandlerWholeBinary.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #11
Source File: PojoMessageHandlerWholeText.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #12
Source File: ConvertingEncoderDecoderSupport.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * @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;
	}
}
 
Example #13
Source File: PojoMessageHandlerWholeText.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@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;
}
 
Example #14
Source File: PojoMethodMapping.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #15
Source File: ChatMessageDecoder.java    From training with MIT License 5 votes vote down vote up
@Override
public ChatMessage decode(final String textMessage) throws DecodeException {
	ChatMessage chatMessage = new ChatMessage();
	JsonObject obj = Json.createReader(new StringReader(textMessage))
			.readObject();
	chatMessage.setMessage(obj.getString("message"));
	chatMessage.setSender(obj.getString("sender"));
	chatMessage.setReceived(new Date());
	return chatMessage;
}
 
Example #16
Source File: WS2RESTAdapter.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void onError(Exception error) {
    LOG.error(error.getMessage(), error);
    if (error instanceof DecodeException || error instanceof EncodeException) {
        try {
            connection.close(VIOLATED_POLICY.getCode(), error.getMessage());
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }
}
 
Example #17
Source File: WSConnectionImpl.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void onError(Session session, Throwable thr) {
    if (thr instanceof DecodeException) {
        for (WSMessageReceiver receiver : messageReceivers) {
            receiver.onError((DecodeException)thr);
        }
    }
    super.onError(session, thr);
}
 
Example #18
Source File: MessageDecoder.java    From javaee7-websocket with MIT License 5 votes vote down vote up
@Override
public BetMessage decode(String string) throws DecodeException {
    BetMessage msg = null;
    if (willDecode(string)) {
        switch (messageMap.get("type")) {
            case "betMatchWinner":
                msg = new BetMessage(messageMap.get("name"));
                break;
        }
    } else {
        throw new DecodeException(string, "[Message] Can't decode.");
    }
    return msg;
}
 
Example #19
Source File: GsonProxyMessageDecoder.java    From devicehive-java-server with Apache License 2.0 5 votes vote down vote up
@Override
public List<ProxyMessage> decode(String s) throws DecodeException {
    JsonElement object = parser.parse(s);
    if (object instanceof JsonArray) {
        List<ProxyMessage> list = new ArrayList<>();
        object.getAsJsonArray().forEach(elem -> list.add(buildMessage(elem.getAsJsonObject())));
        return list;
    }
    if (object instanceof JsonObject) {
        return Collections.singletonList(buildMessage(object.getAsJsonObject()));
    }
    throw new JsonParseException(String.format("Cannot deserialize ProxyMessage from '%s'", s));
}
 
Example #20
Source File: Message.java    From jetty-web-sockets-jsr356 with Apache License 2.0 5 votes vote down vote up
@Override
public Message decode( final String str ) throws DecodeException {
	final Message message = new Message();
	
	try( final JsonReader reader = factory.createReader( new StringReader( str ) ) ) {
		final JsonObject json = reader.readObject();
		message.setUsername( json.getString( "username" ) );
		message.setMessage( json.getString( "message" ) );
	}
	
	return message;
}
 
Example #21
Source File: MessageDecoder.java    From diirt with MIT License 5 votes vote down vote up
@Override
public Message decode(Reader reader) throws DecodeException, IOException {
    JsonReader jReader = Json.createReader(reader);
    JsonObject jObject = jReader.readObject();
    String messageType = jObject.getString("message", null);
    switch (messageType) {
        case "subscribe":
            return new MessageSubscribe(jObject);
        case "write":
            return new MessageWrite(jObject);
        case "pause":
            return new MessagePause(jObject);
        case "resume":
            return new MessageResume(jObject);
        case "unsubscribe":
            return new MessageUnsubscribe(jObject);
        case "event":
            String eventType = jObject.getString("type");
            switch(eventType) {
                case "connection":
                    return new MessageConnectionEvent(jObject);
                case "value":
                    return new MessageValueEvent(jObject);
                case "writeCompleted":
                    return new MessageWriteCompletedEvent(jObject);
                case "error":
                    return new MessageErrorEvent(jObject);
                default:
                    throw new DecodeException("", "Event " + eventType + " is not supported");
            }
        default:
            throw MessageDecodeException.unsupportedMessage(jObject);
    }
}
 
Example #22
Source File: MessageDecoder.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
/**
 * Decode the given String into an AEL Message object.
 *
 * @param string string to be decoded.
 * @return the decoded message as an Message object.
 */
@Override
public Message decode( String string ) throws DecodeException {
  try {
    byte[] data = EncodeUtil.decodeBase64Zipped( string );
    InputStream is = new ByteArrayInputStream( data );
    ObjectInputStream ois = new ObjectInputStream( is );
    Object o = ois.readObject();
    ois.close();
    return (Message) o;
  } catch ( Exception e ) {
    throw new RuntimeException( "Unexpected error trying to decode object.", e );
  }
}
 
Example #23
Source File: ServerContainerInitializeListener.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public RestInputMessage decode(String s) throws DecodeException {
    try {
        return jsonMessageConverter.fromString(s, RestInputMessage.class);
    } catch (JsonException e) {
        throw new DecodeException(s, e.getMessage(), e);
    }
}
 
Example #24
Source File: TestEncodingDecoding.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #25
Source File: ConvertingEncoderDecoderSupportTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void decodeFromBinaryCannotConvert() throws Exception {
	setup(NoConvertersConfig.class);
	Decoder.Binary<MyType> decoder = new MyBinaryDecoder();
	assertThat(decoder.willDecode(CONVERTED_BYTES), is(false));
	thown.expect(DecodeException.class);
	thown.expectCause(isA(ConverterNotFoundException.class));
	decoder.decode(CONVERTED_BYTES);
}
 
Example #26
Source File: TestEncodingDecoding.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #27
Source File: PojoMessageHandlerPartialBase.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public final void onMessage(T message, boolean last) {
    if (params.length == 1 && params[0] instanceof DecodeException) {
        ((WsSession) session).getLocal().onError(session,
                (DecodeException) params[0]);
        return;
    }
    Object[] parameters = params.clone();
    if (indexBoolean != -1) {
        parameters[indexBoolean] = Boolean.valueOf(last);
    }
    if (indexSession != -1) {
        parameters[indexSession] = session;
    }
    if (convert) {
        parameters[indexPayload] = ((ByteBuffer) message).array();
    } else {
        parameters[indexPayload] = message;
    }
    Object result = null;
    try {
        result = method.invoke(pojo, parameters);
    } catch (IllegalAccessException | InvocationTargetException e) {
        handlePojoMethodException(e);
    }
    processResult(result);
}
 
Example #28
Source File: TestEncodingDecoding.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #29
Source File: ConvertingEncoderDecoderSupportTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void decodeFromTextCannotConvert() throws Exception {
	setup(NoConvertersConfig.class);
	Decoder.Text<MyType> decoder = new MyTextDecoder();
	assertThat(decoder.willDecode(CONVERTED_TEXT), is(false));
	thown.expect(DecodeException.class);
	thown.expectCause(isA(ConverterNotFoundException.class));
	decoder.decode(CONVERTED_TEXT);
}
 
Example #30
Source File: Message.java    From sample-room-java with Apache License 2.0 5 votes vote down vote up
/**
 * Parse a string read from the WebSocket, and convert it into
 * a message
 * @param s String read from WebSocket
 * @throws DecodeException
 * @see MessageDecoder#decode(String)
 */
public Message(String s) throws DecodeException {
    // this is getting parsed in a low-level/raw way.
    // We don't split on commas arbitrarily: there are commas in the
    // json payload, which means unnecessary splitting and joining.
    ArrayList<String> list = new ArrayList<>(3);

    int brace = s.indexOf('{'); // first brace
    int i = 0;
    int j = s.indexOf(',');
    while (j > 0 && j < brace) {
        list.add(s.substring(i, j).trim());
        i = j + 1;
        j = s.indexOf(',', i);
    }

    if ( list.isEmpty() ) {
        // UMMM. Badness. Bad message. Bad!
        throw new DecodeException(s,
                "Badly formatted payload, unable to target and targetId: \"" + s + "\"");
    }

    // stash all of the rest in the data field.
    this.payload = s.substring(i).trim();

    // The flowTarget is always present.
    // The destination may or may not be present, but shouldn't return null.
    this.target = Target.valueOf(list.get(0));
    this.targetId = list.size() > 1 ? list.get(1) : "";
}