users@jersey.java.net

Re: Downloading file using Jersey client API ?

From: James Weir <James.Weir_at_Sun.COM>
Date: Fri, 29 Feb 2008 11:06:51 +0100

Paul Sandoz wrote:
> James Weir wrote:
>> My question is how do I use the Client API to retrieve the contents
>> and store them locally on disk ?
>> At the moment I am battling to get it to work. Any ideas ? or
>> examples you have so I can see how to do this ?
>
> You can do this:
>
> ResourceProxy r = ... // note that i am going to rename this to
> // WebResource
> File f = r.get(File.class);
>
> but it will create the file in a temporary directory location (i am
> not sure if you can specify what that temporary location should be
> using a system property). Then you could move the file from the
> temporary location using renameTo.
>
>
> Alternatively you can do this:
>
> ResourceProxy r = ... // note that i am going to rename this to
> // WebResource
> InputStream in = r.get(InputStream.class);
> FileOutputStream out = new FileOutputStream(<location>);
> // Read bytes from in and write bytes to out.
>
> It sucks a bit because it would be nice to pass in an instance of
> File, but that is not the way the message body readers work. I think
> you could encapsulate the above functionality in a helper, as follows:
>
> FileCreator.create(<location>, r.get(InputStream.class));
>
>
>> Also, am I setting the MediaType correctly here ?, I am currently
>> using MimeTypeMap to get the mime type of the file
>
> What API is "MimeTypeMap" from ? I presume it tries to guess the media
> type from the file name and the contents (magic number).
>
It uses javax.activation.MimetypesFileTypeMap. The MimetypesFileMap
class is used to map a File to a Mime Type. Mime types supported are
defined in a ressource file inside the activation.jar. The built-in
mime-type list is very limited but a mechanism is available to add very
easily more Mime Types/extensions.

The MimetypesFileTypeMap looks in various places in the user's system
for MIME types file entries. When requests are made to search for MIME
types in the MimetypesFileTypeMap, it searches MIME types files in the
following order:

   1. Programmatically added entries to the MimetypesFileTypeMap instance.
   2. The file .mime.types in the user's home directory.
   3. The file <java.home>/lib/mime.types.
   4. The file or resources named META-INF/mime.types.
   5. The file or resource named META-INF/mimetypes.default (usually
      found only in the activation.jar file).


I am unsure it is doing something clever with the file's magic number.
I only used this to get started, there are better ways I would like to
know about it :)


> You can set the entity and the media type using ok:
>
> return Response.ok(in, mt).
> lastModified(lastModified).tag(et).build();
>
> Paul.
>