JAVA-18120 Fix ItemsUnitTest of Jersey module (#13683)

Co-authored-by: timis1 <noreplay@yahoo.com>
This commit is contained in:
timis1 2023-03-22 18:15:33 +02:00 committed by GitHub
parent 59a6f32654
commit b0869ea476
37 changed files with 239 additions and 212 deletions

View File

@ -100,7 +100,7 @@
</build> </build>
<properties> <properties>
<jersey.version>2.38</jersey.version> <jersey.version>3.1.1</jersey.version>
<maven-war-plugin.version>3.3.2</maven-war-plugin.version> <maven-war-plugin.version>3.3.2</maven-war-plugin.version>
</properties> </properties>

View File

@ -1,19 +1,20 @@
package com.baeldung.jersey.client; 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 org.glassfish.jersey.client.ClientConfig;
import com.baeldung.jersey.client.filter.RequestClientFilter; import com.baeldung.jersey.client.filter.RequestClientFilter;
import com.baeldung.jersey.client.filter.ResponseClientFilter; import com.baeldung.jersey.client.filter.ResponseClientFilter;
import com.baeldung.jersey.client.interceptor.RequestClientWriterInterceptor; import com.baeldung.jersey.client.interceptor.RequestClientWriterInterceptor;
import com.baeldung.jersey.server.Greetings;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.core.Response;
public class JerseyClient { public class JerseyClient {
private static final String URI_GREETINGS = "http://localhost:8080/jersey/greetings"; public static final String URI_GREETINGS = "http://localhost:8080/jersey/greetings";
public static String getHelloGreeting() { public static String getHelloGreeting() {
return createClient().target(URI_GREETINGS) return createClient().target(URI_GREETINGS)
@ -38,6 +39,7 @@ public class JerseyClient {
config.register(RequestClientFilter.class); config.register(RequestClientFilter.class);
config.register(ResponseClientFilter.class); config.register(ResponseClientFilter.class);
config.register(RequestClientWriterInterceptor.class); config.register(RequestClientWriterInterceptor.class);
config.register(Greetings.class);
return ClientBuilder.newClient(config); return ClientBuilder.newClient(config);
} }

View File

@ -9,17 +9,17 @@ import org.glassfish.jersey.client.oauth1.ConsumerCredentials;
import org.glassfish.jersey.client.oauth1.OAuth1ClientSupport; import org.glassfish.jersey.client.oauth1.OAuth1ClientSupport;
import org.glassfish.jersey.client.oauth2.OAuth2ClientSupport; import org.glassfish.jersey.client.oauth2.OAuth2ClientSupport;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Feature;
import javax.ws.rs.core.Response;
import javax.ws.rs.sse.InboundSseEvent;
import javax.ws.rs.sse.SseEventSource;
import static org.glassfish.jersey.client.authentication.HttpAuthenticationFeature.*; import static org.glassfish.jersey.client.authentication.HttpAuthenticationFeature.*;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.Invocation;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.Feature;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.sse.InboundSseEvent;
import jakarta.ws.rs.sse.SseEventSource;
public class JerseyClientHeaders { public class JerseyClientHeaders {
private static final String BEARER_CONSUMER_SECRET = "my-consumer-secret"; private static final String BEARER_CONSUMER_SECRET = "my-consumer-secret";

View File

@ -1,9 +1,10 @@
package com.baeldung.jersey.client.filter; package com.baeldung.jersey.client.filter;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import java.io.IOException; import java.io.IOException;
import jakarta.ws.rs.client.ClientRequestContext;
import jakarta.ws.rs.client.ClientRequestFilter;
public class AddHeaderOnRequestFilter implements ClientRequestFilter { public class AddHeaderOnRequestFilter implements ClientRequestFilter {
public static final String FILTER_HEADER_VALUE = "filter-header-value"; public static final String FILTER_HEADER_VALUE = "filter-header-value";

View File

@ -2,13 +2,13 @@ package com.baeldung.jersey.client.filter;
import java.io.IOException; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import jakarta.ws.rs.client.ClientRequestContext;
import jakarta.ws.rs.client.ClientRequestFilter;
import jakarta.ws.rs.ext.Provider;
@Provider @Provider
public class RequestClientFilter implements ClientRequestFilter { public class RequestClientFilter implements ClientRequestFilter {

View File

@ -2,14 +2,14 @@ package com.baeldung.jersey.client.filter;
import java.io.IOException; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import jakarta.ws.rs.client.ClientRequestContext;
import jakarta.ws.rs.client.ClientResponseContext;
import jakarta.ws.rs.client.ClientResponseFilter;
import jakarta.ws.rs.ext.Provider;
@Provider @Provider
public class ResponseClientFilter implements ClientResponseFilter { public class ResponseClientFilter implements ClientResponseFilter {

View File

@ -2,14 +2,14 @@ package com.baeldung.jersey.client.interceptor;
import java.io.IOException; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.ext.Provider;
import jakarta.ws.rs.ext.WriterInterceptor;
import jakarta.ws.rs.ext.WriterInterceptorContext;
@Provider @Provider
public class RequestClientWriterInterceptor implements WriterInterceptor { public class RequestClientWriterInterceptor implements WriterInterceptor {

View File

@ -1,12 +1,12 @@
package com.baeldung.jersey.exceptionhandling; package com.baeldung.jersey.exceptionhandling;
import javax.ws.rs.ApplicationPath;
import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.ResourceConfig;
import com.baeldung.jersey.exceptionhandling.rest.exceptions.IllegalArgumentExceptionMapper; import com.baeldung.jersey.exceptionhandling.rest.exceptions.IllegalArgumentExceptionMapper;
import com.baeldung.jersey.exceptionhandling.rest.exceptions.ServerExceptionMapper; import com.baeldung.jersey.exceptionhandling.rest.exceptions.ServerExceptionMapper;
import jakarta.ws.rs.ApplicationPath;
@ApplicationPath("/exception-handling/*") @ApplicationPath("/exception-handling/*")
public class ExceptionHandlingConfig extends ResourceConfig { public class ExceptionHandlingConfig extends ResourceConfig {

View File

@ -2,19 +2,19 @@ package com.baeldung.jersey.exceptionhandling.rest;
import java.util.Optional; import java.util.Optional;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.baeldung.jersey.exceptionhandling.data.Stock; import com.baeldung.jersey.exceptionhandling.data.Stock;
import com.baeldung.jersey.exceptionhandling.repo.Db; import com.baeldung.jersey.exceptionhandling.repo.Db;
import com.baeldung.jersey.exceptionhandling.service.Repository; import com.baeldung.jersey.exceptionhandling.service.Repository;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Path("/stocks") @Path("/stocks")
public class StocksResource { public class StocksResource {
private static final Db<Stock> stocks = Repository.STOCKS_DB; private static final Db<Stock> stocks = Repository.STOCKS_DB;

View File

@ -2,18 +2,6 @@ package com.baeldung.jersey.exceptionhandling.rest;
import java.util.Optional; import java.util.Optional;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import com.baeldung.jersey.exceptionhandling.data.Stock; import com.baeldung.jersey.exceptionhandling.data.Stock;
import com.baeldung.jersey.exceptionhandling.data.Wallet; import com.baeldung.jersey.exceptionhandling.data.Wallet;
import com.baeldung.jersey.exceptionhandling.repo.Db; import com.baeldung.jersey.exceptionhandling.repo.Db;
@ -21,6 +9,17 @@ import com.baeldung.jersey.exceptionhandling.rest.exceptions.InvalidTradeExcepti
import com.baeldung.jersey.exceptionhandling.rest.exceptions.RestErrorResponse; import com.baeldung.jersey.exceptionhandling.rest.exceptions.RestErrorResponse;
import com.baeldung.jersey.exceptionhandling.service.Repository; import com.baeldung.jersey.exceptionhandling.service.Repository;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Path("/wallets") @Path("/wallets")
public class WalletsResource { public class WalletsResource {
private static final Db<Stock> stocks = Repository.STOCKS_DB; private static final Db<Stock> stocks = Repository.STOCKS_DB;
@ -84,7 +83,7 @@ public class WalletsResource {
RestErrorResponse response = new RestErrorResponse(); RestErrorResponse response = new RestErrorResponse();
response.setSubject(wallet); response.setSubject(wallet);
response.setMessage("insufficient balance"); response.setMessage("insufficient balance");
throw new WebApplicationException(Response.status(Status.NOT_ACCEPTABLE) throw new WebApplicationException(Response.status(Response.Status.NOT_ACCEPTABLE)
.entity(response) .entity(response)
.build()); .build());
} }

View File

@ -1,8 +1,8 @@
package com.baeldung.jersey.exceptionhandling.rest.exceptions; package com.baeldung.jersey.exceptionhandling.rest.exceptions;
import javax.ws.rs.core.MediaType; import jakarta.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import jakarta.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper; import jakarta.ws.rs.ext.ExceptionMapper;
public class IllegalArgumentExceptionMapper implements ExceptionMapper<IllegalArgumentException> { public class IllegalArgumentExceptionMapper implements ExceptionMapper<IllegalArgumentException> {
public static final String DEFAULT_MESSAGE = "an illegal argument was provided"; public static final String DEFAULT_MESSAGE = "an illegal argument was provided";

View File

@ -1,7 +1,7 @@
package com.baeldung.jersey.exceptionhandling.rest.exceptions; package com.baeldung.jersey.exceptionhandling.rest.exceptions;
import javax.ws.rs.WebApplicationException; import jakarta.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response; import jakarta.ws.rs.core.Response;
public class InvalidTradeException extends WebApplicationException { public class InvalidTradeException extends WebApplicationException {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;

View File

@ -1,19 +1,18 @@
package com.baeldung.jersey.exceptionhandling.rest.exceptions; package com.baeldung.jersey.exceptionhandling.rest.exceptions;
import javax.ws.rs.WebApplicationException; import jakarta.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType; import jakarta.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import jakarta.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status; import jakarta.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.ExceptionMapper;
public class ServerExceptionMapper implements ExceptionMapper<WebApplicationException> { public class ServerExceptionMapper implements ExceptionMapper<WebApplicationException> {
public static final String HTTP_405_MESSAGE = "use one of"; public static final String HTTP_405_MESSAGE = "use one of";
@Override @Override
public Response toResponse(final WebApplicationException exception) { public Response toResponse(final WebApplicationException exception) {
String message = exception.getMessage(); String message;
Response response = exception.getResponse(); Response response = exception.getResponse();
Status status = response.getStatusInfo() Response.Status status = response.getStatusInfo()
.toEnum(); .toEnum();
switch (status) { switch (status) {

View File

@ -2,14 +2,17 @@ package com.baeldung.jersey.server;
import com.baeldung.jersey.client.filter.AddHeaderOnRequestFilter; import com.baeldung.jersey.client.filter.AddHeaderOnRequestFilter;
import javax.annotation.security.RolesAllowed; import jakarta.annotation.security.RolesAllowed;
import javax.ws.rs.GET; import jakarta.ws.rs.GET;
import javax.ws.rs.Path; import jakarta.ws.rs.Path;
import javax.ws.rs.Produces; import jakarta.ws.rs.Produces;
import javax.ws.rs.core.*; import jakarta.ws.rs.core.Context;
import javax.ws.rs.sse.OutboundSseEvent; import jakarta.ws.rs.core.HttpHeaders;
import javax.ws.rs.sse.Sse; import jakarta.ws.rs.core.MediaType;
import javax.ws.rs.sse.SseEventSink; import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.sse.OutboundSseEvent;
import jakarta.ws.rs.sse.Sse;
import jakarta.ws.rs.sse.SseEventSink;
@Path("/echo-headers") @Path("/echo-headers")
public class EchoHeaders { public class EchoHeaders {

View File

@ -1,13 +1,12 @@
package com.baeldung.jersey.server; package com.baeldung.jersey.server;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import com.baeldung.jersey.server.config.HelloBinding; import com.baeldung.jersey.server.config.HelloBinding;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Response;
@Path("/greetings") @Path("/greetings")
public class Greetings { public class Greetings {
@ -26,7 +25,7 @@ public class Greetings {
@POST @POST
@Path("/custom") @Path("/custom")
public Response getCustomGreeting(String name) { public Response getCustomGreeting(String name) {
return Response.status(Status.OK.getStatusCode()) return Response.status(Response.Status.OK.getStatusCode())
.build(); .build();
} }
} }

View File

@ -1,8 +1,8 @@
package com.baeldung.jersey.server; package com.baeldung.jersey.server;
import javax.ws.rs.FormParam; import jakarta.ws.rs.FormParam;
import javax.ws.rs.HeaderParam; import jakarta.ws.rs.HeaderParam;
import javax.ws.rs.PathParam; import jakarta.ws.rs.PathParam;
public class ItemParam { public class ItemParam {

View File

@ -1,6 +1,15 @@
package com.baeldung.jersey.server; package com.baeldung.jersey.server;
import javax.ws.rs.*; import jakarta.ws.rs.BeanParam;
import jakarta.ws.rs.CookieParam;
import jakarta.ws.rs.FormParam;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.MatrixParam;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.QueryParam;
@Path("items") @Path("items")
public class Items { public class Items {

View File

@ -2,11 +2,11 @@ package com.baeldung.jersey.server;
import com.baeldung.jersey.server.model.Person; import com.baeldung.jersey.server.model.Person;
import javax.ws.rs.GET; import jakarta.ws.rs.GET;
import javax.ws.rs.Path; import jakarta.ws.rs.Path;
import javax.ws.rs.Produces; import jakarta.ws.rs.Produces;
import javax.ws.rs.core.MediaType; import jakarta.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import jakarta.ws.rs.core.Response;
@Path("/response") @Path("/response")
public class Responder { public class Responder {

View File

@ -3,7 +3,7 @@ package com.baeldung.jersey.server.config;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; import java.lang.annotation.RetentionPolicy;
import javax.ws.rs.NameBinding; import jakarta.ws.rs.NameBinding;
@NameBinding @NameBinding
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)

View File

@ -1,13 +1,13 @@
package com.baeldung.jersey.server.config; 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 com.baeldung.jersey.server.Greetings; import com.baeldung.jersey.server.Greetings;
import com.baeldung.jersey.server.filter.ResponseServerFilter; import com.baeldung.jersey.server.filter.ResponseServerFilter;
import jakarta.ws.rs.container.DynamicFeature;
import jakarta.ws.rs.container.ResourceInfo;
import jakarta.ws.rs.core.FeatureContext;
import jakarta.ws.rs.ext.Provider;
@Provider @Provider
public class HelloDynamicBinding implements DynamicFeature { public class HelloDynamicBinding implements DynamicFeature {

View File

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

View File

@ -4,10 +4,10 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; import java.lang.annotation.RetentionPolicy;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import javax.validation.Constraint; import jakarta.validation.Constraint;
import javax.validation.ConstraintValidator; import jakarta.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext; import jakarta.validation.ConstraintValidatorContext;
import javax.validation.Payload; import jakarta.validation.Payload;
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { SerialNumber.Validator.class }) @Constraint(validatedBy = { SerialNumber.Validator.class })
@ -21,7 +21,7 @@ public @interface SerialNumber {
Class<? extends Payload>[] payload() default {}; Class<? extends Payload>[] payload() default {};
public class Validator implements ConstraintValidator<SerialNumber, String> { class Validator implements ConstraintValidator<SerialNumber, String> {
@Override @Override
public void initialize(final SerialNumber serial) { public void initialize(final SerialNumber serial) {
} }

View File

@ -2,14 +2,15 @@ package com.baeldung.jersey.server.filter;
import java.io.IOException; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.PreMatching;
import jakarta.ws.rs.ext.Provider;
@Provider @Provider
@PreMatching @PreMatching
public class PrematchingRequestFilter implements ContainerRequestFilter { public class PrematchingRequestFilter implements ContainerRequestFilter {

View File

@ -2,13 +2,13 @@ package com.baeldung.jersey.server.filter;
import java.io.IOException; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerResponseContext;
import jakarta.ws.rs.container.ContainerResponseFilter;
public class ResponseServerFilter implements ContainerResponseFilter { public class ResponseServerFilter implements ContainerResponseFilter {
private static final Logger LOG = LoggerFactory.getLogger(ResponseServerFilter.class); private static final Logger LOG = LoggerFactory.getLogger(ResponseServerFilter.class);

View File

@ -2,18 +2,18 @@ package com.baeldung.jersey.server.filter;
import java.io.IOException; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.baeldung.jersey.server.config.HelloBinding; import com.baeldung.jersey.server.config.HelloBinding;
import jakarta.annotation.Priority;
import jakarta.ws.rs.Priorities;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.Provider;
@Provider @Provider
@Priority(Priorities.AUTHORIZATION) @Priority(Priorities.AUTHORIZATION)
@HelloBinding @HelloBinding

View File

@ -19,10 +19,7 @@ public class EmbeddedHttpServer {
try { try {
final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, new ViewApplicationConfig(), false); final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, new ViewApplicationConfig(), false);
Runtime.getRuntime() Runtime.getRuntime().addShutdownHook(new Thread(server::shutdownNow));
.addShutdownHook(new Thread(() -> {
server.shutdownNow();
}));
server.start(); server.start();
@ -34,8 +31,8 @@ public class EmbeddedHttpServer {
} }
public static HttpServer startServer() { public static HttpServer startServer(URI url) {
final ResourceConfig rc = new ResourceConfig().packages("com.baeldung.jersey.server"); final ResourceConfig rc = new ResourceConfig().packages("com.baeldung.jersey.server");
return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI.toString()), rc); return GrizzlyHttpServerFactory.createHttpServer(URI.create(url.toString()), rc);
} }
} }

View File

@ -7,14 +7,14 @@ import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.stream.Collectors; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.ext.Provider;
import jakarta.ws.rs.ext.ReaderInterceptor;
import jakarta.ws.rs.ext.ReaderInterceptorContext;
@Provider @Provider
public class RequestServerReaderInterceptor implements ReaderInterceptor { public class RequestServerReaderInterceptor implements ReaderInterceptor {

View File

@ -1,8 +1,8 @@
package com.baeldung.jersey.server.model; package com.baeldung.jersey.server.model;
import javax.validation.constraints.Min; import jakarta.validation.constraints.Min;
import javax.validation.constraints.Size; import jakarta.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlRootElement;
@XmlRootElement @XmlRootElement
public class Fruit { public class Fruit {

View File

@ -1,9 +1,9 @@
package com.baeldung.jersey.server.providers; package com.baeldung.jersey.server.providers;
import javax.validation.ConstraintViolation; import jakarta.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException; import jakarta.validation.ConstraintViolationException;
import javax.ws.rs.core.Response; import jakarta.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper; import jakarta.ws.rs.ext.ExceptionMapper;
public class FruitExceptionMapper implements ExceptionMapper<ConstraintViolationException> { public class FruitExceptionMapper implements ExceptionMapper<ConstraintViolationException> {

View File

@ -5,20 +5,6 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.glassfish.jersey.server.mvc.ErrorTemplate; import org.glassfish.jersey.server.mvc.ErrorTemplate;
import org.glassfish.jersey.server.mvc.Template; import org.glassfish.jersey.server.mvc.Template;
import org.glassfish.jersey.server.mvc.Viewable; import org.glassfish.jersey.server.mvc.Viewable;
@ -27,6 +13,19 @@ import com.baeldung.jersey.server.constraints.SerialNumber;
import com.baeldung.jersey.server.model.Fruit; import com.baeldung.jersey.server.model.Fruit;
import com.baeldung.jersey.service.SimpleStorageService; import com.baeldung.jersey.service.SimpleStorageService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.FormParam;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Path("/fruit") @Path("/fruit")
public class FruitResource { public class FruitResource {
@ -66,7 +65,7 @@ public class FruitResource {
@Path("/create") @Path("/create")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void createFruit( public void createFruit(
@NotNull(message = "Fruit name must not be null") @FormParam("name") String name, @NotNull(message = "Fruit name must not be null") @FormParam("name") String name,
@NotNull(message = "Fruit colour must not be null") @FormParam("colour") String colour) { @NotNull(message = "Fruit colour must not be null") @FormParam("colour") String colour) {
Fruit fruit = new Fruit(name, colour); Fruit fruit = new Fruit(name, colour);
@ -94,7 +93,7 @@ public class FruitResource {
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
public Response createNewFruit(@Valid Fruit fruit) { public Response createNewFruit(@Valid Fruit fruit) {
String result = "Fruit saved : " + fruit; String result = "Fruit saved : " + fruit;
return Response.status(Status.CREATED.getStatusCode()) return Response.status(Response.Status.CREATED.getStatusCode())
.entity(result) .entity(result)
.build(); .build();
} }

View File

@ -7,7 +7,7 @@ import com.baeldung.jersey.server.model.Fruit;
public class SimpleStorageService { public class SimpleStorageService {
private static final Map<String, Fruit> fruits = new HashMap<String, Fruit>(); private static final Map<String, Fruit> fruits = new HashMap<>();
public static void storeFruit(final Fruit fruit) { public static void storeFruit(final Fruit fruit) {
fruits.put(fruit.getName(), fruit); fruits.put(fruit.getName(), fruit);
@ -17,7 +17,7 @@ public class SimpleStorageService {
return fruits.entrySet() return fruits.entrySet()
.stream() .stream()
.filter(map -> name.equals(map.getKey())) .filter(map -> name.equals(map.getKey()))
.map(map -> map.getValue()) .map(Map.Entry::getValue)
.findFirst() .findFirst()
.get(); .get();
} }

View File

@ -1,35 +1,53 @@
package com.baeldung.jersey.client; package com.baeldung.jersey.client;
import javax.ws.rs.core.Response; import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Assert; import java.net.URI;
import org.junit.Ignore;
import org.junit.Test; import org.glassfish.grizzly.http.server.HttpServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import com.baeldung.jersey.server.http.EmbeddedHttpServer;
import jakarta.ws.rs.core.Response;
@Ignore
public class JerseyClientIntegrationTest { public class JerseyClientIntegrationTest {
private static int HTTP_OK = 200; private static int HTTP_OK = 200;
private static HttpServer httpServer;
@BeforeAll
public static void beforeAllTests() {
httpServer = EmbeddedHttpServer.startServer(URI.create("http://localhost:8080/jersey"));
}
@AfterAll
public static void afterAllTests() {
httpServer.stop();
}
@Test @Test
public void givenGreetingResource_whenCallingHelloGreeting_thenHelloReturned() { public void givenGreetingResource_whenCallingHelloGreeting_thenHelloReturned() {
String response = JerseyClient.getHelloGreeting(); String response = JerseyClient.getHelloGreeting();
Assert.assertEquals("hello", response); assertEquals("hello", response);
} }
@Test @Test
public void givenGreetingResource_whenCallingHiGreeting_thenHiReturned() { public void givenGreetingResource_whenCallingHiGreeting_thenHiReturned() {
String response = JerseyClient.getHiGreeting(); String response = JerseyClient.getHiGreeting();
Assert.assertEquals("hi", response); assertEquals("hi", response);
} }
@Test @Test
public void givenGreetingResource_whenCallingCustomGreeting_thenCustomGreetingReturned() { public void givenGreetingResource_whenCallingCustomGreeting_thenCustomGreetingReturned() {
Response response = JerseyClient.getCustomGreeting(); Response response = JerseyClient.getCustomGreeting();
Assert.assertEquals(HTTP_OK, response.getStatus()); assertEquals(HTTP_OK, response.getStatus());
} }
} }

View File

@ -2,31 +2,30 @@ package com.baeldung.jersey.exceptionhandling.rest;
import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.startsWith; import static org.hamcrest.CoreMatchers.startsWith;
import static org.junit.Assert.assertEquals; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertThat; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.HashMap; import java.util.HashMap;
import javax.ws.rs.client.Entity; import org.glassfish.jersey.server.ResourceConfig;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.glassfish.jersey.test.JerseyTest; import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties; import org.glassfish.jersey.test.TestProperties;
import org.junit.Test; import org.junit.jupiter.api.Test;
import com.baeldung.jersey.exceptionhandling.ExceptionHandlingConfig;
import com.baeldung.jersey.exceptionhandling.data.Stock; import com.baeldung.jersey.exceptionhandling.data.Stock;
import com.baeldung.jersey.exceptionhandling.data.Wallet; import com.baeldung.jersey.exceptionhandling.data.Wallet;
import com.baeldung.jersey.exceptionhandling.rest.exceptions.IllegalArgumentExceptionMapper; import com.baeldung.jersey.exceptionhandling.rest.exceptions.IllegalArgumentExceptionMapper;
import com.baeldung.jersey.exceptionhandling.rest.exceptions.RestErrorResponse; import com.baeldung.jersey.exceptionhandling.rest.exceptions.RestErrorResponse;
import com.baeldung.jersey.exceptionhandling.rest.exceptions.ServerExceptionMapper; import com.baeldung.jersey.exceptionhandling.rest.exceptions.ServerExceptionMapper;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.client.Invocation;
import jakarta.ws.rs.core.Application;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
public class StocksResourceIntegrationTest extends JerseyTest { public class StocksResourceIntegrationTest extends JerseyTest {
private static final Entity<String> EMPTY_BODY = Entity.json(""); private static final Entity<String> EMPTY_BODY = Entity.json("");
private static final Stock STOCK = new Stock("BAEL", 51.57); private static final Stock STOCK = new Stock("BAEL", 51.57);
@ -36,8 +35,13 @@ public class StocksResourceIntegrationTest extends JerseyTest {
@Override @Override
protected Application configure() { protected Application configure() {
forceSet(TestProperties.CONTAINER_PORT, "0"); final ResourceConfig resourceConfig = new ResourceConfig();
return new ExceptionHandlingConfig(); resourceConfig.register(StocksResource.class);
resourceConfig.register(WalletsResource.class);
resourceConfig.register(IllegalArgumentExceptionMapper.class);
resourceConfig.register(ServerExceptionMapper.class);
resourceConfig.packages("com.baeldung.jersey.exceptionhandling.rest");
return resourceConfig;
} }
private Invocation.Builder stocks(String path) { private Invocation.Builder stocks(String path) {
@ -56,7 +60,7 @@ public class StocksResourceIntegrationTest extends JerseyTest {
public void whenMethodNotAllowed_thenCustomMessage() { public void whenMethodNotAllowed_thenCustomMessage() {
Response response = stocks("").get(); Response response = stocks("").get();
assertEquals(Status.METHOD_NOT_ALLOWED.getStatusCode(), response.getStatus()); assertEquals(Response.Status.METHOD_NOT_ALLOWED.getStatusCode(), response.getStatus());
String content = response.readEntity(String.class); String content = response.readEntity(String.class);
assertThat(content, containsString(ServerExceptionMapper.HTTP_405_MESSAGE)); assertThat(content, containsString(ServerExceptionMapper.HTTP_405_MESSAGE));
@ -64,9 +68,9 @@ public class StocksResourceIntegrationTest extends JerseyTest {
@Test @Test
public void whenTickerNotExists_thenRestErrorResponse() { public void whenTickerNotExists_thenRestErrorResponse() {
Response response = stocks("/UNDEFINED").get(); Response response = stocks("/TEST").get();
assertEquals(Status.EXPECTATION_FAILED.getStatusCode(), response.getStatus()); assertEquals(Response.Status.EXPECTATION_FAILED.getStatusCode(), response.getStatus());
RestErrorResponse content = response.readEntity(RestErrorResponse.class); RestErrorResponse content = response.readEntity(RestErrorResponse.class);
assertThat(content.getMessage(), startsWith(IllegalArgumentExceptionMapper.DEFAULT_MESSAGE)); assertThat(content.getMessage(), startsWith(IllegalArgumentExceptionMapper.DEFAULT_MESSAGE));
@ -77,7 +81,7 @@ public class StocksResourceIntegrationTest extends JerseyTest {
wallets("").post(entity(WALLET)); wallets("").post(entity(WALLET));
Response response = wallets("/%s/%d", MY_WALLET, INSUFFICIENT_AMOUNT).put(EMPTY_BODY); Response response = wallets("/%s/%d", MY_WALLET, INSUFFICIENT_AMOUNT).put(EMPTY_BODY);
assertEquals(Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus()); assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus());
String content = response.readEntity(String.class); String content = response.readEntity(String.class);
assertThat(content, containsString(Wallet.MIN_CHARGE_MSG)); assertThat(content, containsString(Wallet.MIN_CHARGE_MSG));
@ -89,7 +93,7 @@ public class StocksResourceIntegrationTest extends JerseyTest {
wallets("").post(entity(WALLET)); wallets("").post(entity(WALLET));
Response response = wallets("/%s/buy/%s", MY_WALLET, STOCK.getId()).post(EMPTY_BODY); Response response = wallets("/%s/buy/%s", MY_WALLET, STOCK.getId()).post(EMPTY_BODY);
assertEquals(Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus()); assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus());
RestErrorResponse content = response.readEntity(RestErrorResponse.class); RestErrorResponse content = response.readEntity(RestErrorResponse.class);
assertNotNull(content.getSubject()); assertNotNull(content.getSubject());

View File

@ -6,8 +6,6 @@ import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest; import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test; import org.junit.Test;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;
import java.util.Base64; import java.util.Base64;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -15,6 +13,9 @@ import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import jakarta.ws.rs.core.Application;
import jakarta.ws.rs.core.Response;
public class EchoHeadersUnitTest extends JerseyTest { public class EchoHeadersUnitTest extends JerseyTest {
private static final String SIMPLE_HEADER_KEY = "my-header-key"; private static final String SIMPLE_HEADER_KEY = "my-header-key";

View File

@ -2,16 +2,15 @@ package com.baeldung.jersey.server;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest; import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test; import org.junit.Test;
import jakarta.ws.rs.core.Application;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
public class GreetingsResourceIntegrationTest extends JerseyTest { public class GreetingsResourceIntegrationTest extends JerseyTest {
@Override @Override
@ -24,7 +23,7 @@ public class GreetingsResourceIntegrationTest extends JerseyTest {
Response response = target("/greetings/hi").request() Response response = target("/greetings/hi").request()
.get(); .get();
assertEquals("Http Response should be 200: ", Status.OK.getStatusCode(), response.getStatus()); assertEquals("Http Response should be 200: ", Response.Status.OK.getStatusCode(), response.getStatus());
assertEquals("Http Content-Type should be: ", MediaType.TEXT_HTML, response.getHeaderString(HttpHeaders.CONTENT_TYPE)); assertEquals("Http Content-Type should be: ", MediaType.TEXT_HTML, response.getHeaderString(HttpHeaders.CONTENT_TYPE));
String content = response.readEntity(String.class); String content = response.readEntity(String.class);

View File

@ -1,35 +1,32 @@
package com.baeldung.jersey.server; package com.baeldung.jersey.server;
import static com.baeldung.jersey.server.http.EmbeddedHttpServer.BASE_URI;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import org.glassfish.grizzly.http.server.HttpServer; import org.glassfish.grizzly.http.server.HttpServer;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.junit.jupiter.api.Disabled;
import com.baeldung.jersey.server.http.EmbeddedHttpServer; import com.baeldung.jersey.server.http.EmbeddedHttpServer;
@Disabled import jakarta.ws.rs.client.ClientBuilder;
@Ignore import jakarta.ws.rs.client.WebTarget;
public class ItemsUnitTest { public class ItemsUnitTest {
private HttpServer server; private HttpServer server;
private WebTarget target; private WebTarget target;
@Before @Before
public void setUp() throws Exception { public void setUp() {
server = EmbeddedHttpServer.startServer(); server = EmbeddedHttpServer.startServer(BASE_URI);
target = ClientBuilder.newClient().target(EmbeddedHttpServer.BASE_URI.toString()); target = ClientBuilder.newClient().target(BASE_URI.toString());
} }
@After @After
public void tearDown() throws Exception { public void tearDown() {
server.stop(); server.stop();
} }

View File

@ -5,13 +5,6 @@ import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.glassfish.jersey.test.JerseyTest; import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties; import org.glassfish.jersey.test.TestProperties;
import org.junit.Test; import org.junit.Test;
@ -20,6 +13,12 @@ import com.baeldung.jersey.server.config.ViewApplicationConfig;
import com.baeldung.jersey.server.model.Fruit; import com.baeldung.jersey.server.model.Fruit;
import com.baeldung.jersey.server.providers.FruitExceptionMapper; import com.baeldung.jersey.server.providers.FruitExceptionMapper;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.core.Application;
import jakarta.ws.rs.core.Form;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
public class FruitResourceIntegrationTest extends JerseyTest { public class FruitResourceIntegrationTest extends JerseyTest {
@Override @Override
@ -71,7 +70,7 @@ public class FruitResourceIntegrationTest extends JerseyTest {
Response response = target("fruit/created").request() Response response = target("fruit/created").request()
.post(Entity.json("{\"name\":\"strawberry\",\"weight\":20}")); .post(Entity.json("{\"name\":\"strawberry\",\"weight\":20}"));
assertEquals("Http Response should be 201 ", Status.CREATED.getStatusCode(), response.getStatus()); assertEquals("Http Response should be 201 ", Response.Status.CREATED.getStatusCode(), response.getStatus());
assertThat(response.readEntity(String.class), containsString("Fruit saved : Fruit [name: strawberry colour: null]")); assertThat(response.readEntity(String.class), containsString("Fruit saved : Fruit [name: strawberry colour: null]"));
} }