@Override
  public void deploy(final DeploymentPhaseContext phaseContext)
      throws DeploymentUnitProcessingException {

    // Check if we already have an OSGi deployment
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    Deployment deployment = OSGiDeploymentAttachment.getDeployment(deploymentUnit);

    ServiceRegistry serviceRegistry = phaseContext.getServiceRegistry();
    String location =
        DeploymentHolderService.getLocation(serviceRegistry, deploymentUnit.getName());
    VirtualFile virtualFile = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot();

    // Check for attached BundleInfo
    BundleInfo info = BundleInfoAttachment.getBundleInfo(deploymentUnit);
    if (deployment == null && info != null) {
      deployment = DeploymentFactory.createDeployment(info);
      deployment.addAttachment(BundleInfo.class, info);
      OSGiDeploymentAttachment.attachDeployment(deploymentUnit, deployment);
    }

    // Check for attached OSGiMetaData
    OSGiMetaData metadata = OSGiMetaDataAttachment.getOSGiMetaData(deploymentUnit);
    if (deployment == null && metadata != null) {
      String symbolicName = metadata.getBundleSymbolicName();
      Version version = metadata.getBundleVersion();
      deployment =
          DeploymentFactory.createDeployment(
              AbstractVFS.adapt(virtualFile), location, symbolicName, version);
      deployment.addAttachment(OSGiMetaData.class, metadata);
      OSGiDeploymentAttachment.attachDeployment(deploymentUnit, deployment);
    }

    // Check for attached XModule
    XModule resModule = XModuleAttachment.getXModuleAttachment(deploymentUnit);
    if (deployment == null && resModule != null) {
      String symbolicName = resModule.getName();
      Version version = resModule.getVersion();
      deployment =
          DeploymentFactory.createDeployment(
              AbstractVFS.adapt(virtualFile), location, symbolicName, version);
      deployment.addAttachment(XModule.class, resModule);
      OSGiDeploymentAttachment.attachDeployment(deploymentUnit, deployment);
    }

    // Create the {@link OSGiDeploymentService}
    if (deployment != null) {

      // Prevent garbage collection of the MountHandle which will close the file
      MountHandle mount =
          deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT).getMountHandle();
      deployment.addAttachment(MountHandle.class, mount);

      // Mark the bundle to start automatically
      deployment.setAutoStart(true);

      OSGiDeploymentService.addService(phaseContext);
    }
  }
  @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 ServiceName getServiceName(Deployment dep, int state) {
   // Currently the bundleId is needed for uniqueness because of
   // [MSC-97] Cannot re-install service with same name
   Long bundleId = dep.getAttachment(Long.class);
   ServiceName serviceName =
       ServiceName.of(
           BUNDLE_BASE_NAME, "" + bundleId, "" + dep.getSymbolicName(), "" + dep.getVersion());
   if (state == Bundle.INSTALLED || state == Bundle.RESOLVED || state == Bundle.ACTIVE) {
     serviceName = serviceName.append(ConstantsHelper.bundleState(state));
   }
   return serviceName;
 }
  @Override
  protected InvocationContext getInvocationContext(Bundle bundle) {
    if (bundle == null) throw MESSAGES.illegalArgumentNull("bundle");

    UserBundleState userBundle = UserBundleState.assertBundleState(bundle);
    Deployment dep = userBundle.getDeployment();

    InvocationContext inv = dep.getAttachment(INVOCATION_CONTEXT_KEY);
    if (inv == null) {
      // TODO: support multiple roots defined in Bundle-ClassPath
      VirtualFile rootFile = userBundle.getDeployment().getRoot();
      Attachable att = new AttachableSupport() {};
      inv = new AbstractInvocationContext(systemContext, userBundle, rootFile, att);
      dep.putAttachment(INVOCATION_CONTEXT_KEY, inv);
    }
    return inv;
  }
 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;
 }
  /** Get the {@link org.jboss.as.server.deployment.DeploymentUnit} name for the given deployment */
  public static String getContextName(Deployment dep) {
    String name = dep.getLocation();

    // The location prefix for non-osgi modules
    String prefix = "module:deployment.";
    if (name.startsWith(prefix)) name = name.substring(prefix.length());

    if (name.endsWith("/")) name = name.substring(0, name.length() - 1);
    int idx = name.lastIndexOf("/");
    if (idx > 0) name = name.substring(idx + 1);

    return name;
  }
 @Override
 public void uninstallBundle(Deployment dep) {
   Bundle bundle = dep.getAttachment(Bundle.class);
   UserBundleState userBundle = UserBundleState.assertBundleState(bundle);
   uninstallBundle(userBundle, 0);
 }