ru.schernolyas.websockettest.testproject.ws.EnvelopeDecoder.java Source code

Java tutorial

Introduction

Here is the source code for ru.schernolyas.websockettest.testproject.ws.EnvelopeDecoder.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.schernolyas.websockettest.testproject.ws;

import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import ru.schernolyas.websockettest.testproject.ws.dto.Envelope;

/**
 *
 * @author 
 */
public class EnvelopeDecoder implements Decoder.Text<Envelope> {

    @Override
    public Envelope decode(String jsonStr) throws DecodeException {
        Envelope env = new Envelope();
        JSONParser parser = new JSONParser();
        try {
            JSONObject jsonData = (JSONObject) parser.parse(jsonStr);
            env.setData(((JSONObject) jsonData.get("data")).toJSONString());
            env.setType((String) jsonData.get("type"));
            env.setSequenceId((String) jsonData.get("sequence_id"));
        } catch (ParseException pe) {
            throw new DecodeException(jsonStr, "Can not parse JSON", pe);
        }
        return env;
    }

    @Override
    public boolean willDecode(String s) {
        return s != null;
    }

    @Override
    public void init(EndpointConfig config) {

    }

    @Override
    public void destroy() {

    }

}