private void deploy(WebApp webApp) {

    Bundle bundle = webApp.getBundle();
    String contextName = webApp.getContextName();

    eventDispatcher.webEvent(
        new WebEvent(WebEvent.DEPLOYING, "/" + contextName, bundle, bundleContext.getBundle()));
    if (!contexts.containsKey(contextName)) {
      LinkedList<WebApp> queue = new LinkedList<WebApp>();
      contexts.put(contextName, queue);
      queue.add(webApp);

      // let the publisher set the deployment state and send web event
      m_publisher.publish(webApp, eventDispatcher, bundleContext);
    } else {
      LinkedList<WebApp> queue = contexts.get(contextName);
      queue.add(webApp);

      Collection<Long> duplicateIds = new LinkedList<Long>();
      for (WebApp duplicateWebApp : queue) {
        duplicateIds.add(duplicateWebApp.getBundle().getBundleId());
      }

      webApp.setDeploymentState(WebApp.WAITING_STATE);
      eventDispatcher.webEvent(
          new WebEvent(
              WebEvent.WAITING,
              "/" + contextName,
              bundle,
              bundleContext.getBundle(),
              duplicateIds));
    }
  }
  private void undeploy(WebApp webApp) {

    String contextName = webApp.getContextName();
    LinkedList<WebApp> queue = contexts.get(contextName);
    if (queue != null) {

      // Are we the published web app??
      if (queue.get(0) == webApp) {

        webApp.setDeploymentState(WebApp.UNDEPLOYED_STATE);
        eventDispatcher.webEvent(
            new WebEvent(
                WebEvent.UNDEPLOYING,
                "/" + contextName,
                webApp.getBundle(),
                bundleContext.getBundle()));
        m_publisher.unpublish(webApp);
        eventDispatcher.webEvent(
            new WebEvent(
                WebEvent.UNDEPLOYED,
                "/" + contextName,
                webApp.getBundle(),
                bundleContext.getBundle()));
        queue.removeFirst();

        // Below checks if another webapp is waiting for the context, if so the webapp is published.
        LOG.debug("Check for a waiting webapp.");
        if (!queue.isEmpty()) {
          LOG.debug("Found another bundle waiting for the context");
          WebApp next = queue.getFirst();

          eventDispatcher.webEvent(
              new WebEvent(
                  WebEvent.DEPLOYING,
                  "/" + contextName,
                  next.getBundle(),
                  bundleContext.getBundle()));

          // let the publisher set the deployment state and send web event
          m_publisher.publish(next, eventDispatcher, bundleContext);
        } else {
          contexts.remove(contextName);
        }

      } else if (queue.remove(webApp)) {
        webApp.setDeploymentState(WebApp.UNDEPLOYED_STATE);
        eventDispatcher.webEvent(
            new WebEvent(
                WebEvent.UNDEPLOYED,
                "/" + contextName,
                webApp.getBundle(),
                bundleContext.getBundle()));
      } else {
        LOG.debug("Web application was not in the deployment queue");
      }

    } else {
      LOG.debug(String.format("No web application published under context: %s", contextName));
    }
  }
  @Override
  protected String customResolveManagementName(String pattern, String answer) {
    String bundleId = "" + bundleContext.getBundle().getBundleId();
    String symbolicName = bundleContext.getBundle().getSymbolicName();
    if (symbolicName != null) {
      symbolicName = Matcher.quoteReplacement(symbolicName);
    } else {
      symbolicName = "";
    }
    String version = Matcher.quoteReplacement(bundleContext.getBundle().getVersion().toString());

    answer = answer.replaceFirst("#bundleId#", bundleId);
    answer = answer.replaceFirst("#symbolicName#", symbolicName);
    answer = answer.replaceFirst("#version#", version);

    // we got a candidate then find a free name
    // true = check fist if the candidate as-is is free, if not then use the counter
    answer =
        OsgiNamingHelper.findFreeCamelContextName(
            bundleContext,
            answer,
            OsgiCamelContextPublisher.CONTEXT_MANAGEMENT_NAME_PROPERTY,
            CONTEXT_COUNTER,
            true);

    return answer;
  }
Example #4
0
  /**
   * Called when this bundle is started so the Framework can perform the bundle-specific activities
   * necessary to start this bundle. This method can be used to register services or to allocate any
   * resources that this bundle needs.
   *
   * <p>This method must complete and return to its caller in a timely manner.
   *
   * @param context The execution context of the bundle being started.
   * @throws Exception If this method throws an exception, this bundle is marked as stopped and the
   *     Framework will remove this bundle's listeners, unregister all services registered by this
   *     bundle, and release all services used by this bundle.
   */
  @Override
  public void start(BundleContext context) throws Exception {
    this.context = context;
    initMembers();
    this.activatorLogger.info(
        "Starting APSActivator for bundle '"
            + context.getBundle().getSymbolicName()
            + "' with activatorMode: "
            + this.activatorMode);
    Bundle bundle = context.getBundle();

    List<Class> classEntries = new LinkedList<>();
    if (!this.activatorMode) {
      classEntries.addAll(this.managedInstances.keySet());
    }
    collectClassEntries(bundle, classEntries, "/");

    for (Class entryClass : classEntries) {
      OSGiServiceProvider serviceProvider =
          (OSGiServiceProvider) entryClass.getAnnotation(OSGiServiceProvider.class);
      if (serviceProvider != null && serviceProvider.threadStart()) {
        new StartThread(entryClass, context).start();
      } else {
        handleServiceInstances(entryClass, context);
        handleFieldInjections(entryClass, context);
        handleServiceRegistrations(entryClass, context);
        handleMethods(entryClass, context);
      }
    }
  }
Example #5
0
 public Source resolve(String href, String base) throws TransformerException {
   if (href == null || href.trim().length() == 0) {
     throw new TransformerException("href is null");
   }
   try {
     String aname = defaultXslStylesheetBase + href;
     if (aname.indexOf("..") != -1) {
       aname = new File(aname).getCanonicalPath().toString();
     }
     if (m_bundleContect.getBundle().getEntry(aname) == null) {
       aname = defaultXslStylesheetBase2 + href;
     }
     if (m_bundleContect.getBundle().getEntry(aname) == null) {
       aname = defaultXslStylesheetBase3 + href;
     }
     SAXSource ss =
         new SAXSource(new InputSource(m_bundleContect.getBundle().getEntry(aname).openStream()));
     XMLReader reader = m_saxParserFactory.newSAXParser().getXMLReader();
     ReaderConfig rc = ((WstxSAXParser) reader).getStaxConfig();
     rc.setXMLResolver(new XslURIResolver(m_bundleContect, m_saxParserFactory));
     ss.setXMLReader(reader);
     return ss;
   } catch (Exception e) {
     throw new RuntimeException("XslURIResolver.resolve", e);
   }
 }
Example #6
0
  /**
   * Gets the default logger level. The property is searched inside the framework properties, the
   * system properties, and in the manifest from the given bundle context. By default, set the level
   * to {@link Logger#WARNING}.
   *
   * @param context the bundle context.
   * @return the default log level.
   */
  private static int getDefaultLevel(BundleContext context) {
    // First check in the framework and in the system properties
    String level = context.getProperty(IPOJO_LOG_LEVEL_PROP);

    // If null, look in the bundle manifest
    if (level == null) {
      String key = IPOJO_LOG_LEVEL_PROP.replace('.', '-');
      level = (String) context.getBundle().getHeaders().get(key);
    }

    // if still null try the second header
    if (level == null) {
      level = (String) context.getBundle().getHeaders().get(IPOJO_LOG_LEVEL_HEADER);
    }

    if (level != null) {
      if (level.equalsIgnoreCase("info")) {
        return INFO;
      } else if (level.equalsIgnoreCase("debug")) {
        return DEBUG;
      } else if (level.equalsIgnoreCase("warning")) {
        return WARNING;
      } else if (level.equalsIgnoreCase("error")) {
        return ERROR;
      }
    }

    // Either l is null, either the specified log level was unknown
    // Set the default to WARNING
    return WARNING;
  }
  /**
   * Constructs a new <code>NamespaceManager</code> instance.
   *
   * @param context containing bundle context
   */
  public NamespaceManager(BundleContext context) {
    this.context = context;

    extenderInfo =
        context.getBundle().getSymbolicName()
            + "|"
            + OsgiBundleUtils.getBundleVersion(context.getBundle());

    // detect package admin
    this.namespacePlugins = new NamespacePlugins();
  }
Example #8
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();
  }
  /**
   * locateProxyTarget.
   *
   * @return a {@link org.ops4j.pax.wicket.spi.ProxyTarget} object.
   */
  public ProxyTarget locateProxyTarget() {
    if (bundleContext == null) {
      throw new IllegalStateException("Bundle context is not allowed to be null");
    }
    ClassLoader oldClassloader = Thread.currentThread().getContextClassLoader();
    String filter = getApplicationContextFilter(bundleContext.getBundle().getSymbolicName());
    ServiceReference<?>[] references = null;
    try {
      references = bundleContext.getServiceReferences(getContainerClass().getName(), filter);
    } catch (InvalidSyntaxException e) {
      throw new IllegalStateException("not possible", e);
    }
    if (references == null || references.length == 0) {
      throw new IllegalStateException(
          String.format(
              "Found zero service references for %s; this is not OK...",
              bundleContext.getBundle().getSymbolicName()));
    }
    try {
      Thread.currentThread().setContextClassLoader(parent.getClassLoader());
      final BeanReactor<Container> strategy = createStrategy();
      for (ServiceReference<?> serviceReference : references) {
        @SuppressWarnings("unchecked")
        final Container service = (Container) bundleContext.getService(serviceReference);
        try {
          if (!strategy.containsBean(service)) {
            continue;
          }
          return new ProxyTarget() {

            public Object getTarget() {
              return strategy.createBean(service);
            }
          };
        } finally {
          bundleContext.ungetService(serviceReference);
        }
      }
    } finally {
      Thread.currentThread().setContextClassLoader(oldClassloader);
    }
    throw new IllegalStateException(
        String.format(
            "Bundle %s can no longer attach bean %s, class %s to page %s",
            bundleContext.getBundle().getSymbolicName(),
            beanType.getName(),
            beanType.getName(),
            parent.getName()));
  }
  /** Dispose of this component activator instance and all the component managers. */
  void dispose(int reason) {
    if (m_context == null) {
      return;
    }

    // mark instance inactive (no more component activations)
    m_active = false;

    log(
        LogService.LOG_DEBUG,
        "BundleComponentActivator : Bundle [{0}] will destroy {1} instances",
        new Object[] {
          new Long(m_context.getBundle().getBundleId()), new Integer(m_managers.size())
        },
        null,
        null);

    while (m_managers.size() != 0) {
      ComponentHolder holder = (ComponentHolder) m_managers.get(0);
      try {
        m_managers.remove(holder);
        holder.disposeComponents(reason);
      } catch (Exception e) {
        log(
            LogService.LOG_ERROR,
            "BundleComponentActivator : Exception invalidating",
            holder.getComponentMetadata(),
            e);
      } finally {
        m_componentRegistry.unregisterComponentHolder(holder.getComponentMetadata().getName());
      }
    }

    log(
        LogService.LOG_DEBUG,
        "BundleComponentActivator : Bundle [{0}] STOPPED",
        new Object[] {new Long(m_context.getBundle().getBundleId())},
        null,
        null);

    if (m_logService != null) {
      m_logService.close();
      m_logService = null;
    }

    m_componentActor = null;
    m_componentRegistry = null;
    m_context = null;
  }
  private ServiceRegistration<?> registerPerformanceLog(BundleContext context) {
    Object service = createPerformanceLog(context.getBundle());
    String serviceName = FrameworkLog.class.getName();
    Dictionary<String, Object> serviceProperties = new Hashtable<String, Object>(7);
    Dictionary<String, String> headers = context.getBundle().getHeaders();

    serviceProperties.put(Constants.SERVICE_VENDOR, headers.get(Constants.BUNDLE_VENDOR));
    serviceProperties.put(Constants.SERVICE_RANKING, new Integer(Integer.MIN_VALUE));
    serviceProperties.put(
        Constants.SERVICE_PID,
        context.getBundle().getBundleId() + '.' + service.getClass().getName());
    serviceProperties.put(FrameworkLog.SERVICE_PERFORMANCE, Boolean.TRUE.toString());

    return context.registerService(serviceName, service, serviceProperties);
  }
  @Override
  public void start(BundleContext context) throws Exception {
    this.logger = LoggerActivator.getLogger();
    this.logger.info("Starting the " + context.getBundle().getSymbolicName() + " bundle...");

    PermissionActivator.configTracker =
        new ServiceTracker<Config, Config>(context, Config.class, null);
    PermissionActivator.configTracker.open();

    PermissionActivator.messengerTracker =
        new ServiceTracker<MessengerService, MessengerService>(
            context, MessengerService.class, null);
    PermissionActivator.messengerTracker.open();

    /* Register the Permissions service. */
    this.logger.debug("Registering the Permissions SOAP interface service.");
    ServletContainerService soapService = new ServletContainerService();
    soapService.addServlet(new ServletContainer(new AxisServlet(), true));
    this.soapRegistration =
        context.registerService(ServletContainerService.class, soapService, null);

    this.pageRegistrations = new ArrayList<ServiceRegistration<HostedPage>>(3);
    this.pageRegistrations.add(
        context.registerService(HostedPage.class, UsersPage.getHostedPage(), null));
    this.pageRegistrations.add(
        context.registerService(HostedPage.class, UserClassesPage.getHostedPage(), null));
    this.pageRegistrations.add(
        context.registerService(HostedPage.class, KeysPage.getHostedPage(), null));
  }
 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();
   }
 }
  @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();
  }
Example #15
0
  @Override
  public void updateBundleVersion(
      long bundleId, String groupId, String artifactId, String version) {
    Bundle bundle = context.getBundle(bundleId);
    if (bundle == null) {
      logger.warn(String.format("bundle %d not found", bundleId));
      throw new IllegalStateException("bundle " + bundleId + " not found");
    }

    MavenResolver resolver =
        new MavenResolver(
            getLocalRepository(), config.getRepositories(), null, getKeyStoreManager());
    Version v = (version != null) ? new Version(version) : null;
    MavenArtifact artifact = new MavenArtifact(groupId, artifactId, v);

    if (isBuiltinArtifact(artifact.getGroupId(), artifact.getArtifactId()))
      throw new IllegalStateException("provided in system bundle");

    try {
      File file = resolver.resolve(artifact);
      if (!isBundleJar(file))
        throw new IllegalStateException(
            "invalid OSGi bundle: " + groupId + "/" + artifactId + " (" + version + ")");

      bundle.update(new FileInputStream(file));
    } catch (Exception e) {
      throw new IllegalStateException("bundleId: " + bundleId + ", version: " + version, e);
    }
  }
  @Override
  public void start(BundleContext context) throws Exception {
    LOG.info("Starting Bundle");

    // Get our name.
    String myName = context.getBundle().getSymbolicName();

    // Find reference.
    ServiceReference<HelloService> ref = context.getServiceReference(HelloService.class);
    if (ref != null) {
      try {
        // Print service properties.
        String props = getServiceProperties(ref);
        LOG.info(
            "Calling HelloService#sayHello('{}') Published by {}. Props:\n{}",
            myName,
            ref.getBundle().getSymbolicName(),
            props);
        // Get the service
        HelloService service = context.getService(ref);
        if (service != null) {
          service.sayHello(myName);
        }
      } finally {
        // Release reference
        context.ungetService(ref);
      }
    }
  }
 @Test
 public void testBundleInjection() throws Exception {
   assertNotNull("BundleContext injected", context);
   assertEquals("System Bundle ID", 0, context.getBundle().getBundleId());
   assertNotNull("Bundle injected", bundle);
   OSGiTestHelper.assertBundleState(Bundle.RESOLVED, bundle.getState());
 }
 private Bundle getBundle(long bundleId) {
   Bundle bundle = bundleContext.getBundle(bundleId);
   if (bundle == null || !motechBundleFilter.passesCriteria(bundle)) {
     throw new BundleNotFoundException("Bundle with id [" + bundleId + "] not found");
   }
   return bundle;
 }
Example #19
0
 /**
  * Checks if the component bundle context has enough permission to register the given service.
  *
  * @param itf the service interface
  * @param comp the component bundle context
  * @return <code>true</code> if the bundle has enough permission to register the service, <code>
  *     false</code> otherwise.
  */
 public static boolean hasPermissionToRegisterService(String itf, BundleContext comp) {
   if (System.getSecurityManager() != null) {
     final Permission perm = new ServicePermission(itf, ServicePermission.REGISTER);
     return comp.getBundle().hasPermission(perm);
   }
   return true;
 }
Example #20
0
  /*
   * (non-Javadoc)
   *
   * @see org.araqne.bundle.BundleManager#uninstallBundle(long)
   */
  @Override
  public boolean uninstallBundle(long bundleId) {
    Bundle bundle = context.getBundle(bundleId);
    if (bundle == null) {
      logger.warn(String.format("bundle %d not found.", bundleId));
      return false;
    }

    try {
      String downloadRoot = getDownloadRoot();

      String prefix = getPrefix();

      File bundleLocation = new File(bundle.getLocation().replace(prefix, ""));

      // prevents destruction out of the download directory.
      // delete cached bundle in download directory for redownloading
      if (bundle.getLocation().startsWith(prefix + downloadRoot)) {
        File bundleDirectory = new File(bundleLocation.getParent());
        bundleLocation.delete();
        deleteDirectory(bundleDirectory);
      }
      bundle.uninstall();
      return true;
    } catch (BundleException e) {
      logger.error(e.getMessage());
      return false;
    }
  }
Example #21
0
  /*
   * (non-Javadoc)
   *
   * @see org.araqne.bundle.BundleManager#getBundleLocation(long)
   */
  @Override
  public String getBundleLocation(long bundleId) {
    Bundle bundle = context.getBundle(bundleId);
    if (bundle == null) throw new IllegalStateException("bundle not found: " + bundleId);

    return bundle.getLocation();
  }
Example #22
0
 /* (non-Javadoc)
  * @see javax.security.auth.spi.LoginModule#initialize(javax.security.auth.Subject, javax.security.auth.callback.CallbackHandler, java.util.Map, java.util.Map)
  */
 public void initialize(
     Subject subject,
     CallbackHandler callbackHandler,
     Map<String, ?> sharedState,
     Map<String, ?> options) {
   if (bundleContext == null) {
     throw new IllegalStateException(
         "ProxyLoginModule not initialized. Init must be called prior any invocation.");
   }
   Map<String, ?> newOptions = new HashMap<String, Object>(options);
   String module = (String) newOptions.remove(PROPERTY_MODULE);
   if (module == null) {
     throw new IllegalStateException(
         "Option " + PROPERTY_MODULE + " must be set to the name of the factory service");
   }
   String bundleId = (String) newOptions.remove(PROPERTY_BUNDLE);
   if (bundleId == null) {
     throw new IllegalStateException(
         "Option " + PROPERTY_BUNDLE + " must be set to the name of the factory service");
   }
   Bundle bundle = bundleContext.getBundle(Long.parseLong(bundleId));
   if (bundle == null) {
     throw new IllegalStateException("No bundle found for id " + bundleId);
   }
   try {
     target = (LoginModule) bundle.loadClass(module).newInstance();
   } catch (Exception e) {
     throw new IllegalStateException(
         "Can not load or create login module " + module + " for bundle " + bundleId, e);
   }
   target.initialize(subject, callbackHandler, sharedState, newOptions);
 }
  public DelegatedExecutionOsgiBundleApplicationContext createApplicationContext(
      BundleContext bundleContext) throws Exception {
    Bundle bundle = bundleContext.getBundle();
    ApplicationContextConfiguration config = new BlueprintContainerConfig(bundle);
    String bundleName = OsgiStringUtils.nullSafeNameAndSymName(bundle);
    if (log.isTraceEnabled())
      log.trace("Created configuration " + config + " for bundle " + bundleName);

    // it's not a spring bundle, ignore it
    if (!config.isSpringPoweredBundle()) {
      if (log.isDebugEnabled())
        log.debug("No blueprint configuration found in bundle " + bundleName + "; ignoring it...");
      return null;
    }

    log.info(
        "Discovered configurations "
            + ObjectUtils.nullSafeToString(config.getConfigurationLocations())
            + " in bundle ["
            + bundleName
            + "]");

    DelegatedExecutionOsgiBundleApplicationContext sdoac =
        new OsgiBundleXmlApplicationContext(config.getConfigurationLocations());
    sdoac.setBundleContext(bundleContext);
    sdoac.setPublishContextAsService(config.isPublishContextAsService());

    return sdoac;
  }
Example #24
0
  /**
   * This method is called upon plug-in activation
   *
   * @param context
   * @throws Exception
   */
  public void start(BundleContext context) throws Exception {
    super.start(context);
    iconsUrl = context.getBundle().getEntry(ICONS_PATH);
    Authenticator.setDefault(new UDIGAuthenticator());
    /*
     * TODO Further code can nuke the previously set authenticator. Proper security access
     * should be configured to prevent this.
     */
    disableCerts();
    try {
      loadVersion();

      java.lang.System.setProperty(
          "http.agent",
          "uDig "
              + getVersion()
              + " (http://udig.refractions.net)"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
      java.lang.System.setProperty(
          "https.agent",
          "uDig "
              + getVersion()
              + " (http://udig.refractions.net)"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    } catch (Throwable e) {
      log("error determining version", e); // $NON-NLS-1$
    }
  }
  /**
   * Gets the MetaData location, parses the meta data and requests the processing of binder
   * instances
   *
   * @param descriptorLocations A comma separated list of locations of component descriptors. This
   *     must not be <code>null</code>.
   * @throws IllegalStateException If the bundle has already been uninstalled.
   */
  private void initialize(String descriptorLocations) {

    // 112.4.1: The value of the the header is a comma separated list of XML entries within the
    // Bundle
    StringTokenizer st = new StringTokenizer(descriptorLocations, ", ");

    while (st.hasMoreTokens()) {
      String descriptorLocation = st.nextToken();

      URL[] descriptorURLs = findDescriptors(m_context.getBundle(), descriptorLocation);
      if (descriptorURLs.length == 0) {
        // 112.4.1 If an XML document specified by the header cannot be located in the bundle and
        // its attached
        // fragments, SCR must log an error message with the Log Service, if present, and continue.
        log(
            LogService.LOG_ERROR,
            "Component descriptor entry ''{0}'' not found",
            new Object[] {descriptorLocation},
            null,
            null);
        continue;
      }

      // load from the descriptors
      for (int i = 0; i < descriptorURLs.length; i++) {
        loadDescriptor(descriptorURLs[i]);
      }
    }
  }
  public static void indexTargetPlatform(
      OutputStream outputStream,
      List<File> additionalJarFiles,
      long stopWaitTimeout,
      String... dirNames)
      throws Exception {

    Framework framework = null;

    Path tempPath = Files.createTempDirectory(null);

    ClassLoader classLoader = TargetPlatformIndexerUtil.class.getClassLoader();

    try (InputStream inputStream =
        classLoader.getResourceAsStream("META-INF/system.packages.extra.mf")) {

      Map<String, String> properties = new HashMap<>();

      properties.put(Constants.FRAMEWORK_STORAGE, tempPath.toString());

      Manifest extraPackagesManifest = new Manifest(inputStream);

      Attributes attributes = extraPackagesManifest.getMainAttributes();

      properties.put(
          Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, attributes.getValue("Export-Package"));

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

      FrameworkFactory frameworkFactory = serviceLoader.iterator().next();

      framework = frameworkFactory.newFramework(properties);

      framework.init();

      BundleContext bundleContext = framework.getBundleContext();

      Bundle systemBundle = bundleContext.getBundle(0);

      TargetPlatformIndexer targetPlatformIndexer =
          new TargetPlatformIndexer(systemBundle, additionalJarFiles, dirNames);

      targetPlatformIndexer.index(outputStream);
    } finally {
      framework.stop();

      FrameworkEvent frameworkEvent = framework.waitForStop(stopWaitTimeout);

      if (frameworkEvent.getType() == FrameworkEvent.WAIT_TIMEDOUT) {
        throw new Exception(
            "OSGi framework event "
                + frameworkEvent
                + " triggered after a "
                + stopWaitTimeout
                + "ms timeout");
      }

      PathUtil.deltree(tempPath);
    }
  }
  /**
   * Called upon starting of the bundle. This method invokes initialize() which parses the metadata
   * and creates the instance managers
   *
   * @param componentRegistry The <code>ComponentRegistry</code> used to register components with to
   *     ensure uniqueness of component names and to ensure configuration updates.
   * @param context The bundle context owning the components
   * @throws ComponentException if any error occurrs initializing this class
   */
  BundleComponentActivator(
      ComponentRegistry componentRegistry,
      ComponentActorThread componentActor,
      BundleContext context,
      ScrConfiguration configuration)
      throws ComponentException {
    // keep the parameters for later
    m_componentRegistry = componentRegistry;
    m_componentActor = componentActor;
    m_context = context;

    // mark this instance active
    m_active = true;

    // have the LogService handy (if available)
    m_logService = new ServiceTracker(context, Activator.LOGSERVICE_CLASS, null);
    m_logService.open();
    m_configuration = configuration;

    // Get the Metadata-Location value from the manifest
    String descriptorLocations =
        (String) m_context.getBundle().getHeaders().get("Service-Component");
    if (descriptorLocations == null) {
      throw new ComponentException("Service-Component entry not found in the manifest");
    }

    initialize(descriptorLocations);
  }
  private Map<String, Properties> getBundleDefaultProperties(long bundleId) throws IOException {
    Bundle bundle = bundleContext.getBundle(bundleId);
    // Find all property files in main bundle directory
    Enumeration<URL> enumeration = bundle.findEntries("", "*.properties", false);
    Map<String, Properties> allDefaultProperties = new LinkedHashMap<>();

    if (enumeration != null) {
      while (enumeration.hasMoreElements()) {
        InputStream is = null;
        URL url = enumeration.nextElement();
        try {
          is = url.openStream();
          Properties defaultBundleProperties = new Properties();
          defaultBundleProperties.load(is);
          if (!url.getFile().isEmpty()) {
            // We want to store plain filename, without unnecessary slash prefix
            allDefaultProperties.put(url.getFile().substring(1), defaultBundleProperties);
          }
        } catch (IOException e) {
          LOGGER.error("Error while reading or retrieving default properties", e);
        } finally {
          IOUtils.closeQuietly(is);
        }
      }
    }
    return allDefaultProperties;
  }
  public void execute(@Observes(precedence = Integer.MAX_VALUE) EventContext<BeforeSuite> event)
      throws Exception {

    Bundle bundle = FrameworkUtil.getBundle(getClass());

    BundleContext bundleContext = bundle.getBundleContext();

    Filter filter =
        FrameworkUtil.createFilter(
            "(&(objectClass=org.springframework.context.ApplicationContext)"
                + "(org.springframework.context.service.name="
                + bundleContext.getBundle().getSymbolicName()
                + "))");

    ServiceTracker<ApplicationContext, ApplicationContext> serviceTracker =
        new ServiceTracker<>(bundleContext, filter, null);

    serviceTracker.open();

    try {
      serviceTracker.waitForService(30 * 1000L);
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }

    serviceTracker.close();

    event.proceed();
  }
  /**
   * Creates task action event requests for tracked entity instance creation, program enrollment,
   * and program stage events.
   *
   * @return the new Channel Request
   */
  public ChannelRequest build() {

    ProgramActionBuilder programActionBuilder = new ProgramActionBuilder();
    CreateInstanceActionBuilder createInstanceActionBuilder = new CreateInstanceActionBuilder();
    StageActionBuilder stageActionBuilder = new StageActionBuilder();
    SendDataValueSetActionBuilder sendDataValueSetActionBuilder =
        new SendDataValueSetActionBuilder();

    List<ActionEventRequest> actions = new ArrayList<>();

    List<Program> programs = programService.findByRegistration(true);
    actions.addAll(programActionBuilder.build(programs, serverVersion));

    List<Stage> stages = stageService.findAll();
    actions.addAll(stageActionBuilder.build(stages));

    List<TrackedEntityAttribute> attributes = trackedEntityAttributeService.findAll();
    List<TrackedEntity> trackedEntities = trackedEntityService.findAll();
    actions.addAll(createInstanceActionBuilder.build(attributes, trackedEntities));
    actions.addAll(
        sendDataValueSetActionBuilder.addSendDataValueSetActions(dataSetService.findAll()));
    actions.add(addSendDataValue());

    return new ChannelRequest(
        DisplayNames.DHIS2_DISPLAY_NAME,
        bundleContext.getBundle().getSymbolicName(),
        bundleContext.getBundle().getVersion().toString(),
        null,
        new ArrayList<>(),
        actions);
  }