Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I serve a particular classpath resource at a given address using embedded jetty?

I'm looking to expose a clientacesspolicy.xml file from an embedded jetty server.

My current attempt looks like this:

ContextHandler capHandler = new ContextHandler();
capHandler.setContextPath("/clientaccesspolicy.xml");
capHandler.setBaseResource(Resource.newClassPathResource("clientaccesspolicy.xml"));
HandlerList handlers = new HandlerList();
handlers.addHandler(capHandler);
...
httpServer.setHandler(handlers);

But I get a 404 accessing http://localhost:9000/clientaccesspolicy.xml

How can I expose a classpath resource to a given URL programmatically in Jetty?

Thanks, Andy

like image 910
Andy Avatar asked Feb 02 '12 12:02

Andy


2 Answers

Actually, you can just register a class path as a class path resource (surprisingly).

ResourceHandler resHandler = new ResourceHandler();
resHandler.setBaseResource(Resource.newClassPathResource("/"));
server.setHandler(resHandler);

Then you can access whatever files are in your class path. So if you have a file.xml it will be served from localhost:9000/file.xml.

like image 167
Dariusz Starzyński Avatar answered Sep 21 '22 16:09

Dariusz Starzyński


Your code doesn't work because a ContextHandler doesn't actually server up content. A small adjustment will make it sort of work, but to do what you really want you'll need to write your own handler.

The "sort of works" version:

ContextHandler capHandler = new ContextHandler();
capHandler.setContextPath("/clientaccesspolicy.xml");
ResourceHandler resHandler = new ResourceHandler();
resHandler.setBaseResource(Resource.newClassPathResource("clientaccesspolicy.xml"));
capHandler.setHandler(resHandler);

But, that version treats /clientaccesspolicy.xml as a directory, so it redirects to /clientaccesspolicy.xml/ and then displays the contents of the XML file.

What it looks like you want is a version of the ResourceHandler that has a lookup of url => resource. Jetty doesn't ship with a handler that does that, but you should be able to create a subclass of ResourceHandler and then override getResource. In that case you won't need [or want] the ContextHandler, just check for calls to "/clientaccesspolicy.xml" and map it to the correct ClassPath Resource.

like image 37
Tim Avatar answered Sep 24 '22 16:09

Tim