Попытка простой реализации REST на OSGi Equinox + Jetty - простое развертывание REST с использованием web.xml
Ниже приведены подробности моей реализации:
Файл ресурса:
@Path("jsonstatus")
public class JsonResource {
private static Logger logger = LoggerFactory.getLogger(JsonResource.class);
@GET
@Produces("application/json")
public String listConferences() {
logger.info("Returning the status");
return "{\"status\": \"success\"}";
}
}
Реализация приложения:
public class JerseyApplication extends Application {
private static Logger logger = LoggerFactory.getLogger(JerseyApplication.class.getName());
@Override
public Set<Class<?>> getClasses() {
logger.info("--Returning all the claess-");
Set<Class<?>> result = new HashSet<Class<?>>();
result.add(JsonResource.class);
result.add(StatusResource.class);
return result;
}
}
web.xml:
<servlet>
<servlet-name>SimpleREST</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>my.learnings.osgi.rest.jetty.activator.JerseyApplication</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SimpleREST</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
Добавлены все ядра OSGi, консоли и джеты: Когда я запускаю Equinox, я получаю следующую ошибку. При развертывании с использованием web.xml
активатор не отображается в комплекте.
Но если удалить активатор и файл web.xml, REST API работает, ошибок при запуске равноденствия нет.
Простой активатор:
@Override
public void start(BundleContext context) throws Exception {
logger.info("Starting the bundle");
ServletContextHandler ch = new ServletContextHandler();
ch.setContextPath("/");
ServletHolder holder = new ServletHolder(new ServletContainer());
holder.setInitParameter("javax.ws.rs.Application", JerseyApplication.class.getName());
ch.addServlet(holder, "/*");
context.registerService(ContextHandler.class.getName(), ch, null);
}
При поиске в интернете, я увидел, нужно настроить JNDI, это очень простой простой REST, который не требует базы данных. Так запутался, зачем нам нужен JNDI. В некоторой статье обсуждалась инициализация java.naming.factory.initial. Но те даны для jboss. Не уверен, как настроить начальный контекст для jetty. Все комбинации, которые я пробовал, находятся в коде github.
Если бы вы могли помочь настроить начальный контекст в OSGi-jetty, это действительно помогло бы. Я ищу развертывание с web.xml способ создания сервлета на OSGi с Jetty
Ниже хранилище содержит код, который я пробовал:
https://github.com/pkolanda/my-learning-osgi-simple-rest-with-jetty
чтобы запустить код, mvn clean install и запустите сценарий оболочки run.sh в папке target / my-learning-osgi-simple-rest-with-jetty-0.1.
А пока я заглядываю в этот пост
Войти:
11:14:33.951 [Start Level: Equinox Container: 6ee1939d-123f-4def-860f-dfc2e21bdfc4] WARN o.eclipse.jetty.webapp.WebAppContext - Failed startup of context o.e.j.w.WebAppContext@7c19344a{/my-learning-osgi-simple-rest-with-jetty-1.0-SNAPSHOT,file:///tmp/jetty-0.0.0.0-8081-my-learning-osgi-simple-rest-with-jetty-1.0-SNAPSHOT.jar-_my-learning-osgi-simple-rest-with-jetty-1.0-SNAPSHOT-any-9046322855444487913.dir/webapp/,UNAVAILABLE}{file:/home/prakash/mygit/my-learning-osgi-simple-rest-with-jetty/target/my-learning-osgi-simple-rest-with-jetty-0.1/plugins/my-learning-osgi-simple-rest-with-jetty-1.0-SNAPSHOT.jar}
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:350)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at org.eclipse.jetty.plus.webapp.EnvConfiguration.createEnvContext(EnvConfiguration.java:258)
at org.eclipse.jetty.plus.webapp.EnvConfiguration.preConfigure(EnvConfiguration.java:67)
at org.eclipse.jetty.webapp.WebAppContext.preConfigure(WebAppContext.java:506)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:544)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:46)
at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:192)
at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:505)
at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:151)
at org.eclipse.jetty.osgi.boot.BundleWebAppProvider.bundleAdded(BundleWebAppProvider.java:214)
at org.eclipse.jetty.osgi.boot.BundleWebAppProvider$WebAppTracker.addingBundle(BundleWebAppProvider.java:80)
at org.osgi.util.tracker.BundleTracker$Tracked.customizerAdding(BundleTracker.java:475)
at org.osgi.util.tracker.BundleTracker$Tracked.customizerAdding(BundleTracker.java:1)
at org.osgi.util.tracker.AbstractTracked.trackAdding(AbstractTracked.java:256)
at org.osgi.util.tracker.AbstractTracked.track(AbstractTracked.java:229)
at org.osgi.util.tracker.BundleTracker$Tracked.bundleChanged(BundleTracker.java:450)
at org.eclipse.osgi.internal.framework.BundleContextImpl.dispatchEvent(BundleContextImpl.java:911)
at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:233)
at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:151)
at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEventPrivileged(EquinoxEventPublisher.java:233)
at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEvent(EquinoxEventPublisher.java:140)
at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEvent(EquinoxEventPublisher.java:132)
at org.eclipse.osgi.internal.framework.EquinoxContainerAdaptor.publishModuleEvent(EquinoxContainerAdaptor.java:194)
at org.eclipse.osgi.container.Module.publishEvent(Module.java:483)
at org.eclipse.osgi.container.Module.start(Module.java:474)
at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1783)
at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1763)
at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1725)
at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1656)
at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1)
at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:233)
at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:343)
____________________________
Welcome to Apache Felix Gogo
g!