Example #1
0
  /*
   * (non-Javadoc)
   * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
   */
  public void start(BundleContext bundleContext) throws Exception {
    Activator.context = bundleContext;

    plugin = this;

    GLLogger.infoTech("initializing the igraph plugin for genlab...", getClass());

    IgraphLibFactory.isIGraphAvailable();

    // declare the LCF algos
    bundleContext.addBundleListener(
        new BundleListener() {

          @Override
          public void bundleChanged(BundleEvent event) {

            if (event.getType() != BundleEvent.STARTED) return;

            if (!event.getBundle().getSymbolicName().equals("genlab.core")) return;

            GLLogger.infoTech("declaring famous LCF graphs", getClass());
            FamousLCFGraphs.declareFamousLCF();
          }
        });
  }
  /**
   * 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();
  }
Example #3
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");
  }
 /**
  * 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 */
 }
Example #5
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);
  }
  @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());
  }
  private void startInternal(BundleContext bundleContext) {
    // register the LogReaderService
    LogReaderServiceImpl logReader = new LogReaderServiceImpl(100);
    String readerServiceName = LogReaderService.class.getName();
    m_registrationLogReaderService =
        bundleContext.registerService(readerServiceName, logReader, null);

    // Tracking for the EventAdmin
    try {
      m_eventAdmin = new EventAdminTracker(bundleContext);
    } catch (NoClassDefFoundError e) {
      // If we hit a NoClassDefFoundError, this means the event admin package is not available,
      // so use a dummy poster
      m_eventAdmin =
          new EventAdminPoster() {
            public void postEvent(
                Bundle bundle,
                int level,
                LogEntry entry,
                String message,
                Throwable exception,
                ServiceReference sr,
                Map context) {}

            public void destroy() {}
          };
    }

    // register the Pax Logging service
    m_paxLogging =
        new PaxLoggingServiceImpl(bundleContext, logReader.getAccessDelegate(), m_eventAdmin);
    Hashtable<String, String> serviceProperties = new Hashtable<String, String>();
    serviceProperties.put(Constants.SERVICE_ID, "org.ops4j.pax.logging.configuration");
    serviceProperties.put(Constants.SERVICE_PID, CONFIGURATION_PID);
    m_RegistrationPaxLogging =
        bundleContext.registerService(LOG_SERVICE_INTERFACE_NAMES, m_paxLogging, serviceProperties);

    // Add a global handler for all JDK Logging (java.util.logging).
    if (!Boolean.valueOf(bundleContext.getProperty("org.ops4j.pax.logging.skipJUL"))) {
      LogManager manager = LogManager.getLogManager();
      manager.reset();

      // clear out old handlers
      Logger rootLogger = manager.getLogger("");
      Handler[] handlers = rootLogger.getHandlers();
      for (Handler handler : handlers) {
        rootLogger.removeHandler(handler);
      }

      rootLogger.setFilter(null);

      m_JdkHandler = new JdkHandler(m_paxLogging);
      rootLogger.addHandler(m_JdkHandler);
    }
    m_frameworkHandler = new FrameworkHandler(m_paxLogging);
    bundleContext.addBundleListener(m_frameworkHandler);
    bundleContext.addFrameworkListener(m_frameworkHandler);
    bundleContext.addServiceListener(m_frameworkHandler);
  }
 /** component start */
 public void init() throws Exception {
   bundleContext.addBundleListener(this);
   // for (Bundle bundle : bundleContext.getBundles()) {
   // switch (bundle.getState()) {
   // case Bundle.RESOLVED:
   // case Bundle.STARTING:
   // case Bundle.ACTIVE:
   // bundleChanged(new BundleEvent(BundleEvent.RESOLVED, bundle));
   // }
   // }
 }
Example #9
0
 public void postConstruct() {
   logger.debug("postConstruct {" + bundleContext.getBundle() + "}");
   loadPredefinedSegments(bundleContext);
   loadPredefinedScorings(bundleContext);
   for (Bundle bundle : bundleContext.getBundles()) {
     if (bundle.getBundleContext() != null) {
       loadPredefinedSegments(bundle.getBundleContext());
       loadPredefinedScorings(bundle.getBundleContext());
     }
   }
   bundleContext.addBundleListener(this);
   initializeTimer();
 }
Example #10
0
  public Loader(final SlingRepository repository, final BundleContext bundleContext) {
    this.bundleContext = bundleContext;
    this.slingRepository = repository;
    this.delayedBundles = new ArrayList<Bundle>();

    // scan existing bundles
    bundleContext.addBundleListener(this);
    for (Bundle bundle : bundleContext.getBundles()) {
      if (bundle.getState() != Bundle.UNINSTALLED) {
        registerBundle(bundle);
      }
    }
  }
  public void testStart() throws Exception {
    MockControl bundleContextControl = MockControl.createControl(BundleContext.class);
    BundleContext context = (BundleContext) bundleContextControl.getMock();
    // platform determination

    // extracting bundle id from bundle
    bundleContextControl.expectAndReturn(context.getBundle(), new MockBundle());

    // look for existing resolved bundles
    bundleContextControl.expectAndReturn(context.getBundles(), new Bundle[0], 2);

    // register namespace and entity resolving service
    // context.registerService((String[]) null, null, null);
    // bundleContextControl.setMatcher(MockControl.ALWAYS_MATCHER);
    // bundleContextControl.setReturnValue(null);

    // register context service
    context.registerService((String[]) null, null, null);
    bundleContextControl.setMatcher(MockControl.ALWAYS_MATCHER);
    bundleContextControl.setReturnValue(null, MockControl.ONE_OR_MORE);

    // create task executor
    EntryLookupControllingMockBundle aBundle = new EntryLookupControllingMockBundle(null);
    aBundle.setEntryReturnOnNextCallToGetEntry(null);
    bundleContextControl.expectAndReturn(context.getBundle(), aBundle, MockControl.ONE_OR_MORE);

    // listen for bundle events
    context.addBundleListener(null);
    bundleContextControl.setMatcher(MockControl.ALWAYS_MATCHER);
    bundleContextControl.setVoidCallable(2);

    bundleContextControl.expectAndReturn(
        context.registerService(new String[0], null, new Properties()),
        new MockServiceRegistration(),
        MockControl.ONE_OR_MORE);
    bundleContextControl.setMatcher(MockControl.ALWAYS_MATCHER);

    bundleContextControl.replay();

    this.listener.start(context);
    bundleContextControl.verify();
  }
Example #12
0
  // called by the initializer after the initial entities bundle was generated
  public void start() {
    LOGGER.info("Scanning for MDS annotations");
    bundlesToRefresh = new ArrayList<>();

    TransactionTemplate tmpl = new TransactionTemplate(transactionManager);

    tmpl.execute(
        new TransactionCallbackWithoutResult() {
          @Override
          protected void doInTransactionWithoutResult(TransactionStatus status) {
            schemaChangeLockManager.acquireLock(
                MdsBundleWatcher.class.getName() + " - start annotation processing");

            processInstalledBundles();

            schemaChangeLockManager.releaseLock(
                MdsBundleWatcher.class.getName() + " - start annotation processing");
          }
        });

    tmpl.execute(
        new TransactionCallbackWithoutResult() {
          @Override
          protected void doInTransactionWithoutResult(TransactionStatus status) {
            schemaChangeLockManager.acquireLock(
                MdsBundleWatcher.class.getName() + " - start refreshing bundles");

            // if we found annotations, we will refresh the bundle in order to start weaving the
            // classes it exposes
            if (!bundlesToRefresh.isEmpty()) {
              refreshBundles(bundlesToRefresh);
            }

            schemaChangeLockManager.releaseLock(
                MdsBundleWatcher.class.getName() + " - start refreshing bundles");
          }
        });

    bundleContext.addBundleListener(this);
  }
Example #13
0
  private RepositoryAdminImpl createRepositoryAdmin() throws Exception {
    BundleContext bundleContext = (BundleContext) EasyMock.createMock(BundleContext.class);
    Bundle systemBundle = (Bundle) EasyMock.createMock(Bundle.class);

    Activator.setContext(bundleContext);
    EasyMock.expect(bundleContext.getProperty(RepositoryAdminImpl.REPOSITORY_URL_PROP))
        .andReturn(getClass().getResource("/referred.xml").toExternalForm());
    EasyMock.expect(bundleContext.getProperty((String) EasyMock.anyObject()))
        .andReturn(null)
        .anyTimes();
    EasyMock.expect(bundleContext.getBundle(0)).andReturn(systemBundle);
    EasyMock.expect(systemBundle.getHeaders()).andReturn(new Hashtable());
    EasyMock.expect(systemBundle.getRegisteredServices()).andReturn(null);
    EasyMock.expect(new Long(systemBundle.getBundleId())).andReturn(new Long(0)).anyTimes();
    EasyMock.expect(systemBundle.getBundleContext()).andReturn(bundleContext);
    bundleContext.addBundleListener((BundleListener) EasyMock.anyObject());
    bundleContext.addServiceListener((ServiceListener) EasyMock.anyObject());
    EasyMock.expect(bundleContext.getBundles()).andReturn(new Bundle[] {systemBundle});
    final Capture c = new Capture();
    EasyMock.expect(bundleContext.createFilter((String) capture(c)))
        .andAnswer(
            new IAnswer() {
              public Object answer() throws Throwable {
                return FilterImpl.newInstance((String) c.getValue());
              }
            })
        .anyTimes();
    EasyMock.replay(new Object[] {bundleContext, systemBundle});

    RepositoryAdminImpl repoAdmin =
        new RepositoryAdminImpl(bundleContext, new Logger(bundleContext));

    // force initialization && remove all initial repositories
    Repository[] repos = repoAdmin.listRepositories();
    for (int i = 0; repos != null && i < repos.length; i++) {
      repoAdmin.removeRepository(repos[i].getURI());
    }

    return repoAdmin;
  }
 public void addBundleListener(BundleListener listener) {
   delegate.addBundleListener(listener);
 }
Example #15
0
 public void start(BundleContext context) {
   context.addBundleListener(this);
 }
  @Test
  public void testBundleListener() throws Exception {
    Bundle bundle = installBundle(getBundleArchiveA());
    try {
      bundle.start();
      BundleContext bundleContext = bundle.getBundleContext();
      assertNotNull(bundleContext);

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

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

      bundle.stop();

      getSystemContext().addBundleListener(this);

      bundle.start();
      assertBundleEvent(BundleEvent.STARTING, bundle);
      assertBundleEvent(BundleEvent.STARTED, bundle);
      assertNoBundleEvent();

      bundle.stop();
      assertBundleEvent(BundleEvent.STOPPING, bundle);
      assertBundleEvent(BundleEvent.STOPPED, bundle);
      assertNoBundleEvent();

      getSystemContext().removeBundleListener(this);
      bundle.start();
      bundle.stop();
      assertNoBundleEvent();

      getSystemContext().addBundleListener(this);
      getSystemContext().addBundleListener(this);
      bundle.start();
      assertBundleEvent(BundleEvent.STARTING, bundle);
      assertBundleEvent(BundleEvent.STARTED, bundle);
      assertNoBundleEvent();

      bundle.stop();
      assertBundleEvent(BundleEvent.STOPPING, bundle);
      assertBundleEvent(BundleEvent.STOPPED, bundle);
      assertNoBundleEvent();

      bundle.start();
      assertBundleEvent(BundleEvent.STARTING, bundle);
      assertBundleEvent(BundleEvent.STARTED, bundle);
      assertNoBundleEvent();

      // [TODO] test asynch BundleListener
    } finally {
      bundle.uninstall();
    }
    assertBundleEvent(BundleEvent.STOPPING, bundle);
    assertBundleEvent(BundleEvent.STOPPED, bundle);
    assertBundleEvent(BundleEvent.UNINSTALLED, bundle);
    getSystemContext().removeBundleListener(this);
  }
 /**
  * The activate method which called when the bundle is started. This will check for the presence
  * of ManagedService and then configure logging. Else this will throw a runtime exception.
  *
  * @param bundleContext BundleContext of this bundle
  * @throws Exception Could be thrown while bundle starting
  */
 public void start(BundleContext bundleContext) throws Exception {
   this.bundleContext = bundleContext;
   bundleContext.addBundleListener(this);
   configureLogging(bundleContext);
 }
Example #18
0
  public void start(BundleContext context) throws Exception {
    super.start(context);
    System.out.println("CCWPlugin.start: ENTER");
    plugin = this;

    context.addBundleListener(
        new BundleListener() {

          @Override
          public void bundleChanged(BundleEvent evt) {
            if (evt.getBundle() == CCWPlugin.this.getBundle()
                && evt.getType() == BundleEvent.STARTED) {

              tracer =
                  new Tracer(evt.getBundle().getBundleContext(), TraceOptions.getTraceOptions());

              // We immediately give control back to the OSGi framework application
              // by starting the code in a new thread
              new Thread(
                      new Runnable() {
                        @Override
                        public void run() {
                          // Some Eclipse plugins, such as LaunchingResourceManager
                          // call PlatformUI.getWorbench() and checking for null,
                          // even though null is not a valid return value
                          // (instead, an exception is thrown), resulting
                          // in the whole Eclipse to collapse.
                          // Let's protect this code once and for all by ensuring
                          // That the Workbench has been initialized before calling
                          // the initialization code
                          while (!PlatformUI.isWorkbenchRunning()) {
                            try {
                              if (CCWPlugin.this.getBundle().getState() != Bundle.ACTIVE) return;
                              Thread.sleep(200);
                            } catch (InterruptedException e) {
                              e.printStackTrace();
                            }
                          }

                          // The Workbench may not be initialized, causing weird issues e.g. in
                          // Kepler
                          // WorkbenchThemeManager.getInstance() in Kepler for instance does
                          // not ensure the instance is created in the UI Thread
                          // Once the Workbench is initialized, WorkbenchThemeManager & all
                          // are ensured to be created, so this removes a bunch of plugin startup
                          // race conditions
                          final IWorkbench workbench = PlatformUI.getWorkbench();
                          final AtomicBoolean isWorkbenchInitialized = new AtomicBoolean();
                          while (true) {
                            workbench
                                .getDisplay()
                                .syncExec(
                                    new Runnable() {
                                      @Override
                                      public void run() {
                                        if (workbench.getActiveWorkbenchWindow() != null) {
                                          // we've got an active window, so workbench is
                                          // initialized!
                                          isWorkbenchInitialized.set(true);
                                        }
                                      }
                                    });
                            if (isWorkbenchInitialized.get()) {
                              break;
                            } else {
                              try {
                                Thread.sleep(200);
                              } catch (InterruptedException e) {
                                e.printStackTrace();
                              }
                            }
                          }

                          // Here, the workbench is initialized
                          if (System.getProperty("ccw.autostartnrepl") != null) {
                            try {
                              startREPLServer();
                            } catch (Exception e) {
                              e.printStackTrace();
                            }
                          }

                          getNatureAdapter().start();
                        }
                      })
                  .start();
            }
          }
        });

    System.out.println("CCWPlugin.start: EXIT");
  }
Example #19
0
 public BundleManagerService(BundleContext bc) {
   this.context = bc;
   bc.addBundleListener(this);
   config = new BundleConfig(getConfigService());
   installPlugins();
 }
Example #20
0
  private Command getExecuteCommand(BundleContext context) throws IOException {
    Map<String, Command> commands = new HashMap<String, Command>();

    commands.put(
        "help", new HelpCommand(commands).setContext(context).setHelp("help - display commands."));
    commands.put(
        "install",
        new InstallCommand()
            .setContext(context)
            .setHelp("install <url> - Install the bundle jar at the given url."));
    commands.put(
        "start",
        new StartCommand()
            .setContext(context)
            .setHelp("start <id> - Start the bundle with the given bundle id."));
    commands.put(
        "stop",
        new StopCommand()
            .setContext(context)
            .setHelp("stop <id> - Stop the bundle with the given bundle id."));
    commands.put(
        "uninstall",
        new UninstallCommand()
            .setContext(context)
            .setHelp("uninstall <id> - Uninstall the bundle with the given bundle id."));
    commands.put(
        "update",
        new UpdateCommand()
            .setContext(context)
            .setHelp("update <id> - Update the bundle with the given bundle id."));
    commands.put(
        "startlevel",
        new StartLevelCommand()
            .setContext(context)
            .setHelp("startlevel [<level>] - Get or set the framework startlevel."));
    commands.put(
        "bundlelevel",
        new BundleLevelCommand()
            .setContext(context)
            .setHelp("bundlelevel [-i] [<level>] <id> - Get or set (initial) bundle startlevel."));
    commands.put(
        "refresh",
        new RefreshCommand().setContext(context).setHelp("refresh [<id> ...] - refresh bundles."));
    commands.put(
        "resolve",
        new ResolveCommand().setContext(context).setHelp("resolve [<id> ...] - resolve bundles."));
    commands.put(
        "bundles",
        new BundlesCommand()
            .setContext(context)
            .setHelp("bundles - Print information about the currently installed bundles"));
    commands.put(
        "obr-repo",
        new RepositoryCommand()
            .setContext(context)
            .setHelp("obr-repo {list-urls|add-url <url> |remove-url <url>|list}"));
    commands.put(
        "obr-resolver",
        new ResolverCommand().setContext(context).setHelp("obr-resolver <resource-filter>"));
    commands.put(
        "dpa",
        new DeploymentPackageCommand()
            .setContext(context)
            .setHelp("dpa {list|install <url>|uninstall <name>}"));
    commands.put(
        "cm",
        new ConfigAdminCommand()
            .setContext(context)
            .setHelp(
                "cm {list|add-cfg <pid> [key=value ...]|add-factory-cfg <pid> [key=value]|remove-factory-cfg <pid>|remove-cfg <pid>}"));
    commands.put("type", new MetaDataCommand().setContext(context).setHelp("type <bundle-id>"));

    HistoryDecorator command =
        new HistoryDecorator(new ExecuteCommand(commands), readHistory(context));
    context.addFrameworkListener(command);
    context.addBundleListener(command);
    m_history = command;

    commands.put(
        "history",
        new HistoryCommand(command)
            .setContext(context)
            .setHelp("history {<n>} - Show the last commands (up to <n> if present)."));

    return command;
  }