Post a Joda LocalDateTime as a property. Spring MVC - spring

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.

Related

spring jpa query is returning 404 no message [duplicate]

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.

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.

#Valid for long data type is not working for mandatory check

I have the below input class and when i trigger the api without 'interactionId' param in the input,
I expect validation error message "interactionId cannot be empty" but the validation passes through which i guess could be due to the fact that interactionId has a default value of 0.
Can someone pls. help to enforce this validation on the 'long' parameter when its not given in input?
with #NotEmpty for the customerId param, its working as expected. Using #NotEmpty for the long param "interactionId" is throwing a different error that #notempty cannot be used for long.
public class Input {
#NotEmpty(message = "customerId cannot be empty")
private String customerId;
#Valid
#NotNull(message = "interactionId cannot be empty")
private long interactionId;
// setters and getters
}
my controller class:
#RestController
public class Controller {
#PostMapping(value="/detailed-customer-transaction", produces =
MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public ResponseEntity<Object> detailTransactions(#Valid #RequestBody Input
params)
{
return new ResponseEntity<>(Dao.detailTransactions(params), HttpStatus.OK);
}
Above issues is resolved after changing to Long instead of long.
Query #2
I need another help. I have a String input param which takes date-time format in below format. Given its a string parameter, how can i validate for the pattern="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
long should be Long, because long is a primary type in java, not an object, so Long is an object that can be checked whether it is null

Request body Object Not being Validated

I have one REST API which is using a POST Call to create a record, I'm expecting certain Object to be passed in post call, if anything is missing i have to reject straight away from their only,
#RequestMapping(value="/saveEssentialDetails",produces={"application/json"},method=RequestMethod.POST)
ResponseEntity<?> saveEssentialDetails(#ApiParam(value="Body Parameters")#RequestBody #Validated EssentialDetails essentialDetails, BindingResult bindingResult)throws Exception;
and the Essential Model class is as follow
#Data
#NoArgsConstructor
#Document(collection="essentialDetails")
public class EssentialDetails {
#NotNull
Integer dpId;
#Id
#NotEmpty
String tpId;
#NotEmpty
List<FamousFor> famousFor;
#NotEmpty
List<OpenHours> openHours;
#NotEmpty
Pictures uploadedImages;
#NotEmpty
List<FloorDescription> floorDescriptions;
#NotEmpty
List<Outlets> mallOutlets;
}
But while making a Post Call with Missing attributes i'm allowed to make an entry in MongoDB, which i don't want to persist as it's not a proper request,#Validation is not working for me, i'm using spring boot 2.0.6 with MongoDb 4.0.4,
any help would be highly appreciated. Thanks well in advance
#Validated can be used to validate a object with a custom validation object. Example usage:
#RequestMapping(value = "/")
public String request(#Validated(Account.ValidationStepOne.class) Account account)
Instead of using #Validated use #Valid which does check for the validation annotations that you are using in your entity.

Time string to Calendar

I am using the jquery timepicker plugin and it works fine. I can select a time and submit my form. I am using spring MVC 3.0 and the problem comes in when I attempt to parse a string ,which represents time, as a java carlendar.
I have been reading up on this date/time conversion, http://www.odi.ch/prog/design/datetime.php, and it seems quite complicated. Can someone please offer some form of advice. Here is my code, which is spring specific.
#RequestMapping(value = "scheduleadd", method = RequestMethod.POST)
public String scheduleadd( #Valid Schedule schedule, BindingResult bindingResult,
#RequestParam("startdate") #org.springframework.format.annotation.DateTimeFormat(iso=ISO.DATE) java.util.Calendar startdate,
#RequestParam("enddate") #org.springframework.format.annotation.DateTimeFormat(iso=ISO.DATE) java.util.Calendar enddate,
#RequestParam("starttime") #org.springframework.format.annotation.DateTimeFormat(iso=ISO.NONE) java.util.Calendar starttime,
#RequestParam("endtime") #org.springframework.format.annotation.DateTimeFormat(iso=ISO.NONE) java.util.Calendar endtime,
#RequestParam("moduleInstanceId") Long mId, Model uiModel, HttpServletRequest httpServletRequest) { //my stuff goes here}
As you can see, I am trying to parse a string like "09:30" as java Carlendar. Do I need the date part? How do I specify the date part ?
Use the pattern attribute of #DateTimeFormat to specify that the "time" fields are not fully-formed ISO datetimes, but rather just times; e.g.:
...
#RequestParam("starttime") #DateTimeFormat(pattern="hh:mm") Calendar starttime,
#RequestParam("endtime") #DateTimeFormat(pattern="hh:mm") Calendar endtime,
...
And in your scheduleadd() method, combine the Calendar fields to get a fully-formed datetime:
startdate.set(Calendar.HOUR_OF_DAY, starttime.get(Calendar.HOUR_OF_DAY));
startdate.set(Calendar.MINUTE, starttime.get(Calendar.MINUTE));
...

Resources