Added onMessageConsumed logic.

Related to:  https://github.com/andsel/moquette/issues/156
This commit is contained in:
Dee Eldredge
2016-03-23 23:09:16 +01:00
committed by andsel
parent 0b883d1f9a
commit f44283d5f0
9 changed files with 1043 additions and 982 deletions
@@ -1,41 +1,44 @@
/* /*
* Copyright (c) 2012-2015 The original author or authors * Copyright (c) 2012-2015 The original author or authors
* ------------------------------------------------------ * ------------------------------------------------------
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution. * and Apache License v2.0 which accompanies this distribution.
* *
* The Eclipse Public License is available at * The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html * http://www.eclipse.org/legal/epl-v10.html
* *
* The Apache License v2.0 is available at * The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php * http://www.opensource.org/licenses/apache2.0.php
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.interception; package io.moquette.interception;
import io.moquette.interception.messages.*; import io.moquette.interception.messages.*;
/** /**
* Basic abstract class usefull to avoid empty methods creation in subclasses. * Basic abstract class usefull to avoid empty methods creation in subclasses.
* *
* Created by andrea on 08/12/15. * Created by andrea on 08/12/15.
*/ */
public abstract class AbstractInterceptHandler implements InterceptHandler { public abstract class AbstractInterceptHandler implements InterceptHandler {
@Override @Override
public void onConnect(InterceptConnectMessage msg) {} public void onConnect(InterceptConnectMessage msg) {}
@Override @Override
public void onDisconnect(InterceptDisconnectMessage msg) {} public void onDisconnect(InterceptDisconnectMessage msg) {}
@Override @Override
public void onPublish(InterceptPublishMessage msg) {} public void onPublish(InterceptPublishMessage msg) {}
@Override @Override
public void onSubscribe(InterceptSubscribeMessage msg) {} public void onSubscribe(InterceptSubscribeMessage msg) {}
@Override @Override
public void onUnsubscribe(InterceptUnsubscribeMessage msg) {} public void onUnsubscribe(InterceptUnsubscribeMessage msg) {}
}
@Override
public void onMessageConsumed(InterceptConsumedMessage msg) {}
}
@@ -1,49 +1,52 @@
/* /*
* Copyright (c) 2012-2015 The original author or authors * Copyright (c) 2012-2015 The original author or authors
* ------------------------------------------------------ * ------------------------------------------------------
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution. * and Apache License v2.0 which accompanies this distribution.
* *
* The Eclipse Public License is available at * The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html * http://www.eclipse.org/legal/epl-v10.html
* *
* The Apache License v2.0 is available at * The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php * http://www.opensource.org/licenses/apache2.0.php
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.interception; package io.moquette.interception;
import io.moquette.parser.proto.messages.AbstractMessage; import io.moquette.parser.proto.messages.AbstractMessage;
import io.moquette.spi.impl.subscriptions.Subscription; import io.moquette.spi.impl.subscriptions.Subscription;
import io.moquette.interception.messages.InterceptConnectMessage; import io.moquette.interception.messages.InterceptConnectMessage;
import io.moquette.interception.messages.InterceptDisconnectMessage; import io.moquette.interception.messages.InterceptConsumedMessage;
import io.moquette.interception.messages.InterceptPublishMessage; import io.moquette.interception.messages.InterceptDisconnectMessage;
import io.moquette.interception.messages.InterceptSubscribeMessage; import io.moquette.interception.messages.InterceptPublishMessage;
import io.moquette.interception.messages.InterceptUnsubscribeMessage; import io.moquette.interception.messages.InterceptSubscribeMessage;
import io.moquette.interception.messages.InterceptUnsubscribeMessage;
/**
* This interface is used to inject code for intercepting broker events. /**
* <p> * This interface is used to inject code for intercepting broker events.
* The events can act only as observers. * <p>
* <p> * The events can act only as observers.
* Almost every method receives a subclass of {@link AbstractMessage}, except * <p>
* <code>onDisconnect</code> that receives the client id string and * Almost every method receives a subclass of {@link AbstractMessage}, except
* <code>onSubscribe</code> and <code>onUnsubscribe</code> that receive a * <code>onDisconnect</code> that receives the client id string and
* {@link Subscription} object. * <code>onSubscribe</code> and <code>onUnsubscribe</code> that receive a
* * {@link Subscription} object.
* @author Wagner Macedo *
*/ * @author Wagner Macedo
public interface InterceptHandler { */
public interface InterceptHandler {
void onConnect(InterceptConnectMessage msg);
void onConnect(InterceptConnectMessage msg);
void onDisconnect(InterceptDisconnectMessage msg);
void onDisconnect(InterceptDisconnectMessage msg);
void onPublish(InterceptPublishMessage msg);
void onPublish(InterceptPublishMessage msg);
void onSubscribe(InterceptSubscribeMessage msg);
void onSubscribe(InterceptSubscribeMessage msg);
void onUnsubscribe(InterceptUnsubscribeMessage msg);
} void onUnsubscribe(InterceptUnsubscribeMessage msg);
void onMessageConsumed(InterceptConsumedMessage msg);
}
@@ -1,47 +1,49 @@
/* /*
* Copyright (c) 2012-2015 The original author or authors * Copyright (c) 2012-2015 The original author or authors
* ------------------------------------------------------ * ------------------------------------------------------
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution. * and Apache License v2.0 which accompanies this distribution.
* *
* The Eclipse Public License is available at * The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html * http://www.eclipse.org/legal/epl-v10.html
* *
* The Apache License v2.0 is available at * The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php * http://www.opensource.org/licenses/apache2.0.php
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.interception; package io.moquette.interception;
import io.moquette.parser.proto.messages.ConnectMessage; import io.moquette.interception.messages.InterceptConsumedMessage;
import io.moquette.parser.proto.messages.PublishMessage; import io.moquette.parser.proto.messages.ConnectMessage;
import io.moquette.spi.impl.subscriptions.Subscription; import io.moquette.parser.proto.messages.PublishMessage;
import io.moquette.spi.impl.subscriptions.Subscription;
/**
* This interface is to be used internally by the broker components. /**
* <p> * This interface is to be used internally by the broker components.
* An interface is used instead of a class to allow more flexibility in changing * <p>
* an implementation. * An interface is used instead of a class to allow more flexibility in changing
* <p> * an implementation.
* Interceptor implementations forward notifications to a <code>InterceptHandler</code>, * <p>
* that is normally a field. So, the implementations should act as a proxy to a custom * Interceptor implementations forward notifications to a <code>InterceptHandler</code>,
* intercept handler. * that is normally a field. So, the implementations should act as a proxy to a custom
* * intercept handler.
* @see InterceptHandler *
* @author Wagner Macedo * @see InterceptHandler
*/ * @author Wagner Macedo
public interface Interceptor { */
public interface Interceptor {
void notifyClientConnected(ConnectMessage msg);
void notifyClientConnected(ConnectMessage msg);
void notifyClientDisconnected(String clientID);
void notifyClientDisconnected(String clientID);
void notifyTopicPublished(PublishMessage msg, String clientID);
void notifyTopicPublished(PublishMessage msg, String clientID);
void notifyTopicSubscribed(Subscription sub);
void notifyTopicSubscribed(Subscription sub);
void notifyTopicUnsubscribed(String topic, String clientID);
void notifyTopicUnsubscribed(String topic, String clientID);
}
void notifyMessageConsumed(InterceptConsumedMessage msg);
}
@@ -0,0 +1,15 @@
package io.moquette.interception.messages;
import static io.moquette.spi.IMessagesStore.StoredMessage;
public class InterceptConsumedMessage {
final private StoredMessage msg;
public InterceptConsumedMessage( final StoredMessage msg) {
this.msg = msg;
}
public StoredMessage getMsg() {
return msg;
}
}
@@ -1,141 +1,144 @@
/* /*
* Copyright (c) 2012-2015 The original author or authors * Copyright (c) 2012-2015 The original author or authors
* ------------------------------------------------------ * ------------------------------------------------------
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution. * and Apache License v2.0 which accompanies this distribution.
* *
* The Eclipse Public License is available at * The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html * http://www.eclipse.org/legal/epl-v10.html
* *
* The Apache License v2.0 is available at * The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php * http://www.opensource.org/licenses/apache2.0.php
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi; package io.moquette.spi;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import io.moquette.spi.impl.subscriptions.Subscription; import io.moquette.spi.IMessagesStore.StoredMessage;
import io.moquette.spi.impl.subscriptions.Subscription;
/**
* Store used to handle the persistence of the subscriptions tree. /**
* * Store used to handle the persistence of the subscriptions tree.
* @author andrea *
*/ * @author andrea
public interface ISessionsStore { */
public interface ISessionsStore {
void updateCleanStatus(String clientID, boolean cleanSession);
void updateCleanStatus(String clientID, boolean cleanSession);
class ClientTopicCouple {
public final String topicFilter; class ClientTopicCouple {
public final String clientID; public final String topicFilter;
public final String clientID;
public ClientTopicCouple(String clientID, String topicFilter) {
this.clientID = clientID; public ClientTopicCouple(String clientID, String topicFilter) {
this.topicFilter = topicFilter; this.clientID = clientID;
} this.topicFilter = topicFilter;
}
@Override
public boolean equals(Object o) { @Override
if (this == o) return true; public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false; if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ClientTopicCouple that = (ClientTopicCouple) o;
ClientTopicCouple that = (ClientTopicCouple) o;
if (topicFilter != null ? !topicFilter.equals(that.topicFilter) : that.topicFilter != null) return false;
return !(clientID != null ? !clientID.equals(that.clientID) : that.clientID != null); if (topicFilter != null ? !topicFilter.equals(that.topicFilter) : that.topicFilter != null) return false;
} return !(clientID != null ? !clientID.equals(that.clientID) : that.clientID != null);
}
@Override
public int hashCode() { @Override
int result = topicFilter != null ? topicFilter.hashCode() : 0; public int hashCode() {
result = 31 * result + (clientID != null ? clientID.hashCode() : 0); int result = topicFilter != null ? topicFilter.hashCode() : 0;
return result; result = 31 * result + (clientID != null ? clientID.hashCode() : 0);
} return result;
}
@Override
public String toString() { @Override
return "ClientTopicCouple{" + public String toString() {
"topicFilter='" + topicFilter + '\'' + return "ClientTopicCouple{" +
", clientID='" + clientID + '\'' + "topicFilter='" + topicFilter + '\'' +
'}'; ", clientID='" + clientID + '\'' +
} '}';
}
}
}
void initStore();
void initStore();
/**
* Add a new subscription to the session /**
*/ * Add a new subscription to the session
void addNewSubscription(Subscription newSubscription); */
void addNewSubscription(Subscription newSubscription);
/**
* Removed a specific subscription /**
* */ * Removed a specific subscription
void removeSubscription(String topic, String clientID); * */
void removeSubscription(String topic, String clientID);
/**
* Remove all the subscriptions of the session /**
*/ * Remove all the subscriptions of the session
void wipeSubscriptions(String sessionID); */
void wipeSubscriptions(String sessionID);
/**
* Return all topic filters to recreate the subscription tree. /**
* */ * Return all topic filters to recreate the subscription tree.
List<ClientTopicCouple> listAllSubscriptions(); * */
List<ClientTopicCouple> listAllSubscriptions();
/**
* @return the subscription stored by clientID and topicFilter, if any else null; /**
* */ * @return the subscription stored by clientID and topicFilter, if any else null;
Subscription getSubscription(ClientTopicCouple couple); * */
Subscription getSubscription(ClientTopicCouple couple);
/**
* @return true iff there are subscriptions persisted with clientID /**
*/ * @return true iff there are subscriptions persisted with clientID
boolean contains(String clientID); */
boolean contains(String clientID);
ClientSession createNewSession(String clientID, boolean cleanSession);
ClientSession createNewSession(String clientID, boolean cleanSession);
/**
* @param clientID the client owning the session. /**
* @return the session for the given clientID, null if not found. * @param clientID the client owning the session.
* */ * @return the session for the given clientID, null if not found.
ClientSession sessionForClient(String clientID); * */
ClientSession sessionForClient(String clientID);
void inFlightAck(String clientID, int messageID);
void inFlightAck(String clientID, int messageID);
/**
* Save the binding messageID, clientID <-> guid /**
* */ * Save the binding messageID, clientID <-> guid
void inFlight(String clientID, int messageID, String guid); * */
void inFlight(String clientID, int messageID, String guid);
/**
* Return the next valid packetIdentifier for the given client session. /**
* */ * Return the next valid packetIdentifier for the given client session.
int nextPacketID(String clientID); * */
int nextPacketID(String clientID);
/**
* Store the guid to be later published. /**
* */ * Store the guid to be later published.
void bindToDeliver(String guid, String clientID); * */
void bindToDeliver(String guid, String clientID);
/**
* List the guids for retained messages for the session /**
* */ * List the guids for retained messages for the session
Collection<String> enqueued(String clientID); * */
Collection<String> enqueued(String clientID);
/**
* Remove form the queue of stored messages for session. /**
* */ * Remove form the queue of stored messages for session.
void removeEnqueued(String clientID, String guid); * */
void removeEnqueued(String clientID, String guid);
void secondPhaseAcknowledged(String clientID, int messageID);
void secondPhaseAcknowledged(String clientID, int messageID);
void secondPhaseAckWaiting(String clientID, int messageID);
void secondPhaseAckWaiting(String clientID, int messageID);
String mapToGuid(String clientID, int messageID);
} String mapToGuid(String clientID, int messageID);
public StoredMessage getInflightMessage(String clientID, int messageID);
}
@@ -1,109 +1,121 @@
/* /*
* Copyright (c) 2012-2015 The original author or authors * Copyright (c) 2012-2015 The original author or authors
* ------------------------------------------------------ * ------------------------------------------------------
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution. * and Apache License v2.0 which accompanies this distribution.
* *
* The Eclipse Public License is available at * The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html * http://www.eclipse.org/legal/epl-v10.html
* *
* The Apache License v2.0 is available at * The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php * http://www.opensource.org/licenses/apache2.0.php
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.impl; package io.moquette.spi.impl;
import io.moquette.interception.InterceptHandler; import io.moquette.interception.InterceptHandler;
import io.moquette.interception.Interceptor; import io.moquette.interception.Interceptor;
import io.moquette.interception.messages.*; import io.moquette.interception.messages.*;
import io.moquette.parser.proto.messages.ConnectMessage; import io.moquette.parser.proto.messages.ConnectMessage;
import io.moquette.spi.impl.subscriptions.Subscription; import io.moquette.spi.impl.subscriptions.Subscription;
import io.moquette.parser.proto.messages.PublishMessage; import io.moquette.parser.proto.messages.PublishMessage;
import java.util.List; import java.util.List;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
/** /**
* An interceptor that execute the interception tasks asynchronously. * An interceptor that execute the interception tasks asynchronously.
* *
* @author Wagner Macedo * @author Wagner Macedo
*/ */
final class BrokerInterceptor implements Interceptor { final class BrokerInterceptor implements Interceptor {
private final List<InterceptHandler> handlers; private final List<InterceptHandler> handlers;
private final ExecutorService executor; private final ExecutorService executor;
BrokerInterceptor(List<InterceptHandler> handlers) { BrokerInterceptor(List<InterceptHandler> handlers) {
this.handlers = handlers; this.handlers = handlers;
executor = Executors.newFixedThreadPool(1); executor = Executors.newFixedThreadPool(1);
} }
/** /**
* Shutdown graciously the executor service * Shutdown graciously the executor service
*/ */
void stop() { void stop() {
executor.shutdown(); executor.shutdown();
} }
@Override @Override
public void notifyClientConnected(final ConnectMessage msg) { public void notifyClientConnected(final ConnectMessage msg) {
for (final InterceptHandler handler : this.handlers) { for (final InterceptHandler handler : this.handlers) {
executor.execute(new Runnable() { executor.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
handler.onConnect(new InterceptConnectMessage(msg)); handler.onConnect(new InterceptConnectMessage(msg));
} }
}); });
} }
} }
@Override @Override
public void notifyClientDisconnected(final String clientID) { public void notifyClientDisconnected(final String clientID) {
for (final InterceptHandler handler : this.handlers) { for (final InterceptHandler handler : this.handlers) {
executor.execute(new Runnable() { executor.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
handler.onDisconnect(new InterceptDisconnectMessage(clientID)); handler.onDisconnect(new InterceptDisconnectMessage(clientID));
} }
}); });
} }
} }
@Override @Override
public void notifyTopicPublished(final PublishMessage msg, final String clientID) { public void notifyTopicPublished(final PublishMessage msg, final String clientID) {
for (final InterceptHandler handler : this.handlers) { for (final InterceptHandler handler : this.handlers) {
executor.execute(new Runnable() { executor.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
handler.onPublish(new InterceptPublishMessage(msg, clientID)); handler.onPublish(new InterceptPublishMessage(msg, clientID));
} }
}); });
} }
} }
@Override @Override
public void notifyTopicSubscribed(final Subscription sub) { public void notifyTopicSubscribed(final Subscription sub) {
for (final InterceptHandler handler : this.handlers) { for (final InterceptHandler handler : this.handlers) {
executor.execute(new Runnable() { executor.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
handler.onSubscribe(new InterceptSubscribeMessage(sub)); handler.onSubscribe(new InterceptSubscribeMessage(sub));
} }
}); });
} }
} }
@Override @Override
public void notifyTopicUnsubscribed(final String topic, final String clientID) { public void notifyTopicUnsubscribed(final String topic, final String clientID) {
for (final InterceptHandler handler : this.handlers) { for (final InterceptHandler handler : this.handlers) {
executor.execute(new Runnable() { executor.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
handler.onUnsubscribe(new InterceptUnsubscribeMessage(topic, clientID)); handler.onUnsubscribe(new InterceptUnsubscribeMessage(topic, clientID));
} }
}); });
} }
} }
}
@Override
public void notifyMessageConsumed( final InterceptConsumedMessage msg ) {
for (final InterceptHandler handler : this.handlers) {
executor.execute(new Runnable() {
@Override
public void run() {
handler.onMessageConsumed(msg);
}
});
}
}
}
@@ -1,240 +1,252 @@
/* /*
* Copyright (c) 2012-2015 The original author or authors * Copyright (c) 2012-2015 The original author or authors
* ------------------------------------------------------ * ------------------------------------------------------
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution. * and Apache License v2.0 which accompanies this distribution.
* *
* The Eclipse Public License is available at * The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html * http://www.eclipse.org/legal/epl-v10.html
* *
* The Apache License v2.0 is available at * The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php * http://www.opensource.org/licenses/apache2.0.php
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.persistence; package io.moquette.spi.persistence;
import io.moquette.spi.ClientSession; import io.moquette.spi.ClientSession;
import io.moquette.spi.IMessagesStore; import io.moquette.spi.IMessagesStore;
import io.moquette.spi.ISessionsStore; import io.moquette.spi.IMessagesStore.StoredMessage;
import io.moquette.spi.impl.Utils; import io.moquette.spi.ISessionsStore;
import io.moquette.spi.impl.subscriptions.Subscription; import io.moquette.spi.impl.Utils;
import io.moquette.spi.persistence.MapDBPersistentStore.PersistentSession; import io.moquette.spi.impl.subscriptions.Subscription;
import org.mapdb.DB; import io.moquette.spi.persistence.MapDBPersistentStore.PersistentSession;
import org.slf4j.Logger; import org.mapdb.DB;
import org.slf4j.LoggerFactory; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.ConcurrentMap; import java.util.*;
import java.util.concurrent.ConcurrentMap;
/**
* ISessionsStore implementation backed by MapDB. /**
* * ISessionsStore implementation backed by MapDB.
* @author andrea *
*/ * @author andrea
class MapDBSessionsStore implements ISessionsStore { */
class MapDBSessionsStore implements ISessionsStore {
private static final Logger LOG = LoggerFactory.getLogger(MapDBSessionsStore.class);
private static final Logger LOG = LoggerFactory.getLogger(MapDBSessionsStore.class);
//maps clientID->[MessageId -> guid]
private ConcurrentMap<String, Map<Integer, String>> m_inflightStore; //maps clientID->[MessageId -> guid]
//map clientID <-> set of currently in flight packet identifiers private ConcurrentMap<String, Map<Integer, String>> m_inflightStore;
private Map<String, Set<Integer>> m_inFlightIds; //map clientID <-> set of currently in flight packet identifiers
private ConcurrentMap<String, PersistentSession> m_persistentSessions; private Map<String, Set<Integer>> m_inFlightIds;
//maps clientID->[guid*], insertion order cares, it's queue private ConcurrentMap<String, PersistentSession> m_persistentSessions;
private ConcurrentMap<String, List<String>> m_enqueuedStore; //maps clientID->[guid*], insertion order cares, it's queue
//maps clientID->[messageID*] private ConcurrentMap<String, List<String>> m_enqueuedStore;
private ConcurrentMap<String, Set<Integer>> m_secondPhaseStore; //maps clientID->[messageID*]
private ConcurrentMap<String, Set<Integer>> m_secondPhaseStore;
private final DB m_db;
private final IMessagesStore m_messagesStore; private final DB m_db;
private final IMessagesStore m_messagesStore;
MapDBSessionsStore(DB db, IMessagesStore messagesStore) {
m_db = db; MapDBSessionsStore(DB db, IMessagesStore messagesStore) {
m_messagesStore = messagesStore; m_db = db;
} m_messagesStore = messagesStore;
}
@Override
public void initStore() { @Override
m_inflightStore = m_db.getHashMap("inflight"); public void initStore() {
m_inFlightIds = m_db.getHashMap("inflightPacketIDs"); m_inflightStore = m_db.getHashMap("inflight");
m_persistentSessions = m_db.getHashMap("sessions"); m_inFlightIds = m_db.getHashMap("inflightPacketIDs");
m_enqueuedStore = m_db.getHashMap("sessionQueue"); m_persistentSessions = m_db.getHashMap("sessions");
m_secondPhaseStore = m_db.getHashMap("secondPhase"); m_enqueuedStore = m_db.getHashMap("sessionQueue");
} m_secondPhaseStore = m_db.getHashMap("secondPhase");
}
@Override
public void addNewSubscription(Subscription newSubscription) { @Override
LOG.debug("addNewSubscription invoked with subscription {}", newSubscription); public void addNewSubscription(Subscription newSubscription) {
final String clientID = newSubscription.getClientId(); LOG.debug("addNewSubscription invoked with subscription {}", newSubscription);
m_db.getHashMap("subscriptions_" + clientID).put(newSubscription.getTopicFilter(), newSubscription); final String clientID = newSubscription.getClientId();
m_db.getHashMap("subscriptions_" + clientID).put(newSubscription.getTopicFilter(), newSubscription);
if (LOG.isTraceEnabled()) {
LOG.trace("subscriptions_{}: {}", clientID, m_db.getHashMap("subscriptions_" + clientID)); if (LOG.isTraceEnabled()) {
} LOG.trace("subscriptions_{}: {}", clientID, m_db.getHashMap("subscriptions_" + clientID));
} }
}
@Override
public void removeSubscription(String topicFilter, String clientID) { @Override
LOG.debug("removeSubscription topic filter: {} for clientID: {}", topicFilter, clientID); public void removeSubscription(String topicFilter, String clientID) {
if (!m_db.exists("subscriptions_" + clientID)) { LOG.debug("removeSubscription topic filter: {} for clientID: {}", topicFilter, clientID);
return; if (!m_db.exists("subscriptions_" + clientID)) {
} return;
m_db.getHashMap("subscriptions_" + clientID).remove(topicFilter); }
} m_db.getHashMap("subscriptions_" + clientID).remove(topicFilter);
}
@Override
public void wipeSubscriptions(String clientID) { @Override
LOG.debug("wipeSubscriptions"); public void wipeSubscriptions(String clientID) {
if (LOG.isTraceEnabled()) { LOG.debug("wipeSubscriptions");
LOG.trace("Subscription pre wipe: subscriptions_{}: {}", clientID, m_db.getHashMap("subscriptions_" + clientID)); if (LOG.isTraceEnabled()) {
} LOG.trace("Subscription pre wipe: subscriptions_{}: {}", clientID, m_db.getHashMap("subscriptions_" + clientID));
m_db.delete("subscriptions_" + clientID); }
if (LOG.isTraceEnabled()) { m_db.delete("subscriptions_" + clientID);
LOG.trace("Subscription post wipe: subscriptions_{}: {}", clientID, m_db.getHashMap("subscriptions_" + clientID)); if (LOG.isTraceEnabled()) {
} LOG.trace("Subscription post wipe: subscriptions_{}: {}", clientID, m_db.getHashMap("subscriptions_" + clientID));
} }
}
@Override
public List<ClientTopicCouple> listAllSubscriptions() { @Override
final List<ClientTopicCouple> allSubscriptions = new ArrayList<>(); public List<ClientTopicCouple> listAllSubscriptions() {
for (String clientID : m_persistentSessions.keySet()) { final List<ClientTopicCouple> allSubscriptions = new ArrayList<>();
ConcurrentMap<String, Subscription> clientSubscriptions = m_db.getHashMap("subscriptions_" + clientID); for (String clientID : m_persistentSessions.keySet()) {
for (String topicFilter : clientSubscriptions.keySet()) { ConcurrentMap<String, Subscription> clientSubscriptions = m_db.getHashMap("subscriptions_" + clientID);
allSubscriptions.add(new ClientTopicCouple(clientID, topicFilter)); for (String topicFilter : clientSubscriptions.keySet()) {
} allSubscriptions.add(new ClientTopicCouple(clientID, topicFilter));
} }
LOG.debug("retrieveAllSubscriptions returning subs {}", allSubscriptions); }
return allSubscriptions; LOG.debug("retrieveAllSubscriptions returning subs {}", allSubscriptions);
} return allSubscriptions;
}
@Override
public Subscription getSubscription(ClientTopicCouple couple) { @Override
ConcurrentMap<String, Subscription> clientSubscriptions = m_db.getHashMap("subscriptions_" + couple.clientID); public Subscription getSubscription(ClientTopicCouple couple) {
LOG.debug("subscriptions_{}: {}", couple.clientID, clientSubscriptions); ConcurrentMap<String, Subscription> clientSubscriptions = m_db.getHashMap("subscriptions_" + couple.clientID);
return clientSubscriptions.get(couple.topicFilter); LOG.debug("subscriptions_{}: {}", couple.clientID, clientSubscriptions);
} return clientSubscriptions.get(couple.topicFilter);
}
@Override
public boolean contains(String clientID) { @Override
return m_db.exists("subscriptions_" + clientID); public boolean contains(String clientID) {
} return m_db.exists("subscriptions_" + clientID);
}
@Override
public ClientSession createNewSession(String clientID, boolean cleanSession) { @Override
LOG.debug("createNewSession for client <{}> with clean flag <{}>", clientID, cleanSession); public ClientSession createNewSession(String clientID, boolean cleanSession) {
if (m_persistentSessions.containsKey(clientID)) { LOG.debug("createNewSession for client <{}> with clean flag <{}>", clientID, cleanSession);
LOG.error("already exists a session for client <{}>, bad condition", clientID); if (m_persistentSessions.containsKey(clientID)) {
throw new IllegalArgumentException("Can't create a session with the ID of an already existing" + clientID); LOG.error("already exists a session for client <{}>, bad condition", clientID);
} throw new IllegalArgumentException("Can't create a session with the ID of an already existing" + clientID);
LOG.debug("clientID {} is a newcome, creating it's empty subscriptions set", clientID); }
m_persistentSessions.putIfAbsent(clientID, new PersistentSession(cleanSession)); LOG.debug("clientID {} is a newcome, creating it's empty subscriptions set", clientID);
return new ClientSession(clientID, m_messagesStore, this, cleanSession); m_persistentSessions.putIfAbsent(clientID, new PersistentSession(cleanSession));
} return new ClientSession(clientID, m_messagesStore, this, cleanSession);
}
@Override
public ClientSession sessionForClient(String clientID) { @Override
if (!m_persistentSessions.containsKey(clientID)) { public ClientSession sessionForClient(String clientID) {
return null; if (!m_persistentSessions.containsKey(clientID)) {
} return null;
}
PersistentSession storedSession = m_persistentSessions.get(clientID);
return new ClientSession(clientID, m_messagesStore, this, storedSession.cleanSession); PersistentSession storedSession = m_persistentSessions.get(clientID);
} return new ClientSession(clientID, m_messagesStore, this, storedSession.cleanSession);
}
@Override
public void updateCleanStatus(String clientID, boolean cleanSession) { @Override
m_persistentSessions.put(clientID, new MapDBPersistentStore.PersistentSession(cleanSession)); public void updateCleanStatus(String clientID, boolean cleanSession) {
} m_persistentSessions.put(clientID, new MapDBPersistentStore.PersistentSession(cleanSession));
}
/**
* Return the next valid packetIdentifier for the given client session. /**
* */ * Return the next valid packetIdentifier for the given client session.
@Override * */
public int nextPacketID(String clientID) { @Override
Set<Integer> inFlightForClient = this.m_inFlightIds.get(clientID); public int nextPacketID(String clientID) {
if (inFlightForClient == null) { Set<Integer> inFlightForClient = this.m_inFlightIds.get(clientID);
int nextPacketId = 1; if (inFlightForClient == null) {
inFlightForClient = new HashSet<>(); int nextPacketId = 1;
inFlightForClient.add(nextPacketId); inFlightForClient = new HashSet<>();
this.m_inFlightIds.put(clientID, inFlightForClient); inFlightForClient.add(nextPacketId);
return nextPacketId; this.m_inFlightIds.put(clientID, inFlightForClient);
return nextPacketId;
}
}
int maxId = inFlightForClient.isEmpty() ? 0 : Collections.max(inFlightForClient);
int nextPacketId = (maxId + 1) % 0xFFFF; int maxId = inFlightForClient.isEmpty() ? 0 : Collections.max(inFlightForClient);
inFlightForClient.add(nextPacketId); int nextPacketId = (maxId + 1) % 0xFFFF;
return nextPacketId; inFlightForClient.add(nextPacketId);
} return nextPacketId;
}
@Override
public void inFlightAck(String clientID, int messageID) { @Override
Map<Integer, String> m = this.m_inflightStore.get(clientID); public void inFlightAck(String clientID, int messageID) {
if (m == null) { Map<Integer, String> m = this.m_inflightStore.get(clientID);
LOG.error("Can't find the inFlight record for client <{}>", clientID); if (m == null) {
return; LOG.error("Can't find the inFlight record for client <{}>", clientID);
} return;
m.remove(messageID); }
m.remove(messageID);
//remove from the ids store
Set<Integer> inFlightForClient = this.m_inFlightIds.get(clientID); //remove from the ids store
if (inFlightForClient != null) { Set<Integer> inFlightForClient = this.m_inFlightIds.get(clientID);
inFlightForClient.remove(messageID); if (inFlightForClient != null) {
} inFlightForClient.remove(messageID);
} }
}
@Override
public void inFlight(String clientID, int messageID, String guid) { @Override
Map<Integer, String> m = this.m_inflightStore.get(clientID); public void inFlight(String clientID, int messageID, String guid) {
if (m == null) { Map<Integer, String> m = this.m_inflightStore.get(clientID);
m = new HashMap<>(); if (m == null) {
} m = new HashMap<>();
m.put(messageID, guid); }
this.m_inflightStore.put(clientID, m); m.put(messageID, guid);
} this.m_inflightStore.put(clientID, m);
}
@Override
public void bindToDeliver(String guid, String clientID) { @Override
List<String> guids = Utils.defaultGet(m_enqueuedStore, clientID, new ArrayList<String>()); public void bindToDeliver(String guid, String clientID) {
guids.add(guid); List<String> guids = Utils.defaultGet(m_enqueuedStore, clientID, new ArrayList<String>());
m_enqueuedStore.put(clientID, guids); guids.add(guid);
} m_enqueuedStore.put(clientID, guids);
}
@Override
public Collection<String> enqueued(String clientID) { @Override
return Utils.defaultGet(m_enqueuedStore, clientID, new ArrayList<String>()); public Collection<String> enqueued(String clientID) {
} return Utils.defaultGet(m_enqueuedStore, clientID, new ArrayList<String>());
}
@Override
public void removeEnqueued(String clientID, String guid) { @Override
List<String> guids = Utils.defaultGet(m_enqueuedStore, clientID, new ArrayList<String>()); public void removeEnqueued(String clientID, String guid) {
guids.remove(guid); List<String> guids = Utils.defaultGet(m_enqueuedStore, clientID, new ArrayList<String>());
m_enqueuedStore.put(clientID, guids); guids.remove(guid);
} m_enqueuedStore.put(clientID, guids);
}
@Override
public void secondPhaseAcknowledged(String clientID, int messageID) { @Override
Set<Integer> messageIDs = Utils.defaultGet(m_secondPhaseStore, clientID, new HashSet<Integer>()); public void secondPhaseAcknowledged(String clientID, int messageID) {
messageIDs.remove(messageID); Set<Integer> messageIDs = Utils.defaultGet(m_secondPhaseStore, clientID, new HashSet<Integer>());
m_secondPhaseStore.put(clientID, messageIDs); messageIDs.remove(messageID);
} m_secondPhaseStore.put(clientID, messageIDs);
}
@Override
public void secondPhaseAckWaiting(String clientID, int messageID) { @Override
Set<Integer> messageIDs = Utils.defaultGet(m_secondPhaseStore, clientID, new HashSet<Integer>()); public void secondPhaseAckWaiting(String clientID, int messageID) {
messageIDs.add(messageID); Set<Integer> messageIDs = Utils.defaultGet(m_secondPhaseStore, clientID, new HashSet<Integer>());
m_secondPhaseStore.put(clientID, messageIDs); messageIDs.add(messageID);
} m_secondPhaseStore.put(clientID, messageIDs);
}
@Override
public String mapToGuid(String clientID, int messageID) { @Override
ConcurrentMap<Integer, String> messageIdToGuid = m_db.getHashMap(messageId2GuidsMapName(clientID)); public String mapToGuid(String clientID, int messageID) {
return messageIdToGuid.get(messageID); ConcurrentMap<Integer, String> messageIdToGuid = m_db.getHashMap(messageId2GuidsMapName(clientID));
} return messageIdToGuid.get(messageID);
}
static String messageId2GuidsMapName(String clientID) {
return "guidsMapping_" + clientID; static String messageId2GuidsMapName(String clientID) {
} return "guidsMapping_" + clientID;
} }
@Override
public StoredMessage getInflightMessage( String clientID, int messageID ) {
Map<Integer, String> clientEntries = m_inflightStore.get( clientID );
if( clientEntries == null )
return null;
String guid = clientEntries.get( messageID );
if( guid == null )
return null;
return m_messagesStore.getMessageByGuid( guid );
}
}
@@ -1,120 +1,125 @@
/* /*
* Copyright (c) 2012-2015 The original author or authors * Copyright (c) 2012-2015 The original author or authors
* ------------------------------------------------------ * ------------------------------------------------------
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution. * and Apache License v2.0 which accompanies this distribution.
* *
* The Eclipse Public License is available at * The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html * http://www.eclipse.org/legal/epl-v10.html
* *
* The Apache License v2.0 is available at * The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php * http://www.opensource.org/licenses/apache2.0.php
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.impl; package io.moquette.spi.impl;
import io.moquette.interception.messages.*; import io.moquette.interception.messages.*;
import io.moquette.parser.proto.messages.ConnectMessage; import io.moquette.parser.proto.messages.ConnectMessage;
import io.moquette.interception.InterceptHandler; import io.moquette.interception.InterceptHandler;
import io.moquette.parser.proto.messages.AbstractMessage; import io.moquette.parser.proto.messages.AbstractMessage;
import io.moquette.parser.proto.messages.PublishMessage; import io.moquette.parser.proto.messages.PublishMessage;
import io.moquette.spi.impl.subscriptions.Subscription; import io.moquette.spi.impl.subscriptions.Subscription;
import org.junit.AfterClass; import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import java.util.Arrays; import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.*; import static org.junit.Assert.*;
/** /**
* @author Wagner Macedo * @author Wagner Macedo
*/ */
public class BrokerInterceptorTest { public class BrokerInterceptorTest {
// value to check for changes after every notification // value to check for changes after every notification
private static final AtomicInteger n = new AtomicInteger(0); private static final AtomicInteger n = new AtomicInteger(0);
// Interceptor loaded with a custom InterceptHandler special for the tests // Interceptor loaded with a custom InterceptHandler special for the tests
private static final class MockObserver implements InterceptHandler { private static final class MockObserver implements InterceptHandler {
@Override @Override
public void onConnect(InterceptConnectMessage msg) { public void onConnect(InterceptConnectMessage msg) {
n.set(40); n.set(40);
} }
@Override @Override
public void onDisconnect(InterceptDisconnectMessage msg) { public void onDisconnect(InterceptDisconnectMessage msg) {
n.set(50); n.set(50);
} }
@Override @Override
public void onPublish(InterceptPublishMessage msg) { public void onPublish(InterceptPublishMessage msg) {
n.set(60); n.set(60);
} }
@Override @Override
public void onSubscribe(InterceptSubscribeMessage msg) { public void onSubscribe(InterceptSubscribeMessage msg) {
n.set(70); n.set(70);
} }
@Override @Override
public void onUnsubscribe(InterceptUnsubscribeMessage msg) { public void onUnsubscribe(InterceptUnsubscribeMessage msg) {
n.set(80); n.set(80);
} }
}
@Override
private static final BrokerInterceptor interceptor = new BrokerInterceptor(Arrays.<InterceptHandler>asList(new MockObserver())); public void onMessageConsumed( InterceptConsumedMessage msg ) {
n.set(90);
@BeforeClass }
public static void beforeAllTests() { }
// check if any of the handler methods was called before notifications
assertEquals(0, n.get()); private static final BrokerInterceptor interceptor = new BrokerInterceptor(Arrays.<InterceptHandler>asList(new MockObserver()));
}
@BeforeClass
@AfterClass public static void beforeAllTests() {
public static void afterAllTests() { // check if any of the handler methods was called before notifications
interceptor.stop(); assertEquals(0, n.get());
} }
/* Used to wait handler notification by the interceptor internal thread */ @AfterClass
private static void interval() throws InterruptedException { public static void afterAllTests() {
Thread.sleep(100); interceptor.stop();
} }
@Test /* Used to wait handler notification by the interceptor internal thread */
public void testNotifyClientConnected() throws Exception { private static void interval() throws InterruptedException {
interceptor.notifyClientConnected(new ConnectMessage()); Thread.sleep(100);
interval(); }
assertEquals(40, n.get());
} @Test
public void testNotifyClientConnected() throws Exception {
@Test interceptor.notifyClientConnected(new ConnectMessage());
public void testNotifyClientDisconnected() throws Exception { interval();
interceptor.notifyClientDisconnected("cli1234"); assertEquals(40, n.get());
interval(); }
assertEquals(50, n.get());
} @Test
public void testNotifyClientDisconnected() throws Exception {
@Test interceptor.notifyClientDisconnected("cli1234");
public void testNotifyTopicPublished() throws Exception { interval();
interceptor.notifyTopicPublished(new PublishMessage(), "cli1234"); assertEquals(50, n.get());
interval(); }
assertEquals(60, n.get());
} @Test
public void testNotifyTopicPublished() throws Exception {
@Test interceptor.notifyTopicPublished(new PublishMessage(), "cli1234");
public void testNotifyTopicSubscribed() throws Exception { interval();
interceptor.notifyTopicSubscribed(new Subscription("cli1", "o2", AbstractMessage.QOSType.MOST_ONE)); assertEquals(60, n.get());
interval(); }
assertEquals(70, n.get());
} @Test
public void testNotifyTopicSubscribed() throws Exception {
@Test interceptor.notifyTopicSubscribed(new Subscription("cli1", "o2", AbstractMessage.QOSType.MOST_ONE));
public void testNotifyTopicUnsubscribed() throws Exception { interval();
interceptor.notifyTopicUnsubscribed("o2", "cli1234"); assertEquals(70, n.get());
interval(); }
assertEquals(80, n.get());
} @Test
} public void testNotifyTopicUnsubscribed() throws Exception {
interceptor.notifyTopicUnsubscribed("o2", "cli1234");
interval();
assertEquals(80, n.get());
}
}
@@ -1,235 +1,241 @@
/* /*
* Copyright (c) 2012-2015 The original author or authors * Copyright (c) 2012-2015 The original author or authors
* ------------------------------------------------------ * ------------------------------------------------------
* All rights reserved. This program and the accompanying materials * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 * are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution. * and Apache License v2.0 which accompanies this distribution.
* *
* The Eclipse Public License is available at * The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html * http://www.eclipse.org/legal/epl-v10.html
* *
* The Apache License v2.0 is available at * The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php * http://www.opensource.org/licenses/apache2.0.php
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.persistence; package io.moquette.spi.persistence;
import io.moquette.spi.ClientSession; import io.moquette.spi.ClientSession;
import io.moquette.spi.IMessagesStore; import io.moquette.spi.IMessagesStore;
import io.moquette.spi.ISessionsStore; import io.moquette.spi.IMessagesStore.StoredMessage;
import io.moquette.spi.impl.Utils; import io.moquette.spi.ISessionsStore;
import io.moquette.spi.impl.subscriptions.Subscription; import io.moquette.spi.impl.Utils;
import io.moquette.spi.impl.subscriptions.Subscription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.*;
/**
* /**
* @author andrea *
*/ * @author andrea
public class MemorySessionStore implements ISessionsStore { */
private static final Logger LOG = LoggerFactory.getLogger(MemorySessionStore.class); public class MemorySessionStore implements ISessionsStore {
private static final Logger LOG = LoggerFactory.getLogger(MemorySessionStore.class);
private Map<String, Set<Subscription>> m_persistentSubscriptions = new HashMap<>();
private Map<String, Set<Subscription>> m_persistentSubscriptions = new HashMap<>();
private Map<String, MapDBPersistentStore.PersistentSession> m_persistentSessions = new HashMap<>();
private Map<String, MapDBPersistentStore.PersistentSession> m_persistentSessions = new HashMap<>();
//maps clientID->[MessageId -> guid]
private Map<String, Map<Integer, String>> m_inflightStore = new HashMap<>(); //maps clientID->[MessageId -> guid]
// private Map<String, Set<Integer>> m_inflightIDs = new HashMap<>(); private Map<String, Map<Integer, String>> m_inflightStore = new HashMap<>();
//maps clientID->[guid*] // private Map<String, Set<Integer>> m_inflightIDs = new HashMap<>();
private Map<String, Set<String>> m_enqueuedStore = new HashMap<>(); //maps clientID->[guid*]
//maps clientID->[messageID*] private Map<String, Set<String>> m_enqueuedStore = new HashMap<>();
private Map<String, Set<Integer>> m_secondPhaseStore = new HashMap<>(); //maps clientID->[messageID*]
private Map<String, Set<Integer>> m_secondPhaseStore = new HashMap<>();
private Map<String, Map<Integer, String>> m_messageToGuids;
private final IMessagesStore m_messagesStore; private Map<String, Map<Integer, String>> m_messageToGuids;
private final IMessagesStore m_messagesStore;
public MemorySessionStore(IMessagesStore messagesStore, Map<String, Map<Integer, String>> messageToGuids) {
m_messageToGuids = messageToGuids; public MemorySessionStore(IMessagesStore messagesStore, Map<String, Map<Integer, String>> messageToGuids) {
this.m_messagesStore = messagesStore; m_messageToGuids = messageToGuids;
} this.m_messagesStore = messagesStore;
}
@Override
public void removeSubscription(String topic, String clientID) { @Override
LOG.debug("removeSubscription topic filter: {} for clientID: {}", topic, clientID); public void removeSubscription(String topic, String clientID) {
if (!m_persistentSubscriptions.containsKey(clientID)) { LOG.debug("removeSubscription topic filter: {} for clientID: {}", topic, clientID);
return; if (!m_persistentSubscriptions.containsKey(clientID)) {
} return;
Set<Subscription> clientSubscriptions = m_persistentSubscriptions.get(clientID); }
//search for the subscription to remove Set<Subscription> clientSubscriptions = m_persistentSubscriptions.get(clientID);
Subscription toBeRemoved = null; //search for the subscription to remove
for (Subscription sub : clientSubscriptions) { Subscription toBeRemoved = null;
if (sub.getTopicFilter().equals(topic)) { for (Subscription sub : clientSubscriptions) {
toBeRemoved = sub; if (sub.getTopicFilter().equals(topic)) {
break; toBeRemoved = sub;
} break;
} }
}
if (toBeRemoved != null) {
clientSubscriptions.remove(toBeRemoved); if (toBeRemoved != null) {
} clientSubscriptions.remove(toBeRemoved);
} }
}
@Override
public void initStore() { @Override
public void initStore() {
}
}
@Override
public void addNewSubscription(Subscription newSubscription) { @Override
final String clientID = newSubscription.getClientId(); public void addNewSubscription(Subscription newSubscription) {
if (!m_persistentSubscriptions.containsKey(clientID)) { final String clientID = newSubscription.getClientId();
m_persistentSubscriptions.put(clientID, new HashSet<Subscription>()); if (!m_persistentSubscriptions.containsKey(clientID)) {
} m_persistentSubscriptions.put(clientID, new HashSet<Subscription>());
}
Set<Subscription> subs = m_persistentSubscriptions.get(clientID);
subs.remove(newSubscription); //same topic and clientID Set<Subscription> subs = m_persistentSubscriptions.get(clientID);
subs.add(newSubscription); subs.remove(newSubscription); //same topic and clientID
m_persistentSubscriptions.put(clientID, subs); subs.add(newSubscription);
} m_persistentSubscriptions.put(clientID, subs);
}
@Override
public void wipeSubscriptions(String clientID) { @Override
m_persistentSubscriptions.remove(clientID); public void wipeSubscriptions(String clientID) {
} m_persistentSubscriptions.remove(clientID);
}
@Override
public boolean contains(String clientID) { @Override
return m_persistentSubscriptions.containsKey(clientID); public boolean contains(String clientID) {
} return m_persistentSubscriptions.containsKey(clientID);
}
@Override
public ClientSession createNewSession(String clientID, boolean cleanSession) { @Override
LOG.debug("createNewSession for client <{}>", clientID); public ClientSession createNewSession(String clientID, boolean cleanSession) {
if (m_persistentSessions.containsKey(clientID)) { LOG.debug("createNewSession for client <{}>", clientID);
LOG.error("already exists a session for client <{}>, bad condition", clientID); if (m_persistentSessions.containsKey(clientID)) {
throw new IllegalArgumentException("Can't create a session with the ID of an already existing" + clientID); LOG.error("already exists a session for client <{}>, bad condition", clientID);
} throw new IllegalArgumentException("Can't create a session with the ID of an already existing" + clientID);
LOG.debug("clientID {} is a newcome, creating it's empty subscriptions set", clientID); }
m_persistentSubscriptions.put(clientID, new HashSet<Subscription>()); LOG.debug("clientID {} is a newcome, creating it's empty subscriptions set", clientID);
m_persistentSessions.put(clientID, new MapDBPersistentStore.PersistentSession(cleanSession)); m_persistentSubscriptions.put(clientID, new HashSet<Subscription>());
return new ClientSession(clientID, m_messagesStore, this, cleanSession); m_persistentSessions.put(clientID, new MapDBPersistentStore.PersistentSession(cleanSession));
} return new ClientSession(clientID, m_messagesStore, this, cleanSession);
}
@Override
public ClientSession sessionForClient(String clientID) { @Override
if (!m_persistentSessions.containsKey(clientID)) { public ClientSession sessionForClient(String clientID) {
return null; if (!m_persistentSessions.containsKey(clientID)) {
} return null;
}
MapDBPersistentStore.PersistentSession storedSession = m_persistentSessions.get(clientID);
return new ClientSession(clientID, m_messagesStore, this, storedSession.cleanSession); MapDBPersistentStore.PersistentSession storedSession = m_persistentSessions.get(clientID);
} return new ClientSession(clientID, m_messagesStore, this, storedSession.cleanSession);
}
@Override
public void updateCleanStatus(String clientID, boolean cleanSession) { @Override
m_persistentSessions.put(clientID, new MapDBPersistentStore.PersistentSession(cleanSession)); public void updateCleanStatus(String clientID, boolean cleanSession) {
} m_persistentSessions.put(clientID, new MapDBPersistentStore.PersistentSession(cleanSession));
}
@Override
public List<ClientTopicCouple> listAllSubscriptions() { @Override
List<ClientTopicCouple> allSubscriptions = new ArrayList<>(); public List<ClientTopicCouple> listAllSubscriptions() {
for (Map.Entry<String, Set<Subscription>> entry : m_persistentSubscriptions.entrySet()) { List<ClientTopicCouple> allSubscriptions = new ArrayList<>();
for (Subscription sub : entry.getValue()) { for (Map.Entry<String, Set<Subscription>> entry : m_persistentSubscriptions.entrySet()) {
allSubscriptions.add(sub.asClientTopicCouple()); for (Subscription sub : entry.getValue()) {
} allSubscriptions.add(sub.asClientTopicCouple());
} }
return allSubscriptions; }
} return allSubscriptions;
}
@Override
public Subscription getSubscription(ClientTopicCouple couple) { @Override
Set<Subscription> subscriptions = m_persistentSubscriptions.get(couple.clientID); public Subscription getSubscription(ClientTopicCouple couple) {
if (subscriptions == null || subscriptions.isEmpty()) { Set<Subscription> subscriptions = m_persistentSubscriptions.get(couple.clientID);
return null; if (subscriptions == null || subscriptions.isEmpty()) {
} return null;
for (Subscription sub : subscriptions) { }
if (sub.getTopicFilter().equals(couple.topicFilter)) { for (Subscription sub : subscriptions) {
return sub; if (sub.getTopicFilter().equals(couple.topicFilter)) {
} return sub;
} }
return null; }
} return null;
}
@Override
public void inFlightAck(String clientID, int messageID) { @Override
Map<Integer, String> m = this.m_inflightStore.get(clientID); public void inFlightAck(String clientID, int messageID) {
if (m == null) { Map<Integer, String> m = this.m_inflightStore.get(clientID);
LOG.error("Can't find the inFlight record for client <{}>", clientID); if (m == null) {
return; LOG.error("Can't find the inFlight record for client <{}>", clientID);
} return;
m.remove(messageID); }
} m.remove(messageID);
}
@Override
public void inFlight(String clientID, int messageID, String guid) { @Override
Map<Integer, String> m = this.m_inflightStore.get(clientID); public void inFlight(String clientID, int messageID, String guid) {
if (m == null) { Map<Integer, String> m = this.m_inflightStore.get(clientID);
m = new HashMap<>(); if (m == null) {
} m = new HashMap<>();
m.put(messageID, guid); }
this.m_inflightStore.put(clientID, m); m.put(messageID, guid);
} this.m_inflightStore.put(clientID, m);
}
/**
* Return the next valid packetIdentifier for the given client session. /**
* */ * Return the next valid packetIdentifier for the given client session.
@Override * */
public int nextPacketID(String clientID) { @Override
Map<Integer, String> m = this.m_inflightStore.get(clientID); public int nextPacketID(String clientID) {
if (m == null) { Map<Integer, String> m = this.m_inflightStore.get(clientID);
m = new HashMap<>(); if (m == null) {
int nextPacketId = 1; m = new HashMap<>();
m.put(nextPacketId, null); int nextPacketId = 1;
return nextPacketId; m.put(nextPacketId, null);
} return nextPacketId;
int maxId = Collections.max(m.keySet()); }
int nextPacketId = (maxId + 1) % 0xFFFF; int maxId = Collections.max(m.keySet());
m.put(nextPacketId, null); int nextPacketId = (maxId + 1) % 0xFFFF;
return nextPacketId; m.put(nextPacketId, null);
} return nextPacketId;
}
@Override
public void bindToDeliver(String guid, String clientID) { @Override
Set<String> guids = Utils.defaultGet(m_enqueuedStore, clientID, new HashSet<String>()); public void bindToDeliver(String guid, String clientID) {
guids.add(guid); Set<String> guids = Utils.defaultGet(m_enqueuedStore, clientID, new HashSet<String>());
m_enqueuedStore.put(clientID, guids); guids.add(guid);
} m_enqueuedStore.put(clientID, guids);
}
@Override
public Collection<String> enqueued(String clientID) { @Override
return Utils.defaultGet(m_enqueuedStore, clientID, new HashSet<String>()); public Collection<String> enqueued(String clientID) {
} return Utils.defaultGet(m_enqueuedStore, clientID, new HashSet<String>());
}
@Override
public void removeEnqueued(String clientID, String guid) { @Override
Set<String> guids = Utils.defaultGet(m_enqueuedStore, clientID, new HashSet<String>()); public void removeEnqueued(String clientID, String guid) {
guids.remove(guid); Set<String> guids = Utils.defaultGet(m_enqueuedStore, clientID, new HashSet<String>());
m_enqueuedStore.put(clientID, guids); guids.remove(guid);
} m_enqueuedStore.put(clientID, guids);
}
@Override
public void secondPhaseAcknowledged(String clientID, int messageID) { @Override
Set<Integer> messageIDs = Utils.defaultGet(m_secondPhaseStore, clientID, new HashSet<Integer>()); public void secondPhaseAcknowledged(String clientID, int messageID) {
messageIDs.remove(messageID); Set<Integer> messageIDs = Utils.defaultGet(m_secondPhaseStore, clientID, new HashSet<Integer>());
m_secondPhaseStore.put(clientID, messageIDs); messageIDs.remove(messageID);
} m_secondPhaseStore.put(clientID, messageIDs);
}
@Override
public void secondPhaseAckWaiting(String clientID, int messageID) { @Override
Set<Integer> messageIDs = Utils.defaultGet(m_secondPhaseStore, clientID, new HashSet<Integer>()); public void secondPhaseAckWaiting(String clientID, int messageID) {
messageIDs.add(messageID); Set<Integer> messageIDs = Utils.defaultGet(m_secondPhaseStore, clientID, new HashSet<Integer>());
m_secondPhaseStore.put(clientID, messageIDs); messageIDs.add(messageID);
} m_secondPhaseStore.put(clientID, messageIDs);
}
@Override
public String mapToGuid(String clientID, int messageID) { @Override
HashMap<Integer, String> guids = (HashMap<Integer, String>) Utils.defaultGet(m_messageToGuids, public String mapToGuid(String clientID, int messageID) {
clientID, new HashMap<Integer, String>()); HashMap<Integer, String> guids = (HashMap<Integer, String>) Utils.defaultGet(m_messageToGuids,
return guids.get(messageID); clientID, new HashMap<Integer, String>());
} return guids.get(messageID);
} }
@Override
public StoredMessage getInflightMessage( String clientID, int messageID ) {
return null;
}
}