嵌入式码头与泽西岛或resteasy

时间:2011-09-14 19:01:15

标签: jetty jersey resteasy

我希望使用嵌入式码头和JAX-RS(无论是resteasy还是jersey)制作RESTful服务。 我正在尝试使用maven / eclipse设置创建。 如果我尝试关注http://wikis.sun.com/pages/viewpage.action?pageId=21725365链接,则无法解决ServletHolder sh = new ServletHolder(ServletContainer.class);

中的错误
public class Main {

    @Path("/")
    public static class TestResource {

        @GET
        public String get() {
            return "GET";
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {
        ServletHolder sh = new ServletHolder(ServletContainer.class);

        /*
         * For 0.8 and later the "com.sun.ws.rest" namespace has been renamed to
         * "com.sun.jersey". For 0.7 or early use the commented out code instead
         */
        // sh.setInitParameter("com.sun.ws.rest.config.property.resourceConfigClass",
        // "com.sun.ws.rest.api.core.PackagesResourceConfig");
        // sh.setInitParameter("com.sun.ws.rest.config.property.packages",
        // "jetty");
        sh.setInitParameter("com.sun.jersey.config.property.resourceConfigClass",
            "com.sun.jersey.api.core.PackagesResourceConfig");
        sh.setInitParameter("com.sun.jersey.config.property.packages",
            "edu.mit.senseable.livesingapore.platform.restws");
        // sh.setInitParameter("com.sun.jersey.config.property.packages",
        // "jetty");
        Server server = new Server(9999);

        ServletContextHandler context = new ServletContextHandler(server, "/",
            ServletContextHandler.SESSIONS);
        context.addServlet(sh, "/*");
        server.start();
        server.join();
        // Client c = Client.create();
        // WebResource r = c.resource("http://localhost:9999/");
        // System.out.println(r.get(String.class));
        //
        // server.stop();
    }
}

即使这不起作用。 任何人都可以建议我/教程/示例吗?

4 个答案:

答案 0 :(得分:18)

呵呵,链接页面是古老的 - 3年前的最后更新。

你真的需要码头吗?泽西岛与Grizzly(参见http://grizzly.java.net)的整合经过了充分的测试,它也充当了Glassfish传输层,可以像你的例子一样使用它。

请参阅Jersey工作区的helloworld示例,com.sun.jersey.samples.helloworld.Main类启动Grizzly并“部署”helloworld app:http://repo1.maven.org/maven2/com/sun/jersey/samples/helloworld/1.9.1/helloworld-1.9.1-project.zip

如果你真的需要基于码头的样品,我想我应该能够提供它(随时与我联系)。

编辑:

好吧,如果你真的想要码头,你可以拥有它:)看起来很简单。我按照http://docs.codehaus.org/display/JETTY/Embedding+Jetty的说明进行了启动helloworld示例:

public static void main(String[] args) throws Exception {
    Server server = new Server(8080);
    Context root = new Context(server,"/",Context.SESSIONS);
    root.addServlet(new ServletHolder(new ServletContainer(new PackagesResourceConfig("com.sun.jersey.samples.helloworld"))), "/");
    server.start();
}

http://localhost:8080/helloworld可以访问。我使用了Jetty 6.1.16。希望它有所帮助!

您可以在用户指南中找到有关在servlet环境中配置Jersey的更多信息,请参阅http://jersey.java.net/nonav/documentation/latest/

编辑:

依赖..但这有点难以指定,最近在球衣上发生了变化..所以..

前1.10:

<dependency>
    <groupId>org.mortbay.jetty</groupId>
    <artifactId>jetty</artifactId>
    <version>6.1.16</version>
</dependency>
<dependency>
     <groupId>com.sun.jersey</groupId>
     <artifactId>jersey-server</artifactId>
     <version>${jersey.version}</version>
</dependency>

后1.10:

<dependency>
    <groupId>org.mortbay.jetty</groupId>
    <artifactId>jetty</artifactId>
    <version>6.1.16</version>
</dependency>
<dependency>
     <groupId>com.sun.jersey</groupId>
     <artifactId>jersey-servlet</artifactId>
     <version>${jersey.version}</version>
</dependency>

你需要这个码头的maven repo:

<repositories>
    <repository>
        <id>codehaus-release-repo</id>
        <name>Codehaus Release Repo</name>
        <url>http://repository.codehaus.org</url>
    </repository>
</repositories>

答案 1 :(得分:11)

这是一个github仓库,其中包含基于Maven的HelloWorld示例,为主分支上的Grizzly和“jetty”分支上的Jetty配置:

https://github.com/jesperfj/jax-rs-heroku

尽管有回购品名称,但它不是Heroku特有的。通过运行Procfile中指定的命令启动服务器,例如

$ java -cp "target/dependency/*":target/classes Main

答案 2 :(得分:4)

没有web.xml的具有reaseasy的嵌入式jetty

java代码:

