Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to configure JAX-RS method with variable number of URI parameters?

is it possible to configure GET method to read variable number of URI parameters and interpret them either as variable argument (array) or collection? I know query parameters can be read as list/set but I can't go for them in my case.

E.g.:

@GET
@Produces("text/xml")
@Path("list/{taskId}")
public String getTaskCheckLists(@PathParam("taskId") int... taskId) {
    return Arrays.toString(taskId);
}

Thanks in advance

like image 324
zeratul021 Avatar asked Sep 02 '10 16:09

zeratul021


2 Answers

If I understand your question correctly, the @Path annotation can take a regular expression to specify a list of path components. For example, something like:

@GET
@Path("/list/{taskid:.+}")
public String getTaskCheckLists(@PathParam("taskid") List<PathSegment> taskIdList) {
    ......
}

There's a more extensive example here.

like image 107
Dave Ray Avatar answered Sep 22 '22 06:09

Dave Ray


I am not submitting this as an answer as it is merely an edge case on the currently accepted answer which is what I've also used. In my case (Jersey 1.19) /list/{taskid:.+} would not work for the edge case of zero variable parameters. Changing the RegEx to /list/{taskid:.*} took care of that. See also this article (which seems to be applicable).

Moreover, upon changing the regexp to cardinality indicator to * (instead of +) I also had to deal programmatically with the case of empty strings as I would translate the List<PathSegment> into a List<String> (to pass it into my DB-access code).

The reason I am translating from PathSegment to String is that I didn't want a class from the javax.ws.rs.core package to pollute my Data Access Layer code.

Here's a complete example:

@Path("/listDirs/{dirs:.*}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response listDirs(@PathParam("dirs") List<PathSegment> pathSegments) {
    List<String> dirs = new ArrayList<>();
    for (PathSegment pathSegment: pathSegments) {
        String path = pathSegment.getPath();
        if ((path!=null) && (!path.trim().equals("")))
            dirs.add(pathSegment.getPath());
    }
    List<String> valueFromDB = db.doSomeQuery(dirs);
    // construct JSON response object ...
}
like image 31
Marcus Junius Brutus Avatar answered Sep 18 '22 06:09

Marcus Junius Brutus