예제 #1
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();
    }
  }
예제 #2
0
 protected Bundle getInstalledBundle(String symbolicName) {
   for (Bundle b : bundleContext.getBundles()) {
     if (b.getSymbolicName().equals(symbolicName)) {
       return b;
     }
   }
   for (Bundle b : bundleContext.getBundles()) {
     System.err.println("Bundle: " + b.getSymbolicName());
   }
   throw new RuntimeException("Bundle " + symbolicName + " does not exist");
 }
예제 #3
0
  /*
   * Launches against the agent
   */
  public void testSimpleLauncher() throws Exception {
    Project project = workspace.getProject("p1");
    Run bndrun = new Run(workspace, project.getBase(), project.getFile("one.bndrun"));
    bndrun.setProperty("-runpath", "biz.aQute.remote.launcher");
    bndrun.setProperty("-runbundles", "bsn-1,bsn-2");
    bndrun.setProperty("-runremote", "test");

    final RemoteProjectLauncherPlugin pl =
        (RemoteProjectLauncherPlugin) bndrun.getProjectLauncher();
    pl.prepare();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicInteger exitCode = new AtomicInteger(-1);

    List<? extends RunSession> sessions = pl.getRunSessions();
    assertEquals(1, sessions.size());

    final RunSession session = sessions.get(0);

    Thread t =
        new Thread("test-launch") {
          public void run() {
            try {
              exitCode.set(session.launch());
            } catch (Exception e) {
              e.printStackTrace();
            } finally {
              latch.countDown();
            }
          }
        };
    t.start();
    Thread.sleep(500);

    for (Bundle b : context.getBundles()) {
      System.out.println(b.getLocation());
    }
    assertEquals(4, context.getBundles().length);
    String p1 = t1.getAbsolutePath();
    System.out.println(p1);

    assertNotNull(context.getBundle(p1));
    assertNotNull(context.getBundle(t2.getAbsolutePath()));

    pl.cancel();
    latch.await();

    assertEquals(-3, exitCode.get());

    bndrun.close();
  }
예제 #4
0
  private void processInstalledBundles() {
    List<MDSProcessorOutput> outputs = new ArrayList<>();

    for (Bundle bundle : bundleContext.getBundles()) {
      MDSProcessorOutput output = process(bundle);
      if (hasNonEmptyOutput(output)) {
        outputs.add(output);

        bundlesToRefresh.add(bundle);
        try {
          migrationService.processBundle(bundle);
        } catch (IOException e) {
          LOGGER.error(
              "An error occurred while copying the migrations from bundle: {}",
              bundle.getSymbolicName(),
              e);
        }

        addEditableLookups(output, bundle);
      }
    }

    for (MDSProcessorOutput output : outputs) {
      processAnnotationScanningResults(
          output.getEntityProcessorOutputs(), output.getLookupProcessorOutputs());
    }
  }
예제 #5
0
  @Before
  public void areWeReady() {
    assertNotNull(bc);
    boolean debugit = false;
    Bundle b[] = bc.getBundles();
    for (int i = 0; i < b.length; i++) {
      int state = b[i].getState();
      if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) {
        log.debug("Bundle:" + b[i].getSymbolicName() + " state:" + stateToString(state));
        debugit = true;
      }
    }
    if (debugit) {
      log.debug("Do some debugging because some bundle is " + "unresolved");
    }

    // Assert if true, if false we are good to go!
    assertFalse(debugit);

    // Now lets create a hosttracker for testing purpose
    ServiceReference s = bc.getServiceReference(ISwitchManager.class.getName());
    if (s != null) {
      this.switchManager = (ISwitchManager) bc.getService(s);
    }

    // If StatisticsManager is null, cannot run tests.
    assertNotNull(this.switchManager);
  }
 public static FrameworkDTO newFrameworkDTO(
     BundleContext systemBundleContext, Map<String, String> configuration) {
   FrameworkDTO dto = new FrameworkDTO();
   dto.properties = asProperties(configuration);
   if (systemBundleContext == null) {
     dto.bundles = newList(0);
     dto.services = newList(0);
     return dto;
   }
   Bundle[] bundles = systemBundleContext.getBundles();
   int size = bundles == null ? 0 : bundles.length;
   List<BundleDTO> bundleDTOs = newList(size);
   for (int i = 0; i < size; i++) {
     bundleDTOs.add(newBundleDTO(bundles[i]));
   }
   dto.bundles = bundleDTOs;
   try {
     ServiceReference<?>[] references = systemBundleContext.getAllServiceReferences(null, null);
     size = references == null ? 0 : references.length;
     List<ServiceReferenceDTO> refDTOs = newList(size);
     for (int i = 0; i < size; i++) {
       ServiceReferenceDTO serviceRefDTO = getServiceReferenceDTO(references[i]);
       if (serviceRefDTO != null) {
         refDTOs.add(serviceRefDTO);
       }
     }
     dto.services = refDTOs;
   } catch (InvalidSyntaxException e) {
     dto.services = newList(0);
   }
   return dto;
 }
예제 #7
0
 protected Class<?> getClass(String name) {
   BundleContext bundleContext = null;
   Bundle currentBundle = FrameworkUtil.getBundle(getClass());
   if (currentBundle != null) {
     bundleContext = currentBundle.getBundleContext();
   }
   if (bundleContext != null) {
     Bundle[] bundles = bundleContext.getBundles();
     for (Bundle bundle : bundles) {
       if (bundle.getState() >= Bundle.RESOLVED) {
         try {
           return bundle.loadClass(name);
         } catch (ClassNotFoundException e) {
           // Ignore
         }
       }
     }
   } else {
     try {
       return Class.forName(name);
     } catch (ClassNotFoundException e) {
       LOG.warn("Failed to find class for {}", name);
       throw new RuntimeException(e);
     }
   }
   LOG.warn("Failed to find class for {}", name);
   throw new RuntimeException(new ClassNotFoundException(name));
 }
예제 #8
0
  private void initialize(final BundleContext context) {
    if (Debug.DEBUG_GENERAL) Debug.println("> AspectJHook.initialize() context=" + context);

    this.bundleContext = context;

    final ISupplementerRegistry supplementerRegistry = getSupplementerRegistry();
    adaptorFactory.initialize(context, supplementerRegistry);

    final ServiceReference serviceReference =
        context.getServiceReference(PackageAdmin.class.getName());
    final PackageAdmin packageAdmin = (PackageAdmin) context.getService(serviceReference);

    supplementerRegistry.setBundleContext(context);
    supplementerRegistry.setPackageAdmin(packageAdmin);
    context.addBundleListener(new SupplementBundleListener(supplementerRegistry));

    // final re-build supplementer final registry state for final installed bundles
    final Bundle[] installedBundles = context.getBundles();
    for (int i = 0; i < installedBundles.length; i++) {
      supplementerRegistry.addSupplementer(installedBundles[i], false);
    }
    for (int i = 0; i < installedBundles.length; i++) {
      supplementerRegistry.addSupplementedBundle(installedBundles[i]);
    }

    if (Debug.DEBUG_GENERAL)
      Debug.println("< AspectJHook.initialize() adaptorFactory=" + adaptorFactory);
  }
  /**
   * Starts the OSGi bundle by registering the engine with the bundle of the Restlet API.
   *
   * @param context The bundle context.
   */
  public void start(BundleContext context) throws Exception {
    org.restlet.engine.Engine.register(false);

    // Discover helpers in installed bundles and start
    // the bundle if necessary
    for (final Bundle bundle : context.getBundles()) {
      registerHelpers(bundle);
    }

    // Listen to installed bundles
    context.addBundleListener(
        new BundleListener() {
          public void bundleChanged(BundleEvent event) {
            switch (event.getType()) {
              case BundleEvent.INSTALLED:
                registerHelpers(event.getBundle());
                break;

              case BundleEvent.UNINSTALLED:
                break;
            }
          }
        });

    Engine.getInstance().registerDefaultConnectors();
    Engine.getInstance().registerDefaultAuthentications();
    Engine.getInstance().registerDefaultConverters();
  }
예제 #10
0
  @Before
  public void areWeReady() {
    assertNotNull(bc);
    boolean debugit = false;
    Bundle b[] = bc.getBundles();
    for (int i = 0; i < b.length; i++) {
      int state = b[i].getState();
      if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) {
        System.out.println(">>> " + b[i].getSymbolicName() + " " + stateToString(state));
        log.debug("Bundle:" + b[i].getSymbolicName() + " state:" + stateToString(state));
        debugit = true;
      }
    }

    if (debugit) {
      log.debug("Do some debugging because some bundle is unresolved");
    }

    // Assert if true, if false we are good to go!
    assertFalse(debugit);

    ServiceReference r = bc.getServiceReference(IAffinityManager.class.getName());

    if (r != null) {
      this.manager = (IAffinityManager) bc.getService(r);
    }

    // If AffinityManager is null, cannot run tests.
    assertNotNull(this.manager);
  }
 /**
  * Open this {@code BundleTracker} and begin tracking bundles.
  *
  * <p>Bundle which match the state criteria specified when this {@code BundleTracker} was created
  * are now tracked by this {@code BundleTracker}.
  *
  * @throws java.lang.IllegalStateException If the {@code BundleContext} with which this {@code
  *     BundleTracker} was created is no longer valid.
  * @throws java.lang.SecurityException If the caller and this class do not have the appropriate
  *     {@code AdminPermission[context bundle,LISTENER]}, and the Java Runtime Environment supports
  *     permissions.
  */
 public void open() {
   final Tracked t;
   synchronized (this) {
     if (tracked != null) {
       return;
     }
     if (DEBUG) {
       System.out.println("BundleTracker.open"); // $NON-NLS-1$
     }
     t = new Tracked();
     synchronized (t) {
       context.addBundleListener(t);
       Bundle[] bundles = context.getBundles();
       if (bundles != null) {
         int length = bundles.length;
         for (int i = 0; i < length; i++) {
           int state = bundles[i].getState();
           if ((state & mask) == 0) {
             /* null out bundles whose states are not interesting */
             bundles[i] = null;
           }
         }
         /* set tracked with the initial bundles */
         t.setInitial(bundles);
       }
     }
     tracked = t;
   }
   /* Call tracked outside of synchronized region */
   t.trackInitial(); /* process the initial references */
 }
예제 #12
0
  @Test
  public void shouldSendEventWhenChannelWasUpdated() {
    Channel channel = new Channel("displayName", BUNDLE_SYMBOLIC_NAME, VERSION);

    EventParameter eventParameter = new EventParameter("displayName", "eventKey");
    TriggerEvent triggerEvent =
        new TriggerEvent("displayName", "subject", null, Arrays.asList(eventParameter), "");

    channel.getTriggerTaskEvents().add(triggerEvent);

    when(channelsDataService.findByModuleName(channel.getModuleName())).thenReturn(channel);

    when(bundleContext.getBundles()).thenReturn(new Bundle[] {bundle});
    when(bundle.getSymbolicName()).thenReturn(BUNDLE_SYMBOLIC_NAME);

    ArgumentCaptor<MotechEvent> captor = ArgumentCaptor.forClass(MotechEvent.class);
    Channel updatedChannel = new Channel("displayName2", BUNDLE_SYMBOLIC_NAME, VERSION);
    updatedChannel.getTriggerTaskEvents().add(triggerEvent);
    channelService.addOrUpdate(updatedChannel);

    ArgumentCaptor<TransactionCallback> transactionCaptor =
        ArgumentCaptor.forClass(TransactionCallback.class);
    verify(channelsDataService).doInTransaction(transactionCaptor.capture());
    transactionCaptor.getValue().doInTransaction(null);
    verify(channelsDataService).update(channel);

    verify(eventRelay).sendEventMessage(captor.capture());

    MotechEvent event = captor.getValue();

    assertEquals(CHANNEL_UPDATE_SUBJECT, event.getSubject());
    assertEquals(BUNDLE_SYMBOLIC_NAME, event.getParameters().get(CHANNEL_MODULE_NAME));
  }
