Skip to content

Instantly share code, notes, and snippets.

@avianey
Last active June 18, 2019 09:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avianey/55eb0d3ecaba6891d6db to your computer and use it in GitHub Desktop.
Save avianey/55eb0d3ecaba6891d6db to your computer and use it in GitHub Desktop.
Jersey custom parameter, annotation and exception mapping
@Provider
public class BusinessExceptionMapper implements ExceptionMapper<BusinessException> {
private static final Logger log = Logger.getLogger(TestEndpoint.class.getName());
private static final ResourceBundle resource =
ResourceBundle.getBundle("com.blogspot.avianey");
@Override
public Response toResponse(BusinessException e) {
log.log(Level.FINER, "Business problem while executing testMethod", e);
return Response.status(Status.BAD_REQUEST)
.type(MediaType.TEXT_PLAIN)
.entity(resource.getString(e.getMessage()))
.build();
}
}
/**
* A DateParam to validate the format of date parameters received by Jersey
*/
public class DateParam {
private Date date;
public DateParam(String dateStr) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {
this.date = sdf.parse(dateStr);
} catch (ParseException pe) {
throw new WebApplicationException(Status.BAD_REQUEST);
}
}
public Date value() {
return this.date;
}
}
@Target({ ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface LoggedUser {}
@Provider
public class LoggedUserProvider extends AbstractHttpContextInjectable<User>
implements InjectableProvider<Context, Type> {
private final HttpServletRequest r;
public LoggedUserProvider(@Context HttpServletRequest r) {
this.r = r;
}
/**
* From interface InjectableProvider
*/
@Override
public Injectable<user> getInjectable(ComponentContext ic, Context a, Type c) {
if (c.equals(User.class)) {
return this;
}
return null;
}
/**
* From interface InjectableProvider
* A new Injectable is instanciated per request
*/
@Override
public ComponentScope getScope() {
return ComponentScope.PerRequest;
}
/**
* From interface Injectable
* Get the logged User associated with the request
* Or throw an Unauthorized HTTP status code
*/
@Override
public User getValue(HttpContext c) {
final User user = Contestr.getSessionUser(r);
if (user == null) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
return user;
}
}
@Provider
public class LoggedUserProvider
implements Injectable<User>, InjectableProvider<LoggedUser, Type> {
private final HttpServletRequest r;
public LoggedUserProvider(@Context HttpServletRequest r) {
this.r = r;
}
@Override
public Injectable<user> getInjectable(ComponentContext cc, LoggedUser a, Type c) {
if (c.equals(User.class)) {
return this;
}
return null;
}
/**
* From interface InjectableProvider
* A new Injectable is instanciated per request
*/
@Override
public ComponentScope getScope() {
return ComponentScope.PerRequest;
}
/**
* From interface Injectable
* Get the logged User associated with the request
* Or throw an Unauthorized HTTP status code
*/
@Override
public User getValue() {
final User user = (User) r.getSession().getAttribute("user");
if (user == null) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
return user;
}
}
@Provider
public class TechnicalExceptionMapper implements ExceptionMapper<TechnicalException> {
private static final Logger log = Logger.getLogger(TestEndpoint.class.getName());
private static final ResourceBundle resource =
ResourceBundle.getBundle("com.blogspot.avianey");
@Override
public Response toResponse(TechnicalException e) {
log.log(Level.FINER, "Technical problem while executing testMethod", e);
return Response.status(Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN)
.entity(resource.getString("error.internal"))
.build();
}
}
@Path("/test")
@Produces("application/json")
public class TestEndpoint {
private static final Logger log = Logger.getLogger(TestEndpoint.class.getName());
private static final ResourceBundle resource =
ResourceBundle.getBundle("com.blogspot.avianey");
@Inject TestService service;
@POST
@Path("{pathParam: \\d+}")
public String testMethod(
@PathParam("pathParam") Long id,
@FormParam("date") String dateStr,
@Context HttpServletRequest request) {
// verifying that the user is logged in
User user = (User) request.getSession().getAttribute("user");
if (user == null) {
throw new WebApplicationException(Status.UNAUTHORIZED);
}
// verifying the format of the sent date
Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {
date = sdf.parse(dateStr);
} catch (ParseException pe) {
throw new WebApplicationException(Status.BAD_REQUEST);
}
try {
// calling the business logic
return service.testOperation(id, date, user);
} catch (BusinessException boe) {
log.log(Level.FINER, "Business problem while executing testMethod", boe);
throw new WebApplicationException(
Response.status(Status.BAD_REQUEST)
.type(MediaType.TEXT_PLAIN)
.entity(resource.getString(boe.getMessage()))
.build());
} catch (TechnicalException te) {
log.log(Level.FINER, "Technical problem while executing testMethod", te);
throw new WebApplicationException(
Response.status(Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN)
.entity(resource.getString("error.internal"))
.build());
}
}
}
@Path("/test")
@Produces("application/json")
public class TestEndpoint {
private static final Logger log = Logger.getLogger(TestEndpoint.class.getName());
@Inject TestService service;
@POST
@Path("{pathParam: \\d+}")
public String testMethod(
@PathParam("pathParam") Long id,
@FormParam("date") String dateStr,
@Context HttpServletRequest request) {
// verifying that the user is logged in
User user = (User) request.getSession().getAttribute("user");
if (user == null) {
throw new WebApplicationException(Status.UNAUTHORIZED);
}
// verifying the format of the sent date
Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {
date = sdf.parse(dateStr);
} catch (ParseException pe) {
throw new WebApplicationException(Status.BAD_REQUEST);
}
// calling the business logic
// no need to catch exception here anymore
return service.testOperation(id, date, user);
}
}
@Path("/test")
@Produces("application/json")
public class TestEndpoint {
private static final Logger log = Logger.getLogger(TestEndpoint.class.getName());
@Inject TestService service;
@POST
@Path("{pathParam: \\d+}")
public String testMethod(
@PathParam("pathParam") Long id,
@FormParam("date") DateParam date,
@Context HttpServletRequest request) {
// verifying that the user is logged in
User user = (User) request.getSession().getAttribute("user");
if (user == null) {
throw new WebApplicationException(Status.UNAUTHORIZED);
}
// calling the business logic
return service.testOperation(id, date.value(), user);
}
}
@Path("/test")
@Produces("application/json")
public class TestEndpoint {
@Inject TestService service;
@POST
@Path("{pathParam: \\d+}")
public String testMethod(
@PathParam("pathParam") Long id,
@FormParam("date") DateParam date,
@Context User user) {
// calling the business logic
return service.testOperation(id, date.value(), user);
}
}
@Path("/test")
@Produces("application/json")
public class TestEndpoint {
@Inject TestService service;
@POST
@Path("{pathParam: \\d+}")
public String testMethod(
@PathParam("pathParam") Long id,
@FormParam("date") DateParam date,
@LoggedUser User user) {
// calling the business logic
return service.testOperation(id, date.value(), user);
}
}
<servlet>
<servlet-name>Jersey</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>pkg.provider; pkg.endpoint</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment