RESTful web service based Java Jersey: how best to handle the path parameter for a file entity

I am writing a Java based REST web service using jersey. The object for which I am writing a web service is a media file. The client requesting the media file must send the path and file name as a path parameter. The valid data transfer path can be up to five directories deep. Now the challenge is to write one method to handle all the possibilities of the depth of the path. Using the path parameter is the only permitted choice in terms of a business scenario. The following is a contract that processes a media request:

public Response getMediaFile(@PathParam("path") String path, @PathParam("filename") String filename); 

The problem with this method is that if the request is like / media / filedir 1 / filedir2 / filename, then the file name will not be selected correctly.

The solution I implemented is that I overloaded this method to handle all directory depths, but I'm not sure if this is the best solution:

 public Response getMediaFile(@PathParam("path1") String path1, @PathParam("path2") String path2, @PathParam("filename") String filename); public Response getMediaFile(@PathParam("path1") String path1, @PathParam("path2") String path2, @PathParam("path3") String path3, @PathParam("filename") String filename); 

And so on.

+4
source share
2 answers

You should be able to use the regular expression in the @PathParam annotation to handle all path filtering logic. For example, this will give you a path to a file that contains no more than 5 directories:

 @Path("{path:(?:[^/]+/){0,4}[^/]+}") 

You will then enter this value into the method as expected:

 @Path("{path:(?:[^/]+/){0,4}[^/]+}") /* Other attributes too... */ public Response getMediaFile(@PathParam("path") String path) { File file=new File(MEDIA_HOME_DIR, path); if(file.exists()) { // Process file } else { // No such file } } 

The regular expression will handle the "five directories" constraint, and if the number changes from five in the future, it will be easy to fix. You can also easily filter file names if you only need to map .jpg files (for example).

With that in mind, you just need to serve the media. :)

+2
source

The JAX-RS specification tells us about URI patterns:

Pattern parameters can optionally specify the regular expression used to match their values. The default value matches any text and ends at the end of the path segment.

If you want to match "end of path segment", use the correct regular expression. This works for you:

 @Path("{path:.*}/{filename}") 
+1
source

Source: https://habr.com/ru/post/1483922/


All Articles