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

Java tutorial

Introduction

Here is the source code for ru.schernolyas.websockettest.testproject.ws.EnvelopeEncoder.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.EncodeException;
import javax.websocket.Encoder;
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 EnvelopeEncoder implements Encoder.Text<Envelope> {

    @Override
    public String encode(Envelope env) throws EncodeException {
        JSONObject obj = new JSONObject();
        obj.put("type", env.getType());
        obj.put("sequence_id", env.getSequenceId());
        JSONParser parser = new JSONParser();
        try {
            JSONObject jsonData = (JSONObject) parser.parse(env.getData());
            obj.put("data", jsonData.toJSONString());
        } catch (ParseException pe) {
            throw new EncodeException(env, "Can not parse JSON", pe);
        }

        return obj.toJSONString();
    }

    @Override
    public void init(EndpointConfig config) {

    }

    @Override
    public void destroy() {

    }

}