12.9. RESTEasy インターセプター
12.9.1. JAX-RS 呼び出しのインターセプト
RESTEasy は JAX-RS 呼び出しをインターセプトでき、インターセプターと呼ばれるリスナーのようなオブジェクトでルーティングを行います。このトピックでは、インターセプター4種について説明していきます。
例12.3 MessageBodyReader/Writer インターセプター
@Provider
と、 @ServerInterceptor
または @ClientInterceptor
がアノテートされます。
MessageBodyReader.readFrom()
あるいは MessageBodyWriter.writeTo()
の呼び出しをラップします。また、出力、入力ストリームをラップする際にも利用可能です。
public interface MessageBodyReaderInterceptor { Object read(MessageBodyReaderContext context) throws IOException, WebApplicationException; } public interface MessageBodyWriterInterceptor { void write(MessageBodyWriterContext context) throws IOException, WebApplicationException; }
MessageBodyReaderContext.proceed()
あるいは MessageBodyWriterContext.proceed()
が呼び出され、これ以上呼び出すインターセプターがない場合、MessageBodyReader あるいは MessageBodyWriter の readFrom()
あるいは writeTo()
が呼び出されます。このラッピングにより、オブジェクトがReader あるいは Writer に到達前にオブジェクトを変更することができ、proceed()
を返すまでに消去できます。
@Provider @ServerInterceptor public class MyHeaderDecorator implements MessageBodyWriterInterceptor { public void write(MessageBodyWriterContext context) throws IOException, WebApplicationException { context.getHeaders().add("My-Header", "custom"); context.proceed(); } }
例12.4 PreProcessInterceptor
public interface PreProcessInterceptor { ServerResponse preProcess(HttpRequest request, ResourceMethod method) throws Failure, WebApplicationException; }
preProcess()
メソッドは ServerResponse を返し、基礎となる JAX-RS メソッドは呼び出されず、ランタイムがレスポンスを処理しクライアントに返します。preProcess()
メソッドが ServerResponse を返さない場合は、基礎となる JAX-RS メソッドが呼び出されます。
例12.5 PostProcessInterceptors
public interface PostProcessInterceptor { void postProcess(ServerResponse response); }
例12.6 ClientExecutionInterceptors
@ClientInterceptor
や @Provider
のアノテーションが付けられます。MessageBodyWriter の実行後、および ClientRequest がクライアント側で構築された後に実行されます。
public interface ClientExecutionInterceptor { ClientResponse execute(ClientExecutionContext ctx) throws Exception; } public interface ClientExecutionContext { ClientRequest getRequest(); ClientResponse proceed() throws Exception; }