@Override
  public ServiceName installBundle(
      Deployment dep, ServiceTarget serviceTarget, ServiceListener<XBundle> listener)
      throws BundleException {
    if (dep == null) throw MESSAGES.illegalArgumentNull("deployment");

    ServiceName serviceName;

    // If a bundle containing the same location identifier is already installed,
    // the Bundle object for that bundle is returned.
    XBundle bundle = getBundleByLocation(dep.getLocation());
    if (bundle instanceof AbstractBundleState) {
      LOGGER.debugf("Installing an already existing bundle: %s", dep);
      AbstractBundleState bundleState = AbstractBundleState.assertBundleState(bundle);
      serviceName = bundleState.getServiceName(Bundle.INSTALLED);
      VFSUtils.safeClose(dep.getRoot());
    } else {
      try {
        Long bundleId;
        String symbolicName = dep.getSymbolicName();
        XEnvironment env = injectedEnvironment.getValue();

        // The storage state exists when we re-create the bundle from persistent storage
        StorageState storageState = dep.getAttachment(StorageState.class);
        if (storageState != null) {
          LOGGER.debugf("Found storage state: %s", storageState);
          bundleId = env.nextResourceIdentifier(storageState.getBundleId(), symbolicName);
        } else {
          bundleId = env.nextResourceIdentifier(null, symbolicName);
        }
        dep.addAttachment(Long.class, bundleId);

        // Check that we have valid metadata
        OSGiMetaData metadata = dep.getAttachment(OSGiMetaData.class);
        if (metadata == null) {
          DeploymentFactoryPlugin plugin = getFrameworkState().getDeploymentFactoryPlugin();
          metadata = plugin.createOSGiMetaData(dep);
        }

        // Create the bundle services
        if (metadata.getFragmentHost() == null) {
          serviceName =
              HostBundleInstalledService.addService(
                  serviceTarget, getFrameworkState(), dep, listener);
        } else {
          serviceName =
              FragmentBundleInstalledService.addService(
                  serviceTarget, getFrameworkState(), dep, listener);
        }
      } catch (RuntimeException rte) {
        VFSUtils.safeClose(dep.getRoot());
        throw rte;
      } catch (BundleException ex) {
        VFSUtils.safeClose(dep.getRoot());
        throw ex;
      }
    }
    dep.addAttachment(ServiceName.class, serviceName);
    return serviceName;
  }
 @Override
 public void start(StartContext context) throws StartException {
   LOGGER.infoFrameworkImplementation(implementationVersion);
   serviceTarget = context.getChildTarget();
   LOGGER.debugf("Framework properties");
   for (Entry<String, Object> entry : properties.entrySet()) {
     LOGGER.debugf(" %s = %s", entry.getKey(), entry.getValue());
   }
 }
 void awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
   LOGGER.debugf("awaitTermination: %dms", unit.toMillis(timeout));
   synchronized (shutdownInitiated) {
     if (shutdownInitiated.get() == false) {
       LOGGER.debugf("shutdownInitiated.wait");
       shutdownInitiated.wait(2000);
     }
   }
   serviceContainer.awaitTermination(timeout == 0 ? Long.MAX_VALUE : timeout, unit);
 }
  void removeBundle(UserBundleState userBundle, int options) {
    LOGGER.tracef("Start removing bundle: %s", userBundle);

    if ((options & Bundle.STOP_TRANSIENT) == 0) {
      BundleStoragePlugin storagePlugin = getFrameworkState().getBundleStoragePlugin();
      storagePlugin.deleteStorageState(userBundle.getStorageState());
    }

    XEnvironment env = getFrameworkState().getEnvironment();
    for (XBundleRevision abr : userBundle.getAllBundleRevisions()) {
      env.uninstallResources(abr);
    }

    FrameworkEventsPlugin eventsPlugin = getFrameworkState().getFrameworkEventsPlugin();
    eventsPlugin.fireBundleEvent(userBundle, BundleEvent.UNRESOLVED);

    ModuleManagerPlugin moduleManager = getFrameworkState().getModuleManagerPlugin();
    for (XBundleRevision brev : userBundle.getAllBundleRevisions()) {
      UserBundleRevision userRev = (UserBundleRevision) brev;
      if (userRev.isFragment() == false) {
        ModuleIdentifier identifier = moduleManager.getModuleIdentifier(brev);
        moduleManager.removeModule(brev, identifier);
      }
      userRev.close();
    }

    LOGGER.debugf("Removed bundle: %s", userBundle);
  }
 void shutdown() {
   if (allowContainerShutdown) {
     serviceContainer.shutdown();
     synchronized (shutdownInitiated) {
       shutdownInitiated.set(true);
       LOGGER.debugf("shutdownInitiated.notifyAll");
       shutdownInitiated.notifyAll();
     }
   }
 }
 public void start(final StartContext context) throws StartException {
   ServiceController<?> controller = context.getController();
   LOGGER.tracef("Starting: %s", controller.getName());
   List<Bundle> bundles = new ArrayList<Bundle>(installedBundles);
   Collections.sort(bundles, new BundleComparator());
   for (Bundle bundle : bundles) {
     TypeAdaptor adaptor = (TypeAdaptor) bundle;
     Deployment dep = adaptor.adapt(Deployment.class);
     OSGiMetaData metadata = adaptor.adapt(OSGiMetaData.class);
     if (dep.isAutoStart() && metadata.getFragmentHost() == null) {
       try {
         bundle.start(Bundle.START_ACTIVATION_POLICY);
       } catch (BundleException ex) {
         LOGGER.errorCannotStartBundle(ex, bundle);
       }
     }
   }
   LOGGER.debugf("Started: %s", controller.getName());
   installedBundles = null;
   tracker = null;
 }
  void shutdownManager(boolean stopForUpdate) {

    // If the Framework is not STARTING and not ACTIVE there is nothing to do
    int state = getManagerState();
    if (state != Bundle.STARTING && state != Bundle.ACTIVE) return;

    LOGGER.debugf("Stop framework");

    stoppedEvent = stopForUpdate ? FrameworkEvent.STOPPED_UPDATE : FrameworkEvent.STOPPED;
    getSystemBundle().changeState(Bundle.STOPPING);
    setManagerState(Bundle.STOPPING);

    // Move to start level 0 in the current thread
    FrameworkCoreServices coreServices = getFrameworkState().getCoreServices();
    StartLevelPlugin startLevel = coreServices.getStartLevelPlugin();
    if (startLevel != null) {
      startLevel.decreaseStartLevel(0);
    } else {
      // No Start Level Service available, stop all bundles individually...
      // All installed bundles must be stopped without changing each bundle's persistent autostart
      // setting
      for (Bundle bundle : getBundles()) {
        if (bundle.getBundleId() != 0) {
          try {
            bundle.stop(Bundle.STOP_TRANSIENT);
          } catch (Exception ex) {
            // Any exceptions that occur during bundle stopping must be wrapped in a BundleException
            // and then
            // published as a framework event of type FrameworkEvent.ERROR
            fireFrameworkError(bundle, "stopping bundle", ex);
          }
        }
      }
    }

    cachedSystemBundle = getSystemBundle();
    shutdownContainer.shutdown();
    setManagerState(Bundle.RESOLVED);
  }
 void setServiceMode(ServiceName serviceName, Mode mode) {
   ServiceController<?> controller = serviceContainer.getService(serviceName);
   if (controller == null)
     LOGGER.debugf("Cannot set mode %s on non-existing service: %s", mode, serviceName);
   else setServiceMode(controller, mode);
 }