예제 #13
0
  @Test
  public void shouldUseCorrectClassLoaderWhenCreatingInstances() throws ClassNotFoundException {
    mockSampleFields();
    mockEntity();
    mockDataService();

    Bundle ddeBundle = mock(Bundle.class);
    Bundle entitiesBundle = mock(Bundle.class);
    when(bundleContext.getBundles()).thenReturn(new Bundle[] {ddeBundle, entitiesBundle});

    when(entity.getBundleSymbolicName()).thenReturn("org.motechproject.test");

    when(entitiesBundle.getSymbolicName())
        .thenReturn(Constants.BundleNames.MDS_ENTITIES_SYMBOLIC_NAME);
    when(ddeBundle.getSymbolicName()).thenReturn("org.motechproject.test");

    Class testClass = TestSample.class;
    when(entitiesBundle.loadClass(testClass.getName())).thenReturn(testClass);
    when(ddeBundle.loadClass(testClass.getName())).thenReturn(testClass);

    EntityRecord entityRecord =
        new EntityRecord(null, ENTITY_ID, Collections.<FieldRecord>emptyList());

    when(entity.isDDE()).thenReturn(true);
    instanceService.saveInstance(entityRecord);
    verify(ddeBundle).loadClass(TestSample.class.getName());

    when(entity.isDDE()).thenReturn(false);
    instanceService.saveInstance(entityRecord);
    verify(entitiesBundle).loadClass(TestSample.class.getName());

    verify(motechDataService, times(2)).create(any(TestSample.class));
  }
예제 #14
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();
   }
 }
예제 #15
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);
  }
예제 #16
0
  @Override
  public int complete(String buffer, int cursor, List<CharSequence> candidates) {
    Bundle[] bundles = bundleContext.getBundles();

    List<Long> bundleIds = new ArrayList<Long>();
    for (Bundle b : bundles) {
      if (matcher.bundleMatches(b)) {
        bundleIds.add(b.getBundleId());
      }
    }

    SortedSet<String> variants = new TreeSet<String>();
    if (buffer.matches("^[0-9]+$")) {
      for (Long l : bundleIds) {
        variants.add(String.valueOf(l));
      }
    } else {
      for (Long l : bundleIds) {
        variants.add(bundleContext.getBundle(l).getSymbolicName());
      }
    }
    if (buffer.isEmpty()) {
      candidates.addAll(variants);
    } else {
      for (String match : variants.tailSet(buffer)) {
        if (!match.startsWith(buffer)) {
          break;
        }
        candidates.add(match.substring(buffer.length()));
      }
    }
    return candidates.isEmpty() ? -1 : buffer.length();
  }
예제 #17
0
  @Override
  public synchronized void start(BundleContext bundleContext) throws Exception {

    // This is how we replace the default FactoryFinder strategy
    // with one that is more compatible in an OSGi env.
    FactoryFinder.setObjectFactory(this);

    debug("activating");
    this.bundleContext = bundleContext;

    cachePackageCapabilities(
        Service.class, Transport.class, DiscoveryAgent.class, PersistenceAdapter.class);

    debug("checking existing bundles");
    bundleContext.addBundleListener(this);
    for (Bundle bundle : bundleContext.getBundles()) {
      if (bundle.getState() == Bundle.RESOLVED
          || bundle.getState() == Bundle.STARTING
          || bundle.getState() == Bundle.ACTIVE
          || bundle.getState() == Bundle.STOPPING) {
        register(bundle);
      }
    }
    debug("activated");
  }
  @Before
  public void areWeReady() {
    assertNotNull(bc);
    boolean debugit = false;
    Bundle b[] = bc.getBundles();
    for (Bundle element : b) {
      int state = element.getState();
      if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) {
        log.debug("Bundle:" + element.getSymbolicName() + " state:" + stateToString(state));
        debugit = true;
      }
    }
    if (debugit) {
      log.debug("Do some debugging because some bundle is " + "unresolved");
    }

    // Assert if true, if false we are good to go!
    assertFalse(debugit);

    ServiceReference r = bc.getServiceReference(IForwardingRulesManager.class.getName());
    if (r != null) {
      this.manager = (IForwardingRulesManager) bc.getService(r);
    }
    // If StatisticsManager is null, cannot run tests.
    assertNotNull(this.manager);
  }
  /**
   * test the supplementer registry with a supplemented bundle
   *
   * @throws Exception
   */
  public void testSupplementerRegistryWithCombinedSupplementer() throws Exception {
    Hashtable headers = new Hashtable();
    headers.put("Eclipse-SupplementImporter", "test.import1");
    headers.put("Eclipse-SupplementExporter", "test.export1");
    headers.put("Eclipse-SupplementBundle", "symbolic-name-supplementedBundle1");
    EasyMock.expect(bundle.getHeaders()).andStubReturn(headers);
    EasyMock.expect(bundle.getSymbolicName()).andStubReturn("supplementer");
    EasyMock.expect(context.getBundles()).andReturn(new Bundle[] {bundle});

    EasyMock.expect(supplementedBundle1.getHeaders()).andStubReturn(new Hashtable());

    headers = new Hashtable();
    headers.put("Export-Package", "test.export1");
    EasyMock.expect(supplementedBundle2.getHeaders()).andStubReturn(headers);

    headers = new Hashtable();
    headers.put("Import-Package", "test.import1");
    EasyMock.expect(supplementedBundle3.getHeaders()).andStubReturn(headers);

    EasyMock.replay(mocks);

    registry.addBundle(bundle);
    registry.addBundle(supplementedBundle1);
    registry.addBundle(supplementedBundle2);
    registry.addBundle(supplementedBundle3);

    Supplementer[] supplementers = registry.getSupplementers(supplementedBundle1);
    assertSame(bundle, supplementers[0].getSupplementerBundle());
    supplementers = registry.getSupplementers(supplementedBundle2);
    assertSame(bundle, supplementers[0].getSupplementerBundle());
    supplementers = registry.getSupplementers(supplementedBundle3);
    assertSame(bundle, supplementers[0].getSupplementerBundle());

    EasyMock.verify(mocks);
  }
예제 #20
0
 public void startBundle(String bundleSymbolicName) throws BundleException {
   for (Bundle bundle : bundleCtx.getBundles()) {
     if (bundleSymbolicName.equals(bundle.getSymbolicName())) {
       bundle.start();
     }
   }
 }
예제 #21
0
  /**
   * Forcing the registry of the HttpService, usually need it when the felix framework is reloaded
   * and we need to update the bundle context of our already registered services.
   *
   * @param context
   */
  private void forceHttpServiceLoading(BundleContext context) throws Exception {

    try {
      // Working with the http bridge
      if (OSGIProxyServlet.servletConfig
          != null) { // If it is null probably the servlet wasn't even been loaded...

        try {
          OSGIProxyServlet.bundleContext.getBundle();
        } catch (IllegalStateException e) {

          Bundle[] bundles = context.getBundles();
          for (Bundle bundle : bundles) {
            if (bundle.getSymbolicName().equals(OSGIUtil.BUNDLE_HTTP_BRIDGE_SYMBOLIC_NAME)) {
              // If we are here is because we have an invalid bundle context, so we need to provide
              // a new one
              BundleContext httpBundle = bundle.getBundleContext();
              OSGIProxyServlet.tracker =
                  new DispatcherTracker(httpBundle, null, OSGIProxyServlet.servletConfig);
              OSGIProxyServlet.tracker.open();
              OSGIProxyServlet.bundleContext = httpBundle;
            }
          }
        }
      }
    } catch (Exception e) {
      Logger.error(this, "Error loading HttpService.", e);
      throw e;
    }
  }
예제 #22
0
 protected void findBundlesWithFramentsToRefresh(Set<Bundle> toRefresh) {
   for (Bundle b : toRefresh) {
     if (b.getState() != Bundle.UNINSTALLED) {
       String hostHeader = (String) b.getHeaders().get(Constants.FRAGMENT_HOST);
       if (hostHeader != null) {
         Clause[] clauses = Parser.parseHeader(hostHeader);
         if (clauses != null && clauses.length > 0) {
           Clause path = clauses[0];
           for (Bundle hostBundle : bundleContext.getBundles()) {
             if (hostBundle.getSymbolicName().equals(path.getName())) {
               String ver = path.getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE);
               if (ver != null) {
                 VersionRange v = VersionRange.parseVersionRange(ver);
                 if (v.contains(hostBundle.getVersion())) {
                   toRefresh.add(hostBundle);
                 }
               } else {
                 toRefresh.add(hostBundle);
               }
             }
           }
         }
       }
     }
   }
 }
예제 #23
0
  @Test
  public void shouldSendEventWhenChannelWasDeleted() {
    Channel channel = new Channel("displayName", BUNDLE_SYMBOLIC_NAME, VERSION);

    when(channelsDataService.findByModuleName(channel.getModuleName())).thenReturn(channel);
    when(bundleContext.getBundles()).thenReturn(new Bundle[] {bundle});
    when(bundle.getSymbolicName()).thenReturn(BUNDLE_SYMBOLIC_NAME);

    ArgumentCaptor<MotechEvent> captor = ArgumentCaptor.forClass(MotechEvent.class);
    Channel deletedChannel = new Channel("displayName2", BUNDLE_SYMBOLIC_NAME, VERSION);
    channelService.delete(deletedChannel.getModuleName());

    ArgumentCaptor<TransactionCallback> transactionCaptor =
        ArgumentCaptor.forClass(TransactionCallback.class);
    verify(channelsDataService).doInTransaction(transactionCaptor.capture());
    transactionCaptor.getValue().doInTransaction(null);
    verify(channelsDataService).delete(channel);

    verify(eventRelay).sendEventMessage(captor.capture());

    MotechEvent event = captor.getValue();

    assertEquals(CHANNEL_DEREGISTER_SUBJECT, event.getSubject());
    assertEquals(BUNDLE_SYMBOLIC_NAME, event.getParameters().get(CHANNEL_MODULE_NAME));
  }
  /**
   * Process Provide-Capability headers and populate a counter which keep all the expected service
   * counts. Register timers to track the service availability as well as pending service
   * registrations.
   *
   * <p>If there are no RequireCapabilityListener instances then this method returns.
   *
   * @param bundleContext OSGi bundle context of the Carbon.core bundle
   * @throws Exception if the service component activation fails
   */
  @Activate
  public void start(BundleContext bundleContext) throws Exception {
    try {

      logger.debug("Initialize - Startup Order Resolver.");

      // 1) Process OSGi manifest headers to calculate the expected list required capabilities.
      processManifestHeaders(Arrays.asList(bundleContext.getBundles()), supportedManifestHeaders);

      // 2) Check for any startup components with pending required capabilities.
      if (startupComponentManager.getPendingComponents().size() == 0) {
        // There are no registered RequiredCapabilityListener
        // Clear all the populated maps.
        startupComponentManager = null;
        osgiServiceTracker = null;
        return;
      }

      // 3) Register capability trackers to get notified when required capabilities are available.
      startCapabilityTrackers();

      // 4) Schedule a time task to check for startup components with zero pending required
      // capabilities.
      scheduleCapabilityListenerTimer();

      // 5) Start a timer to track pending capabilities, pending CapabilityProvider services,
      // pending RequiredCapabilityLister services.
      schedulePendingCapabilityTimerTask();

    } catch (Throwable e) {
      logger.error("Error occurred in Startup Order Resolver.", e);
    }
  }
  @Test
  public void testClientDeploymentAsArchive() throws Exception {

    String symbolicName = "archive-deployer-test-bundle";
    Archive<?> archive = provider.getClientDeployment(symbolicName);
    String depname = archiveDeployer.deploy(archive);
    Bundle bundle = null;
    try {
      for (Bundle aux : context.getBundles()) {
        if (symbolicName.equals(aux.getSymbolicName())) {
          bundle = aux;
          break;
        }
      }
      // Assert that the bundle is there
      assertNotNull("Bundle found", bundle);

      // Start the bundle
      bundle.start();
      OSGiTestHelper.assertBundleState(Bundle.ACTIVE, bundle.getState());

      // Stop the bundle
      bundle.stop();
      OSGiTestHelper.assertBundleState(Bundle.RESOLVED, bundle.getState());
    } finally {
      archiveDeployer.undeploy(depname);
      // FIXME JBAS-9359
      // OSGiTestHelper.assertBundleState(Bundle.UNINSTALLED, bundle.getState());
    }
  }
