how to convert the data of value attribute of request parameter to string content in spring - spring

i want to get the value of ticket id in string data Type
#RequestParam(value = "ticketId" , required = false, defaultValue = "false")
how can i get the value of ticketId in any string data.
Earlier i have tried to do this
***#RequestParam(value = "ticketId" String ticketId, required = false, defaultValue = "false")***

Everything except the syntax is correct.Correct syntax:
#RequestParam(value = "ticketId", required = false) String ticketId

Related

Spring / Swagger-UI - Show example of real values in request model when user clicks on "Try it out" button

How do I make swagger-ui to show pre-populated real values in the Example box below? (The box for request model that shows when user clicks on "Try it out" button in swagger-ui).
I am using SpringBoot/Java and I would like it to show some real values rather than data types. It seam to do that for DOB field by default.
I have MyModel defined as below and I was expecting that using "value" in ApiModelProperty will set these values but it is not:
#ApiModel(description="blahblah")
public class MyModel {
#ApiModelProperty(notes = "some notes", name = "name", required = true, value = "Bot")
private String name;
#ApiModelProperty(notes = "Date of birth", name = "dob", required = true)
private OffsetDateTime dob;
#ApiModelProperty(notes="How old", name = "age", required = true, value = "31")
private Integer age;
...
}
I would like above to look like:
Use example:
#ApiModelProperty(notes = "some notes", name = "name", required = true, example = "Bot")
private String name;

#PathVariable of GetMapping in Spring throws an error when the input is #

I have made an autosuggest input field that automatically searches the database on every keypress. It works fine when i insert regular characters like letters and numbers but it gets spooky when you try start the search request with the character #. Doing that throws the error org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'long'; nested exception is java.lang.NumberFormatException: For input string: "get"
When i add some letters before the # (for example des#) it will throw an 404 page not found error and if i use the % character it will throw an 400 'unauthorized' error.
This strange behavior has probably something to do that i'm expecting a GetRequest instead of a PostRequest. If i turn it into a PostMapping i'm sure the errors will dissapear. But my question is; why is this happening? Does # have a special meaning? Why does spring seemingly try to convert # to a long value even though the pathvariable is typed as String? And why has the input string become "get" according to the error? I know that in an url # has a special meaning in that it signifies an href anchor but why should it be a special character for spring?
Heres the code of my getMapping
#GetMapping("/get/varietynames/{searchString}/{languageCode}")
public List<CropVarietyNameSelectionDTO> getCropVarietySelectionDTOBySearchString(#PathVariable("searchString") #NotBlank #Pattern(regexp = "^[A-Za-z0-9]+$", message = "Search input only allows for letters and numbers")
#Size(min = 1, max = 40, message = "Search input cannot exceed 40 characters") String searchString, #PathVariable("languageCode") String languageCode){
return seedService.getCropVarietySelectionDTOBySearchString(searchString,languageCode);
}
Edit
Request on the frontend side is:
private basePath:string = this.apiUrl + "/seed";
getCropVarietySelectionDTOBySearchString(searchString: string):Observable<CropVarietyNameSelectionDTO[]>{
return (searchString && (searchString.trim().length > 0)) ? this.http.post<CropVarietyNameSelectionDTO[]>(this.basePath + "/get/varietynames/" + this.languageService.getCodeOfPreferredLanguage(), searchString) : Observable.of([]);
}
this.apiUrl = localhost:4200
That is not the correct way or option to use #PathVariable annotation which indicates that a method parameter should be bound to a URI template variable. You need to use #RequestParam annotation which indicates that a method parameter should be bound to a web request parameter. You can see this answer that is a #RequestParam vs #PathVariable
#GetMapping("/get/varietynames")
public List<CropXXXDTO> getXXXXXhString(#RequestParam #NotBlank
#Pattern(regexp = "^xx+$", message = "xxxxx")
#Size(min = 1, max = 40, message = "xxxxx") String searchString,
#RequestParam(required = false, defaultValue = "EN") String languageCode){
return seedService.getXXXXtring(searchString, languageCode);
}
Then you can check the URL by following way:
/get/varietynames?searchString=XXXXX&languageCode=EN

Bean validation - validate optional fields

Given a class that represents payload submitted from a form, I want to apply bean validation to a field that may or may not be present, for example:
class FormData {
#Pattern(...)
#Size(...)
#Whatever(...)
private String optionalField;
...
}
If optionalField is not sent in the payload, I don't want to apply any of the validators above, but if it is sent, I want to apply all of them. How can it be done?
Thanks.
So usually all of these constraints consider null value as valid. If your optional filed is null when it's not part of the payload all should work just fine as it is.
And for any mandatory fields you can put #NotNull on them.
EDIT
here's an example:
class FormData {
#Pattern(regexp = "\\d+")
#Size(min = 3, max = 3)
private final String optionalField;
#Pattern(regexp = "[a-z]+")
#Size(min = 3, max = 3)
#NotNull
private final String mandatoryField;
}
#Test
public void test() {
Validator validator = getValidator();
// optonal field is null so no violations will rise on it
FormData data = new FormData( null, "abc" );
Set<ConstraintViolation<FormData>> violations = validator.validate( data );
assertThat( violations ).isEmpty();
// optional field is present but it should fail the pattern validation:
data = new FormData( "aaa", "abc" );
violations = validator.validate( data );
assertThat( violations ).containsOnlyViolations(
violationOf( Pattern.class ).withProperty( "optionalField" )
);
}
You can see that in the first case you don't get any violations as the optional field is null. but in the second exmaple you receive a violation of pattern constraint as aaa is not a string of digits.

Using #RequestParam annotated method with swagger ui

I am using Springfox libraries to generate documentation for REST service and display it in Swagger UI. I followed the directions in Springfox documentation.
I have one controller, which uses parameters from query string and the method is mapped as following:
#ApiOperation(value = "")
#RequestMapping(method = GET, value = "/customcollection/{id}/data")
public Iterable<CustomeType> getData(#ApiParam(value = "The identifier of the time series.")
#PathVariable String id,
#ApiParam(name = "startDate", value = "start date", defaultValue = "")
#RequestParam("startDate") String startDate,
#ApiParam(name = "endDate", value = "end date", defaultValue = "")
#RequestParam("endDate") String endDate)
The resulting mapper in swagger-ui then displayed as:
GET /customcollection/{id}/data{?startDate,endDate}
Parameters are displayed correctly in the UI:
But when I click on Try it Out, the request URL is misformed:
http://localhost:8080/customcollection/1/data{?startDate,endDate}?startDate=1&endDate=2
How can it be fixed?
This was caused by the line
enableUrlTemplating(true)
in Docket configuration which I copied from example and forgot to remove.
After removing this line everything is working as expected.

Why am I getting "400 Bad Request" for this URL in Spring MVC?

The following URL results in a "400 Bad Request":
http://localhost:8080/springdata_web/rest/errors/test?from=2014-05-25T00:00:00.000Z&to=2014-05-27T00:00:00.000Z
The matching #RequestMapping is below. I can see I am definitely hitting this method because I see the Sysout line in the console using the following URL for example:
http://localhost:8080/springdata_web/rest/errors/test?from=&to=
So I guess it's to do with the Date type and Spring not accepting the format I'm passing in the request params but I don't see why.
#RequestMapping(value = "/test",
method = RequestMethod.GET,
produces = "application/json")
#ResponseBody
public Resource<List<ErrorsDTOEntity>> getAllErrors(
#RequestParam(value = "from", required = true) #DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date from,
#RequestParam(value = "to", required = true) #DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date to) {
System.out.println("getAllErrors(Date, Date);");
List<ErrorsDTOEntity> services = errorsDAO.getAllErrors(from, to);
Resource<List<ErrorsDTOEntity>> toReturn = new Resource<List<ErrorsDTOEntity>>(services);
toReturn.add(linkTo(methodOn(ErrorsController.class).getAllErrors(from, to)).withSelfRel());
return toReturn;
}
It was the format of the date in the URL. This URL-encoded request works:
http://localhost:8080/springdata_web/rest/errors/test?from=2014-05-25T00%3A00%3A00.000%2B0000&to=2014-05-27T00%3A00%3A00.000%2B0000
The date pattern you are passing for ( from / to) is not matching. Underltying pattern for is DateTimeFormat.ISO DATE_TIME:
yyyy-MM-dd'T'hh:mm:ss.SSSZ
so example time is as below :
2000-10-31T01:30:00.000-05:00
try whether following request work:
test?from=2000-10-31T01:30:00.000-05:00&to=2000-10-31T01:30:00.000-05:00
Spring Docs says :

Resources