All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.firebus.adapters.http.websocket.SignalSubscriberWSHandler Maven / Gradle / Ivy

There is a newer version: 1.3.3
Show newest version
package io.firebus.adapters.http.websocket;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import io.firebus.Firebus;
import io.firebus.Payload;
import io.firebus.adapters.http.WebsocketHandler;
import io.firebus.information.ServiceInformation;
import io.firebus.interfaces.Consumer;
import io.firebus.utils.DataException;
import io.firebus.utils.DataMap;

public class SignalSubscriberWSHandler extends WebsocketHandler implements Consumer {

	protected Map> subscriptions;
	
	public SignalSubscriberWSHandler(DataMap c, Firebus f) {
		super(c, f);
		subscriptions = new HashMap>();
	}

	public ServiceInformation getServiceInformation() {
		return null;
	}

	protected void onOpen(String session, String token) {
		List list = new ArrayList();
		subscriptions.put(session, list);
	}

	protected void onStringMessage(String session, String msg) {
		try {
			DataMap req = new DataMap(msg);
			if(req.containsKey("subscribe")) {
				subscriptions.get(session).add(req.getString("subscribe"));
			} else if(req.containsKey("unsubscribe")) {
				String selector = req.getString("unsubscribe");
				if(selector.equals("*"))
					subscriptions.get(session).clear();
				else
					subscriptions.get(session).remove(selector);
			}
		} catch(DataException e) {
			//TODO: Handle this
		}
	}

	protected void onBinaryMessage(String session, byte[] msg) {
		
	}

	protected void onClose(String session) {
		subscriptions.remove(session);
	}

	public void consume(Payload payload) {
		String signal = payload.getString();
		Iterator it = subscriptions.keySet().iterator();
		while(it.hasNext()) {
			String session = it.next();
			List list = subscriptions.get(session);
			for(int i = 0; i < list.size(); i++)
				if(list.get(i).equals(signal))
					sendStringMessage(session, (new DataMap("signal", signal)).toString());
		}
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy