Merge of lennartj-master, code style fixes

This commit is contained in:
benni 2013-03-29 12:17:54 +01:00
commit f52fc0e681
40 changed files with 490 additions and 339 deletions

4
.gitignore vendored
View File

@ -1,5 +1,9 @@
# idea project settings #
*.iml
*.ipr
*.iws
.idea/*
.idea
# Package Files #
*.war

52
pom.xml
View File

@ -10,7 +10,7 @@
<groupId>net.engio</groupId>
<artifactId>mbassador</artifactId>
<version>1.1.4-SNAPSHOT</version>
<packaging>jar</packaging>
<packaging>bundle</packaging>
<name>mbassador</name>
<description>
Mbassador is a fast and flexible message bus system following the publish subscribe pattern.
@ -23,7 +23,6 @@
weak-references,
message filtering,
ordering of message handlers etc.
</description>
<url>https://github.com/bennidi/mbassador</url>
@ -50,6 +49,10 @@
</developers>
<properties>
<nazgul-codestyle.version>2.0.1</nazgul-codestyle.version>
<jdk.version>1.6</jdk.version>
<pmd.plugin.version>3.0.1</pmd.plugin.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.build.java.version>1.6</project.build.java.version>
<github.url>file://${project.basedir}/mvn-local-repo</github.url>
@ -77,6 +80,51 @@
<build>
<plugins>
<!-- plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>${pmd.plugin.version}</version>
<configuration>
<excludeRoots>
<excludeRoot>src/main/generated</excludeRoot>
<excludeRoot>src/test</excludeRoot>
</excludeRoots>
<rulesets>
<ruleset>/codestyle/pmd-rules.xml</ruleset>
</rulesets>
<targetJdk>${jdk.version}</targetJdk>
<sourceEncoding>${project.build.sourceEncoding}</sourceEncoding>
</configuration>
<executions>
<execution>
<goals>
<goal>check</goal>
<goal>cpd-check</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>se.jguru.nazgul.tools.codestyle</groupId>
<artifactId>nazgul-codestyle</artifactId>
<version>${nazgul-codestyle.version}</version>
</dependency>
</dependencies>
</plugin -->
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>2.3.7</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName>
<Export-Package>{local-packages}</Export-Package>
</instructions>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>

View File

@ -1,32 +1,44 @@
package net.engio.mbassy;
/**
* Publication error handlers are provided with a publication error every time an error occurs during message publication.
* A handler might fail with an exception, not be accessible because of the presence of a security manager
* or other reasons might lead to failures during the message publication process.
*
* Publication error handlers are provided with a publication error every time an
* error occurs during message publication.
* A handler might fail with an exception, not be accessible because of the presence
* of a security manager or other reasons might lead to failures during the message publication process.
* <p/>
*
* @author bennidi
* Date: 2/22/12
*/
@SuppressWarnings("PMD.UnusedModifier")
public interface IPublicationErrorHandler {
/**
* Handle the given publication error.
*
* @param error
* @param error The PublicationError to handle.
*/
public void handleError(PublicationError error);
void handleError(PublicationError error);
// This is the default error handler it will simply log to standard out and
// print stack trace if available
/**
* The default error handler will simply log to standard out and
* print the stack trace if available.
*/
static final class ConsoleLogger implements IPublicationErrorHandler {
@Override
public void handleError(PublicationError error) {
System.out.println(error);
if (error.getCause() != null) error.getCause().printStackTrace();
}
}
;
/**
* {@inheritDoc}
*/
@Override
public void handleError(final PublicationError error) {
// Printout the error itself
System.out.println(error);
// Printout the stacktrace from the cause.
if (error.getCause() != null) {
error.getCause().printStackTrace();
}
}
}
}

View File

