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

de.codecamp.messages.proxy.NamedArgsMessageProxyInvocationHandler Maven / Gradle / Ivy

package de.codecamp.messages.proxy;


import de.codecamp.messages.ResolvableMessage;
import de.codecamp.messages.ResolvableMessage.Builder;
import de.codecamp.messages.codegen.MessageProxyInterface;
import de.codecamp.messages.codegen.MessageProxyMethod;
import de.codecamp.messages.codegen.MessageProxyParam;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;


/**
 * An {@link InvocationHandler} for {@link MessageProxyInterface} interfaces that uses a
 * {@link NamedArgsMessageProvider}.
 *
 * @see MessageProxyUtils#createNamedArgsMessageProxy(Class, NamedArgsMessageProvider)
 */
public class NamedArgsMessageProxyInvocationHandler
  extends
    AbstractMessageProxyInvocationHandler
{

  private final NamedArgsMessageProvider messageProvider;


  /**
   * Constructs a new {@link NamedArgsMessageProxyInvocationHandler}.
   *
   * @param messageProvider
   *          the message provider used to resolve and format message keys
   */
  public NamedArgsMessageProxyInvocationHandler(NamedArgsMessageProvider messageProvider)
  {
    if (messageProvider == null)
      throw new IllegalArgumentException("messageProvider must not be null");

    this.messageProvider = messageProvider;
  }


  @Override
  public Object invoke(Object proxy, Method method, Object[] args)
    throws Throwable
  {
    MessageProxyMethod messageProxyMethodAt = method.getAnnotation(MessageProxyMethod.class);
    if (messageProxyMethodAt != null)
    {
      String code = messageProxyMethodAt.code();

      Builder builder = ResolvableMessage.forCode(code);
      if (method.getParameterCount() > 0)
      {
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++)
        {
          Parameter param = parameters[i];

          String argName = null;

          MessageProxyParam argNameAt = param.getAnnotation(MessageProxyParam.class);
          if (argNameAt != null)
            argName = !argNameAt.name().isEmpty() ? argNameAt.name() : null;

          builder.arg(argName, args[i]);
        }
      }

      return messageProvider.getMessage(builder.build());
    }

    else
    {
      return super.invoke(proxy, method, args);
    }
  }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy