Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST PathParam with Multiple Types

Tags:

java

rest

jersey

I've got a REST service set up to access information stored in a database.

I'd like to be able to access based on either an item's id or name.

So lets say I've got a record

name | id | description
mine | 65 | "my thing"

I'd like to be able to access this item through either:

myurl.com/items/65
myurl.com/items/mine

I'm using Jersey (Java library). Is there a way I can define the PathParam to accept either an int or a String WITHOUT using object.typeOf()?

I'd like to avoid this:

@PATH("/items/{identifier}
@GET
public String getItem(@PathParam("identifier") Object identifier){
     if(identifier.typeOf().equals(String.typeOf()))....

}

Thanks

like image 824
Tyler DeWitt Avatar asked May 12 '11 18:05

Tyler DeWitt


1 Answers

If you're looking for a "clean" solution - I don't think there is one. But you could do this:

@PATH("/items/{identifier}")
public String getItem(@PathParam("identifier") String identifier){
   try {
       return getByID( Long.parseLong(identifier) );
   } catch (NumberFormatException ex) {
       return getByName( identifier );
   }
}

Also, this won't compile - there's no such method as typeOf():

if(identifier.typeOf().equals(String.typeOf()))

I think you meant:

if (identifier instanceof String) 

EDIT: And anyway, your original idea (setting the parameter type to Object, then checking for the exact instance type) won't work; the container has no way of knowing that the path element may be an integer, so it won't attempt to parse it as an integer, and it'll just give you a String every time.

like image 53
Mike Baranczak Avatar answered Oct 14 '22 18:10

Mike Baranczak