if there is an enum type in some standard Java class library that defines symbolic constants for all of the valid HTTP response codes - spring

if there is an enum type in some standard Java class library that defines symbolic constants for all of the valid HTTP response codes. It should support conversion to/from the corresponding integer values.
I'm debugging some Java code that uses javax.ws.rs.core.Response.Status
public abstract class Response implements AutoCloseable {
public abstract int getStatus();
public abstract StatusType getStatusInfo();
public abstract Object getEntity();
public abstract <T> T readEntity(Class<T> entityType);
public abstract <T> T readEntity(Class<T> entityType, Annotation[] annotations);
public abstract boolean hasEntity();
public abstract boolean bufferEntity();
#Override
public abstract void close();
public abstract Locale getLanguage();
public abstract int getLength();
public abstract Set<String> getAllowedMethods();
public abstract Date getDate();
public abstract Date getLastModified();
public abstract URI getLocation();
public abstract boolean hasLink(String relation);
public abstract String getHeaderString(String name);
public static abstract class ResponseBuilder {
protected ResponseBuilder() {
}
public abstract Response build();
#Override
#SuppressWarnings("CloneDoesntDeclareCloneNotSupportedException")
public abstract ResponseBuilder clone();
public abstract ResponseBuilder status(int status);
public abstract ResponseBuilder status(int status, String reasonPhrase);
public ResponseBuilder status(StatusType status) {
if (status == null) {
throw new IllegalArgumentException();
}
return status(status.getStatusCode(), status.getReasonPhrase());
}
public ResponseBuilder status(Status status) {
return status((StatusType) status);
}
public abstract ResponseBuilder entity(Object entity);
public abstract ResponseBuilder entity(Object entity, Annotation[] annotations);
public abstract ResponseBuilder allow(String... methods);
public abstract ResponseBuilder allow(Set<String> methods);
public abstract ResponseBuilder encoding(String encoding);
public abstract ResponseBuilder header(String name, Object value);
public abstract ResponseBuilder language(String language);
public abstract ResponseBuilder language(Locale language);
public abstract ResponseBuilder type(String type);
public abstract ResponseBuilder contentLocation(URI location);
public abstract ResponseBuilder expires(Date expires);
public abstract ResponseBuilder lastModified(Date lastModified);
public abstract ResponseBuilder location(URI location);
#SuppressWarnings("HtmlTagCanBeJavadocTag")
public abstract ResponseBuilder tag(String tag);
public abstract ResponseBuilder link(URI uri, String rel);
public abstract ResponseBuilder link(String uri, String rel);
}
public interface StatusType {
public int getStatusCode();
public Status.Family getFamily();
public String getReasonPhrase();
public default Status toEnum() {
return Status.fromStatusCode(getStatusCode());
}
}
public enum Status implements StatusType {
OK(200, "OK"),
CREATED(201, "Created"),
ACCEPTED(202, "Accepted"),
NO_CONTENT(204, "No Content"),
RESET_CONTENT(205, "Reset Content"),
PARTIAL_CONTENT(206, "Partial Content"),
MOVED_PERMANENTLY(301, "Moved Permanently"),
FOUND(302, "Found"),
SEE_OTHER(303, "See Other"),
NOT_MODIFIED(304, "Not Modified"),
USE_PROXY(305, "Use Proxy"),
TEMPORARY_REDIRECT(307, "Temporary Redirect"),
BAD_REQUEST(400, "Bad Request"),
UNAUTHORIZED(401, "Unauthorized"),
PAYMENT_REQUIRED(402, "Payment Required"),
FORBIDDEN(403, "Forbidden"),
NOT_FOUND(404, "Not Found"),
METHOD_NOT_ALLOWED(405, "Method Not Allowed"),
NOT_ACCEPTABLE(406, "Not Acceptable"),
PROXY_AUTHENTICATION_REQUIRED(407, "Proxy Authentication Required"),
REQUEST_TIMEOUT(408, "Request Timeout"),
CONFLICT(409, "Conflict"),
GONE(410, "Gone"),
LENGTH_REQUIRED(411, "Length Required"),
PRECONDITION_FAILED(412, "Precondition Failed"),
REQUEST_ENTITY_TOO_LARGE(413, "Request Entity Too Large"),
REQUEST_URI_TOO_LONG(414, "Request-URI Too Long"),
UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"),
REQUESTED_RANGE_NOT_SATISFIABLE(416, "Requested Range Not Satisfiable"),
EXPECTATION_FAILED(417, "Expectation Failed"),
PRECONDITION_REQUIRED(428, "Precondition Required"),
TOO_MANY_REQUESTS(429, "Too Many Requests"),
REQUEST_HEADER_FIELDS_TOO_LARGE(431, "Request Header Fields Too Large"),
INTERNAL_SERVER_ERROR(500, "Internal Server Error"),
NOT_IMPLEMENTED(501, "Not Implemented"),
BAD_GATEWAY(502, "Bad Gateway"),
SERVICE_UNAVAILABLE(503, "Service Unavailable"),
GATEWAY_TIMEOUT(504, "Gateway Timeout"),
HTTP_VERSION_NOT_SUPPORTED(505, "HTTP Version Not Supported"),
NETWORK_AUTHENTICATION_REQUIRED(511, "Network Authentication Required");
private final int code;
private final String reason;
private final Family family;
public enum Family {
INFORMATIONAL,
SUCCESSFUL,
REDIRECTION,
CLIENT_ERROR,
SERVER_ERROR,
OTHER;
public static Family familyOf(final int statusCode) {
switch (statusCode / 100) {
case 1:
return Family.INFORMATIONAL;
case 2:
return Family.SUCCESSFUL;
case 3:
return Family.REDIRECTION;
case 4:
return Family.CLIENT_ERROR;
case 5:
return Family.SERVER_ERROR;
default:
return Family.OTHER;
}
}
}
Status(final int statusCode, final String reasonPhrase) {
this.code = statusCode;
this.reason = reasonPhrase;
this.family = Family.familyOf(statusCode);
}
#Override
public Family getFamily() {
return family;
}
#Override
public int getStatusCode() {
return code;
}
#Override
public String getReasonPhrase() {
return toString();
}
#Override
public String toString() {
return reason;
}
public static Status fromStatusCode(final int statusCode) {
for (Status s : Status.values()) {
if (s.code == statusCode) {
return s;
}
}
return null;
}
}
}

