@Test
  public void testStopedBundleContext() throws Exception {
    Bundle bundle = installBundle(getBundleArchiveA());
    try {
      bundle.start();
      BundleContext bundleContext = bundle.getBundleContext();
      assertNotNull(bundleContext);

      // The context should be illegal to use.
      bundle.stop();
      try {
        bundleContext.getProperty(getClass().getName());
        fail("Should not be here!");
      } catch (IllegalStateException t) {
        // expected
      }

      // The context should not become reusable after we restart the bundle
      bundle.start();
      try {
        bundleContext.getProperty(getClass().getName());
        fail("Should not be here!");
      } catch (IllegalStateException t) {
        // expected
      }
    } finally {
      bundle.uninstall();
    }
  }
  @Test
  public void testClientBlueprintContainerOnlyStartsWhenServiceStarted() throws Exception {
    // Stop everything before we start
    Bundle bcli = getInstalledBundle("org.apache.aries.samples.blueprint.helloworld.client");
    assertNotNull(bcli);
    bcli.stop();

    Bundle bser = getInstalledBundle("org.apache.aries.samples.blueprint.helloworld.server");
    assertNotNull(bser);
    bser.stop();

    // Wait for everything to shut down
    Thread.sleep(1000);

    // When everything is stopped, there should be no blueprint container for either the client or
    // the server

    assertClientBlueprintContainerNull();
    assertServerBlueprintContainerNull();

    // If we start the client first, it shouldn't have a blueprint container
    bcli.start();

    // Wait for everything to get started
    Thread.sleep(1000);
    assertClientBlueprintContainerNull();

    // Then when we start the server both it and the client should have blueprint containers
    bser.start();
    // Wait for everything to get started
    Thread.sleep(1000);
    assertClientBlueprintContainerNotNull();
    assertServerBlueprintContainerNotNull();
  }
  public static void checkSanity(int expectMinor) throws BundleException {
    Bundle bundle = CompilerUtils.getActiveGroovyBundle();
    assertNotNull("No active Groovy bundle found", bundle);
    assertEquals(
        "Wrong version for groovy bundle: " + bundle.getVersion(),
        expectMinor,
        bundle.getVersion().getMinor());
    if (bundle.getState() != Bundle.ACTIVE) {
      bundle.start();
    }

    bundle = Platform.getBundle("org.eclipse.jdt.core");
    final String qualifier = bundle.getVersion().getQualifier();
    // TODO: the conditions below should be activated... or test will break on non E_3_6 builds...
    // for now leave like this
    // to be 100% sure sanity checks are really executed!
    //		if (StsTestUtil.isOnBuildSite() && StsTestUtil.ECLIPSE_3_6_OR_LATER) {
    assertTrue(
        "JDT patch not properly installed (org.eclipse.jdt.core version = "
            + bundle.getVersion()
            + ")",
        qualifier.contains("xx") || qualifier.equals("qualifier"));
    //		}
    if (bundle.getState() != Bundle.ACTIVE) {
      bundle.start();
    }
    assertTrue(
        "Groovy language support is not active",
        LanguageSupportFactory.getEventHandler()
            .getClass()
            .getName()
            .endsWith("GroovyEventHandler"));
  }
  @Test
  public void testOwnerCannotSeeServiceClass() throws Exception {
    final Bundle bundleA = installBundle(getBundleArchiveA());
    final Bundle bundleB = installBundle(getBundleArchiveB());
    try {
      bundleA.start();
      bundleB.start();

      BundleContext contextA = bundleA.getBundleContext();
      BundleContext contextB = bundleB.getBundleContext();

      final CountDownLatch latch = new CountDownLatch(1);
      ServiceListener listener =
          new ServiceListener() {
            public void serviceChanged(ServiceEvent event) {
              latch.countDown();
            }
          };
      contextB.addServiceListener(listener);

      Object service = bundleB.loadClass(B.class.getName()).newInstance();
      ServiceRegistration reg = contextA.registerService(B.class.getName(), service, null);

      ServiceReference ref = reg.getReference();
      assertTrue(ref.isAssignableTo(bundleA, B.class.getName()));
      assertTrue(ref.isAssignableTo(bundleB, B.class.getName()));

      if (latch.await(5, TimeUnit.SECONDS) == false) throw new TimeoutException();

    } finally {
      bundleA.uninstall();
      bundleB.uninstall();
    }
  }
