dealing with exceptions in #JsonFormat pattern - spring

I am using the #JsonFormat annotation from the fasterxml.jackson library:
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private Date endDate;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private Date startDateInUtc;
When the date format isn't correct, I don't get an exception, but instead, get the wrong date object (e.g. month 13 becomes January).
Based on my research, I came across two possible solutions:
Playing with the ObjectMapper. (with the setDateFormat function)
Creating my own Json Deserializer class, that will throw an error when the format is not valid:
public class JsonDateDeserializer extends JsonDeserializer<Date> {
public static final String DATE_FORMAT = "yyyy-MM-dd";
#Override
public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
format.setLenient(false);
String dateString = jsonParser.getText();
try {
return format.parse(dateString);
} catch (ParseException e) {
throw new InvalidFormatException(String.format("Date format should be %s", DATE_FORMAT), dateString, Date.class);
}
}
}
With neither solution can I specify a different format for different fields.
Although I can define multiple deserializers, it looks to me like a pretty ugly way to do this.
I thought that the #JsonFormat annotation was designed to deal with different formats of dates in different fields, but as I said, there is no exception when an invalid format is entered.
Could someone suggest an elegant solution to this problem?

Related

LastModifiedDate is not getting updated for an entity using spring-data-elasticsearch

// Entity model definition
#Builder.Default
#LastModifiedDate
#Field(type = FieldType.Date, name = "modified_dt", format = DateFormat.basic_date_time)
private Instant modifiedDate = Instant.now();
// update attribute call
protected void updateAttribute(String id, Document document) throws Exception {
UpdateQuery updateQuery = UpdateQuery.builder(id).withDocument(document).build();
UpdateResponse updateResponse = operations.update(updateQuery, indexCoordinates());
Result result = updateResponse.getResult();
if (!result.equals(Result.UPDATED)) {
throw new Exception();
}
}
From version 7 the date format is different since yyyy has been replaced by uuuu, maybe it's related to this:
https://www.elastic.co/guide/en/elasticsearch/reference/current/migrate-to-java-time.html#java-time-migration-incompatible-date-formats
Also the Lombok annotation #Builder.Default won't work for parameterless constructors, so maybe it's also interfering.

Spring Data Elasticsearch Repository query define date input parameter format

