ApiKeyInterceptor extends AbstractInterceptor { String unauthorized(ActionInvocation invocation, ApiKeyPermissionService.Status reason) throws IOException { ActionProxy proxy = invocation.getProxy(); int httpCode = ResponseCodes.RESPONSE_UNAUTHORIZED; String message = "permission denied"; switch (reason) { case UNAUTHORIZED: httpCode = ResponseCodes.RESPONSE_UNAUTHORIZED; break; case RATE_EXCEEDED: httpCode = ResponseCodes.RESPONSE_TOO_MANY_REQUESTS; message = "rate limit exceeded"; break; case AUTHORIZED: throw new IllegalStateException("Valid status code " + reason + " in unauthorized response"); default: httpCode = ResponseCodes.RESPONSE_UNAUTHORIZED; } ResponseBean response = new ResponseBean(1, httpCode, message, null); DefaultHttpHeaders methodResult = new DefaultHttpHeaders().withStatus(response.getCode()); return _handlerSelector.handleResult(proxy.getConfig(), methodResult, response); }  @Inject void setMimeTypeHandlerSelector(ContentTypeHandlerManager sel); @Override String intercept(ActionInvocation invocation); @Autowired void setKeyService(ApiKeyPermissionService _keyService); ApiKeyPermissionService getKeyService();  }
@Test public void testUnauthorized200() throws Exception { ApiKeyPermissionService.Status reason = Status.AUTHORIZED; try { _aki.unauthorized(_ai, reason); fail("expected illegal state exception"); } catch (IllegalStateException ise) {} }
@Test public void testUnauthorized401() throws Exception { ApiKeyPermissionService.Status reason = Status.UNAUTHORIZED; assertEquals(_aki.unauthorized(_ai, reason), "SUCCESS"); verify(mockContentTypeHandlerManager).handleResult((ActionConfig) anyObject(), methodResultCaptor.capture(), responseCaptor.capture()); assertThat(methodResultCaptor.getValue().getStatus(), equalTo(401)); assertThat(responseCaptor.getValue().getText(), equalTo("permission denied")); assertThat(responseCaptor.getValue().getCode(), equalTo(401)); }
@Test public void testUnauthorized429() throws Exception { ApiKeyPermissionService.Status reason = Status.RATE_EXCEEDED; assertEquals(_aki.unauthorized(_ai, reason), "SUCCESS"); verify(mockContentTypeHandlerManager).handleResult((ActionConfig) anyObject(), methodResultCaptor.capture(), responseCaptor.capture()); assertThat(methodResultCaptor.getValue().getStatus(), equalTo(429)); assertThat(responseCaptor.getValue().getText(), equalTo("rate limit exceeded")); assertThat(responseCaptor.getValue().getCode(), equalTo(429)); }