BAEL-1551 Jersey filters and interceptors

This commit is contained in:
Marcos Lopez Gonzalez 2018-02-25 21:36:23 +01:00
parent a4d682e57b
commit f532a2cf0b
16 changed files with 443 additions and 4 deletions

63
jersey/pom.xml Normal file
View File

@ -0,0 +1,63 @@
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>jersey</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<jersey.version>2.26</jersey.version>
<slf4j.version>1.7.25</slf4j.version>
<maven-war-plugin.version>3.2.0</maven-war-plugin.version>
</properties>
<build>
<finalName>jersey</finalName>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.bundles</groupId>
<artifactId>jaxrs-ri</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,45 @@
package com.baeldung.jersey.client;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
import com.baeldung.jersey.client.filter.RequestClientFilter;
import com.baeldung.jersey.client.filter.ResponseClientFilter;
import com.baeldung.jersey.client.interceptor.RequestClientWriterInterceptor;
public class JerseyClient {
private static final String URI_GREETINGS = "http://localhost:8080/jersey/greetings";
public static String getHelloGreeting() {
return createClient().target(URI_GREETINGS)
.request()
.get(String.class);
}
public static String getHiGreeting() {
return createClient().target(URI_GREETINGS + "/hi")
.request()
.get(String.class);
}
public static Response getCustomGreeting() {
return createClient().target(URI_GREETINGS + "/custom")
.request()
.post(Entity.text("custom"));
}
private static Client createClient() {
ClientConfig config = new ClientConfig();
config.register(RequestClientFilter.class);
config.register(ResponseClientFilter.class);
config.register(RequestClientWriterInterceptor.class);
return ClientBuilder.newClient(config);
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.jersey.client.filter;
import java.io.IOException;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.ext.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Provider
public class RequestClientFilter implements ClientRequestFilter {
private static final Logger LOG = LoggerFactory.getLogger(RequestClientFilter.class);
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
LOG.info("Request client filter");
requestContext.setProperty("test", "test client request filter");
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.jersey.client.filter;
import java.io.IOException;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientResponseContext;
import javax.ws.rs.client.ClientResponseFilter;
import javax.ws.rs.ext.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Provider
public class ResponseClientFilter implements ClientResponseFilter {
private static final Logger LOG = LoggerFactory.getLogger(ResponseClientFilter.class);
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
LOG.info("Response client filter");
responseContext.getHeaders()
.add("X-Test-Client", "Test response client filter");
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.jersey.client.interceptor;
import java.io.IOException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Provider
public class RequestClientWriterInterceptor implements WriterInterceptor {
private static final Logger LOG = LoggerFactory.getLogger(RequestClientWriterInterceptor.class);
@Override
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
LOG.info("request writer interceptor in the client side");
context.getOutputStream()
.write(("Message added in the writer interceptor in the client side").getBytes());
context.proceed();
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.jersey.server;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import com.baeldung.jersey.server.config.HelloBinding;
@Path("/greetings")
public class Greetings {
@GET
@HelloBinding
public String getHelloGreeting() {
return "hello";
}
@GET
@Path("/hi")
public String getHiGreeting() {
return "hi";
}
@POST
@Path("/custom")
public String getCustomGreeting(String name) {
return "hello " + name;
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.jersey.server.config;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.ws.rs.NameBinding;
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
public @interface HelloBinding {
}

View File

@ -0,0 +1,31 @@
package com.baeldung.jersey.server.config;
import javax.ws.rs.container.DynamicFeature;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.ext.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baeldung.jersey.server.Greetings;
import com.baeldung.jersey.server.filter.ResponseServerFilter;
@Provider
public class HelloDynamicBinding implements DynamicFeature {
private static final Logger LOG = LoggerFactory.getLogger(HelloDynamicBinding.class);
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
LOG.info("Hello dynamic binding");
if (Greetings.class.equals(resourceInfo.getResourceClass()) && resourceInfo.getResourceMethod()
.getName()
.contains("HiGreeting")) {
context.register(ResponseServerFilter.class);
}
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.jersey.server.config;
import javax.ws.rs.ApplicationPath;
import org.glassfish.jersey.server.ResourceConfig;
@ApplicationPath("/*")
public class ServerConfig extends ResourceConfig {
public ServerConfig() {
packages("com.baeldung.jersey.server");
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.jersey.server.filter;
import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.ext.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Provider
@PreMatching
public class PrematchingRequestFilter implements ContainerRequestFilter {
private static final Logger LOG = LoggerFactory.getLogger(PrematchingRequestFilter.class);
@Override
public void filter(ContainerRequestContext ctx) throws IOException {
LOG.info("prematching filter");
if (ctx.getMethod()
.equals("DELETE")) {
LOG.info("\"Deleting request");
}
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.jersey.server.filter;
import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ResponseServerFilter implements ContainerResponseFilter {
private static final Logger LOG = LoggerFactory.getLogger(ResponseServerFilter.class);
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
LOG.info("Response server filter");
responseContext.getHeaders()
.add("X-Test", "Filter test");
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.jersey.server.filter;
import java.io.IOException;
import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baeldung.jersey.server.config.HelloBinding;
@Provider
@Priority(Priorities.AUTHORIZATION)
@HelloBinding
public class RestrictedOperationsRequestFilter implements ContainerRequestFilter {
private static final Logger LOG = LoggerFactory.getLogger(RestrictedOperationsRequestFilter.class);
@Override
public void filter(ContainerRequestContext ctx) throws IOException {
LOG.info("Restricted operations filter");
if (ctx.getLanguage() != null && "EN".equals(ctx.getLanguage()
.getLanguage())) {
LOG.info("Aborting request");
ctx.abortWith(Response.status(Response.Status.FORBIDDEN)
.entity("Cannot access")
.build());
}
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.jersey.server.interceptor;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.ReaderInterceptor;
import javax.ws.rs.ext.ReaderInterceptorContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Provider
public class RequestServerReaderInterceptor implements ReaderInterceptor {
private static final Logger LOG = LoggerFactory.getLogger(RequestServerReaderInterceptor.class);
@Override
public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException {
LOG.info("Request reader interceptor in the server side");
InputStream is = context.getInputStream();
String body = new BufferedReader(new InputStreamReader(is)).lines()
.collect(Collectors.joining("\n"));
context.setInputStream(new ByteArrayInputStream((body + " message added in server reader interceptor").getBytes()));
return context.proceed();
}
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern> %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,33 @@
package com.baeldung.jersey.client;
import javax.ws.rs.core.Response;
import org.junit.Assert;
import org.junit.Test;
public class JerseyClientTest {
private static int HTTP_OK = 200;
@Test
public void getHelloGreetingTest() {
String response = JerseyClient.getHelloGreeting();
Assert.assertEquals("hello", response);
}
@Test
public void getHiGreetingTest() {
String response = JerseyClient.getHiGreeting();
Assert.assertEquals("hi", response);
}
@Test
public void getCustomGreetingTest() {
Response response = JerseyClient.getCustomGreeting();
Assert.assertEquals(HTTP_OK, response.getStatus());
}
}

View File

@ -1,6 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
@ -281,7 +280,8 @@
<module>lucene</module>
<module>vraptor</module>
<module>persistence-modules/java-cockroachdb</module>
</modules>
<module>jersey</module>
</modules>
<dependencies>
<!-- logging -->
@ -384,4 +384,4 @@
</extension>
</extensions>
</build>
</project>
</project>