package se.hiq.jee7demo.chat;
import java.io.StringReader;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonReader;
import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
/**
* @author Jonas Heineson
*/
public class ObjectModelJsonEncoder implements Encoder.Text<ChatMessage>, Decoder.Text<ChatMessage> {
@Override
public String encode(ChatMessage chatMessage) throws EncodeException {
JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
return objectBuilder
.add("sender", chatMessage.getSender())
.add("message", chatMessage.getMessage())
.build().toString();
}
@Override
public void init(EndpointConfig endpointConfig) {
}
@Override
public void destroy() {
}
@Override
public ChatMessage decode(String s) throws DecodeException {
JsonReader jsonReader = Json.createReader(new StringReader(s));
JsonObject jsonObject = jsonReader.readObject();
return new ChatMessage(jsonObject.getString("sender"), jsonObject.getString("message"));
}
@Override
public boolean willDecode(String s) {
return true;
}
}