2014-04-01 68 views
2

我有興趣在我的WAR中添加OSGI容器,但是我找不到關於如何執行此操作的教程或文檔。我發現了一些根本沒用的東西。 我對Felix實現和Atlassian實現感興趣。在戰爭中嵌入OSGI

我願意這樣做,讓我的戰爭接受插件,我可以動態擴展我的Web應用程序,並將其部署到任何Web服務器。

指向文檔或任何東西的任何鏈接?任何幫助表示讚賞。

回答

5

將OSGi Framework啓動程序添加到Web應用程序並不是什麼大不了的事情。

您需要添加一個監聽器啓動框架啓動在web.xml

<listener> 
    <listener-class>at.badgateway.StartupListener</listener-class> 
</listener> 

的startuplistener可能看起來像這樣

public class StartupListener implements ServletContextListener { 

//vars 

    @Override 
    public void contextInitialized(ServletContextEvent event) { 
     // set props 
    Map<String, String> config = new HashMap<String, String>(); 
    config.put(Constants.FRAMEWORK_STORAGE, "path to cache"); 
    config.put(Constants.FRAMEWORK_STORAGE_CLEAN, "true"); 

     try { 
        // get framework and start it 
      FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator().next(); 
      framework = frameworkFactory.newFramework(config); 
      framework.start(); 

        // start existing bundles 
      bundleContext = framework.getBundleContext(); 
      starter = new MyBundleStarter(servletContext, bundleContext); 
      starter.launch(); 

     } catch (Exception ex) 
    } 

    @Override 
    public void contextDestroyed(ServletContextEvent arg0) { 
     // stop framework 
    } 
} 

照顧MyBundlestarter類的上面的引用,它是激活你的戰爭中包含的所有包的類。 (例如/ WEB-INF/OSGi的捆綁)

import org.osgi.framework.Bundle; 
import org.osgi.framework.BundleContext; 
public class MyBundleStarter{ 

    private BundleContext bundleContext = null; 

    public void launch() throws Exception { 

     ArrayList<Bundle> availableBundles= new ArrayList<Bundle>(); 
     //get and open available bundles 
     for (URL url : getBundlesInWar()) { 
      Bundle bundle = bundleContext.installBundle(url.getFile(), url.openStream()); 
      availableBundles.add(bundle); 
     } 

     //start the bundles 
     for (Bundle bundle : availableBundles) { 
      try{ 
      bundle.start(); 
      }catch() 
     } 

    private List<URL> getBundlesInWar() throws Exception { 
     // returns a list of URLs located at destination 
    } 
} 

最後但並非最不重要的,你必須OSGi框架添加到項目中。

<dependency> 
    <groupId>org.apache.felix</groupId> 
    <artifactId>org.apache.felix.framework</artifactId> 
    </dependency> 

<dependency> 
     <groupId>org.eclipse.osgi</groupId> 
     <artifactId>org.eclipse.osgi</artifactId> 
    </dependency> 
+0

Martin ..你能給我一些文檔嗎?一些鏈接到OSGI的實施,可以讓你做到這一點? etc – Alex

+0

此代碼適用於equinox和felix。只需將org.eclipse.osgi或org.apache.felix.framework添加到您的pom中,它就會被檢測到,因爲它們包含一個實現FrameworkFactory接口的類。 –

+0

太好了。當我回家時我會嘗試。謝謝 – Alex

0

如果您使用的是WebLogic託管你的應用程序,你可以嵌入OSGi包在你的戰爭,並讓他們部署到系統中定義的OSGi服務器。這很好,因爲來自OSGi日誌服務的日誌消息可以自動在WebLogic日誌中看到。當您取消部署應用程序時,您的軟件包也將從目標OSGi服務器中刪除。

欲瞭解更多信息,請參閱Configuration OSGi containersdeveloping OSGi apps或此blog post

1

我可以看到這是一箇舊帖子,但也許對某人有用: 這個writing在這個主題中包含了很多有用的東西,至少對我來說這是一個非常棒的幫助。 值得看看該頁面上的其他帖子。

+0

是的。它有助於。我會分析它回家。謝謝 – Alex