Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (c) 2010-2011. Axon Framework
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package org.axonframework.commandhandling;
 
 
 import java.util.List;
 import java.util.Map;
 
 import static java.lang.String.format;

Implementation of the CommandBus that dispatches commands to the handlers subscribed to that specific type of command. Interceptors may be configured to add processing to commands regardless of their type, for example logging, security (authorization), sla monitoring, etc.

This class can be monitored as the implementation of the StatisticsProvider interface indicates.

Author(s):
Allard Buijze
Martin Tilma
Since:
0.5
 
 public class SimpleCommandBus implements CommandBus {
 
     private static final Logger logger = LoggerFactory.getLogger(SimpleCommandBus.class);
 
     private final ConcurrentMap<Class<?>, CommandHandler<?>> subscriptions = new ConcurrentHashMap<Class<?>, CommandHandler<?>>();
     private volatile Iterable<? extends CommandHandlerInterceptorinterceptors = Collections.emptyList();
Initializes the SimpleCommandBus and registers the mbeans for management information.
 
     public SimpleCommandBus() {
         this(true);
     }

    
Initiates the SimpleCommandBus and makes the registration of mbeans for management information optional.

Parameters:
registerMBeans true to register the mbeans, false for not registering them.
 
     public SimpleCommandBus(boolean registerMBeans) {
         if (registerMBeans) {
             JmxConfiguration.getInstance().registerMBean(getClass());
         }
     }
 
     @SuppressWarnings({"ThrowableResultOfMethodCallIgnored"})
     @Override
     public void dispatch(Object command) {
         CommandHandler commandHandler = findCommandHandlerFor(command);
         try {
             doDispatch(commandcommandHandler);
         } catch (Error e) {
             throw e;
         } catch (Throwable throwable) {
             .error(format("Processing of a [%s] resulted in an exception: "command.getClass().getSimpleName()),
                          throwable);
         }
     }
 
     @SuppressWarnings({"unchecked"})
     @Override
     public <R> void dispatch(Object commandfinal CommandCallback<R> callback) {
         CommandHandler handler = findCommandHandlerFor(command);
         try {
             Object result = doDispatch(commandhandler);
             callback.onSuccess((R) result);
         } catch (Throwable throwable) {
             callback.onFailure(throwable);
         }
     }
 
     private CommandHandler findCommandHandlerFor(Object command) {
        final CommandHandler handler = .get(command.getClass());
        if (handler == null) {
            throw new NoHandlerForCommandException(format("No handler was subscribed to commands of type [%s]",
                                                          command.getClass().getSimpleName()));
        }
        return handler;
    }
    private Object doDispatch(Object commandCommandHandler commandHandlerthrows Throwable {
        UnitOfWork unitOfWork = .createUnitOfWork();
        InterceptorChain chain = new DefaultInterceptorChain(commandunitOfWorkcommandHandler);
        Object returnValue;
        try {
            returnValue = chain.proceed();
        } catch (Throwable throwable) {
            if (.rollBackOn(throwable)) {
                unitOfWork.rollback(throwable);
            } else {
                unitOfWork.commit();
            }
            throw throwable;
        }
        unitOfWork.commit();
        return returnValue;
    }

    
Subscribe the given handler to commands of type commandType. If a subscription already exists for the given type, then the new handler takes over the subscription.

Parameters:
commandType The type of command to subscribe the handler to
handler The handler instance that handles the given type of command
<T> The Type of command
    @Override
    public <T> void subscribe(Class<T> commandTypeCommandHandler<? super T> handler) {
        .put(commandTypehandler);
        .reportHandlerRegistered(commandType.getSimpleName());
    }

    
    @Override
    public <T> void unsubscribe(Class<T> commandTypeCommandHandler<? super T> handler) {
        .remove(commandTypehandler);
        .recordUnregisteredHandler(commandType.getSimpleName());
    }

    
Registers the given list of interceptors to the command bus. All incoming commands will pass through the interceptors at the given order before the command is passed to the handler for processing. After handling, the afterCommandHandling methods are invoked on the interceptors in the reverse order.

Parameters:
interceptors The interceptors to invoke when commands are dispatched
    public void setInterceptors(List<? extends CommandHandlerInterceptorinterceptors) {
        this. = interceptors;
    }

    
Convenience method that allows you to register command handlers using a Dependency Injection framework. The parameter of this method is a Map<Class<T>, CommandHandler<? super T>>. The key represents the type of command to register the handler for, the value is the actual handler.

Parameters:
handlers The handlers to subscribe in the form of a Map of Class - CommandHandler entries.
    @SuppressWarnings({"unchecked"})
    public void setSubscriptions(Map<?, ?> handlers) {
        for (Map.Entry<?, ?> entry : handlers.entrySet()) {
            subscribe((Class<?>) entry.getKey(), (CommandHandlerentry.getValue());
        }
    }

    
Sets the UnitOfWorkFactory that provides the UnitOfWork instances for handling incoming commands. Defaults to a org.axonframework.unitofwork.DefaultUnitOfWorkFactory.

Parameters:
unitOfWorkFactory The UnitOfWorkFactory providing UoW instances for this Command Bus.
    public void setUnitOfWorkFactory(UnitOfWorkFactory unitOfWorkFactory) {
        this. = unitOfWorkFactory;
    }

    
Sets the RollbackConfiguration that allows you to change when the UnitOfWork is committed. If not set the RollbackOnAllExceptionsConfiguration will be used, which triggers a rollback on all exceptions.

Parameters:
rollbackConfiguration The RollbackConfiguration.
    public void setRollbackConfiguration(RollbackConfiguration rollbackConfiguration) {
        this. = rollbackConfiguration;
    }
New to GrepCode? Check out our FAQ X