Esempio n. 5
0
  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
   */
  public void start(BundleContext context) throws Exception {
    super.start(context);
    plugin = this;
    // create a new RobotDeviceListener
    Bundle[] bundles = context.getBundles();
    // ("org.eclipse.equinox.event");
    Bundle r_osgi = null;
    for (int i = 0; i < bundles.length; i++) {
      Bundle bundle = bundles[i];
      System.out.println("Bundle.getSymbolicName(): " + bundle.getSymbolicName());
      if ("org.eclipse.equinox.event".equals(bundle.getSymbolicName())) {
        bundle.start();
      } else if ("org.eclipse.equinox.log".equals(bundle.getSymbolicName())) {
        bundle.start();
      } else if ("ch.ethz.iks.r_osgi.remote".equals(bundle.getSymbolicName())) {
        r_osgi = bundle;
      } else if ("org.leibnix.device.clocktimer.interfaces".equals(bundle.getSymbolicName())) {
        bundle.start();
      }
    }
    if (r_osgi != null) {
      r_osgi.start();
    }
    // ServiceReference ref = context
    // .getServiceReference(RemoteOSGiService.class.getName());
    // if (ref != null) {
    // remote = (RemoteOSGiService) context.getService(ref);
    //
    // DeviceListener listener = new DeviceListener(context, remote);
    //
    // // register for discovery
    // context.registerService(DiscoveryListener.class.getName(),
    // listener, null);
    // }

    //		ServiceReference ref = context
    //				.getServiceReference(RemoteOSGiService.class.getName());
    //		if (ref != null) {
    //			RemoteOSGiService rs = (RemoteOSGiService) context.getService(ref);
    //			ServiceURL[] serviceURLs = rs.connect(InetAddress.getLocalHost(),
    //					9278, null); // FIXME use remote host from preferences
    //
    //			for (ServiceURL service : serviceURLs) {
    //				ServiceType serviceType = service.getServiceType();
    //
    //				System.out.println(serviceType.getConcreteTypeName());
    //				if (serviceType.getConcreteTypeName().endsWith("ClockTimer")) {
    //					rs.fetchService(service);
    //					Object remoteService = rs.getFetchedService(service);
    //					// if (remoteService instanceof IClockTimer) {
    //						IClockTimer clock = (IClockTimer) remoteService;
    //						clock.addTimer("1");
    //					// }
    //					break;
    //				}
    //			}
    //		}

  }
Esempio n. 6
0
  @Test
  public void testUpdateImportedPackagesRemoved() throws Exception {
    Archive<?> assemblyx =
        assembleArchive("bundlex", "/bundles/update/update-bundlex", ObjectX.class);
    Archive<?> assembly1 =
        assembleArchive("bundle1", "/bundles/update/update-bundle1", ObjectA.class);
    Archive<?> assembly2 =
        assembleArchive("bundle2", "/bundles/update/update-bundle101", ObjectB.class);

    Bundle bundleA = installBundle(assembly1);
    Bundle bundleX = installBundle(assemblyx);
    try {
      BundleContext systemContext = getFramework().getBundleContext();
      int beforeCount = systemContext.getBundles().length;

      bundleA.start();
      bundleX.start();

      Class<?> cls = bundleX.loadClass(ObjectX.class.getName());
      cls.newInstance();

      assertBundleState(Bundle.ACTIVE, bundleA.getState());
      assertBundleState(Bundle.ACTIVE, bundleX.getState());
      assertEquals(Version.parseVersion("1.0.0"), bundleA.getVersion());
      assertEquals("update-bundle1", bundleA.getSymbolicName());
      assertLoadClass(bundleA, ObjectA.class.getName());
      assertLoadClassFail(bundleA, ObjectB.class.getName());
      assertLoadClass(bundleX, ObjectA.class.getName());

      bundleA.update(toInputStream(assembly2));
      assertBundleState(Bundle.ACTIVE, bundleA.getState());
      assertBundleState(Bundle.ACTIVE, bundleX.getState());
      assertEquals(Version.parseVersion("1.0.1"), bundleA.getVersion());
      // Assembly X depends on a package in the bundle, this should still be available
      assertLoadClass(bundleX, ObjectA.class.getName());

      getSystemContext().addFrameworkListener(this);
      getPackageAdmin().refreshPackages(new Bundle[] {bundleA});
      assertFrameworkEvent(FrameworkEvent.ERROR, bundleX, BundleException.class);
      assertFrameworkEvent(
          FrameworkEvent.PACKAGES_REFRESHED, getSystemContext().getBundle(0), null);

      assertBundleState(Bundle.ACTIVE, bundleA.getState());
      // Bundle X is installed because it cannot be resolved any more
      assertBundleState(Bundle.INSTALLED, bundleX.getState());
      assertEquals(Version.parseVersion("1.0.1"), bundleA.getVersion());
      // Nobody depends on the packages, so we can update them straight away
      assertLoadClass(bundleA, ObjectB.class.getName());
      assertLoadClassFail(bundleA, ObjectA.class.getName());

      int afterCount = systemContext.getBundles().length;
      assertEquals("Bundle count", beforeCount, afterCount);
    } finally {
      getSystemContext().removeFrameworkListener(this);
      bundleX.uninstall();
      bundleA.uninstall();
    }
  }
  @Test
  public void testFragmentExportsPackage() throws Exception {
    Bundle hostA = installBundle(getHostA());
    assertBundleState(Bundle.INSTALLED, hostA.getState());

    Bundle hostC = installBundle(getHostC());
    assertBundleState(Bundle.INSTALLED, hostA.getState());

    hostA.start();
    assertBundleState(Bundle.ACTIVE, hostA.getState());

    try {
      // HostA does not export the package needed by HostC
      hostC.start();
      fail("Unresolved constraint expected");
    } catch (BundleException ex) {
      assertBundleState(Bundle.INSTALLED, hostC.getState());
    }

    Bundle fragA = installBundle(getFragmentA());
    assertBundleState(Bundle.INSTALLED, fragA.getState());

    try {
      // FragA does not attach to the already resolved HostA
      // HostA does not export the package needed by HostC
      hostC.start();
      fail("Unresolved constraint expected");
    } catch (BundleException ex) {
      assertBundleState(Bundle.INSTALLED, hostC.getState());
    }

    // Refreshing HostA causes the FragA to get attached
    refreshPackages(new Bundle[] {hostA});

    // Load class provided by the fragment
    assertLoadClass(hostA, FragBeanA.class.getName());
    assertLoadClass(hostC, FragBeanA.class.getName(), hostA);

    // HostC should now resolve and start
    hostC.start();
    assertBundleState(Bundle.ACTIVE, hostC.getState());

    hostA.uninstall();
    assertBundleState(Bundle.UNINSTALLED, hostA.getState());

    hostC.uninstall();
    assertBundleState(Bundle.UNINSTALLED, hostC.getState());

    fragA.uninstall();
    assertBundleState(Bundle.UNINSTALLED, fragA.getState());
  }
 @Test
 public void testDependentBundleLifecyclePermutation1Test() throws Exception {
   Bundle paxWebBundle = getBundleForSymbolicName("org.ops4j.pax.web.pax-web-jetty-bundle");
   Bundle restServiceProviderBundle =
       getBundleForSymbolicName("org.developers.blog.osgi.webservice.jaxrs-provider");
   paxWebBundle.stop();
   restServiceProviderBundle.stop();
   assertFalse(checkRestServiceRunning(false));
   paxWebBundle.start();
   assertTrue(waitForBundle(paxWebBundle));
   restServiceProviderBundle.start();
   assertTrue(waitForBundle(restServiceProviderBundle));
   assertTrue(checkRestServiceRunning(true));
 }
	public void testBasic() throws BundleException, InvalidSyntaxException, InterruptedException {
		// get the system region
		Region systemRegion = digraph.getRegion(0);
		// create a disconnected test region
		Region testRegion = digraph.createRegion(getName());
		List<Bundle> bundles = new ArrayList<Bundle>();
		// Install all test bundles
		Bundle pp1, cp2, sc1;
		bundles.add(pp1 = bundleInstaller.installBundle(PP1, testRegion));
		// should be able to start pp1 because it depends on nothing
		pp1.start();
		// do a sanity check that we have no services available in the isolated region
		assertNull("Found some services.", pp1.getBundleContext().getAllServiceReferences(null, null));
		assertEquals("Found extra bundles in region", 1, pp1.getBundleContext().getBundles().length);
		pp1.stop();

		bundles.add(bundleInstaller.installBundle(SP1, testRegion));
		bundles.add(bundleInstaller.installBundle(CP1, testRegion));
		bundles.add(bundleInstaller.installBundle(PP2, testRegion));
		bundles.add(bundleInstaller.installBundle(SP2, testRegion));
		bundles.add(cp2 = bundleInstaller.installBundle(CP2, testRegion));
		bundles.add(bundleInstaller.installBundle(PC1, testRegion));
		bundles.add(bundleInstaller.installBundle(BC1, testRegion));
		bundles.add(sc1 = bundleInstaller.installBundle(SC1, testRegion));
		bundles.add(bundleInstaller.installBundle(CC1, testRegion));

		// Import the system bundle from the systemRegion
		digraph.connect(testRegion, digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_BUNDLE_NAMESPACE, "(id=0)").build(), systemRegion);
		// must import Boolean services into systemRegion to test
		digraph.connect(systemRegion, digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_SERVICE_NAMESPACE, "(objectClass=java.lang.Boolean)").build(), testRegion);

		bundleInstaller.resolveBundles(bundles.toArray(new Bundle[bundles.size()]));
		for (Bundle bundle : bundles) {
			assertEquals("Bundle did not resolve: " + bundle.getSymbolicName(), Bundle.RESOLVED, bundle.getState());
			bundle.start();
		}
		BundleContext context = getContext();
		ServiceTracker<Boolean, Boolean> cp2Tracker = new ServiceTracker<Boolean, Boolean>(context, context.createFilter("(&(objectClass=java.lang.Boolean)(bundle.id=" + cp2.getBundleId() + "))"), null);
		ServiceTracker<Boolean, Boolean> sc1Tracker = new ServiceTracker<Boolean, Boolean>(context, context.createFilter("(&(objectClass=java.lang.Boolean)(bundle.id=" + sc1.getBundleId() + "))"), null);

		cp2Tracker.open();
		sc1Tracker.open();

		assertNotNull("The cp2 bundle never found the service.", cp2Tracker.waitForService(2000));
		assertNotNull("The sc1 bundle never found the service.", sc1Tracker.waitForService(2000));
		cp2Tracker.close();
		sc1Tracker.close();
	}
Esempio n. 10
0
 public void startBundle(String bundleSymbolicName) throws BundleException {
   for (Bundle bundle : bundleCtx.getBundles()) {
     if (bundleSymbolicName.equals(bundle.getSymbolicName())) {
       bundle.start();
     }
   }
 }
  @Test
  public void testProperties() throws Exception {
    Bundle bundle = installBundle(getBundleArchiveA());
    try {
      bundle.start();
      BundleContext bundleContext = bundle.getBundleContext();
      assertNotNull(bundleContext);
      assertEquals("1.5", bundleContext.getProperty(Constants.FRAMEWORK_VERSION));
      assertEquals("jboss.org", bundleContext.getProperty(Constants.FRAMEWORK_VENDOR));
      assertEquals(
          Locale.getDefault().getLanguage(),
          bundleContext.getProperty(Constants.FRAMEWORK_LANGUAGE));
      assertSystemProperty(bundleContext, "os.name", Constants.FRAMEWORK_OS_NAME);
      String fwOSVersion = bundleContext.getProperty(Constants.FRAMEWORK_OS_VERSION);
      assertTrue(fwOSVersion.length() > 0);
      assertTrue(System.getProperty("os.version").startsWith(fwOSVersion));
      assertSystemProperty(bundleContext, "os.arch", Constants.FRAMEWORK_PROCESSOR);

      assertNull(bundleContext.getProperty(getClass().getName()));
      System.setProperty(getClass().getName(), "test");
      assertEquals("test", bundleContext.getProperty(getClass().getName()));

      bundle.stop();
      try {
        bundleContext.getProperty(getClass().getName());
        fail("Should not be here!");
      } catch (IllegalStateException t) {
        // expected
      }
    } finally {
      bundle.uninstall();
    }
  }
  @Test
  public void testServiceReferenceFromListener() throws Exception {
    Bundle bundle = installBundle(getBundleArchiveA());
    try {
      bundle.start();

      final BundleContext context = bundle.getBundleContext();
      final AtomicInteger counter = new AtomicInteger();
      ServiceListener listener =
          new ServiceListener() {
            @Override
            public void serviceChanged(ServiceEvent event) {
              if (ServiceEvent.REGISTERED == event.getType()) {
                ServiceReference sref = context.getServiceReference(BundleContext.class.getName());
                if (context.getService(sref) != null) counter.incrementAndGet();
              }
            }
          };
      context.addServiceListener(listener);
      context.registerService(BundleContext.class.getName(), context, null);
      Assert.assertEquals(1, counter.get());

    } finally {
      bundle.uninstall();
    }
  }
  @Test
  public void testObjectClassFilter() throws Exception {
    Bundle bundle = installBundle(getBundleArchiveA());
    try {
      bundle.start();
      BundleContext context = bundle.getBundleContext();
      assertNotNull(context);
      assertNoServiceEvent();

      String filter = "(" + Constants.OBJECTCLASS + "=" + BundleContext.class.getName() + ")";
      context.addServiceListener(this, filter);

      ServiceRegistration sreg =
          context.registerService(BundleContext.class.getName(), context, null);
      ServiceReference sref = sreg.getReference();

      assertServiceEvent(ServiceEvent.REGISTERED, sref);

      sreg.unregister();
      assertServiceEvent(ServiceEvent.UNREGISTERING, sref);

      filter = "(objectClass=dummy)";
      context.addServiceListener(this, filter);

      sreg = context.registerService(BundleContext.class.getName(), context, null);
      assertNoServiceEvent();

      sreg.unregister();
      assertNoServiceEvent();
    } finally {
      bundle.uninstall();
    }
  }
  @Test
  public void testFrameworkListener() throws Exception {
    Bundle bundle = installBundle(getBundleArchiveA());
    try {
      bundle.start();
      BundleContext bundleContext = bundle.getBundleContext();
      assertNotNull(bundleContext);

      try {
        bundleContext.addFrameworkListener(null);
        fail("Should not be here!");
      } catch (IllegalArgumentException t) {
        // expected
      }

      try {
        bundleContext.removeFrameworkListener(null);
        fail("Should not be here!");
      } catch (IllegalArgumentException t) {
        // expected
      }

      // todo test events
    } finally {
      bundle.uninstall();
    }
  }
  private Bundle installBundleFromFile(
      File savedBundleFile, boolean startBundle, boolean updateExistingBundle)
      throws IOException, BundleException {
    InputStream bundleInputStream = null;
    try {
      bundleInputStream = FileUtils.openInputStream(savedBundleFile);

      JarInformation jarInformation = new JarInformation(savedBundleFile);
      if (!isValidPluginBundle(jarInformation)) {
        LOG.warn(jarInformation.getFilename() + " is not allowed to install as add-on");
        return null;
      }
      Bundle bundle = findMatchingBundle(jarInformation);

      if (bundle == null) {
        final String bundleFileLocationAsURL = savedBundleFile.toURI().toURL().toExternalForm();
        bundle = bundleContext.installBundle(bundleFileLocationAsURL, bundleInputStream);
      } else if (updateExistingBundle) {
        LOG.info("Updating bundle " + bundle.getSymbolicName() + "|" + bundle.getVersion());
        bundle.update(bundleInputStream);
      }

      if (!isFragmentBundle(bundle) && startBundle) {
        bundle.start();
      }

      return bundle;
    } finally {
      IOUtils.closeQuietly(bundleInputStream);
    }
  }
  private void installAndStartBundles(BundleContext context) throws BundleException {

    m_framework.start();

    StartLevel sl = getStartLevelService(context);

    for (ProvisionOption bundle : m_bundles) {
      Bundle b = null;
      b = context.installBundle(bundle.getURL());
      int startLevel = getStartLevel(bundle);
      sl.setBundleStartLevel(b, startLevel);
      b.start();
      LOG.info("+ Install (start@" + startLevel + ") " + bundle);
    }
    LOG.info("++++ Jump to startlevel: " + Constants.START_LEVEL_TEST_BUNDLE);
    sl.setStartLevel(Constants.START_LEVEL_TEST_BUNDLE);
    // Work around for FELIX-2942
    final CountDownLatch latch = new CountDownLatch(1);
    context.addFrameworkListener(
        new FrameworkListener() {
          public void frameworkEvent(FrameworkEvent frameworkEvent) {
            switch (frameworkEvent.getType()) {
              case FrameworkEvent.STARTLEVEL_CHANGED:
                latch.countDown();
            }
          }
        });
    try {
      latch.await(m_timeout, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }
  }
  @Test
  public void testNullSymbolicName() throws Exception {

    final JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "null-symbolic-name");
    archive.setManifest(
        new Asset() {
          public InputStream openStream() {
            OSGiManifestBuilder builder = OSGiManifestBuilder.newInstance();
            builder.addBundleName(archive.getName());
            return builder.openStream();
          }
        });

    Bundle bundle = installBundle(archive);
    try {
      assertBundleState(Bundle.INSTALLED, bundle.getState());
      assertNull("Null symbolic name", bundle.getSymbolicName());
      assertEquals("null-symbolic-name:0.0.0", bundle.toString());
      bundle.start();
      assertBundleState(Bundle.ACTIVE, bundle.getState());
    } finally {
      bundle.uninstall();
      assertBundleState(Bundle.UNINSTALLED, bundle.getState());
    }
  }
Esempio n. 18
0
 public static void activateBundlesFromFile(BundleContext context, String bundleStartupFileName)
     throws IOException, BundleException {
   Map<String, Version> bundleMap =
       readBundleActivationFile(context.getBundle(), bundleStartupFileName);
   Map<String, Bundle> startupBundleMap = new HashMap<String, Bundle>();
   for (Bundle b : context.getBundles()) {
     String symbolicName = b.getSymbolicName();
     if (bundleMap.containsKey(symbolicName)) {
       Version version = b.getVersion();
       Version reqVersion = bundleMap.get(symbolicName);
       if (version.getMajor() == reqVersion.getMajor()
           && version.getMinor() >= reqVersion.getMinor()) {
         if (startupBundleMap.containsKey(symbolicName)) {
           Bundle previousBundle = startupBundleMap.get(symbolicName);
           if (version.compareTo(previousBundle.getVersion()) <= 0) {
             break;
           }
         }
         startupBundleMap.put(symbolicName, b);
       }
     }
   }
   for (Bundle startupBundle : startupBundleMap.values()) {
     logger.log(Level.INFO, "Starting bundle: " + startupBundle);
     startupBundle.start();
   }
 }
  protected List /*<Exception>*/ installBundles(Properties uploads, boolean start)
      throws IllegalArgumentException {
    if (uploads == null || uploads.isEmpty())
      throw new IllegalArgumentException(
          "Bundle installation request must include at least one uploaded file.");
    List bundles = new LinkedList();
    List errors = new LinkedList();

    for (Enumeration names = uploads.propertyNames(); names.hasMoreElements(); ) {
      try {
        String name = (String) names.nextElement();
        Bundle bundle =
            context.installBundle(
                "uploaded:" + name, new FileInputStream(uploads.getProperty(name)));
        bundles.add(bundle);
      } catch (FileNotFoundException e) {
        errors.add(e);
      } catch (BundleException e) {
        errors.add(e);
      }
    }

    if (start) {
      for (Iterator iter = bundles.iterator(); iter.hasNext(); ) {
        try {
          Bundle bundle = (Bundle) iter.next();
          bundle.start();
        } catch (BundleException e) {
          errors.add(e);
        }
      }
    }

    return errors;
  }
Esempio n. 20
0
 @Override
 public Object execute() throws Exception {
   List<Exception> exceptions = new ArrayList<Exception>();
   List<Bundle> bundles = new ArrayList<Bundle>();
   for (String url : urls) {
     try {
       bundles.add(bundleContext.installBundle(url, null));
     } catch (Exception e) {
       exceptions.add(new Exception("Unable to install bundle " + url, e));
     }
   }
   if (start) {
     for (Bundle bundle : bundles) {
       try {
         bundle.start();
       } catch (Exception e) {
         exceptions.add(new Exception("Unable to start bundle " + bundle.getLocation(), e));
       }
     }
   }
   if (bundles.size() == 1) {
     System.out.println("Bundle ID: " + bundles.get(0).getBundleId());
   } else {
     StringBuffer sb = new StringBuffer("Bundle IDs: ");
     for (Bundle bundle : bundles) {
       if (sb.length() > 0) {
         sb.append(", ");
       }
       sb.append(bundle.getBundleId());
     }
     System.out.println(sb);
   }
   MultiException.throwIf("Error installing bundles", exceptions);
   return null;
 }
 @Test
 public void testUpdateExceptionStop() throws Exception {
   Archive<?> assembly1 =
       assembleArchive(
           "update-bundle-stop-exc1",
           "/bundles/update/update-bundle-stop-exc1",
           BundleStopExActivator.class);
   Archive<?> assembly2 =
       assembleArchive("update-bundle-stop-exc2", "/bundles/update/update-bundle-stop-exc2");
   Bundle bundle1 = installBundle(assembly1);
   try {
     bundle1.start();
     assertEquals(Version.parseVersion("1"), bundle1.getVersion());
     try {
       bundle1.update(toInputStream(assembly2));
       fail("Should have thrown a bundle exception.");
     } catch (BundleException be) {
       // good
     }
     assertEquals(
         "Because bundle.stop() throws an exception the update should not have been applied",
         Version.parseVersion("1"),
         bundle1.getVersion());
   } finally {
     bundle1.uninstall();
   }
 }
Esempio n. 22
0
  public static void main(String[] args) {

    try {

      ServiceLoader<FrameworkFactory> loader = ServiceLoader.load(FrameworkFactory.class);

      FrameworkFactory factory = loader.iterator().next();

      Map<String, Object> config = new HashMap<String, Object>();

      config.put(Constants.FRAMEWORK_STORAGE, "./target/storage");

      Framework framework = factory.newFramework(config);

      framework.start();

      BundleContext context = framework.getBundleContext();

      Bundle bundle =
          context.installBundle("http://www.eclipsezone.com/files/jsig/bundles/HelloWorld.jar");

      bundle.start();

      framework.waitForStop(0);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  @Test
  public void testExecutionEnvironment() throws Exception {

    final JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "valid-execution-env");
    archive.setManifest(
        new Asset() {
          public InputStream openStream() {
            OSGiManifestBuilder builder = OSGiManifestBuilder.newInstance();
            builder.addBundleManifestVersion(2);
            builder.addBundleSymbolicName(archive.getName());
            builder.addRequireExecutionEnvironment("JavaSE-1.6");
            return builder.openStream();
          }
        });

    Bundle bundle = installBundle(archive);
    try {
      assertBundleState(Bundle.INSTALLED, bundle.getState());
      bundle.start();
      assertBundleState(Bundle.ACTIVE, bundle.getState());
    } finally {
      bundle.uninstall();
      assertBundleState(Bundle.UNINSTALLED, bundle.getState());
    }
  }
Esempio n. 24
0
  @SuppressWarnings("deprecation")
  public void testAllResolved() {
    assertNotNull("Expected a Bundle Context", context);
    StringBuilder sb = new StringBuilder();

    for (Bundle b : context.getBundles()) {
      if (b.getState() == Bundle.INSTALLED
          && b.getHeaders().get(aQute.bnd.osgi.Constants.FRAGMENT_HOST) == null) {
        try {
          b.start();
        } catch (BundleException e) {
          sb.append(b.getBundleId())
              .append(" ")
              .append(b.getSymbolicName())
              .append(";")
              .append(b.getVersion())
              .append("\n");
          sb.append("    ").append(e.getMessage()).append("\n\n");
          System.err.println(e.getMessage());
        }
      }
    }
    Matcher matcher = IP_P.matcher(sb);
    String out =
        matcher.replaceAll(
            "\n\n         " + aQute.bnd.osgi.Constants.IMPORT_PACKAGE + ": $1;version=[$2,$3)\n");
    assertTrue("Unresolved bundles\n" + out, sb.length() == 0);
  }
  @Test
  public void testInvalidExecutionEnvironment() throws Exception {

    final JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "invalid-execution-env");
    archive.setManifest(
        new Asset() {
          public InputStream openStream() {
            OSGiManifestBuilder builder = OSGiManifestBuilder.newInstance();
            builder.addBundleManifestVersion(2);
            builder.addBundleSymbolicName(archive.getName());
            builder.addRequireExecutionEnvironment("UU/VV", "XX/YY");
            return builder.openStream();
          }
        });

    Bundle bundle = installBundle(archive);
    try {
      assertBundleState(Bundle.INSTALLED, bundle.getState());
      try {
        bundle.start();
        fail("BundleException expected");
      } catch (BundleException ex) {
        // expected
      }
      assertBundleState(Bundle.INSTALLED, bundle.getState());
    } finally {
      bundle.uninstall();
      assertBundleState(Bundle.UNINSTALLED, bundle.getState());
    }
  }