Related

How to register hibernate custom multiple EventListeners

My scenario is need yo track entity property changes. I have used Hibernate PostUpdateEventListener interface to achieve that.
Following is my generic event listener class.
public abstract class EventListener<DOMAIN extends BaseModel> implements PostUpdateEventListener {
public abstract LogSupport getService();
public abstract BaseModel getLogDomain(DOMAIN domain);
#SuppressWarnings("unchecked")
private DOMAIN getDomain(BaseModel model) {
return (DOMAIN) model;
}
public void postUpdate(PostUpdateEvent event, BaseModel model) {
getService().createUpdateLog(getDomain(model), getPostUpdateEventNotes(event));
}
private String getPostUpdateEventNotes(PostUpdateEvent event) {
StringBuilder sb = new StringBuilder();
for (int p : event.getDirtyProperties()) {
sb.append("\t");
sb.append(event.getPersister().getEntityMetamodel().getProperties()[p].getName());
sb.append(" (Old value: ")
.append(event.getOldState()[p])
.append(", New value: ")
.append(event.getState()[p])
.append(")\n");
}
System.out.println(sb.toString());
return sb.toString();
}
}
And this is my custom entity listener.
#Component
public class AssetEventListener extends EventListener<Asset> {
private static final long serialVersionUID = -6076678526514705909L;
#Autowired
#Qualifier("assetLogService")
private LogSupport logSupport;
#Override
public LogSupport getService() {
AutowireHelper.autowire(this, logSupport);
return logSupport;
}
#PostPersist
public void onPostInsert(PostInsertEvent event) {
if (event.getEntity() instanceof BaseModel){
super.postPersist( event, (BaseModel) event.getEntity() );
}
}
#Override
public void onPostUpdate(PostUpdateEvent event) {
if (event.getEntity() instanceof BaseModel){
super.postUpdate( event, (BaseModel) event.getEntity() );
}
}
#Override
public BaseModel getLogDomain(Asset domain) {
return domain;
}
#Override
public boolean requiresPostCommitHanding(EntityPersister persister) {
return false;
}
}
And I called it from #EntityListeners
#Entity
#Table(name = "tbl_asset")
#EntityListeners({ AssetEventListener.class })
public class Asset extends BaseModel {
}
Listener not call when update the entity. Any help would be greatly appreciated.
Thanks,

