com.conwet.xjsp.features.MessageChannel.java Source code

Java tutorial

Introduction

Here is the source code for com.conwet.xjsp.features.MessageChannel.java

Source

package com.conwet.xjsp.features;

/*
 * #%L
 * eXtensible JSON Streaming Protocol
 * %%
 * Copyright (C) 2011 - 2014 CoNWeT Lab., Universidad Politcnica de Madrid
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * #L%
 */

import com.conwet.xjsp.XJSPConstants;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.StandardCharsets;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Wrapper on a communication channel for sending JSON messages or fragments
 * atomically.
 *
 * @author sortega
 */
public class MessageChannel {

    private static final Logger logger = LoggerFactory.getLogger(MessageChannel.class);

    private final WritableByteChannel channel;
    private long lastId;

    public MessageChannel(WritableByteChannel channel) {
        this.channel = channel;
        this.lastId = 0;
    }

    synchronized public void sendFragment(String fragment) throws IOException {
        ByteBuffer buffer = ByteBuffer.wrap(fragment.getBytes(StandardCharsets.UTF_8));

        try {
            while (buffer.hasRemaining()) {
                channel.write(buffer);
            }
        } catch (IOException ex) {
            logger.error("Closing connection on exception", ex);
            throw ex;
        }
    }

    synchronized public void sendMessage(String feature, String type, Object payload, FeatureMap fm)
            throws IOException {
        Message message = new ImmutableMessage(feature, type, payload, nextId());
        sendFragment(message.toJSONObject(fm).toJSONString());
    }

    @SuppressWarnings("unchecked")
    synchronized public void sendErrorMessage(Object payload) throws IOException {
        JSONObject message = new JSONObject();
        message.put("id", nextId());
        message.put("type", XJSPConstants.XJSP_PREFIX + ":error");
        message.put("message", payload);
        sendFragment(message.toJSONString());
    }

    @SuppressWarnings("unchecked")
    synchronized public void sendErrorMessage(int errorCode, String errorMessage, String sourceId)
            throws IOException {
        JSONObject payload = new JSONObject();
        payload.put("code", errorCode);
        payload.put("message", errorMessage);
        payload.put("id", sourceId);
        sendErrorMessage(payload);
    }

    synchronized public void close() {
        try {
            channel.close();
        } catch (IOException ex) {
            logger.error("Unexpected exception", ex);
        }
    }

    /**
     * @return the next message identifier.
     */
    private String nextId() {
        return Long.toString(++this.lastId);
    }
}