All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.networknt.tram.command.consumer.CommandHandler Maven / Gradle / Ivy

package com.networknt.tram.command.consumer;


import com.networknt.tram.command.common.CommandMessageHeaders;
import com.networknt.tram.command.common.paths.ResourcePath;
import com.networknt.tram.command.common.paths.ResourcePathPattern;
import com.networknt.tram.message.common.Message;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiFunction;


public class CommandHandler {

  private final String channel;
  private final Optional resource;
  private final Class commandClass;
  private final BiFunction, PathVariables, List> handler;

  public  CommandHandler(String channel, Optional resource,
                            Class commandClass,
                            BiFunction, PathVariables, List> handler) {
    this.channel = channel;
    this.resource = resource;
    this.commandClass = commandClass;
    this.handler = (cm, pv) -> handler.apply((CommandMessage) cm, pv);
  }

  public String getChannel() {
    return channel;
  }

  public boolean handles(Message message) {
    return commandTypeMatches(message) && resourceMatches(message);
  }

  private boolean resourceMatches(Message message) {
    return !resource.isPresent() || message.getHeader(CommandMessageHeaders.RESOURCE).map(m -> resourceMatches(m, resource.get())).orElse(false);
  }

  private boolean commandTypeMatches(Message message) {
    return commandClass.getName().equals(
            message.getRequiredHeader(CommandMessageHeaders.COMMAND_TYPE));
  }

  private boolean resourceMatches(String messageResource, String methodPath) {
    ResourcePathPattern r = ResourcePathPattern.parse(methodPath);
    ResourcePath mr = ResourcePath.parse(messageResource);
    return r.isSatisfiedBy(mr);
  }

  public Class getCommandClass() {
    return commandClass;
  }

  public Optional getResource() {
    return resource;
  }

  public List invokeMethod(CommandMessage commandMessage, Map pathVars) {
    return handler.apply(commandMessage, new PathVariables(pathVars));
  }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy