LocalDateTime is converted to OffsetDateTime in client - spring

This is my code to send to the client:
#DateTimeFormat(pattern = FormatConstants.DEFAULT_DATE_FORMAT)
private LocalDateTime finalizationDate;
when i generate client with swagger,apicodegen
it creates jar for our customer and that variable becomes this:
#SerializedName("finalizationDate")
private OffsetDateTime finalizationDate = null;
Why this can be? What can i do? Should i convert our variable to also offsetdatetime?

Related

parse localDateTime string correctly into spring boot #pathVariable

I'm trying to get all data of a user of a user with a timestamp:
#GetMapping("/datum/{userID}/{timeStamp}")
List<Datum> getDataSingleUserTimeRange(#PathVariable Long userID, #PathVariable LocalDateTime timeStamp)
{
....
}
Now to test this Spring Boot rest api, in postman, I made this call GET and url - http://localhost:8080/datum/2/2019-12-15T19:37:15.330995.
But it gives me error saying : Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDateTime'
How can I resolve this ??
You need #DateTimeFormat with custom pattern that matches to your input
#GetMapping("/datum/{userID}/{timeStamp}")
List<Datum> getDataSingleUserTimeRange(#PathVariable Long userID, #PathVariable #DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS") LocalDateTime timeStamp)
{
}
I don't know if it is the most modest way to do this or not, but here is what I have done :
#GetMapping("/datum/{userID}/{timeStamp}")
List<Datum> getDataSingleUserTimeRange(#PathVariable Long userID, #PathVariable String timeStamp)
{
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
LocalDateTime dateTime = LocalDateTime.parse(timeStamp, formatter);
...
return datumRepository.findUsingTime(start,end);
}
Passed as string and parsed that. AnddateTime.truncatedTo(ChronoUnit.NECESARRY_UNIT); can be used as well.

(Spring) When using PUT method, #CreationTimestamp fails

I have this API that uses #CreationTimestamp to auto-generate the date when any information is added to the database, and it works. The problem is, when i use the PUT method in a specific information of the database, the generated Date disappears.
This is how things are structured:
...
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CreationDate", length = 29)
#CreationTimestamp
private Date CreationDate;
...
This is how my PUT method is:
#PutMapping("/SomeURL/{id}")
#ResponseBody
public User editUser(#RequestBody #Valid User T, #PathVariable Integer id) {
return userRepository.save(T);
}
When I use this, the generated Date from the #CreationTimestamp disappears, and that field becomes blank (null).
Why is this happening?
OBS: I dont think is necessary, but this is my POST method:
#PostMapping("/someURL")
public User addUser(#RequestBody #Valid User T) {
return userRepository.save(T);
}
The creation date will be updated when calling save method within your editUser method. The entity possibly does not contain this value, therefore null will be set as updated value. (you can try to debug this to check)
Change the column annotation as followed:
#Column(name = "CreationDate", length = 29, nullable = false, updatable = false)
This should prevent the once created date to be updated.
HTH

How to parse a date of format "2016-08-07T08:50:06.000Z" using Jackson and ObjectMapper

I am trying to parse a Json in the above format using Jackson and Java 8, but unable to do so.
Here is my code -
String date = "{\"requestDate\":\"2016-08-07T08:50:06.000Z\"}";
TestPOJO testPOJO = new ObjectMapper().readValue(date, TestPOJO.class);
System.out.println("testPOJO" + testPOJO.toString());
TestPojo.java
#AllArgsConstructor
#NoArgsConstructor
#Data
#JsonIgnoreProperties(ignoreUnknown = true)
public class TestPOJO {
#JsonProperty("requestDate")
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS", timezone = "GMT")
private LocalDateTime testDate;
}
However for the same pattern I am able to parse it to Calendar Object.
Is there a way pattern to directly parse it as LocalDateTime object ?
Registering the jackson-datatype-jdk8 module will solve your issue.
ObjectMapper mapper = new ObjectMapper().registerModule(new Jdk8Module());

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;

Post a Joda LocalDateTime as a property. Spring MVC

I have to controller that takes a controller that a Notification and returns a json response.
public #ResponseBody ResponseWrapper<Notification> addNotification(
#RequestParam(required = false) String password,
#Valid Notification notification,
BindingResult bindingResult ){.....}
My Notification that is posted includes a LocalDateTime.
notification.time
How can map a String to LocalDateTime when posting. CustomPropertyEditor or is there a better approach.
Also the time is in my wrapper. How can I format it? LocalDateTime in json includes a lot of information I don't need.
You can annotate your field with #DateTimeFormat and provide a pattern. For example
#DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDateTime time;
If Spring finds jodatime on your class path, it will use an appropriate DateTimeFormatter to parse the String date value from the request and generate a LocalDateTime object.

Resources