users@jersey.java.net

[Jersey] Serving static Content out of .jar File

From: Matthias Treydte <waldheinz_at_gmail.com>
Date: Tue, 6 Mar 2012 10:50:57 +0100

Hello,

I'm trying to serve some static resources straight from the .jar file.
To get my hands on the bytes of these resources I'm using the
Class.getResourceAsStream(..) method. This works fine when starting
the project from the IDE (NetBeans), but fails when using the final
.jar. Jersey complains about not having a message body writer at hand
for my response:

> com.sun.jersey.api.MessageException: A message body writer for Java class sun.net.www.protocol.jar.JarURLConnection$JarURLInputStream,
> and Java type class sun.net.www.protocol.jar.JarURLConnection$JarURLInputStream, and MIME media type application/octet-stream was not found

Using the correct (or more specific) MIME type of "application/json"
or the like makes no difference. What makes a difference is when the
project is run before being assembled into a .jar file. In this case
we're getting a plain "java.io.BufferedInputStream" instance, which
Jersey serves happily. What puzzles me most is that I've already
successfully used this technique in an earlier project. Maybe there's
a problem with my Java version (1.7.0_03, x86, on Windows 7 x86_64)?
My resource implementation follows:

@Path("static")
public final class StaticResources {

    public final static String PATH =
            "/class/path/to/files/"; //NOI18N

    private final MimetypesFileTypeMap mimeTypes;

    public StaticResources() {
        this.mimeTypes = new MimetypesFileTypeMap(
                getClass().getResourceAsStream("mimeTypes")); //NOI18N
    }

    @GET
    @Path("{fileName:.*}")
    public Response getStatic(@PathParam("fileName") String file) {
        final InputStream result = getClass().getResourceAsStream(PATH + file);
        if (result != null) {
            final String mt = this.mimeTypes.getContentType(file);
            return Response.ok(result, mt).build();
        } else {
            throw new WebApplicationException(Response.Status.NOT_FOUND);
        }
    }
}


Kind regards,
-Matthias

-- 
For a successful technology, reality must take precedence over public
relations, for nature cannot be fooled. (R.P. Feynman)