Package se.hiq.jee7demo.chat

Source Code of se.hiq.jee7demo.chat.ObjectModelJsonEncoder

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

Related Classes of se.hiq.jee7demo.chat.ObjectModelJsonEncoder

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.