I am using elasticsearch 6.5.3 and Spring Boot 2.1.6 and spring-data-elasticsearch 3.2.0.M1.
I have defined the Elasticsearch configuration as:
#Bean
public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchRestTemplate(client(), new CustomEntityMapper());
}
public static class CustomEntityMapper implements EntityMapper {
private final ObjectMapper objectMapper;
public CustomEntityMapper() {
//we use this so that Elasticsearch understands LocalDate and LocalDateTime objects
objectMapper = new ObjectMapper()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
.disable(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
//MUST be registered BEFORE calling findAndRegisterModules
.registerModule(new JavaTimeModule())
.registerModule(new Jdk8Module());
//only autodetect fields and ignore getters and setters for nonexistent fields when serializing/deserializing
objectMapper.setVisibility(objectMapper.getSerializationConfig().getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
//load the other available modules as well
objectMapper.findAndRegisterModules();
}
#Override
public String mapToString(Object object) throws IOException {
return objectMapper.writeValueAsString(object);
}
#Override
public <T> T mapToObject(String source, Class<T> clazz) throws IOException {
return objectMapper.readValue(source, clazz);
}
}
I have a repository with a method defined as:
List<AccountDateRollSchedule> findAllByNextRollDateTimeLessThanEqual(final LocalDateTime dateTime);
And the POJO AccountDateRollSchedule defines that field as:
#Field(type = FieldType.Date, format = DateFormat.date_hour_minute)
#DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm")
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm")
private LocalDateTime nextRollDateTime;
I see my index properly has that field created as declared and expected:
"nextRollDateTime": {
"type": "date",
"format": "date_hour_minute"
}
Also querying the index returns the field formatted as expected:
"nextRollDateTime" : "2019-06-27T13:34"
My repository query would translate to:
{"query":
{"bool" :
{"must" :
{"range" :
{"nextRollDateTime" :
{"from" : null,
"to" : "?0",
"include_lower" : true,
"include_upper" : true
}
}
}
}
}
}
But passing any LocalDateTime input to the method does NOT respect the format defined for the field, the FULL format is always used instead. Invoking:
findAllByNextRollDateTimeLessThanEqual(LocalDateTime.now(ZoneOffset.UTC).truncatedTo(ChronoUnit.MINUTES));
gives me the following exception (any #DateTimeFormat or #JsonFormat annotation on the method parameter in the repository is ignored):
Unrecognized chars at the end of [2019-07-22T09:07:00.000]: [:00.000]
If I instead change the repository method to accept a String and pass a String formatted exactly as expected as input to it, it works no problem.
Is it possible to somehow define the format used for the date parameter passed in input to the repository method or have Spring use the one configured on the field itself?
I would like not to wrap that method for a simple conversion like this (I did and it works), and I would also like to avoid using long type for the date field
Thanks and cheers
For reference, I also open issue on Spring JIRA
These problems are one reason why we move away from using and exposing the JacksonMapper in Spring Data Elasticsearch. From version 4.0 on all you need on your property is the one annotation:
#Field(type = FieldType.Date, format = DateFormat.date_hour_minute)
private LocalDateTime nextRollDateTime;
This will then be used in writing the index mappings, when entities are indexed and retrieved, and also when repository method and queries are processed.
But for the 3.2.x version you will have to use a workaround like the wrapping you mentioned.

Spring boot - date in response is not well formatted

I have the following entity column definition:
#Column(name= "time")
#Temporal(TemporalType.TIMESTAMP)
private java.util.Calendar time;
When I query and return my data as JSON:
modules = this.moduleStatsRepository.findAll();
JsonArray modulesArray = Application.gson.fromJson(Application.gson.toJson(modules), JsonArray.class);
JsonObject modulesJson = new JsonObject();
modulesJson.add("modules", modulesArray);
modulesJson.addProperty("triggerTimeShortSec", configurationManager.startupConfig.get("stats_trigger_time_sec"));
modulesJson.addProperty("triggerTimeLongSec", Integer.parseInt(configurationManager.startupConfig.get("stats_trigger_time_sec")) * 3);
return Application.gson.toJson(modulesJson);
the time is returned as an object, not really ideal:
Is there any way to customize gson settings to parse dates as ISO 8601?
Many of these things come out of the box with Jackson. With Gson it doesn't seem that there is an option to configure ISO 8601 timestamps, so you'll have to write it yourself by registering a JsonSerializer<Calendar> and perhaps also a JsonDeserializer<Calendar>.
For example, a simplified ISO 8601 string to calendar converter could look like this:
public class CalendarISO8601Serializer implements JsonSerializer<Calendar>, JsonDeserializer<Calendar> {
private static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
#Override
public Calendar deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
try {
Calendar instance = Calendar.getInstance();
instance.setTime(FORMATTER.parse(jsonElement.getAsString()));
return instance;
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
#Override
public JsonElement serialize(Calendar calendar, Type type, JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(FORMATTER.format(calendar.getTime()));
}
}
This means you can no longer rely on the default Gson object created by Spring boot since I don't think it will automatically pick up the serializer as a type adapter. To solve this, you need to create your own Gson bean and add the serializer:
#Bean
public Gson gson() {
return new GsonBuilder()
.registerTypeHierarchyAdapter(Calendar.class, new CalendarISO8601Serializer())
.create();
}
But considering that you're using a public static field (Application.gson), you may want to see for yourself how you want to register that adapter.
just use java.util.Date as Type in your Entity:
#Temporal(TemporalType.TIMESTAMP)
private Date date;

how to avoid rejected value [] issue in spring form submission

i have two dates in form submission in Spring 3 + Hibernate.
#Column(name = "FinStartDate")
private Date finStartDate;
#Column(name = "FinEndDate")
private Date finEndDate;
I'm display/hide dates on the basis of some criteria. When the dates are hidden and submit the form, the following errors
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errors
Field error in object 'register' on field 'obj.finEndDate': rejected value []; codes [typeMismatch]
How to avoid the issue.
#JsonDeserialize(using = LocalDateDeserializer.class)
#JsonSerialize(using = LocalDateSerializer.class)
#DateTimeFormat(pattern = "dd.MM.yyyy")
private Date finEndDate;
Maybe, you should use serializer/deserializer.
I think that you miss a formatter to convert the date String to a Date object.
You can try to annotate your field
#DateTimeFormat(pattern = "yyyy-MM-dd")
or to declare a initbinder in your controller like :
#InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new CustomDateEditor(
dateFormat, false));
}
Or you can declare a formatter in you mvc configuration file that will format every Date object your application is binding to.
Add #DateTimeFormat annotation for following way. If not working update date format. (MM-dd-yyyy, dd-MM-yyyy)
#Column(name = "FinEndDate")
#DateTimeFormat(pattern = "yyyy-MM-dd")
private Date finEndDate;

Spring Controller converts time to it's Local TimeZone

I have spring rest service project and I am using JPA hibernate and I am facing a strange issue in my controller. Below is code snippet:
controller:
#RequestMapping(method = RequestMethod.POST, value=PATH_SEPERATOR+ CREATE_OR_UPDATE_EVENT_METHOD, headers = ACCEPT_APPLICATION_JSON, produces = APPLICATION_JSON)
#ResponseStatus(HttpStatus.CREATED)
#ResponseBody
ResponseBean createOrUpdateEvent(#RequestBody Event eventBean)
{
ResponseBean response = new ResponseBean();
try {
String sysId = eventService.createOrUpdateEvent(eventBean);
response.setStatus(OK);
response.setData(sysId);
} catch(Exception ex) {
response = handleException(CREATE_OR_UPDATE_EVENT_METHOD, ex);
return response;
}
return response;
}
Event.java
#Entity
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "sysId", scope = Event.class)
#Table(name = "event")
public class Event {
#Column(name = "date_time")
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss")
private Date dateTime;
public Date getDateTime() {
return dateTime;
}
public void setDateTime(Date dateTime) {
this.dateTime = dateTime;
}
}
When I pass date to Event bean in createOrUpdateEvent method as String "2014-04-17T17:15:56" which is in IST timezone, the controller convert it to Date with datetime "2014-04-17T22:45:56" IST considering previous time as UTC time. I don't understand this behaviour of auto conversion. I assume that it's because I am accepting parameter as bean, where bean is JPA Entity. Please help me to fix it.
There are several things you must take into consideration. First and foremost you are lacking a time zone information in the provided JSON serialization format "yyyy-MM-dd'T'HH:mm:ss". There's a format character that adds it - Z. Using it should be something like "yyyy-MM-dd'T'HH:mm:ssZ" depending on your preferences. Another thing you should consider is the fact that java.util.Date is not TimeZone aware and when you are creating a new Date(long) it always assumes that the passed date is in the current time zone.
So in order to fix this issue you have to add (and pass) the time zone as I told you and the Json parser will do the rest.

Resources