Skip to content

Instantly share code, notes, and snippets.

@tresbailey
Created October 19, 2012 00:59
Show Gist options
  • Save tresbailey/3915667 to your computer and use it in GitHub Desktop.
Save tresbailey/3915667 to your computer and use it in GitHub Desktop.
Going against the grain on best practices, and presenting an annotation to shunt requests for a given path to a component that forces a return of a different object. Avoids boilerplate in each of the controller methods to search for paths.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.tresback.testing;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* @author rbailey
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RestTestable {
Class target();
String[] path() default {};
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.tresback.testing;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
*
* @author rbailey
*/
@Component
@Aspect
public class RestTestableAspect {
protected final Logger log = LoggerFactory.getLogger(getClass());
@Around(value = "@annotation(com.tresback.testing.RestTestable) && @annotation(RestTestable)", argNames="RestTestable")
public Object processAnnotations(ProceedingJoinPoint pjp, RestTestable restTestable) throws Throwable {
log.debug("Processing annotations");
if ( restTestable != null ) {
log.debug("Testing enabled on path: "+ restTestable.path());
}
int index = 0;
MethodSignature sig = (MethodSignature) pjp.getSignature();
Class[] parameterTypes = sig.getParameterTypes();
log.debug("Got signature: "+ parameterTypes);
log.debug("Argument 0: "+ pjp.getArgs()[0]);
for (Object arg : pjp.getArgs() ) {
log.debug("Arg to check: "+ arg.toString() +" vs: "+ restTestable.path());
if ( (index < restTestable.path().length) &&
(String.class == parameterTypes[index] ) &&
!(arg.toString().equals(restTestable.path()[index])) ) {
log.debug("proceeding");
return pjp.proceed();
}
index++;
}
Class klass = restTestable.target();
Object obj = klass.newInstance();
log.debug("Returning the default object: "+ obj.toString());
return obj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment