Can you have an optional QueryParam in jersey? - java

Using java jersey, I have the following #QueryParam's in my method handler:
#Path("/hello")
handleTestRequest(#QueryParam String name, #QueryParam Integer age)
I know if I do:
http://myaddress/hello?name=something
It will go into that method....
I want to make it so that I can call:
http://myaddress/hello?name=something
And it will also go into that same method. Is there any way I can flag an "optional" PathParam? Does it work with #FormParam too? Or am I required to create a separate method with a different method signature?

In JAX-RS parameters are not mandatory, so if you do not supply an age value, it will be NULL, and your method will still be called.
You can also use #DefaultValue to provide a default age value when it's not present.
The #PathParam parameter and the other parameter-based annotations, #MatrixParam, #HeaderParam, #CookieParam, and #FormParam obey the same rules as #QueryParam.
Reference

You should be able to add the #DefaultValue annotation the age parameter, so that if age isn't supplied, the default value will be used.
#Path("/hello")
handleTestRequest(
#QueryParam("name") String name,
#DefaultValue("-1") #QueryParam("age") Integer age)
According to the Javadocs for #DefaultValue, it should work on all *Param annotations.
Defines the default value of request meta-data that is bound using one of the following annotations: PathParam, QueryParam, MatrixParam, CookieParam, FormParam, or HeaderParam. The default value is used if the corresponding meta-data is not present in the request.

You can always wrap return type in optional, for example: #QueryParam("from") Optional<String> from

Related

Need to include #Json non-null in swagger code gen

I need to add #Json non-null in call level but I am not able to do it from swagger code gen.
Hence, could you please help me with this issue?
you can use the #io.swagger.v3.oas.annotations.media.Schema annotation on your method parameters. This annotation allows you to specify the data type, format, and other properties of the parameter, and you can use it to specify that the parameter is required (non-null) using the required property.
Here is how you might use the #Schema annotation to specify that a method parameter is required:
#GET
#Path("/users/{id}")
public User getUser(
#PathParam("id") #Schema(required = true) String userId
) {
...
}
In this example, the #Schema annotation is used on the userId parameter to specify that it is required. This will ensure that the generated code includes the #Json non-null annotation on the parameter, which will enforce the requirement at runtime.
You can also use the #Schema annotation to specify other properties of the parameter, such as its data type, format, and description. For more information, you can refer to the Swagger Code Gen documentation.

How to check REST invalid query parameter name with RESTEasy?

How to fail on invalid query parameter name with RESTEasy?
Consider a valid REST request like this one: /list?sort-by=date
Then, user makes this request: /list?sort_by=date
See that user replaced hyphen with underscore. It works, but it will ignore parameter and use default sorting (param not mandatory).
With Jackson, if a JSON with invalid member is sent it throws an Exception. I would like a similar behavior to query params (header params would be awesome too). Tested with #BeanParam, but apparently it doesn't use Jackson in this case.
RESTEasy version 3.15.1.
You have to check that in your code. Query params are not in json in standard, you can do that with a class with string constructor.
In fact "sort_by" is not bind to a method parameter, so it's ignored.
If you want that "sort-by" to be mandatory you have to do that in your code :
Required #QueryParam in JAX-RS (and what to do in their absence)
Currently since RESTEasy is built on top of a Servlet, it does not distinguish between URI query strings or url form encoded parameters. Like PathParam, your parameter type can be an String, primitive, or class that has a String constructor or static valueOf() method.
https://docs.jboss.org/resteasy/docs/3.15.1.Final/userguide/html_single/#_QueryParam

How to define the default value for #QueryParam?

When I add the default value of the string in JAX-RS, it doesn't take the value. It stays to null or empty.
#QueryParam("status")
private String status = "confirmed";
When I pass the status as empty or null or undefined it stays as empty or null or undefined. It doesn't take the default as confirmed.
Use the #DefaultValue annotation to specify the default value of the request meta-data that is bound to #PathParam, #QueryParam, #MatrixParam, #CookieParam, #FormParam and #HeaderParam annotations:
#QueryParam("status")
#DefaultValue("confirmed")
private String status;
If a method parameter, resource class field, or resource class bean property is not annotated with #DefaultValue and the corresponding meta-data is not present in the request, the value will be:
An empty collection for List, Set or SortedSet.
null for other object types;
Java-defined default for primitive types.

Using a custom object instead of #FormParam as JAX-RS resource input

I'm having an example code:
#PUT
public String method(#FormParam("firstName") String firstName,
#FormParam("lastName") String lastName ) {
Person person = new Person(firstName, lastName);
// ...
}
I would like to stop using #FormParams and use Person instead:
#PUT
public String method(#Person person) {
// ...
}
What would be the best way to do it?
I'm experimenting with a custom BodyReader but than I have to "manually" parse the InputStream in readFrom method.
Is that the right way to do it and if yes what is the best way to transform the InputStream into KEY => VALUE HashMap?
there is an #BeanParam option, see:
https://jersey.java.net/documentation/latest/jaxrs-resources.html#d0e1905
You have two options:
Probably you transport only a single entity instance within that method, in which case you could simply avoid annotating the person parameter with any JAX-RS annotations. In the JAX-RS specification this is called an entity parameter and there must be a single such parameter in a REST method, and then it is automatically decoded by an registered entity providers.
Change your Person class so that its constructor receives a single String as a parameter, and to the decoding in the constructor. Extracted from here:
In general the Java type of the method parameter may:
Be a primitive type; -Have a constructor that accepts a single
String argument;
Have a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String) and
java.util.UUID.fromString(String));
Have a registered implementation of javax.ws.rs.ext.ParamConverterProvider JAX-RS extension SPI that
returns a javax.ws.rs.ext.ParamConverter instance capable of a "from
string" conversion for the type. or
Be List, Set or SortedSet, where T satisfies 2 or 3 above. The resulting collection is read-only.

Spring MVC default value not working

#RequestMapping(value = "/Fin_AddBankAccount", method = RequestMethod.POST)
public #ResponseBody JsonResponse addCoaCategory(
#RequestParam(value="code", required=true) long code,
#RequestParam(value="startFrom", required=true) long startFrom,
#RequestParam(value="name", required=true, defaultValue="N/A") String name)
{
}
defaultValue="N/A" not working , As I did not provide any text in name field , it store null in database instead of "N/A"?
What is the point of setting a default value if you really want that parameter.
if you mark it as required true(not needed as it is default) then no need of a default value.
If that parameter is not mandatory then mark it as false and give a default value.
Documentation of Spring RequestParam.required
Default is true, leading to an exception thrown in case of the parameter missing in the request. Switch this to false if you prefer a null in case of the parameter missing.
From your question I figured out that you are sending parameter name with empty value using POST request. According to the Spring documentation you should not send name parameter in the request in order to use default value. Simply remove name field from HTML form if it is empty.
It seems that default values makes more sense for GET requests.
make sure you don't pass empty string value
Valid Methods:
1. Fin_AddBankAccount?name=
O/P: name="N/A"
Fin_AddBankAccount?
O/P: name="N/A"
Invalid Methods:
Fin_AddBankAccount?name=""
this will set empty string to variable i.e. name="";
In my project
#RequestParam(value="name", required=true, defaultValue="N/A") String name
This code correctly sets name variable as defaultvalue N/A when requestparam "name" was not provided. My guess is you are not inserting this name variable into the table properly so database is storing null instead of "N/A". Please show us or double check the data access object code. Good luck
Thanks #TiarĂª Balbi, in fact you do not need "required=true" because defaultValue="N/A" implicitly sets this variable as required=false anyways.

Categories

Resources