There are three steps to accomplish this recipe.
- First, we create a User POJO:
public class User implements Serializable{
private String name;
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
- Then, we create a class with two methods (endpoints) for returning User:
@Path("userService")
public class UserService {
@GET
@Path("getUserCoupled/{name}/{email}")
@Produces(MediaType.APPLICATION_JSON)
public Response getUserCoupled(
@PathParam("name") String name,
@PathParam("email") String email){
//GET USER CODE
return Response.ok().build();
}
@GET
@Path("getUserDecoupled")
@Produces(MediaType.APPLICATION_JSON)
public Response getUserDecoupled(@HeaderParam("User")
User user){
//GET USER CODE
return Response.ok().build();
}
}
- Finally, we create another service (another project) to consume UserService:
@Path("doSomethingService")
public class DoSomethingService {
private final String hostURI = "http://localhost:8080/";
private Client client;
private WebTarget target;
@PostConstruct
public void init() {
client = ClientBuilder.newClient();
target = client.target(hostURI + "ch08-decoupled-user/");
}
@Path("doSomethingCoupled")
@Produces(MediaType.APPLICATION_JSON)
public Response doSomethingCoupled(String name, String email){
WebTarget service =
target.path("webresources/userService/getUserCoupled");
service.queryParam("name", name);
service.queryParam("email", email);
Response response;
try {
response = service.request().get();
} catch (ProcessingException e) {
return Response.status(408).build();
}
return
Response.ok(response.readEntity(String.class)).build();
}
@Path("doSomethingDecoupled")
@Produces(MediaType.APPLICATION_JSON)
public Response doSomethingDecoupled(User user){
WebTarget service =
target.path("webresources/userService/getUserDecoupled");
Response response;
try {
response = service.request().header("User",
Entity.json(user)).get();
} catch (ProcessingException e) {
return Response.status(408).build();
}
return
Response.ok(response.readEntity(String.class)).build();
}
}