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

it.netgrid.bauer.impl.MqttTopicFactory Maven / Gradle / Ivy

Go to download

A Bauer binder for MQTT supporting also $share and $retain topics. It is based on the PAHO MQTT library.

The newest version!
package it.netgrid.bauer.impl;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;

import it.netgrid.bauer.ITopicFactory;
import it.netgrid.bauer.Topic;

public class MqttTopicFactory implements ITopicFactory {

    private static final Logger log = LoggerFactory.getLogger(MqttTopicFactory.class);

    private final MqttClientManager manager;
    private final MqttMessageFactory messageFactory;

    private final Map> topics;

    @Inject
    public MqttTopicFactory(MqttClientManager manager, MqttMessageFactory messageFactory) {
        this.topics = new HashMap<>();
        this.messageFactory = messageFactory;
        this.manager = manager;
        this.manager.safeFirstConnection();
    }

    @Override
    @SuppressWarnings("unchecked")
    public  Topic getTopic(String name) {
        if (!topics.containsKey(name)) {
            MqttTopic topic = new MqttTopic(this.messageFactory, this.manager, name, this.mqttPatternFrom(name), this.isSharedTopic(name),
                    this.isRetainedTopic(name));
            topics.put(name, topic);
        } else {
            log.debug(String.format("Topic %s already exists", name));
        }

        return (Topic) topics.get(name);
    }

    public String mqttPatternFrom(String name) {
        String retainPrefix = MqttTopic.RETAIN_MESSAGES_PREFIX + MqttTopic.PATH_SEPARATOR;
        if (name.startsWith(retainPrefix)) {
            return name.substring(retainPrefix.length());
        }

        String sharedPrefix = MqttTopic.SHARED_SUBSCRIPTION_PREFIX + MqttTopic.PATH_SEPARATOR;
        if (name.startsWith(sharedPrefix)) {
            String[] parts = name.split(MqttTopic.PATH_SEPARATOR, 3);
            return parts[parts.length - 1];
        }

        return name;
    }

    public boolean isRetainedTopic(String name) {
        return name != null && name.startsWith(MqttTopic.RETAIN_MESSAGES_PREFIX + MqttTopic.PATH_SEPARATOR);
    }

    public boolean isSharedTopic(String name) {
        return name != null && name.startsWith(MqttTopic.SHARED_SUBSCRIPTION_PREFIX + MqttTopic.PATH_SEPARATOR);
    }

    public int activeTopics() {
        return this.topics.keySet().size();
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy