Endpoint Publish for REST Web Services

2020-06-23 08:34发布

I've published JAX-WS web services with Endpoint.publish during development. Is there any such utility class exists (in JAX-RS) for publishing REST web services in jersey? I referred couple of articles, and majority of them are based on publishing the web services in some containers like Jetty, Grizzly etc.

2条回答
Explosion°爆炸
2楼-- · 2020-06-23 09:04

Jersey-Grizzly has a very simple solution. From https://github.com/jesperfj/jax-rs-heroku:

package embedded.rest.server;

import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.sun.grizzly.http.SelectorThread;
import com.sun.jersey.api.container.grizzly.GrizzlyWebContainerFactory;

@Path("/hello")
public class Main {

    public static void main(String[] args) {        
        final String baseUri = "http://localhost:7080/";
        final Map<String, String> initParams = new HashMap<String, String>();

        // Register the package that contains your javax.ws.rs-annotated beans here
        initParams.put("com.sun.jersey.config.property.packages","embedded.rest.server");

        System.out.println("Starting grizzly...");
        try {
            SelectorThread threadSelector =
                    GrizzlyWebContainerFactory.create(baseUri, initParams);
            System.out.println(String.format("Jersey started with WADL "
                    + "available at %sapplication.wadl.", baseUri));
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String hello() {
        return "Well, this was easy!";
    }
}

If you're using Maven, you'll need the following three dependencies:

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-grizzly</artifactId>
    <version>1.15</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-bundle</artifactId>
    <version>1.15</version>
</dependency>
<dependency>
    <groupId>com.sun.grizzly</groupId>
    <artifactId>grizzly-servlet-webserver</artifactId>
    <version>1.9.18-i</version>
</dependency>

To test it, just open http://localhost:7080/hello in a browser.

查看更多
你好瞎i
3楼-- · 2020-06-23 09:05

I think you can use Provider interface to publishing a RESTful Web Service with JAX-WS.

The example class:

@WebServiceProvider
@BindingType(value=HTTPBinding.HTTP_BINDING)
public class AddNumbersImpl implements Provider {

    @Resource
    protected WebServiceContext wsContext;

    public Source invoke(Source source) {
        try {
            MessageContext mc = wsContext.getMessageContext();
            // check for a PATH_INFO request
            String path = (String)mc.get(MessageContext.PATH_INFO);
            if (path != null && path.contains("/num1") &&
                       path.contains("/num2")) {
                return createResultSource(path);
            }
            String query = (String)mc.get(MessageContext.QUERY_STRING);
            System.out.println("Query String = "+query);
            ServletRequest req = (ServletRequest)mc.get(MessageContext.SERVLET_REQUEST);
            int num1 = Integer.parseInt(req.getParameter("num1"));
            int num2 = Integer.parseInt(req.getParameter("num2"));
            return createResultSource(num1+num2);
        } catch(Exception e) {
            e.printStackTrace();
            throw new HTTPException(500);
        }
    }

    private Source createResultSource(String str) {
        StringTokenizer st = new StringTokenizer(str, "=&/");
        String token = st.nextToken();
        int number1 = Integer.parseInt(st.nextToken());
        st.nextToken();
        int number2 = Integer.parseInt(st.nextToken());
        int sum = number1+number2;
        return createResultSource(sum);
    }

    private Source createResultSource(int sum) {
        String body =
            "<ns:addNumbersResponse xmlns:ns="http://java.duke.org"><ns:return>"
            +sum
            +"</ns:return></ns:addNumbersResponse>";
        Source source = new StreamSource(
            new ByteArrayInputStream(body.getBytes()));
        return source;
    }   
}

To deploy our endpoint on a servlet container running with the JAX-WS RI we need to create a WAR file.

The adjusted web.xml:

<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee">
  <listener>
    <listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener
  </listener>
  <servlet>
    <servlet-name>restful-addnumbers</servlet-name>
    <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>restful-addnumbers</servlet-name>
    <url-pattern>/addnumbers/*</url-pattern>
  </servlet-mapping>
  <session-config>
    <session-timeout>60</session-timeout>
  </session-config>
</web-app>

and need to add sun-jaxws.xml deployment descriptor to the WAR file.

<endpoints
    xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"
    version="2.0">

    <endpoint
        name="restful-addnumbers"
        implementation="restful.server.AddNumbersImpl"
        wsdl="WEB-INF/wsdl/AddNumbers.wsdl"
        url-pattern="/addnumbers/*" />
</endpoints>

Or could be create simple HttpServer

import java.io.IOException;
import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import com.sun.net.httpserver.HttpServer;

public class YourREST {

    static final String BASE_URI = "http://localhost:9999/yourrest/";

    public static void main(String[] args) {
        try {
            HttpServer server = HttpServerFactory.create(BASE_URI);
            server.start();
            System.out.println("Press Enter to stop the server. ");
            System.in.read();
            server.stop(0);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
查看更多
登录 后发表回答