Equivalent of Jackson's #JsonUnwrapped in Jsonb

I tried to implement the equivalent of Jacksons's #JsonUnwrapped in Jsonb (using Yasson) with this:
#Retention(RetentionPolicy.RUNTIME)
#JsonbTypeSerializer(UnwrappedJsonbSerializer.class)
public #interface JsonbUnwrapped {}
public class UnwrappedJsonbSerializer implements JsonbSerializer<Object> {
#Override
public void serialize(Object object, JsonGenerator generator, SerializationContext context) {
context.serialize(object, new UnwrappedJsonGenerator(generator));
}
}
public class UnwrappedJsonGenerator extends JsonGeneratorWrapper {
private int level;
public UnwrappedJsonGenerator(JsonGenerator delegate) {
super(delegate);
}
#Override
public JsonGenerator writeStartObject(String name) {
return level++ == 0 ? this : super.writeStartObject(name);
}
#Override
public JsonGenerator writeStartArray(String name) {
return level++ == 0 ? this : super.writeStartArray(name);
}
#Override
public JsonGenerator writeEnd() {
return --level == 0 ? this : super.writeEnd();
}
}
public class Person {
#JsonbUnwrapped
public Name getName() {
return new Name();
}
public static class Name {
public String getFirstName() {
return "John";
}
public String getLastName() {
return "Doe";
}
}
}
JsonbBuilder.create().toJson(new Person())
But this raises an exception javax.json.bind.JsonbException: Recursive reference has been found in class class Person$Name because my UnwrappedJsonbSerializer calls SerializationContext.serialize() with the same object that was initially passed.
Is there any other way to achieve that without resorting to custom serializers for Person or Name ?

Converter works for RequestParameter but not for RequestBody field

I have the following converter:
#Component
public class CountryEnumConverter implements Converter<String, CountryEnum> {
#Override
public CountryEnum convert(String country) {
CountryEnum countryEnum = CountryEnum.getBySign(country);
if (countryEnum == null) {
throw new IllegalArgumentException(country + " - Country is not supported!");
}
return countryEnum;
}
}
Registered it is invoked when used for RequestParam
#GetMapping(value = RestApiEndpoints.RESULTS, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResultDto> getResults(
Principal principal,
#RequestParam CountryEnum country) {
....
}
But this converter is never invoked when used for field in the RequstBody:
#GetMapping(value = RestApiEndpoints.RESULTS, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResultDto> getResults(
Principal principal,
#RequestBody MyBody myBody) {
....
}
public class MyBody {
#NotNull
private CountryEnum country;
public MyBody() {
}
public CountryEnum getCountry() {
return country;
}
public void setCountry(CountryEnum country) {
this.country = country;
}
}
Your existing org.springframework.core.convert.converter.Converter instance will only work with data submitted as form encoded data. With #RequestBody you are sending JSON data which will be deserialized using using the Jackson library.
You can then create an instance of com.fasterxml.jackson.databind.util.StdConverter<IN, OUT>
public class StringToCountryTypeConverter extends StdConverter<String, CountryType> {
#Override
public CountryType convert(String value) {
//convert and return
}
}
and then apply this on the target property:
public class MyBody {
#NotNull
#JsonDeserialize(converter = StringToCountryTypeConverter.class)
private CountryEnum country;
}
Given the similarity of the 2 interfaces I would expect that you could create one class to handle both scenarios:
public class StringToCountryTypeConverter extends StdConverter<String, CountryType>
implements org.springframework.core.convert.converter.Converter<String, CountryType> {
#Override
public CountryType convert(String value) {
//convert and return
}
}
I found out that if I add the following code to my CountryEnum will do the trick.
#JsonCreator
public static CountryEnum fromString(String value) {
CountryEnumConverter converter = new CountryEnumConverter();
return converter.convert(value);
}

Handler Goblal Exceptions Spring - add data when sending exception

