Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QueryParam binding with enum in jersey

Tags:

rest

jersey

I have a rest URL like this http://www.localhost.com/service/resource?status=ACTIVE,PASSIVE and I have a method like this

@GET public Resource resource(@QueryParam("status") Collection<STATUS> statusList){ } 

where STATUS is an enum?

public enum STATUS{     ACTIVE,PASSIVE,DISABLED } 

My question is there a way for the query param status to be automatically converted to a list of enum type STATUS in jersey or do I have to write my own provider for this?

like image 730
Salil Surendran Avatar asked Jul 17 '12 20:07

Salil Surendran


Video Answer


2 Answers

From the Javadoc, the @QueryParam annotated type must either:

  1. Be a primitive type
  2. Have a constructor that accepts a single String argument
  3. Have a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String))
  4. Be List<T>, Set<T> or SortedSet<T>, where T satisfies 2 or 3 above. The resulting collection is read-only.

For your case I would go with the second option by wrapping the enum in a simple class:

public class StatusList {   private List<STATUS> statusList;    public StatusList(String toParse) {     //code to split the parameter into a list of statuses    }    public List<STATUS> getStatusList() {     return this.statusList;   } } 

Then change your method to:

@GET public Resource resource(@QueryParam("status") StatusList statusList){ } 
like image 84
Eugenio Cuevas Avatar answered Sep 22 '22 23:09

Eugenio Cuevas


Add this method to your enum:

public static YourEnum fromString(final String s) {     return YourEnum.valueOf(s); } 
like image 45
Babken Vardanyan Avatar answered Sep 22 '22 23:09

Babken Vardanyan