Skip to content

Instantly share code, notes, and snippets.

@juliano
Last active December 16, 2015 23:21
Show Gist options
  • Save juliano/5513496 to your computer and use it in GitHub Desktop.
Save juliano/5513496 to your computer and use it in GitHub Desktop.
Interceptor que verifica se os parâmetros informados estão de acordo com a anotação @whitelist
import static br.com.caelum.vraptor.util.collections.Filters.hasAnnotation;
import static com.google.common.collect.Iterables.any;
import static java.util.Arrays.asList;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import br.com.caelum.vraptor.InterceptionException;
import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.core.InterceptorStack;
import br.com.caelum.vraptor.core.MethodInfo;
import br.com.caelum.vraptor.interceptor.Interceptor;
import br.com.caelum.vraptor.interceptor.ParametersInstantiatorInterceptor;
import br.com.caelum.vraptor.ioc.RequestScoped;
import br.com.caelum.vraptor.resource.ResourceMethod;
@Intercepts(after = ParametersInstantiatorInterceptor.class)
@RequestScoped
public class ParametersValidatorInterceptor implements Interceptor {
private final MethodInfo methodInfo;
public ParametersValidatorInterceptor(final MethodInfo methodInfo) {
this.methodInfo = methodInfo;
}
public void intercept(final InterceptorStack stack, final ResourceMethod method,
final Object resourceInstance) throws InterceptionException {
Object[] parameters = methodInfo.getParameters();
List<Object> filteredParameters = filterWithWhiteList(method, parameters);
methodInfo.setParameters(filteredParameters.toArray());
stack.next(method, resourceInstance);
}
private List<Object> filterWithWhiteList(final ResourceMethod method, final Object[] parameters) {
List<Object> filtered = new ArrayList<Object>();
Annotation[][] annotations = method.getMethod().getParameterAnnotations();
for (int i = 0; i < annotations.length; i++) {
Object parameter = parameters[i];
for (Annotation annotation : annotations[i]) {
if (annotation instanceof WhiteList) {
WhiteList whiteList = (WhiteList) annotation;
filtered.add(Clonefy.clone(parameter, whiteList.value()));
}
}
}
return filtered;
}
public boolean accepts(final ResourceMethod method) {
return any(asList(method.getMethod().getParameterAnnotations()),
hasAnnotation(WhiteList.class));
}
}
@raphait
Copy link

raphait commented May 3, 2013

o accepts poderia ficar assim:
return any(asList(method.getMethod().getParameterAnnotations()), hasAnnotation(WhiteList.class))

@juliano
Copy link
Author

juliano commented May 4, 2013

É uma sugestão de refactoring ou os métodos any e hasAnnotation existem? De quais classes eles são?

@carlosspohr
Copy link

Ficou da hora :), parabéns cara.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment