Search code examples
osgiapache-karafosgi-bundlekarafblueprint-osgi

Karaf PaxExam getting java.lang.IllegalStateException: Invalid BundleContext


Hi i am loading some features and bundles in runtime using FeaturesService and BundleContext. All these things are loaded successfully. After that if i do an operation on bundlecontext object i am getting java.lang.IllegalStateException: Invalid BundleContext.

@Inject
FeaturesService service;
@Before
public void init() throws Exception{
    service.installFeature("hibernate");
    service.installFeature("hibernate-validator");
    service.installFeature("transaction");
    service.installFeature("jpa");
    service.installFeature("hibernate-envers");
    service.installFeature("hibernate-envers");
    bc.installBundle("wrap:mvn:com.oracle/ojdbc6/11.2.0").start();
    service.installFeature("DBHandler");
    bc.getBundle(); // Fails
}

After a lot of browsing i understood you need to refresh the bundles. How to do it programatically and get a refeshed bundleContext object


Solution

  • This code fixed my problem

    public  void refreshBundles() { 
    
            Bundle currentBundle = FrameworkUtil.getBundle(MyTest.class); 
            if (currentBundle == null) { 
                return; 
            } 
    
            BundleContext bundleContext = currentBundle.getBundleContext(); 
            if (bundleContext == null) { 
                return; 
            } 
    
            Bundle systemBundle = bundleContext.getBundle(0); 
            if (systemBundle == null) { 
                return; 
            } 
    
            FrameworkWiring frameworkWiring = systemBundle.adapt(FrameworkWiring.class); 
            frameworkWiring.refreshBundles(null); 
            bc = frameworkWiring.getBundle().getBundleContext();
        }