    final QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMinThreads(2); // 10
    threadPool.setMaxThreads(8); // 200
    threadPool.setDetailedDump(false);
    threadPool.setName(SERVER_THREAD_POOL);
    threadPool.setDaemon(true);

    final SelectChannelConnector connector = new SelectChannelConnector();
    connector.setHost(HOST);
    connector.setAcceptors(2);
    connector.setPort(PROXY_SEVLET_PORT);
    connector.setMaxIdleTime(MAX_IDLE_TIME);
    connector.setStatsOn(false);
    connector.setLowResourcesConnections(LOW_RESOURCES_CONNECTIONS);
    connector.setLowResourcesMaxIdleTime(LOW_RESOURCES_MAX_IDLE_TIME);
    connector.setName(HTTP_CONNECTOR_NAME);            

    /* Setup ServletContextHandler */
    final ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
    contextHandler.setContextPath("/");
    contextHandler.addEventListener(new ProxyContextListener());

    contextHandler.setInitParameter("resteasy.servlet.mapping.prefix","/services");

    final ServletHolder restEasyServletHolder = new ServletHolder(new HttpServletDispatcher());
    restEasyServletHolder.setInitOrder(1);

/* Scan package for web services*/
restEasyServletHolder.setInitParameter("javax.ws.rs.Application","com.viacom.pl.cprox.MessageApplication");

    contextHandler.addServlet(restEasyServletHolder, "/services/*");

    final HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] { contextHandler });

    final Server server = new Server();
    server.setThreadPool(threadPool);
    server.setConnectors(new Connector[] { connector });
    server.setHandler(handlers);
    server.setStopAtShutdown(true);
    server.setSendServerVersion(true);
    server.setSendDateHeader(true);
    server.setGracefulShutdown(1000);
    server.setDumpAfterStart(false);
    server.setDumpBeforeStop(false);

    server.start();
    server.join();

Web服务检测器:

package com.viacom.pl.cprox;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.core.Application;

import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.viacom.pl.cprox.services.impl.AbstractWebServiceMethod;

public class MessageApplication extends Application {

    private static final Logger LOGGER = LoggerFactory.getLogger(MessageApplication.class);

    private Set<Object> singletons = new HashSet<Object>();

    @SuppressWarnings("rawtypes")
    public MessageApplication() {

        /* Setup RestEasy */
        Reflections reflections = new Reflections("com.viacom.pl.cprox.services.impl");

        /*All my web services methods wrapper class extends AbstractWebServiceMethod, so it is easy to get sub set of expected result.*/
        Set<Class<? extends AbstractWebServiceMethod>> set = reflections
                .getSubTypesOf(AbstractWebServiceMethod.class);
        for (Class<? extends AbstractWebServiceMethod> clazz : set) {
            try {
                singletons.add(clazz.newInstance());
            } catch (InstantiationException e) {
                LOGGER.error(e.getMessage(), e);
            } catch (IllegalAccessException e) {
                LOGGER.error(e.getMessage(), e);
            }
        }
    }

    @Override
    public Set<Object> getSingletons() {
        return singletons;
    }
}

的pom.xml

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jaxb-provider</artifactId>
    <version>2.2.0.GA</version>
</dependency>
<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.9-RC1</version>
</dependency>

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jaxrs</artifactId>
    <version>3.0.3.Final</version>
</dependency>

答案 3 :(得分:2)

我能够在半小时内启动并运行这个maven原型。

请参阅https://github.com/cb372/jersey-jetty-guice-archetype

步骤:

git clone https://github.com/cb372/jersey-jetty-guice-archetype.git
mvn install
mvn archetype:generate -DarchetypeGroupId=org.birchall \
    -DarchetypeArtifactId=jersey-jetty-guice-archetype -DarchetypeVersion=1.0
mvn compile exec:java -Dexec.mainClass=com.yourpackage.Main

非常感谢cb372创建这个原型。它让它变得如此简单。