All pastes #543821 Raw Edit

Untitled

public java v1 · immutable
·published 2007-06-06 06:07 UTC
rendered paste body
package net.lionsanctuary.podpeople.podcasts.interceptors;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.LinkedList;import java.util.List;import net.lionsanctuary.podpeople.podcasts.api.DummyPodcastFactory;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.AbstractInterceptor;/** * Injects a podcast service into Action implementations. */public class PodcastServiceInjector extends AbstractInterceptor {  private static final int REQUIRED_PARAMETERS = 1;  /**   * Injects the dummy podcast service into the target invocation's action. Any   * method annotated with {@link Source} will be passed the dummy podcast   * service as an argument.   *    * @param invocation   *          the action invocation context to inject against.   * @return the result of continuing invocation after injection.   * @throws Exception   *           if the invocation throws an exception, or if injection fails.   * @see com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com.opensymphony.xwork2.ActionInvocation)   */  @Override  public String intercept (ActionInvocation invocation) throws Exception {    DummyPodcastFactory service = new DummyPodcastFactory ();    Object action = invocation.getAction ();    if (action != null)      for (Method target : findInjectionTargets (action))        injectService (service, action, target);    return invocation.invoke ();  }  private void injectService (DummyPodcastFactory service, Object action,      Method target) throws Exception {    assert (action != null);    assert (target != null);    assert (hasCompatibleSignature (target));    boolean state = forceAccessible (target);    try {      target.invoke (action, service);    } finally {      restoreAccessibleState (target, state);    }  }  private void restoreAccessibleState (Method target, boolean state) {    assert (target != null);    target.setAccessible (state);  }  private boolean forceAccessible (Method target) {    boolean state = target.isAccessible ();    target.setAccessible (true);    return state;  }  private Iterable<Method> findInjectionTargets (Object action) {    assert (action != null);    List<Method> targets = new LinkedList<Method> ();    Class<?> actionClass = action.getClass ();    for (Method method : actionClass.getMethods ()) {      if (hasInjectionAnnotation (method) && hasCompatibleSignature (method))        targets.add (method);    }    return targets;  }  private boolean hasCompatibleSignature (Method method) {    assert (method != null);    return method.getParameterTypes ().length == REQUIRED_PARAMETERS;  }  private boolean hasInjectionAnnotation (Method method) {    assert (method != null);    return method.getAnnotation (Source.class) != null;  }}