Back to Demos

Processor Pattern

Command routing with level-based authorization from ProcessorManager

Execute Command

Stats

All Processors (0)

Production Code (Java)

// From paygate/AmunPaygate - ProcessorManager.java
@Component
public class ProcessorManager {
    private Map<String, Processor> processors = new HashMap<>();

    @PostConstruct
    private void init() {
        // Auto-register processors via annotation scanning
        Reflections reflections = new Reflections("com.amun.paygate.processor");
        Set<Class<?>> classes = reflections.getTypesAnnotatedWith(ProcessorClass.class);

        for (Class<?> clazz : classes) {
            ProcessorClass annotation = clazz.getAnnotation(ProcessorClass.class);
            String command = annotation.command();
            CommandLevel level = annotation.level();

            Processor processor = (Processor) context.getBean(clazz);
            processors.put(command, processor);
            log.info("register `{}` level: {}", command, level);
        }
    }

    public PuElement processCommand(String command, Message request, CommandLevel commandLevel)
            throws CommandNotFoundException, PaygateException, CommandLevelException {

        if (processors.containsKey(command)) {
            Processor processor = processors.get(command);

            // Check permission level
            if (processor.getLevel().compare(commandLevel) > 0) {
                throw new CommandLevelException();
            }

            return processor.executeMessage(request);
        }
        throw new CommandNotFoundException();
    }
}