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

com.swardana.oomsg.tools.Operator Maven / Gradle / Ivy

The newest version!
package com.swardana.oomsg.tools;

import com.swardana.oomsg.Mediator;
import com.swardana.oomsg.Subscriber;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * An operator who managing the communication.
 *
 * @author Sukma Wardana
 * @version 1.0
 * @since 1.0
 */
public class Operator implements Mediator {

	private static final System.Logger LOG = System.getLogger(Operator.class.getName());

	private final Map> observers = new HashMap<>();

	@Override
	public final void subscribe(final String topic, final Subscriber subscriber) {
		if (this.isNewTopic(topic)) {
			this.observers.put(topic, new CopyOnWriteArraySet<>());
		}
		Set subscribers = this.observers.get(topic);
		if (subscribers.contains(subscriber)) {
			LOG.log(
				System.Logger.Level.WARNING,
				"Subscribe the subscriber [{0}] for the topic [{1}], "
					+ "but the same subscriber was already added "
					+ "for this topic in the past.",
				subscriber, topic);
		}
		subscribers.add(subscriber);

	}

	@Override
	public final void unsubscribe(final String topic, final Subscriber subscriber) {
		if (doesTopicExist(topic)) {
			Set subscribers = this.observers.get(topic);
			subscribers.removeIf(sbr -> sbr.equals(subscriber));
			if (subscribers.isEmpty()) {
				this.observers.remove(topic);
			}
		}
	}

	@Override
	public final void publish(final String topic, final Object[] messages) {
		Collection subscribers = this.observers.get(topic);
		if (Objects.nonNull(subscribers)) {
			for (final Subscriber subscriber : subscribers) {
				subscriber.receive(topic, messages);
			}
		}
	}

	@Override
	public final void clear() {
		this.observers.clear();
	}

	private boolean isNewTopic(final String topic) {
		return !this.doesTopicExist(topic);
	}

	private boolean doesTopicExist(final String topic) {
		return this.observers.containsKey(topic);
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy