I tried to override/implement all the attribute in JSR311 but the Jersey binding seems case sensitive:
- 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))
- Be List, Set or SortedSet, where T satisfies 2 or 3 above. The resulting collection is read-only.
How can I make Jersey binding for enum case insensitive?
EDIT:
Here's the code:
The enum:
public enum Color {
GREEN,
BLUE;
public Color fromString(String param) {
String toUpper = param.toUpperCase();
try {
return valueOf(toUpper);
} catch (Exception e) {
return null;
}
}
}
Bean Param:
public class FooQueryParam {
@QueryParam(value = "color")
private Color color;
public Color getColor() {
return color;
}
public void setStatus(Color Color) {
this.color = color;
}
}
The resource:
public Response get(@BeanParam FooQueryParam fooQueryParam) {
//...
}
If you're doing it right it shouldn't be a problem. For example in case 3, using a
fromString
Every enum already has a static
valueOf
method which tries to match the enum value exactly, so we override this behavior by defining thefromString
. We first calltoUpperCase()
then callvalueOf
as it's looking for upper case. If anything fails, like a wrong enum value, we send a 400. You can send something else or stick with the normal 404. Up to you.Here is a complete test case.
Use this dependency
UPDATE
Test using
@BeanParam
The only thing that fails is the error case where I am sending a bad color. It seems with
@BeanParam
the behavior is different. Instead of the expected 400, there is a 500. The other case sentiviity issues are fine