Spring boot - date in response is not well formatted - spring-boot

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;

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.

Mongotemplate: How to convert result field to custom Java Type?

// collection: test
{
...
Datetime: 43665.384931
...
}
public Class POJO {
#Field("ID")
private String id;
#Field("Datetime")
private Date datetime; // Where can I implement a converter to cast double value from mongo to Java type Date here?
}
mongoTemplate.findOne(new Query(), POJO.class, "test")
Where can I implement a converter to cast double value from mongo to Java type Date here?
You may want to give #Field(targetType = FieldType.INT64) of the upcoming Spring Data MongoDB 2.2 release a try. It allows to pass on type information to the conversion subsystem using the ConversionService to perform the required transformations.
class Pojo {
String id;
#Field(targetType = FieldType.INT64) Date date;
}
At the time of writing there are only converters registered for a Date -> String conversion, but none for Date -> Long, so you'll need to register the converter as well.
((GenericConversionService) mongoTemplate.getConverter().getConversionService())
.addConverter(new Converter<Date, Long>() {
#Override
public Long convert(Date source) {
return source.getTime();
}
});
Registering a MongoCustomConversions bean works for me.

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.

Java 8 Date Time api in JPA

What is the best way how to integrate Java 8 Date Time api in jpa?
I have added converters:
#Converter(autoApply = true)
public class LocalDatePersistenceConverter implements AttributeConverter<LocalDate, Date> {
#Override
public Date convertToDatabaseColumn(LocalDate localDate) {
return Date.valueOf(localDate);
}
#Override
public LocalDate convertToEntityAttribute(Date date) {
return date.toLocalDate();
}
}
and
#Converter(autoApply = true)
public class LocalDateTimePersistenceConverter implements AttributeConverter<LocalDateTime, Timestamp> {
#Override
public Timestamp convertToDatabaseColumn(LocalDateTime entityValue) {
return Timestamp.valueOf(entityValue);
}
#Override
public LocalDateTime convertToEntityAttribute(Timestamp databaseValue) {
return databaseValue.toLocalDateTime();
}
}
Everything seems fine, but how should I use JPQL for querying? I am using Spring JPARepository, and goal is to select all entities where date is the same as date given, only difference is that it is saved in entity as LocalDateTime.
So:
public class Entity {
private LocalDateTime dateTime;
...
}
And:
#Query("select case when (count(e) > 0) then true else false end from Entity e where e.dateTime = :date")
public boolean check(#Param("date") LocalDate date);
When executing it just gives me exception, which is correct.
Caused by: java.lang.IllegalArgumentException: Parameter value [2014-01-01] did not match expected type [java.time.LocalDateTime (n/a)]
I have tried many ways, but it seems that none is working, is that even possible?
Hibernate has an extension library, hibernate-java8 I believe, which natively supports many of the time types.
You should use it before writing converters.
in hibernate 5.2 you won't need this additional library, it is part of core.
To query temporal fields you should use the #Temporal Anotation in the temporal fields, add the converters to persistence.xml and also be sure you are using the java.sql.Date,java.sql.Time or java.sql.Timestamp in the converters. (Sometimes i imported from the wrong package)
for example thats works for me:
#Temporal(TemporalType.TIMESTAMP)
#Convert(converter = InstantPersistenceConverter.class)
private Instant StartInstant;
#Temporal(TemporalType.TIME)
#Convert(converter = LocalTimePersistenceConverter.class)
private LocalTime StartTime;
and my Instant converter:
#Converter(autoApply = true)
public class InstantPersistenceConverter implements AttributeConverter <Instant,java.sql.Timestamp>{
#Override
public java.sql.Timestamp convertToDatabaseColumn(Instant entityValue) {
return java.sql.Timestamp.from(entityValue);
}
#Override
public Instant convertToEntityAttribute(java.sql.Timestamp databaseValue) {
return databaseValue.toInstant();
}
}
Did you add LocalDatePersistenceConverter and LocalDateTimePersistenceConverter in persistence.xml placed in 'class' element ?

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