예제 #26
0
  /** {@inheritDoc}. */
  @SuppressWarnings("unchecked")
  @Override
  public List<Map<String, Object>> getServices(String applicationID) {
    List<Map<String, Object>> services =
        configAdminExt.listServices(getDefaultFactoryLdapFilter(), getDefaultLdapFilter());
    List<Map<String, Object>> returnValues = new ArrayList<Map<String, Object>>();
    BundleContext context = getContext();

    if (!services.isEmpty()) {
      Application app = appService.getApplication(applicationID);
      MetaTypeService metatypeService = getMetaTypeService();

      if (app != null) {
        try {
          Set<BundleInfo> bundles = app.getBundles();

          Set<String> bundleLocations = new HashSet<String>();
          Set<MetaTypeInformation> metatypeInformation = new HashSet<MetaTypeInformation>();
          for (BundleInfo info : bundles) {
            bundleLocations.add(info.getLocation());
          }

          for (Bundle bundle : context.getBundles()) {
            for (BundleInfo info : bundles) {
              if (info.getLocation().equals(bundle.getLocation())) {
                metatypeInformation.add(metatypeService.getMetaTypeInformation(bundle));
              }
            }
          }

          for (Map<String, Object> service : services) {
            if (service.containsKey("configurations")) {
              List<Map<String, Object>> configurations =
                  (List<Map<String, Object>>) service.get("configurations");
              for (Map<String, Object> item : configurations) {
                if (item.containsKey("bundle_location")) {
                  String bundleLocation = (String) item.get("bundle_location");
                  if (bundleLocations.contains(bundleLocation)) {
                    returnValues.add(service);
                    break;
                  }
                }
              }
            } else {
              if (checkForMetaTypesForService(metatypeInformation, service)) {
                returnValues.add(service);
              }
            }
          }

        } catch (ApplicationServiceException e) {
          LOGGER.warn("There was an error while trying to access the application", e);
          return new ArrayList<Map<String, Object>>();
        }
      }
    }

    return returnValues;
  }
예제 #27
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;
    //				}
    //			}
    //		}

  }
 private Bundle getBundleForSymbolicName(String symbolicName) {
   for (Bundle b : bundleContext.getBundles()) {
     if (b.getSymbolicName().equals(symbolicName)) {
       return b;
     }
   }
   return null;
 }
예제 #29
0
  @MsgbusMethod
  public void getBundles(Request req, Response resp) {
    List<Object> l = new ArrayList<Object>();
    for (Bundle bundle : bc.getBundles()) {
      l.add(marshal(bundle));
    }

    resp.put("bundles", l);
  }
예제 #30
0
 private Bundle findBundle(String id) {
   Bundle[] bundles = context.getBundles();
   for (Bundle b : bundles) {
     if (b.getSymbolicName().equals(id)) {
       return b;
     }
   }
   return null;
 }