Esempio n. 26
0
 @Override
 public boolean start(OTEStatusCallback<ConfigurationStatus> statusCallback) {
   boolean pass = true;
   sortBundles(installedBundles);
   Iterator<Bundle> iter = installedBundles.iterator();
   while (iter.hasNext()) {
     Bundle bundle = iter.next();
     try {
       String entry = bundle.getHeaders().get("Fragment-Host");
       if (entry == null) {
         int bundleState = bundle.getState();
         if (bundleState != Bundle.ACTIVE) {
           bundle.start();
         }
       }
       // We got here because bundle.start did not exception
       runningBundles.add(bundle);
       iter.remove();
       statusCallback.log("started " + bundle.getSymbolicName());
     } catch (BundleException ex) {
       pass = false;
       statusCallback.error("Failed to start " + bundle.getSymbolicName(), ex);
     } finally {
       statusCallback.incrememtUnitsWorked(1);
     }
   }
   return pass;
 }
  @Test
  public void testSynchronousBundleListener() throws Exception {
    final List<BundleEvent> events = new ArrayList<BundleEvent>();
    BundleListener listener =
        new SynchronousBundleListener() {
          @Override
          public void bundleChanged(BundleEvent event) {
            events.add(event);
          }
        };
    BundleContext context = getSystemContext();
    context.addBundleListener(listener);

    Bundle bundle = installBundle(getBundleArchiveA());
    try {
      bundle.start();
      bundle.stop();
      bundle.update();
    } finally {
      bundle.uninstall();
    }

    assertEquals("Event count in: " + events, 10, events.size());
    assertEquals(BundleEvent.INSTALLED, events.get(0).getType());
    assertEquals(BundleEvent.RESOLVED, events.get(1).getType());
    assertEquals(BundleEvent.STARTING, events.get(2).getType());
    assertEquals(BundleEvent.STARTED, events.get(3).getType());
    assertEquals(BundleEvent.STOPPING, events.get(4).getType());
    assertEquals(BundleEvent.STOPPED, events.get(5).getType());
    assertEquals(BundleEvent.UNRESOLVED, events.get(6).getType());
    assertEquals(BundleEvent.UPDATED, events.get(7).getType());
    assertEquals(BundleEvent.UNRESOLVED, events.get(8).getType());
    assertEquals(BundleEvent.UNINSTALLED, events.get(9).getType());
  }
  @Test
  public void testRegBundleIsRefBundle() throws Exception {
    Bundle bundle = installBundle(getBundleArchiveA());
    try {
      bundle.start();

      final CountDownLatch latch = new CountDownLatch(1);
      ServiceListener listener =
          new ServiceListener() {
            public void serviceChanged(ServiceEvent event) {
              latch.countDown();
            }
          };
      BundleContext context = bundle.getBundleContext();
      context.addServiceListener(listener);

      Object service = bundle.loadClass(A.class.getName()).newInstance();
      ServiceRegistration reg = context.registerService(A.class.getName(), service, null);

      ServiceReference ref = reg.getReference();
      assertTrue(ref.isAssignableTo(bundle, A.class.getName()));

      if (latch.await(5, TimeUnit.SECONDS) == false) throw new TimeoutException();

    } finally {
      bundle.uninstall();
    }
  }
Esempio n. 29
0
 private void installBundle(ZipFile zipFile, List<String> bundles, Application application) {
   for (String location : AtlasConfig.DELAY) {
     String mLocation = contains(bundles, location.replace(".", "_"));
     if (mLocation != null && mLocation.length() > 0) {
       installBundle(zipFile, mLocation, application);
       bundles.remove(mLocation);
     }
   }
   for (String location : bundles) {
     installBundle(zipFile, location, application);
   }
   if (isTargetApp) {
     String[] auto = AtlasConfig.AUTO;
     for (String location : auto) {
       Bundle bundle = OpenAtlas.getInstance().getBundle(location);
       if (bundle != null) {
         try {
           bundle.start();
         } catch (Throwable e) {
           Log.e("BundlesInstaller", "Could not auto start bundle: " + bundle.getLocation(), e);
         }
       }
     }
   }
 }
 @Override
 public BundleInformation restartBundle(long bundleId) throws BundleException {
   Bundle bundle = getBundle(bundleId);
   bundle.stop();
   bundle.start();
   return new BundleInformation(bundle);
 }