Skip to content

Commit 3960410

Browse files
committed
BAEL-2060 - Bean Validation in Jersey
1 parent 364aa9a commit 3960410

8 files changed

Lines changed: 269 additions & 11 deletions

File tree

‎jersey/pom.xml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,11 @@
3939
<artifactId>jersey-mvc-freemarker</artifactId>
4040
<version>${jersey.version}</version>
4141
</dependency>
42+
<dependency>
43+
<groupId>org.glassfish.jersey.ext</groupId>
44+
<artifactId>jersey-bean-validation</artifactId>
45+
<version>${jersey.version}</version>
46+
</dependency>
4247
<dependency>
4348
<groupId>org.glassfish.jersey.test-framework</groupId>
4449
<artifactId>jersey-test-framework-core</artifactId>

‎jersey/src/main/java/com/baeldung/jersey/server/config/ViewApplicationConfig.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
package com.baeldung.jersey.server.config;
22

33
import org.glassfish.jersey.server.ResourceConfig;
4+
import org.glassfish.jersey.server.ServerProperties;
45
import org.glassfish.jersey.server.mvc.freemarker.FreemarkerMvcFeature;
56

67
public class ViewApplicationConfig extends ResourceConfig {
78

89
public ViewApplicationConfig() {
910
packages("com.baeldung.jersey.server");
11+
property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);
1012
property(FreemarkerMvcFeature.TEMPLATE_BASE_PATH, "templates/freemarker");
1113
register(FreemarkerMvcFeature.class);;
1214
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.baeldung.jersey.server.constraints;
2+
3+
import java.lang.annotation.Retention;
4+
import java.lang.annotation.RetentionPolicy;
5+
import java.util.regex.Pattern;
6+
7+
import javax.validation.Constraint;
8+
import javax.validation.ConstraintValidator;
9+
import javax.validation.ConstraintValidatorContext;
10+
import javax.validation.Payload;
11+
12+
@Retention(RetentionPolicy.RUNTIME)
13+
@Constraint(validatedBy = { SerialNumber.Validator.class })
14+
public @interface SerialNumber {
15+
16+
String message()
17+
18+
default "Fruit serial number is not valid";
19+
20+
Class<?>[] groups() default {};
21+
22+
Class<? extends Payload>[] payload() default {};
23+
24+
public class Validator implements ConstraintValidator<SerialNumber, String> {
25+
@Override
26+
public void initialize(final SerialNumber serial) {
27+
}
28+
29+
@Override
30+
public boolean isValid(final String serial, final ConstraintValidatorContext constraintValidatorContext) {
31+
final String serialNumRegex = "^\\d{3}-\\d{3}-\\d{4}$";
32+
return Pattern.matches(serialNumRegex, serial);
33+
}
34+
}
35+
}
Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,57 @@
11
package com.baeldung.jersey.server.model;
22

3+
import javax.validation.constraints.Min;
4+
import javax.validation.constraints.Size;
5+
import javax.xml.bind.annotation.XmlRootElement;
6+
7+
@XmlRootElement
38
public class Fruit {
49

5-
private final String name;
6-
private final String colour;
10+
@Min(value = 10, message = "Fruit weight must be 10 or greater")
11+
private Integer weight;
12+
@Size(min = 5, max = 200)
13+
private String name;
14+
@Size(min = 5, max = 200)
15+
private String colour;
16+
private String serial;
17+
18+
public Fruit() {
19+
}
720

821
public Fruit(String name, String colour) {
922
this.name = name;
1023
this.colour = colour;
1124
}
12-
25+
1326
public String getName() {
1427
return name;
1528
}
29+
30+
public void setName(String name) {
31+
this.name = name;
32+
}
33+
34+
public void setColour(String colour) {
35+
this.colour = colour;
36+
}
1637

1738
public String getColour() {
1839
return colour;
1940
}
41+
42+
public Integer getWeight() {
43+
return weight;
44+
}
45+
46+
public void setWeight(Integer weight) {
47+
this.weight = weight;
48+
}
49+
50+
public String getSerial() {
51+
return serial;
52+
}
53+
54+
public void setSerial(String serial) {
55+
this.serial = serial;
56+
}
2057
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.baeldung.jersey.server.providers;
2+
3+
import javax.validation.ConstraintViolation;
4+
import javax.validation.ConstraintViolationException;
5+
import javax.ws.rs.core.Response;
6+
import javax.ws.rs.ext.ExceptionMapper;
7+
8+
public class FruitExceptionMapper implements ExceptionMapper<ConstraintViolationException> {
9+
10+
@Override
11+
public Response toResponse(final ConstraintViolationException exception) {
12+
return Response.status(Response.Status.BAD_REQUEST)
13+
.entity(prepareMessage(exception))
14+
.type("text/plain")
15+
.build();
16+
}
17+
18+
private String prepareMessage(ConstraintViolationException exception) {
19+
final StringBuilder message = new StringBuilder();
20+
for (ConstraintViolation<?> cv : exception.getConstraintViolations()) {
21+
message.append(cv.getPropertyPath() + " " + cv.getMessage() + "\n");
22+
}
23+
return message.toString();
24+
}
25+
26+
}

‎jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,13 @@
55
import java.util.List;
66
import java.util.Map;
77

8+
import javax.validation.Valid;
9+
import javax.validation.constraints.NotNull;
10+
import javax.ws.rs.Consumes;
11+
import javax.ws.rs.FormParam;
812
import javax.ws.rs.GET;
13+
import javax.ws.rs.POST;
14+
import javax.ws.rs.PUT;
915
import javax.ws.rs.Path;
1016
import javax.ws.rs.PathParam;
1117
import javax.ws.rs.Produces;
@@ -15,7 +21,9 @@
1521
import org.glassfish.jersey.server.mvc.Template;
1622
import org.glassfish.jersey.server.mvc.Viewable;
1723

24+
import com.baeldung.jersey.server.constraints.SerialNumber;
1825
import com.baeldung.jersey.server.model.Fruit;
26+
import com.baeldung.jersey.service.SimpleStorageService;
1927

2028
@Path("/fruit")
2129
public class FruitResource {
@@ -52,4 +60,49 @@ public String getFruitByName(@PathParam("name") String name) {
5260
return name;
5361
}
5462

63+
@POST
64+
@Path("/create")
65+
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
66+
public void createFruit(
67+
@NotNull(message = "Fruit name must not be null") @FormParam("name") String name,
68+
@NotNull(message = "Fruit colour must not be null") @FormParam("colour") String colour) {
69+
70+
Fruit fruit = new Fruit(name, colour);
71+
SimpleStorageService.storeFruit(fruit);
72+
}
73+
74+
@PUT
75+
@Path("/update")
76+
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
77+
public void updateFruit(@SerialNumber @FormParam("serial") String serial) {
78+
Fruit fruit = new Fruit();
79+
fruit.setSerial(serial);
80+
SimpleStorageService.storeFruit(fruit);
81+
}
82+
83+
@POST
84+
@Path("/create")
85+
@Consumes(MediaType.APPLICATION_JSON)
86+
public void createFruit(@Valid Fruit fruit) {
87+
SimpleStorageService.storeFruit(fruit);
88+
}
89+
90+
@GET
91+
@Valid
92+
@Produces(MediaType.APPLICATION_JSON)
93+
@Path("/search/{name}")
94+
public Fruit findFruitByName(@PathParam("name") String name) {
95+
return SimpleStorageService.findByName(name);
96+
}
97+
98+
@GET
99+
@Produces(MediaType.TEXT_HTML)
100+
@Path("/exception")
101+
@Valid
102+
public Fruit exception() {
103+
Fruit fruit = new Fruit();
104+
fruit.setName("a");
105+
fruit.setColour("b");
106+
return fruit;
107+
}
55108
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.baeldung.jersey.service;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
import com.baeldung.jersey.server.model.Fruit;
7+
8+
public class SimpleStorageService {
9+
10+
private static final Map<String, Fruit> fruits = new HashMap<String, Fruit>();
11+
12+
public static void storeFruit(final Fruit fruit) {
13+
fruits.put(fruit.getName(), fruit);
14+
}
15+
16+
public static Fruit findByName(final String name) {
17+
return fruits.entrySet()
18+
.stream()
19+
.filter(map -> name.equals(map.getKey()))
20+
.map(map -> map.getValue())
21+
.findFirst()
22+
.get();
23+
}
24+
25+
}

‎jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java‎

Lines changed: 83 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,41 +2,116 @@
22

33
import static org.hamcrest.CoreMatchers.allOf;
44
import static org.hamcrest.CoreMatchers.containsString;
5+
import static org.junit.Assert.assertEquals;
6+
import static org.junit.Assert.assertThat;
57

8+
import javax.ws.rs.client.Entity;
69
import javax.ws.rs.core.Application;
10+
import javax.ws.rs.core.Form;
11+
import javax.ws.rs.core.MediaType;
12+
import javax.ws.rs.core.Response;
713

814
import org.glassfish.jersey.test.JerseyTest;
9-
import org.junit.Assert;
15+
import org.glassfish.jersey.test.TestProperties;
1016
import org.junit.Test;
1117

1218
import com.baeldung.jersey.server.config.ViewApplicationConfig;
19+
import com.baeldung.jersey.server.model.Fruit;
20+
import com.baeldung.jersey.server.providers.FruitExceptionMapper;
1321

1422
public class FruitResourceIntegrationTest extends JerseyTest {
1523

1624
@Override
1725
protected Application configure() {
18-
return new ViewApplicationConfig();
26+
enable(TestProperties.LOG_TRAFFIC);
27+
enable(TestProperties.DUMP_ENTITY);
28+
29+
ViewApplicationConfig config = new ViewApplicationConfig();
30+
config.register(FruitExceptionMapper.class);
31+
return config;
1932
}
2033

2134
@Test
22-
public void testAllFruit() {
35+
public void givenGetAllFruit_whenCorrectRequest_thenAllTemplateInvoked() {
2336
final String response = target("/fruit/all").request()
2437
.get(String.class);
25-
Assert.assertThat(response, allOf(containsString("banana"), containsString("apple"), containsString("kiwi")));
38+
assertThat(response, allOf(containsString("banana"), containsString("apple"), containsString("kiwi")));
2639
}
2740

2841
@Test
29-
public void testIndex() {
42+
public void givenGetFruit_whenCorrectRequest_thenIndexTemplateInvoked() {
3043
final String response = target("/fruit").request()
3144
.get(String.class);
32-
Assert.assertThat(response, containsString("Welcome Fruit Index Page!"));
45+
assertThat(response, containsString("Welcome Fruit Index Page!"));
3346
}
3447

3548
@Test
36-
public void testErrorTemplate() {
49+
public void givenGetFruitByName_whenFruitUnknown_thenErrorTemplateInvoked() {
3750
final String response = target("/fruit/orange").request()
3851
.get(String.class);
39-
Assert.assertThat(response, containsString("Error - Fruit not found: orange!"));
52+
assertThat(response, containsString("Error - Fruit not found: orange!"));
53+
}
54+
55+
@Test
56+
public void givenCreateFruit_whenFormContainsNullParam_thenResponseCodeIsBadRequest() {
57+
Form form = new Form();
58+
form.param("name", "apple");
59+
form.param("colour", null);
60+
Response response = target("fruit/create").request(MediaType.APPLICATION_FORM_URLENCODED)
61+
.post(Entity.form(form));
62+
63+
assertEquals("Http Response should be 400 ", 400, response.getStatus());
64+
assertThat(response.readEntity(String.class), containsString("Fruit colour must not be null"));
65+
}
66+
67+
@Test
68+
public void givenUpdateFruit_whenFormContainsBadSerialParam_thenResponseCodeIsBadRequest() {
69+
Form form = new Form();
70+
form.param("serial", "2345-2345");
71+
72+
Response response = target("fruit/update").request(MediaType.APPLICATION_FORM_URLENCODED)
73+
.put(Entity.form(form));
74+
75+
assertEquals("Http Response should be 400 ", 400, response.getStatus());
76+
assertThat(response.readEntity(String.class), containsString("Fruit serial number is not valid"));
77+
}
78+
79+
@Test
80+
public void givenCreateFruit_whenFruitIsInvalid_thenResponseCodeIsBadRequest() {
81+
Fruit fruit = new Fruit("Blueberry", "purple");
82+
fruit.setWeight(1);
83+
84+
Response response = target("fruit/create").request(MediaType.APPLICATION_JSON_TYPE)
85+
.post(Entity.entity(fruit, MediaType.APPLICATION_JSON_TYPE));
86+
87+
assertEquals("Http Response should be 400 ", 400, response.getStatus());
88+
assertThat(response.readEntity(String.class), containsString("Fruit weight must be 10 or greater"));
89+
}
90+
91+
@Test
92+
public void givenFruitExists_whenSearching_thenResponseContainsFruit() {
93+
Fruit fruit = new Fruit();
94+
fruit.setName("strawberry");
95+
fruit.setWeight(20);
96+
Response response = target("fruit/create").request(MediaType.APPLICATION_JSON_TYPE)
97+
.post(Entity.entity(fruit, MediaType.APPLICATION_JSON_TYPE));
98+
99+
assertEquals("Http Response should be 204 ", 204, response.getStatus());
100+
101+
final String json = target("fruit/search/strawberry").request()
102+
.get(String.class);
103+
assertThat(json, containsString("{\"name\":\"strawberry\",\"weight\":20}"));
104+
}
105+
106+
@Test
107+
public void givenFruit_whenFruitIsInvalid_thenReponseContainsCustomExceptions() {
108+
final Response response = target("fruit/exception").request()
109+
.get();
110+
111+
assertEquals("Http Response should be 400 ", 400, response.getStatus());
112+
String responseString = response.readEntity(String.class);
113+
assertThat(responseString, containsString("exception.<return value>.colour size must be between 5 and 200"));
114+
assertThat(responseString, containsString("exception.<return value>.name size must be between 5 and 200"));
40115
}
41116

42117
}

0 commit comments

Comments
 (0)