com.conwet.silbops.api.impl.XJSPSubEndpoint.java Source code

Java tutorial

Introduction

Here is the source code for com.conwet.silbops.api.impl.XJSPSubEndpoint.java

Source

package com.conwet.silbops.api.impl;

/*
 * #%L
 * SilboPS API - XJSP binding
 * %%
 * 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 java.io.IOException;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.conwet.silbops.api.AdvertiseListener;
import com.conwet.silbops.api.EndPointException;
import com.conwet.silbops.api.NotificationListener;
import com.conwet.silbops.api.SubEndpoint;
import com.conwet.silbops.model.Advertise;
import com.conwet.silbops.model.Context;
import com.conwet.silbops.model.ContextFunction;
import com.conwet.silbops.model.Subscription;
import com.conwet.silbops.model.MessageType;
import com.conwet.silbops.model.Notification;
import com.conwet.xjsp.features.Message;
import com.conwet.xjsp.features.Session;

/**
 *
 * @author sortega
 */
class XJSPSubEndpoint extends XJSPEndpoint implements SubEndpoint {

    private static final Logger logger = LoggerFactory.getLogger(XJSPSubEndpoint.class);
    private static String FEATURE_NAME = "silbops-subscriber";

    private Set<NotificationListener> notifListeners;
    private Set<AdvertiseListener> adverListeners;
    private Context context;

    XJSPSubEndpoint() {

        notifListeners = new CopyOnWriteArraySet<>();
        adverListeners = new CopyOnWriteArraySet<>();
        context = null;
    }

    @Override
    public String getFeatureName() {

        return FEATURE_NAME;
    }

    @Override
    public void subscribe(Subscription subscription, ContextFunction func) throws EndPointException {

        sendSubscription(MessageType.SUBSCRIBE, subscription, func);
    }

    @Override
    public void unsubscribe(Subscription subscription, ContextFunction func) throws EndPointException {

        sendSubscription(MessageType.UNSUBSCRIBE, subscription, func);
    }

    @SuppressWarnings("unchecked")
    private void sendSubscription(MessageType type, Subscription subscription, ContextFunction func)
            throws EndPointException {
        if (context == null) {

            setContext(new Context());
        }

        JSONObject payload = new JSONObject();
        subscription.setContextFunction(func);
        payload.put("subscription", subscription.toJSON());
        writeJSON(payload, type);
    }

    private void writeJSON(JSONObject payload, MessageType type) throws EndPointException {

        try {
            session.sendMessage(getFeatureName(), type.name(), payload);
        } catch (IOException ex) {
            throw new EndPointException(type + " failed", ex);
        }
    }

    private static <E> void addNotNull(Set<E> set, E elem) {

        set.add(Objects.requireNonNull(elem));
    }

    @Override
    @SuppressWarnings("unchecked")
    public void setContext(Context context) throws EndPointException {

        this.context = Objects.requireNonNull(context, "Context is null");

        JSONObject payload = new JSONObject();
        payload.put("context", context.toJSON());
        writeJSON(payload, MessageType.CONTEXT);
    }

    @Override
    public void addNotificationListener(NotificationListener listener) {

        addNotNull(notifListeners, listener);
    }

    @Override
    public void removeNotificationListener(NotificationListener listener) {

        notifListeners.remove(listener);
    }

    @Override
    public void addAdvertiseListener(AdvertiseListener listener) {

        addNotNull(adverListeners, listener);
    }

    @Override
    public void removeAdvertiseListener(AdvertiseListener listener) {

        adverListeners.remove(listener);
    }

    @Override
    public void handleMessage(Message message, Session session) throws Exception {

        JSONObject payload = (JSONObject) message.getPayload();
        MessageType type = MessageType.valueOf(message.getMessageType());

        switch (type) {

        case NOTIFY: {
            Notification not = Notification.fromJSON((JSONObject) payload.get("notification"));

            for (NotificationListener listener : notifListeners) {

                listener.receiveNotification(not);
            }
            break;
        }
        case ADVERTISE: {

            Advertise subscription = Advertise.fromJSON((JSONArray) payload.get("advertise"));

            for (AdvertiseListener listener : adverListeners) {

                listener.receiveAdvertise(subscription);
            }
            break;
        }
        case UNADVERTISE: {

            Advertise subscription = Advertise.fromJSON((JSONArray) payload.get("advertise"));

            for (AdvertiseListener listener : adverListeners) {

                listener.receiveUnadvertise(subscription);
            }
            break;
        }
        default:
            logger.warn("Unhandled message: {}", message);
        }
    }

    @Override
    public void close() {

        super.close();
        adverListeners.clear();
        notifListeners.clear();
    }
}