package se.hiq.jee7demo.chat;
import java.io.StringReader;
import java.io.StringWriter;
import javax.json.Json;
import javax.json.stream.JsonGenerator;
import javax.json.stream.JsonParser;
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 StreamingJsonEncoder implements Encoder.Text<ChatMessage>, Decoder.Text<ChatMessage> {
@Override
public String encode(ChatMessage chatMessage) throws EncodeException {
StringWriter stringWriter = new StringWriter();
JsonGenerator generator = Json.createGenerator(stringWriter);
generator
.writeStartObject()
.write("sender", chatMessage.getSender())
.write("message", chatMessage.getMessage())
.writeEnd();
generator.close();
return stringWriter.toString();
}
@Override
public void init(EndpointConfig endpointConfig) {
}
@Override
public void destroy() {
}
@Override
public ChatMessage decode(String s) throws DecodeException {
String sender = "";
String message = "";
JsonParser jsonParser = Json.createParser(new StringReader(s));
while (jsonParser.hasNext()) {
JsonParser.Event event = jsonParser.next();
if(event == JsonParser.Event.KEY_NAME && "sender".equals(jsonParser.getString())) {
jsonParser.next(); // Move to next event, which is VALUE_STRING
sender = jsonParser.getString();
}
if(event == JsonParser.Event.KEY_NAME && "message".equals(jsonParser.getString())) {
jsonParser.next();
message = jsonParser.getString();
}
}
return new ChatMessage(sender, message);
}
@Override
public boolean willDecode(String s) {
return true;
}
}