package com.juick.command; import com.juick.User; import com.juick.server.protocol.ProtocolListener; import lombok.Getter; import lombok.Setter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Set; import java.util.regex.Pattern; /** * @author ma1uta */ @Component @Getter public class Processor { private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class); private final Set commands; @Setter private ProtocolListener protocolListener; @Autowired public Processor(Set commands) { this.commands = commands; } public String execute(User sender, String command) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Execute command: {}", command); } command = command != null ? command.trim() : ""; Command defaultCommand = null; Command helpCommand = null; for (Command commandItem : getCommands()) { if (commandItem instanceof ShowHelp) { helpCommand = commandItem; } Pattern pattern = commandItem.pattern(); if (pattern != null && pattern.matcher(command).matches()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Found command processor: {}", commandItem.getClass().getName()); } return commandItem.execute(sender, getProtocolListener(), command); } else { defaultCommand = commandItem; } } if (defaultCommand != null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Found default command processor: {}", defaultCommand.getClass().getName()); } return defaultCommand.execute(sender, getProtocolListener(), command); } LOGGER.debug("Command processor not found, return help"); return helpCommand != null ? helpCommand.execute(sender, getProtocolListener(), command) : "Help not found"; } }