Monday, September 12, 2011

Replacment for Endpoint.publish when using Jersey

Sometimes when working with JAX-WS services it is nice to be able to test the service without having to deploy to a heavyweight server. You can do this using the Endpoint.publish method and just pass in an instance of your server class.

There is something similar in Jersey, but it isn't part of the JAX-RS specification. So you can publish a single resource as follows:

package client;


import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import com.sun.jersey.api.core.ClassNamesResourceConfig;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;


public class Test {
    
    public static void main(String[] args) throws IOException {

        HttpServer create = HttpServerFactory.create(
            "http://localhost:9001/",new ClassNamesResourceConfig(Hello.class));
        create.start();
    }
}

Update: 12th December 2013: The code for this has slightly changed in Jersey 2.0, the following will publish a resource using the HttpServer that comes with the JDK (you will need to include a dep on the jersey-container-jdk-http component):


import com.sun.net.httpserver.HttpServer;

import java.net.URI;

import org.glassfish.jersey.jdkhttp.JdkHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;


public class Test {
    public static void main(String[] args) {
        
        HttpServer d = JdkHttpServerFactory.createHttpServer(
            URI.create("http://localhost:9001"), 
            new ResourceConfig().register(new Hello()));  
   }

1 comment:

ROS Blog said...

I tried this with Netbeans and it worked.
But when tried it with eclipse it did not.
Any hint for this?