I have a doubt about how to pass more data to throw an exception, I want to pass more data at the time of launching it, to put that data in the service response ..
I have an exception handler class labeled #ControllerAdvice in spring, but I don't know the best way to pass the data.
This is the code I have
throw new OcspException("Exception OCSP");
public class OcspException extends RuntimeException {
private static final long serialVersionUID = 1L;
public OcspException(String businessMessage) {
super(businessMessage);
}
public OcspException(String businessMessage, Throwable throwable) {
super(businessMessage, throwable);
}
}
#ExceptionHandler(OcspException.class)
public ResponseEntity<Object> exception(OcspException exception,HttpServletRequest request) {
ResponseException response = new ResponseException();
response.setCode("404");
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
I have the idea to do it, but I don't know if it is a good practice ... in the OcspException class to create attributes with their setter and getters, and create the constructor that receives this data, to then extract the data in exception controller
throw new OcspException("Exception OCSP","Hello");
public class OcspException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String m;
public OcspException(String businessMessage) {
super(businessMessage);
}
public OcspException(String businessMessage, Throwable throwable) {
super(businessMessage, throwable);
}
public OcspException(String businessMessage, String message) {
super(businessMessage);
setM(message);
}
public String getM() {
return m;
}
public void setM(String m) {
this.m = m;
}
}
#ExceptionHandler(OcspException.class)
public ResponseEntity<Object> exception(OcspException exception,HttpServletRequest request) {
ResponseException response = new ResponseException();
response.setCode("404");
response.setDetails(exception.getM() );
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
Try making an model called ErrorDetails which will hold a timestamp, message, and details.
It may look like this:
#Data
#Builder
#AllArgsConstructor
#NoArgsConstructor
public class ErrorDetails {
private LocalDateTime timeStamp;
private String message;
private String details;
}
Here's a sample of what my custom exceptions usually look like:
#Data
#ResponseStatus(value = HttpStatus.NOT_FOUND)
public class OrderNotFoundException extends RuntimeException {
private final String message;
public OrderNotFoundException(String message) {
super(message);
this.message = message;
}
}
Then for the #ExceptionHandler:
#ExceptionHandler(OrderNotFoundException.class)
public ResponseEntity<ErrorDetails>
orderNotFoundException(OrderNotFoundException ex, WebRequest request) {
ErrorDetails errorDetails = ErrorDetails.builder()
.timeStamp(LocalDateTime.now())
.message(ex.getMessage())
.details(request.getDescription(false))
.build();
return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}
The error response for an order not found ends up being this:
{
"timeStamp": "2019-10-07T21:31:37.186",
"message": "Order with id 70 was not found.",
"details": "uri=/api/v1/order"
}
This way you can add whatever extra details in the ErrorDetails object. I hope that helps!

Spring MVC Validation for list and reporting the invalid value

I have a list of strings which should be of a specific format. I need to return the error message with the strings which are not of the format specified. How to do this with spring validation(I am using the hibernate validator).
The annotation:
#Documented
#Retention(RUNTIME)
#Target({FIELD, METHOD})
#Constraint(validatedBy = HostsValidator.class)
public #interface HostsConstraint {
String message();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
The implementation:
public class HostsValidator implements ConstraintValidator<HostsConstraint, List<String>>{
#Override
public void initialize(OriginHostsConstraint constraintAnnotation) {
}
#Override
public boolean isValid(List<String> strings, ConstraintValidatorContext context) {
for (String s : strings) {
if (!s.matches("[0-9]+") {
//How do I say: Invalid string <s> ?
return false;
}
}
}
}
The usage:
public class Test {
#HostsConstraint(message="Invalid string ")
private List<String> hosts;
}
Using validatedValue will give the entire list.
Use JSR 380 validation, it allows container element constraints.
Here is a link to the container element section in the Hibernate Validator 6.0.6.FINAL Document
I think I found a solution but it is coupled to hibernate validator. May be it is even a hacky implementation.
The usage:
public class Test {
#HostsConstraint(message="Invalid string : ${invalidStr}")
private List<String> hosts;
}
The implementation
public class HostsValidator implements ConstraintValidator<HostsConstraint, List<String>>{
#Override
public void initialize(OriginHostsConstraint constraintAnnotation) {}
#Override
public boolean isValid(List<String> strings, ConstraintValidatorContext context) {
for (String s : strings) {
if (!s.matches("[0-9]+") {
ConstraintValidatorContextImpl contextImpl =
(ConstraintValidatorContextImpl) context
.unwrap(HibernateConstraintValidatorContext.class);
contextImpl.addExpressionVariable("invalidStr", s);
return false;
}
}
}
}

Resources