+htp #16438 add Java-side rejection handling support

This commit is contained in:
Johannes Rudolph 2015-09-09 10:31:00 +02:00
parent 96ef8875c8
commit db1be86b02
11 changed files with 427 additions and 2 deletions

View file

@ -56,4 +56,97 @@ public class ExecutionDirectivesTest extends JUnitRouteTest {
.assertStatusCode(400)
.assertEntity("Congratulations you provoked a division by zero!");
}
@Test
public void testHandleMethodRejection() {
RejectionHandler rejectionHandler =
new RejectionHandler() {
@Override
public RouteResult handleMethodRejection(RequestContext ctx, HttpMethod supported) {
return ctx.complete(
HttpResponse.create()
.withStatus(400)
.withEntity("Whoopsie! Unsupported method. Supported would have been " + supported.value()));
}
};
TestRoute route =
testRoute(
handleRejections(rejectionHandler,
get(complete("Successful!"))
)
);
route.run(HttpRequest.GET("/"))
.assertStatusCode(200)
.assertEntity("Successful!");
route.run(HttpRequest.POST("/"))
.assertStatusCode(400)
.assertEntity("Whoopsie! Unsupported method. Supported would have been GET");
}
public static final class TooManyRequestsRejection extends CustomRejection {
final public String message;
TooManyRequestsRejection(String message) {
this.message = message;
}
}
private static Handler testHandler =
new Handler() {
@Override
public RouteResult apply(RequestContext ctx) {
if (ctx.request().getUri().path().startsWith("/test"))
return ctx.complete("Successful!");
else
return ctx.reject(new TooManyRequestsRejection("Too many requests for busy path!"));
}
};
@Test
public void testHandleCustomRejection() {
RejectionHandler rejectionHandler =
new RejectionHandler() {
@Override
public RouteResult handleCustomRejection(RequestContext ctx, CustomRejection rejection) {
if (rejection instanceof TooManyRequestsRejection) {
TooManyRequestsRejection rej = (TooManyRequestsRejection) rejection;
HttpResponse response =
HttpResponse.create()
.withStatus(StatusCodes.TOO_MANY_REQUESTS)
.withEntity(rej.message);
return ctx.complete(response);
} else
return passRejection();
}
};
testRouteWithHandler(handleRejections(rejectionHandler, handleWith(testHandler)));
}
@Test
public void testHandleCustomRejectionByClass() {
Handler1<TooManyRequestsRejection> rejectionHandler =
new Handler1<TooManyRequestsRejection>() {
public RouteResult apply(RequestContext ctx, TooManyRequestsRejection rej) {
HttpResponse response =
HttpResponse.create()
.withStatus(StatusCodes.TOO_MANY_REQUESTS)
.withEntity(rej.message);
return ctx.complete(response);
}
};
testRouteWithHandler(handleRejections(TooManyRequestsRejection.class, rejectionHandler, handleWith(testHandler)));
}
private void testRouteWithHandler(Route innerRoute) {
TestRoute route = testRoute(innerRoute);
route.run(HttpRequest.GET("/test"))
.assertStatusCode(200);
route.run(HttpRequest.GET("/other"))
.assertStatusCode(429)
.assertEntity("Too many requests for busy path!");
}
}