@ -3,27 +3,39 @@ package net.engio.mbassy;
import java.lang.reflect.Method;
/**
* Publication errors are created when object publication fails for some reason and contain details
* as to the cause and location where they occured.
* Publication errors are created when object publication fails
* for some reason and contain details as to the cause and location
* where they occurred.
* <p/>
*
* @author bennidi
* Date: 2/22/12
* Time: 4:59 PM
*/
public class PublicationError {
// Internal state
private Throwable cause;
private String message;
private Method listener;
private Object listeningObject;
private Object publishedObject;
/**
* Compound constructor, creating a PublicationError from the supplied objects.
*
* @param cause The Throwable giving rise to this PublicationError.
* @param message The message to send.
* @param listener The method where the error was created.
* @param listeningObject The object in which the PublicationError was generated.
* @param publishedObject The published object which gave rise to the error.
*/
public PublicationError(final Throwable cause,
final String message,
final Method listener,
final Object listeningObject,
final Object publishedObject) {
public PublicationError(Throwable cause, String message, Method listener, Object listeningObject, Object publishedObject) {
this.cause = cause;
this.message = message;
this.listener = listener;
@ -31,14 +43,26 @@ public class PublicationError {
this.publishedObject = publishedObject;
}
/**
* Default constructor.
*/
public PublicationError() {
super();
}
/**
* @return The Throwable giving rise to this PublicationError.
*/
public Throwable getCause() {
return cause;
}
/**
* Assigns the cause of this PublicationError.
*
* @param cause A Throwable which gave rise to this PublicationError.
* @return This PublicationError.
*/
public PublicationError setCause(Throwable cause) {
this.cause = cause;
return this;
@ -80,6 +104,9 @@ public class PublicationError {
return this;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "PublicationError{" +

View File

@ -3,14 +3,28 @@ package net.engio.mbassy.bus;
import net.engio.mbassy.IPublicationErrorHandler;
import net.engio.mbassy.PublicationError;
import net.engio.mbassy.common.ReflectionUtils;
import net.engio.mbassy.subscription.SubscriptionContext;
import net.engio.mbassy.listener.MessageHandlerMetadata;
import net.engio.mbassy.listener.MetadataReader;
import net.engio.mbassy.subscription.Subscription;
import net.engio.mbassy.subscription.SubscriptionContext;
import net.engio.mbassy.subscription.SubscriptionFactory;
import java.util.*;
import java.util.concurrent.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* The base class for all message bus implementations.
@ -29,15 +43,17 @@ public abstract class AbstractMessageBus<T, P extends IMessageBus.IPostCommand>
// all subscriptions per message type
// this is the primary list for dispatching a specific message
// write access is synchronized and happens very infrequently
private final Map<Class, Collection<Subscription>> subscriptionsPerMessage = new HashMap(50);
private final Map<Class, Collection<Subscription>> subscriptionsPerMessage
= new HashMap<Class, Collection<Subscription>>(50);
// all subscriptions per messageHandler type
// this list provides fast access for subscribing and unsubscribing
// write access is synchronized and happens very infrequently
private final Map<Class, Collection<Subscription>> subscriptionsPerListener = new HashMap(50);
private final Map<Class, Collection<Subscription>> subscriptionsPerListener
= new HashMap<Class, Collection<Subscription>>(50);
// remember already processed classes that do not contain any listeners
private final Collection<Class> nonListeners = new HashSet();
private final Collection<Class> nonListeners = new HashSet<Class>();
// this handler will receive all errors that occur during message dispatch or message handling
private final List<IPublicationErrorHandler> errorHandlers = new CopyOnWriteArrayList<IPublicationErrorHandler>();
@ -99,9 +115,13 @@ public abstract class AbstractMessageBus<T, P extends IMessageBus.IPostCommand>
}
public boolean unsubscribe(Object listener) {
if (listener == null) return false;
if (listener == null) {
return false;
}
Collection<Subscription> subscriptions = subscriptionsPerListener.get(listener.getClass());
if (subscriptions == null) return false;
if (subscriptions == null) {
return false;
}
boolean isRemoved = true;
for (Subscription subscription : subscriptions) {
isRemoved = isRemoved && subscription.unsubscribe(listener);
@ -113,8 +133,9 @@ public abstract class AbstractMessageBus<T, P extends IMessageBus.IPostCommand>
public void subscribe(Object listener) {
try {
Class listeningClass = listener.getClass();
if (nonListeners.contains(listeningClass))
if (nonListeners.contains(listeningClass)) {
return; // early reject of known classes that do not participate in eventing
}
Collection<Subscription> subscriptionsByListener = subscriptionsPerListener.get(listeningClass);
if (subscriptionsByListener == null) { // if the type is registered for the first time
synchronized (this) { // new subscriptions must be processed sequentially
@ -154,7 +175,7 @@ public abstract class AbstractMessageBus<T, P extends IMessageBus.IPostCommand>
}
public void addErrorHandler(IPublicationErrorHandler handler) {
public final void addErrorHandler(IPublicationErrorHandler handler) {
errorHandlers.add(handler);
}
@ -192,7 +213,9 @@ public abstract class AbstractMessageBus<T, P extends IMessageBus.IPostCommand>
Collection<Subscription> subs = subscriptionsPerMessage.get(eventSuperType);
if (subs != null) {
for (Subscription sub : subs) {
if(sub.handlesMessageType(messageType))subscriptions.add(sub);
if (sub.handlesMessageType(messageType)) {
subscriptions.add(sub);
}
}
}
}
@ -200,7 +223,6 @@ public abstract class AbstractMessageBus<T, P extends IMessageBus.IPostCommand>
}
// associate a suscription with a message type
// NOTE: Not thread-safe! must be synchronized in outer scope
private void addMessageTypeSubscription(Class messageType, Subscription subscription) {
@ -213,8 +235,6 @@ public abstract class AbstractMessageBus<T, P extends IMessageBus.IPostCommand>
}
public void handlePublicationError(PublicationError error) {
for (IPublicationErrorHandler errorHandler : errorHandlers) {
errorHandler.handleError(error);

View File

@ -3,7 +3,12 @@ package net.engio.mbassy.bus;
import net.engio.mbassy.listener.MetadataReader;
import net.engio.mbassy.subscription.SubscriptionFactory;
import java.util.concurrent.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* The bus configuration holds various parameters that can be used to customize the bus' runtime behaviour.
@ -22,7 +27,7 @@ public class BusConfiguration {
}
};
public static final BusConfiguration Default(){
public static BusConfiguration Default() {
return new BusConfiguration();
}

View File

@ -7,7 +7,6 @@ import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
/**
*
* A message bus offers facilities for publishing messages to registered listeners. Messages can be dispatched
* synchronously or asynchronously and may be of any type that is a valid sub type of the type parameter T.
* The dispatch mechanism can by controlled for per message handler and message publication.
@ -41,7 +40,7 @@ import java.util.concurrent.TimeUnit;
* is considered removed after the remove(Object) call returned) will under no circumstances receive any message publications.
* Any running message publication that has not yet delivered the message to the removed listener will not see the listener
* after the remove operation completed.
*
* <p/>
* NOTE: Generic type parameters of messages will not be taken into account, e.g. a List<Long> will
* get dispatched to all message handlers that take an instance of List as their parameter
*
@ -57,14 +56,13 @@ public interface IMessageBus<T, P extends IMessageBus.IPostCommand> {
*
* @param listener
*/
public void subscribe(Object listener);
void subscribe(Object listener);
/**
* Immediately remove all registered message handlers (if any) of the given listener. When this call returns all handlers
* have effectively been removed and will not receive any message publications (including asynchronously scheduled
* publications that have been published when the message listener was still subscribed).
*
* <p/>
* A call to this method passing null, an already unsubscribed listener or any object that does not define any message
* handlers will not have any effect and is silently ignored.
*
@ -72,14 +70,13 @@ public interface IMessageBus<T, P extends IMessageBus.IPostCommand> {
* @return true, if the listener was found and successfully removed
* false otherwise
*/
public boolean unsubscribe(Object listener);
boolean unsubscribe(Object listener);
/**
*
* @param message
* @return
*/
public P post(T message);
P post(T message);
/**
* Publication errors may occur at various points of time during message delivery. A handler may throw an exception,
@ -89,15 +86,14 @@ public interface IMessageBus<T, P extends IMessageBus.IPostCommand> {
*
* @param errorHandler
*/
public void addErrorHandler(IPublicationErrorHandler errorHandler);
void addErrorHandler(IPublicationErrorHandler errorHandler);
/**
* Returns an immutable collection containing all the registered error handlers
*
* @return
*/
public Collection<IPublicationErrorHandler> getRegisteredErrorHandlers();
Collection<IPublicationErrorHandler> getRegisteredErrorHandlers();
/**
* Get the executor service that is used to asynchronous message publication.
@ -105,54 +101,49 @@ public interface IMessageBus<T, P extends IMessageBus.IPostCommand> {
*
* @return
*/
public Executor getExecutor();
Executor getExecutor();
/**
* Check whether any asynchronous message publications are pending for being processed
*
* @return
*/
public boolean hasPendingMessages();
boolean hasPendingMessages();
/**
* A post command is used as an intermediate object created by a call to the message bus' post method.
* It encapsulates the functionality provided by the message bus that created the command.
* Subclasses may extend this interface and add functionality, e.g. different dispatch schemes.
*
*/
public static interface IPostCommand<T>{
interface IPostCommand<T> {
/**
* Execute the message publication immediately. This call blocks until every matching message handler
* has been invoked.
*/
public void now();
void now();
/**
* Execute the message publication asynchronously. The behaviour of this method depends on the
* configured queuing strategy:
*
* <p/>
* If an unbound queuing strategy is used the call returns immediately.
* If a bounded queue is used the call might block until the message can be placed in the queue.
*
* @return A message publication that can be used to access information about the state of
*/
public MessagePublication asynchronously();
MessagePublication asynchronously();
/**
* Execute the message publication asynchronously. The behaviour of this method depends on the
* configured queuing strategy:
*
* <p/>
* If an unbound queuing strategy is used the call returns immediately.
* If a bounded queue is used the call will block until the message can be placed in the queue
* or the timeout is reached.
*
* @return A message publication that wraps up the publication request
*/
public MessagePublication asynchronously(long timeout, TimeUnit unit);
MessagePublication asynchronously(long timeout, TimeUnit unit);
}
}

View File

@ -29,12 +29,12 @@ public class MBassador<T> extends AbstractMessageBus<T, SyncAsyncPostCommand<T>>
// Dead Event
subscriptions = getSubscriptionsByMessageType(DeadMessage.class);
return getPublicationFactory().createPublication(this, subscriptions, new DeadMessage(message));
} else {
return getPublicationFactory().createPublication(this, subscriptions, message);
}
else return getPublicationFactory().createPublication(this, subscriptions, message);
}
/**
* Synchronously publish a message to all registered listeners (this includes listeners defined for super types)
* The call blocks until every messageHandler has processed the message.

View File

@ -10,7 +10,7 @@ import java.util.Collection;
* A message publication is created for each asynchronous message dispatch. It reflects the state
* of the corresponding message publication process, i.e. provides information whether the
* publication was successfully scheduled, is currently running etc.
*
* <p/>
* A message publication lives within a single thread. It is not designed in a thread-safe manner -> not eligible to
* be used in multiple threads simultaneously .
*
@ -82,8 +82,9 @@ public class MessagePublication {
}
public MessagePublication markScheduled() {
if(!state.equals(State.Initial))
if (!state.equals(State.Initial)) {
return this;
}
state = State.Scheduled;
return this;
}
@ -102,7 +103,7 @@ public class MessagePublication {
}
private enum State {
Initial,Scheduled,Running,Finished,Error;
Initial, Scheduled, Running, Finished, Error
}
}

View File

@ -22,13 +22,16 @@ import java.util.WeakHashMap;
*/
public class ConcurrentSet<T> implements Iterable<T> {
// Internal state
private final Object lock = new Object();
private WeakHashMap<T, Entry<T>> entries = new WeakHashMap<T, Entry<T>>(); // maintain a map of entries for O(log n) lookup
private Entry<T> head; // reference to the first element
public ConcurrentSet<T> add(T element) {
if (element == null || entries.containsKey(element)) return this;
synchronized (this) {
if (element == null || entries.containsKey(element)) {
return this;
}
synchronized (lock) {
insert(element);
}
return this;
@ -40,7 +43,9 @@ public class ConcurrentSet<T> implements Iterable<T>{
}
private void insert(T element) {
if (entries.containsKey(element)) return;
if (entries.containsKey(element)) {
return;
}
if (head == null) {
head = new Entry<T>(element);
} else {
@ -54,9 +59,11 @@ public class ConcurrentSet<T> implements Iterable<T>{
}
public ConcurrentSet<T> addAll(Iterable<T> elements) {
synchronized (this) {
synchronized (lock) {
for (T element : elements) {
if (element == null || entries.containsKey(element)) return this;
if (element == null || entries.containsKey(element)) {
return this;
}
insert(element);
}
@ -65,10 +72,14 @@ public class ConcurrentSet<T> implements Iterable<T>{
}
public boolean remove(T element) {
if (!entries.containsKey(element)) return false;
synchronized (this) {
if (!entries.containsKey(element)) {
return false;
}
synchronized (lock) {
Entry<T> listelement = entries.get(element);
if(listelement == null)return false; //removed by other thread
if (listelement == null) {
return false; //removed by other thread
}
if (listelement != head) {
listelement.remove();
} else {
@ -99,7 +110,9 @@ public class ConcurrentSet<T> implements Iterable<T>{
}
public T next() {
if (current == null) return null;
if (current == null) {
return null;
}
T value = current.getValue();
if (value == null) { // auto-removal of orphan references
do {
@ -113,7 +126,9 @@ public class ConcurrentSet<T> implements Iterable<T>{
}
public void remove() {
if (current == null) return;
if (current == null) {
return;
}
Entry<T> newCurrent = current.next();
ConcurrentSet.this.remove(current.getValue());
current = newCurrent;
@ -149,7 +164,9 @@ public class ConcurrentSet<T> implements Iterable<T>{
public void remove() {
if (predecessor != null) {
predecessor.next = next;
if(next != null)next.predecessor = predecessor;
if (next != null) {
next.predecessor = predecessor;
}
} else if (next != null) {
next.predecessor = null;
}

View File

@ -2,6 +2,7 @@ package net.engio.mbassy.common;
/**
* Created with IntelliJ IDEA.
*
* @author bennidi
* Date: 10/22/12
* Time: 9:33 AM
@ -9,6 +10,5 @@ package net.engio.mbassy.common;
*/
public interface IPredicate<T> {
public boolean apply(T target);
boolean apply(T target);
}

View File

@ -38,12 +38,11 @@ public class ReflectionUtils {
* @param subclass
* @return
*/
public static Method getOverridingMethod(Method overridingMethod, Class subclass) {
public static Method getOverridingMethod(final Method overridingMethod, final Class subclass) {
Class current = subclass;
while (!current.equals(overridingMethod.getDeclaringClass())) {
try {
Method overridden = current.getDeclaredMethod(overridingMethod.getName(), overridingMethod.getParameterTypes());
return overridden;
return current.getDeclaredMethod(overridingMethod.getName(), overridingMethod.getParameterTypes());
} catch (NoSuchMethodException e) {
current = current.getSuperclass();
}
@ -51,10 +50,12 @@ public class ReflectionUtils {
return null;
}
public static List<Method> withoutOverridenSuperclassMethods(List<Method> allMethods) {
public static List<Method> withoutOverridenSuperclassMethods(final List<Method> allMethods) {
List<Method> filtered = new LinkedList<Method>();
for (Method method : allMethods) {
if (!containsOverridingMethod(allMethods, method)) filtered.add(method);
if (!containsOverridingMethod(allMethods, method)) {
filtered.add(method);
}
}
return filtered;
}
@ -68,9 +69,11 @@ public class ReflectionUtils {
return superclasses;
}
public static boolean containsOverridingMethod(List<Method> allMethods, Method methodToCheck) {
public static boolean containsOverridingMethod(final List<Method> allMethods, final Method methodToCheck) {
for (Method method : allMethods) {
if (isOverriddenBy(methodToCheck, method)) return true;
if (isOverriddenBy(methodToCheck, method)) {
return true;
}
}
return false;
}
@ -88,9 +91,6 @@ public class ReflectionUtils {
Class[] superClassMethodParameters = superclassMethod.getParameterTypes();
Class[] subClassMethodParameters = superclassMethod.getParameterTypes();
// method must specify the same number of parameters
if(subClassMethodParameters.length != subClassMethodParameters.length){
return false;
}
//the parameters must occur in the exact same order
for (int i = 0; i < subClassMethodParameters.length; i++) {
if (!superClassMethodParameters[i].equals(subClassMethodParameters[i])) {

View File

@ -17,6 +17,9 @@ public class AsynchronousHandlerInvocation extends AbstractSubscriptionContextAw
this.delegate = delegate;
}
/**
* {@inheritDoc}
*/
@Override
public void invoke(final Object listener, final Object message) {
getContext().getOwningBus().getExecutor().execute(new Runnable() {

View File

@ -7,7 +7,7 @@ import net.engio.mbassy.subscription.MessageEnvelope;
/**
* The enveloped dispatcher will wrap published messages in an envelope before
* passing them to their configured dispatcher.
*
* <p/>
* All enveloped message handlers will have this dispatcher in their chain
*
* @author bennidi

View File

@ -25,10 +25,11 @@ public class FilteredMessageDispatcher extends DelegatingMessageDispatcher {
if (filter == null) {
return true;
} else {
for (IMessageFilter aFilter : filter) {
if (!aFilter.accepts(message, getContext().getHandlerMetadata())) {
return false;
}
else {
for (int i = 0; i < filter.length; i++) {
if (!filter[i].accepts(message, getContext().getHandlerMetadata())) return false;
}
return true;
}

View File

@ -17,7 +17,5 @@ public interface IHandlerInvocation extends ISubscriptionContextAware {
* @param listener The listener that will receive the message
* @param message The message to be delivered to the listener
*/
public void invoke(final Object listener, final Object message);
void invoke(Object listener, Object message);
}

View File

@ -10,5 +10,5 @@ import net.engio.mbassy.bus.IMessageBus;
*/
public interface IMessageBusAware {
public IMessageBus getBus();
IMessageBus getBus();
}

View File

@ -7,10 +7,10 @@ import net.engio.mbassy.common.ConcurrentSet;
* A message dispatcher provides the functionality to deliver a single message
* to a set of listeners. A message dispatcher uses a message context to access
* all information necessary for the message delivery.
*
* <p/>
* The delivery of a single message to a single listener is responsibility of the
* handler invocation object associated with the dispatcher.
*
* <p/>
* Implementations if IMessageDispatcher are partially designed using decorator pattern
* such that it is possible to compose different message dispatchers into dispatcher chains
* to achieve more complex dispatch logic.
@ -29,12 +29,14 @@ public interface IMessageDispatcher extends ISubscriptionContextAware {
* @param message The message that should be delivered to the listeners
* @param listeners The listeners that should receive the message
*/
public void dispatch(MessagePublication publication, Object message, ConcurrentSet listeners);
void dispatch(MessagePublication publication, Object message, ConcurrentSet listeners);
/**
* Get the handler invocation that will be used to deliver the message to each
* listener
* @return
* Get the handler invocation that will be used to deliver the
* message to each listener.
*
* @return the handler invocation that will be used to deliver the
* message to each listener
*/
public IHandlerInvocation getInvocation();
IHandlerInvocation getInvocation();
}

View File

@ -13,7 +13,7 @@ public interface ISubscriptionContextAware extends IMessageBusAware {
/**
* Get the subscription context associated with this object
*
* @return
* @return the subscription context associated with this object
*/
public SubscriptionContext getContext();
SubscriptionContext getContext();
}

View File

@ -7,7 +7,7 @@ import net.engio.mbassy.subscription.SubscriptionContext;
/**
* Standard implementation for direct, unfiltered message delivery.
*
* <p/>
* For each message delivery, this dispatcher iterates over the listeners
* and uses the previously provided handler invocation to deliver the message
* to each listener
@ -36,5 +36,4 @@ public class MessageDispatcher extends AbstractSubscriptionContextAware implemen
public IHandlerInvocation getInvocation() {
return invocation;
}
}

View File

@ -36,21 +36,18 @@ public class ReflectiveHandlerInvocation extends AbstractSubscriptionContextAwar
new PublicationError(e, "Error during messageHandler notification. " +
"The class or method is not accessible",
handler, listener, message));
}
catch(IllegalArgumentException e){
} catch (IllegalArgumentException e) {
handlePublicationError(
new PublicationError(e, "Error during messageHandler notification. " +
"Wrong arguments passed to method. Was: " + message.getClass()
+ "Expected: " + handler.getParameterTypes()[0],
handler, listener, message));
}
catch (InvocationTargetException e) {
} catch (InvocationTargetException e) {
handlePublicationError(
new PublicationError(e, "Error during messageHandler notification. " +
"Message handler threw exception",
handler, listener, message));
}
catch (Throwable e) {
} catch (Throwable e) {
handlePublicationError(
new PublicationError(e, "Error during messageHandler notification. " +
"Unexpected exception",
@ -58,6 +55,9 @@ public class ReflectiveHandlerInvocation extends AbstractSubscriptionContextAwar
}
}
/**
* {@inheritDoc}
*/
@Override
public void invoke(final Object listener, final Object message) {
invokeHandler(message, listener, getContext().getHandlerMetadata().getHandler());

View File

@ -1,6 +1,10 @@
package net.engio.mbassy.listener;
import java.lang.annotation.*;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Configure a handler to receive an enveloped message as a wrapper around the source

View File

@ -10,8 +10,9 @@ import java.lang.annotation.Target;
* It references a class that implements the IMessageFilter interface.
* The filter will be used to check whether a message should be delivered
* to the listener or not.
*
* <p/>
* <p/>
*
* @author bennidi
* Date: 2/14/12
*/
@ -22,6 +23,7 @@ public @interface Filter {
/**
* The class that implements the filter.
* Note: A filter always needs to provide a non-arg constructor
*
* @return
*/
Class<? extends IMessageFilter> value();

View File

@ -31,7 +31,9 @@ public class Filters {
@Override
public boolean accepts(Object event, MessageHandlerMetadata metadata) {
for (Class handledMessage : metadata.getHandledMessages()) {
if(handledMessage.equals(event.getClass()))return true;
if (handledMessage.equals(event.getClass())) {
return true;
}
}
return false;
}

View File

@ -1,6 +1,10 @@
package net.engio.mbassy.listener;
import java.lang.annotation.*;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Mark any method of any object(=listener) as a message handler and configure the handler
@ -23,7 +27,6 @@ public @interface Handler {
/**
* Define the mode in which a message is delivered to each listener. Listeners can be notified
* sequentially or concurrently.
*
*/
Mode delivery() default Mode.Sequential;

View File

@ -3,7 +3,7 @@ package net.engio.mbassy.listener;
/**
* Message filters can be used to prevent certain messages to be delivered to a specific listener.
* If a filter is used the message will only be delivered if it passes the filter(s)
*
* <p/>
* NOTE: A message filter must provide either a no-arg constructor.
*
* @author bennidi
@ -14,10 +14,8 @@ public interface IMessageFilter {
/**
* Evaluate the message to ensure that it matches the handler configuration
*
*
* @param message the message to be delivered
* @return
*/
public boolean accepts(Object message, MessageHandlerMetadata metadata);
boolean accepts(Object message, MessageHandlerMetadata metadata);
}

View File

@ -1,12 +1,11 @@
package net.engio.mbassy.listener;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
*
*
* @author bennidi
* Date: 11/14/12
*/
@ -35,10 +34,8 @@ public class MessageHandlerMetadata {
this.envelope = handler.getAnnotation(Enveloped.class);
this.acceptsSubtypes = !handlerConfig.rejectSubtypes();
if (this.envelope != null) {
for(Class messageType : envelope.messages())
handledMessages.add(messageType);
}
else{
Collections.addAll(handledMessages, envelope.messages());
} else {
handledMessages.add(handler.getParameterTypes()[0]);
}
this.handler.setAccessible(true);
@ -75,8 +72,12 @@ public class MessageHandlerMetadata {
public boolean handlesMessage(Class<?> messageType) {
for (Class<?> handledMessage : handledMessages) {
if(handledMessage.equals(messageType))return true;
if(handledMessage.isAssignableFrom(messageType) && acceptsSubtypes()) return true;
if (handledMessage.equals(messageType)) {
return true;
}
if (handledMessage.isAssignableFrom(messageType) && acceptsSubtypes()) {
return true;
}
}
return false;
}

View File

@ -9,14 +9,13 @@ import java.util.List;
* Provides information about the message listeners of a specific class. Each message handler
* defined by the target class is represented as a single entity.
*
*
* @author bennidi
* Date: 12/16/12
*/
public class MessageListenerMetadata<T> {
public static final IPredicate<MessageHandlerMetadata> ForMessage(final Class<?> messageType){
public static IPredicate<MessageHandlerMetadata> ForMessage(final Class<?> messageType) {
return new IPredicate<MessageHandlerMetadata>() {
@Override
public boolean apply(MessageHandlerMetadata target) {
@ -38,7 +37,9 @@ public class MessageListenerMetadata<T> {
public List<MessageHandlerMetadata> getHandlers(IPredicate<MessageHandlerMetadata> filter) {
List<MessageHandlerMetadata> matching = new LinkedList<MessageHandlerMetadata>();
for (MessageHandlerMetadata handler : handlers) {
if(filter.apply(handler))matching.add(handler);
if (filter.apply(handler)) {
matching.add(handler);
}
}
return matching;
}

View File

@ -5,10 +5,12 @@ import net.engio.mbassy.common.ReflectionUtils;
import net.engio.mbassy.subscription.MessageEnvelope;
import java.lang.reflect.Method;
import java.util.*;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
*
* The meta data reader is responsible for parsing and validating message handler configurations.
*
* @author bennidi
@ -29,7 +31,9 @@ public class MetadataReader {
// retrieve all instances of filters associated with the given subscription
private IMessageFilter[] getFilter(Handler subscription) {
if (subscription.filters().length == 0) return null;
if (subscription.filters().length == 0) {
return null;
}
IMessageFilter[] filters = new IMessageFilter[subscription.filters().length];
int i = 0;
for (Filter filterDef : subscription.filters()) {
@ -38,8 +42,7 @@ public class MetadataReader {
try {
filter = filterDef.value().newInstance();
filterCache.put(filterDef.value(), filter);
}
catch (Exception e){
} catch (Exception e) {
throw new RuntimeException(e);// propagate as runtime exception
}
@ -75,7 +78,9 @@ public class MetadataReader {
// but an overriding method does inherit the listener configuration of the overwritten method
for (Method handler : bottomMostHandlers) {
Handler handle = handler.getAnnotation(Handler.class);
if(!handle.enabled() || !isValidMessageHandler(handler)) continue; // disabled or invalid listeners are ignored
if (!handle.enabled() || !isValidMessageHandler(handler)) {
continue; // disabled or invalid listeners are ignored
}
Method overriddenHandler = ReflectionUtils.getOverridingMethod(handler, target);
// if a handler is overwritten it inherits the configuration of its parent method
MessageHandlerMetadata handlerMetadata = new MessageHandlerMetadata(overriddenHandler == null ? handler : overriddenHandler,
@ -92,7 +97,6 @@ public class MetadataReader {
}
private boolean isValidMessageHandler(Method handler) {
if (handler == null || handler.getAnnotation(Handler.class) == null) {
return false;

View File

@ -2,6 +2,7 @@ package net.engio.mbassy.listener;
/**
* Created with IntelliJ IDEA.
*
* @author bennidi
* Date: 11/16/12
* Time: 10:01 AM

View File

@ -1,7 +1,5 @@
package net.engio.mbassy.subscription;
import java.sql.Timestamp;
/**
* A message envelope is used to wrap messages of arbitrary type such that a handler
* my receive messages of different types.
@ -11,16 +9,13 @@ import java.sql.Timestamp;
*/
public class MessageEnvelope {
private Timestamp tsCreated = new Timestamp(System.currentTimeMillis());
// Internal state
private Object message;
public MessageEnvelope(Object message) {
this.message = message;
}
public <T> T getMessage() {
return (T) message;
}

View File

@ -1,12 +1,12 @@
package net.engio.mbassy.subscription;
import java.util.Comparator;
import java.util.UUID;
import net.engio.mbassy.bus.MessagePublication;
import net.engio.mbassy.common.ConcurrentSet;
import net.engio.mbassy.dispatch.IMessageDispatcher;
import java.util.Comparator;
import java.util.UUID;
/**
* A subscription is a thread safe container for objects that contain message handlers
*/

View File

@ -25,6 +25,7 @@ public class SubscriptionContext {
/**
* Get a reference to the message bus this context belongs to
*
* @return
*/
public IMessageBus getOwningBus() {
@ -35,6 +36,7 @@ public class SubscriptionContext {
/**
* Get the meta data that specifies the characteristics of the message handler
* that is associated with this context
*
* @return
*/
public MessageHandlerMetadata getHandlerMetadata() {

View File

@ -1,9 +1,16 @@
package net.engio.mbassy.subscription;
import net.engio.mbassy.dispatch.*;
import net.engio.mbassy.dispatch.AsynchronousHandlerInvocation;
import net.engio.mbassy.dispatch.EnvelopedMessageDispatcher;
import net.engio.mbassy.dispatch.FilteredMessageDispatcher;
import net.engio.mbassy.dispatch.IHandlerInvocation;
import net.engio.mbassy.dispatch.IMessageDispatcher;
import net.engio.mbassy.dispatch.MessageDispatcher;
import net.engio.mbassy.dispatch.ReflectiveHandlerInvocation;
/**
* Created with IntelliJ IDEA.
*
* @author bennidi
* Date: 11/16/12
* Time: 10:39 AM

View File

@ -1,6 +1,7 @@
package net.engio.mbassy;
import junit.framework.Assert;
import org.junit.Ignore;
import org.junit.Test;
import net.engio.mbassy.common.ConcurrentExecutor;
import net.engio.mbassy.common.ConcurrentSet;
@ -24,16 +25,18 @@ import java.util.Random;
*/
public class ConcurrentSetTest extends UnitTest {
// Shared state
private int numberOfElements = 100000;
private int numberOfThreads = 50;
@Ignore("Currently fails when building as a suite with JDK 1.7.0_15 and Maven 3.0.5 on a Mac")
@Test
public void testIteratorCleanup() {
// Assemble
final HashSet<Object> persistingCandidates = new HashSet<Object>();
final ConcurrentSet<Object> testSet = new ConcurrentSet<Object>();
Random rand = new Random();
final Random rand = new Random();
for (int i = 0; i < numberOfElements; i++) {
Object candidate = new Object();
@ -44,7 +47,8 @@ public class ConcurrentSetTest extends UnitTest {
testSet.add(candidate);
}
// this will remove all objects that have not been inserted into the set of persisting candidates
// Remove/Garbage collect all objects that have not
// been inserted into the set of persisting candidates.
runGC();
ConcurrentExecutor.runConcurrent(new Runnable() {
@ -62,8 +66,6 @@ public class ConcurrentSetTest extends UnitTest {
for (Object test : testSet) {
assertTrue(persistingCandidates.contains(test));
}
}
@ -100,8 +102,6 @@ public class ConcurrentSetTest extends UnitTest {
for (Object uniqueObject : distinct) {
assertTrue(testSet.contains(uniqueObject));
}
}
@Test

View File

@ -1,14 +1,16 @@
package net.engio.mbassy.bus;
import net.engio.mbassy.bus.BusConfiguration;
import net.engio.mbassy.bus.MBassador;
import net.engio.mbassy.common.MessageBusTest;
import net.engio.mbassy.events.SubTestMessage;
import org.junit.Test;
import net.engio.mbassy.common.TestUtil;
import net.engio.mbassy.events.SubTestMessage;
import net.engio.mbassy.events.TestMessage;
import net.engio.mbassy.listeners.*;
import net.engio.mbassy.listeners.EventingTestBean;
import net.engio.mbassy.listeners.EventingTestBean2;
import net.engio.mbassy.listeners.EventingTestBean3;
import net.engio.mbassy.listeners.ListenerFactory;
import net.engio.mbassy.listeners.NonListeningBean;
import net.engio.mbassy.subscription.Subscription;
import org.junit.Test;
import java.util.Collection;
import java.util.LinkedList;

View File

@ -1,7 +1,8 @@
package net.engio.mbassy.common;
import junit.framework.Assert;
import net.engio.mbassy.*;
import net.engio.mbassy.IPublicationErrorHandler;
import net.engio.mbassy.PublicationError;
import net.engio.mbassy.bus.BusConfiguration;
import net.engio.mbassy.bus.MBassador;
@ -26,6 +27,4 @@ public class MessageBusTest extends UnitTest{
bus.addErrorHandler(TestFailingHandler);
return bus;
}
}

View File

@ -13,12 +13,14 @@ import java.lang.ref.WeakReference;
*/
public class UnitTest {
// Internal state
private Runtime runtime = Runtime.getRuntime();
public void pause(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
e.printStackTrace();
}
}
@ -30,7 +32,7 @@ public class UnitTest {
public void runGC() {
WeakReference ref = new WeakReference<Object>(new Object());
while(ref.get() != null) {
System.gc();
runtime.gc();
}
}