public static IFileArtifactRepository getAggregatedBundleRepository(
      IProvisioningAgent agent, IProfile profile, int repoFilter) {
    List<IFileArtifactRepository> bundleRepositories = new ArrayList<IFileArtifactRepository>();

    // we check for a shared bundle pool first as it should be preferred over the user bundle pool
    // in a shared install
    IArtifactRepositoryManager manager = getArtifactRepositoryManager(agent);
    if ((repoFilter & AGGREGATE_SHARED_CACHE) != 0) {
      String sharedCache = profile.getProperty(IProfile.PROP_SHARED_CACHE);
      if (sharedCache != null) {
        try {
          URI repoLocation = new File(sharedCache).toURI();
          IArtifactRepository repository = manager.loadRepository(repoLocation, null);
          if (repository != null
              && repository instanceof IFileArtifactRepository
              && !bundleRepositories.contains(repository))
            bundleRepositories.add((IFileArtifactRepository) repository);
        } catch (ProvisionException e) {
          // skip repository if it could not be read
        }
      }
    }

    if ((repoFilter & AGGREGATE_CACHE) != 0) {
      IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(agent, profile);
      if (bundlePool != null) bundleRepositories.add(bundlePool);
    }

    if ((repoFilter & AGGREGATE_CACHE_EXTENSIONS) != 0) {
      List<String> repos = getListProfileProperty(profile, CACHE_EXTENSIONS);
      for (String repo : repos) {
        try {
          URI repoLocation;
          try {
            repoLocation = new URI(repo);
          } catch (URISyntaxException e) {
            // in 1.0 we wrote unencoded URL strings, so try as an unencoded string
            repoLocation = URIUtil.fromString(repo);
          }
          IArtifactRepository repository = manager.loadRepository(repoLocation, null);
          if (repository != null
              && repository instanceof IFileArtifactRepository
              && !bundleRepositories.contains(repository))
            bundleRepositories.add((IFileArtifactRepository) repository);
        } catch (ProvisionException e) {
          // skip repositories that could not be read
        } catch (URISyntaxException e) {
          // unexpected, URLs should be pre-checked
          LogHelper.log(new Status(IStatus.ERROR, Activator.ID, e.getMessage(), e));
        }
      }
    }
    return new AggregatedBundleRepository(agent, bundleRepositories);
  }
  private Repositories loadRepositories(String id, URI specifiedUrl) throws Exception {

    IRepositoryIdManager idManager =
        (IRepositoryIdManager) subject.getService(IRepositoryIdManager.SERVICE_NAME);
    idManager.addMapping(id, specifiedUrl);

    IMetadataRepositoryManager metadataManager =
        (IMetadataRepositoryManager) subject.getService(IMetadataRepositoryManager.SERVICE_NAME);
    IMetadataRepository metadataRepo = metadataManager.loadRepository(specifiedUrl, null);

    IArtifactRepositoryManager artifactsManager =
        (IArtifactRepositoryManager) subject.getService(IArtifactRepositoryManager.SERVICE_NAME);
    IArtifactRepository artifactsRepo = artifactsManager.loadRepository(specifiedUrl, null);

    return new Repositories(metadataRepo, artifactsRepo);
  }
  /**
   * Finds available WSO2 features in current profile and search for updates to them in WSO2 p2
   * repository for updates.
   *
   * @param monitor
   * @throws Exception
   */
  public void checkForAvailableUpdates(IProgressMonitor monitor) throws Exception {
    if (monitor == null) {
      monitor = new NullProgressMonitor();
    }
    SubMonitor progress = SubMonitor.convert(monitor, Messages.UpdateManager_18, 6);

    // get all available IUs in update repository
    IMetadataRepository metadataRepo =
        metadataRepoManager.loadRepository(getDevStudioUpdateSite(), progress.newChild(1));
    IQuery<IInstallableUnit> allIUQuery = QueryUtil.createIUAnyQuery();
    IQueryResult<IInstallableUnit> allIUQueryResult =
        metadataRepo.query(allIUQuery, progress.newChild(1));

    // read artifact repository for updates
    IArtifactRepository artifactRepo =
        artifactRepoManager.loadRepository(getDevStudioUpdateSite(), progress.newChild(1));

    // read meta-data of all available features
    Map<String, EnhancedFeature> allFeaturesInUpdateRepo =
        loadWSO2FeaturesInRepo(artifactRepo, allIUQueryResult, progress.newChild(1));

    // get all installed wso2 features
    Collection<IInstallableUnit> installedWSO2Features =
        getInstalledWSO2Features(progress.newChild(1));

    installedWSO2FeaturesMap = new HashMap<String, IInstallableUnit>();
    for (IInstallableUnit iInstallableUnit : installedWSO2Features) {
      installedWSO2FeaturesMap.put(iInstallableUnit.getId(), iInstallableUnit);
    }

    if (progress.isCanceled()) {
      throw new OperationCanceledException();
    }

    URI[] repos = new URI[] {getDevStudioUpdateSite()};
    updateOperation = new UpdateOperation(session, installedWSO2Features);
    updateOperation.getProvisioningContext().setArtifactRepositories(repos);
    updateOperation.getProvisioningContext().setMetadataRepositories(repos);

    // resolve update operation
    IStatus status = updateOperation.resolveModal(progress.newChild(1));
    // user cancelled the job while resolving
    if (status.getSeverity() == IStatus.CANCEL || progress.isCanceled()) {
      throw new OperationCanceledException();
    }
    // there is nothing to update
    if (status.getCode() == UpdateOperation.STATUS_NOTHING_TO_UPDATE) {
      featuresWithPossibleUpdates = new HashMap<String, EnhancedFeature>();
      log.info(Messages.UpdateManager_19);
    } else if (status.getSeverity() == IStatus.ERROR) { // resolution errors
      // something wrong with the updates
      log.info(Messages.UpdateManager_20);
    } else {
      // good to proceed installing updates
      setPossibleUpdates(updateOperation.getPossibleUpdates(), allFeaturesInUpdateRepo);
    }
  }
 public static synchronized IFileArtifactRepository getBundlePoolRepository(
     IProvisioningAgent agent, IProfile profile) {
   URI location = getBundlePoolLocation(agent, profile);
   if (location == null) return null;
   IArtifactRepositoryManager manager = getArtifactRepositoryManager(agent);
   try {
     return (IFileArtifactRepository) manager.loadRepository(location, null);
   } catch (ProvisionException e) {
     // the repository doesn't exist, so fall through and create a new one
   }
   try {
     String repositoryName = Messages.BundlePool;
     Map<String, String> properties = new HashMap<String, String>(1);
     properties.put(IRepository.PROP_SYSTEM, Boolean.TRUE.toString());
     return (IFileArtifactRepository)
         manager.createRepository(location, repositoryName, REPOSITORY_TYPE, properties);
   } catch (ProvisionException e) {
     LogHelper.log(e);
     throw new IllegalArgumentException(NLS.bind(Messages.bundle_pool_not_writeable, location));
   }
 }
 public static void updateRepositoryUsingElements(
     final ProvisioningUI ui, final MetadataRepositoryElement[] elements) {
   ui.signalRepositoryOperationStart();
   IMetadataRepositoryManager metaManager = ProvUI.getMetadataRepositoryManager(ui.getSession());
   IArtifactRepositoryManager artManager = ProvUI.getArtifactRepositoryManager(ui.getSession());
   try {
     int visibilityFlags = ui.getRepositoryTracker().getMetadataRepositoryFlags();
     URI[] currentlyEnabled = metaManager.getKnownRepositories(visibilityFlags);
     URI[] currentlyDisabled =
         metaManager.getKnownRepositories(
             IRepositoryManager.REPOSITORIES_DISABLED | visibilityFlags);
     for (int i = 0; i < elements.length; i++) {
       URI location = elements[i].getLocation();
       if (elements[i].isEnabled()) {
         if (containsURI(currentlyDisabled, location))
           // It should be enabled and is not currently
           setColocatedRepositoryEnablement(ui, location, true);
         else if (!containsURI(currentlyEnabled, location)) {
           // It is not known as enabled or disabled.  Add it.
           metaManager.addRepository(location);
           artManager.addRepository(location);
         }
       } else {
         if (containsURI(currentlyEnabled, location))
           // It should be disabled, and is currently enabled
           setColocatedRepositoryEnablement(ui, location, false);
         else if (!containsURI(currentlyDisabled, location)) {
           // It is not known as enabled or disabled.  Add it and then disable it.
           metaManager.addRepository(location);
           artManager.addRepository(location);
           setColocatedRepositoryEnablement(ui, location, false);
         }
       }
       String name = elements[i].getName();
       if (name != null && name.length() > 0) {
         metaManager.setRepositoryProperty(location, IRepository.PROP_NICKNAME, name);
         artManager.setRepositoryProperty(location, IRepository.PROP_NICKNAME, name);
       }
     }
     // Are there any elements that need to be deleted?  Go over the original state
     // and remove any elements that weren't in the elements we were given
     Set<String> nowKnown = new HashSet<String>();
     for (int i = 0; i < elements.length; i++)
       nowKnown.add(URIUtil.toUnencodedString(elements[i].getLocation()));
     for (int i = 0; i < currentlyEnabled.length; i++) {
       if (!nowKnown.contains(URIUtil.toUnencodedString(currentlyEnabled[i]))) {
         metaManager.removeRepository(currentlyEnabled[i]);
         artManager.removeRepository(currentlyEnabled[i]);
       }
     }
     for (int i = 0; i < currentlyDisabled.length; i++) {
       if (!nowKnown.contains(URIUtil.toUnencodedString(currentlyDisabled[i]))) {
         metaManager.removeRepository(currentlyDisabled[i]);
         artManager.removeRepository(currentlyDisabled[i]);
       }
     }
   } finally {
     ui.signalRepositoryOperationComplete(null, true);
   }
 }
 private IMetadataRepository[] addRepositories(String spec) {
   String[] locations = spec.split(",");
   ArrayList result = new ArrayList();
   for (int i = 0; i < locations.length; i++) {
     URI location = null;
     try {
       location = new URI(locations[i].trim());
       metadataManager.loadRepository(location, null);
       result.add(metadataManager.loadRepository(location, null));
       artifactManager.addRepository(location);
     } catch (URISyntaxException e) {
       LogUtility.logError("Invalid URI for repository " + location, e);
     } catch (ProvisionException e) {
       LogUtility.logWarning("Unable to load repository " + location, e);
     }
   }
   return (IMetadataRepository[]) result.toArray(new IMetadataRepository[result.size()]);
 }
  /**
   * Searches available features in WSO2 p2 repository for the current version of Developer Studio
   * and filters new features that can be installed.
   *
   * @param monitor
   * @throws Exception
   */
  public void checkForAvailableFeatures(IProgressMonitor monitor) throws Exception {
    if (monitor == null) {
      monitor = new NullProgressMonitor();
    }
    SubMonitor progress = SubMonitor.convert(monitor, Messages.UpdateManager_21, 5);

    // get all available IUs in release repository
    IMetadataRepository metadataRepository =
        metadataRepoManager.loadRepository(getDevStudioReleaseSite(), progress.newChild(1));
    IQuery<IInstallableUnit> allIUQuery = QueryUtil.createIUAnyQuery();
    IQueryResult<IInstallableUnit> allIUQueryResult =
        metadataRepository.query(allIUQuery, progress.newChild(1));

    // load artifact repository for releases
    IArtifactRepository artifactRepository =
        artifactRepoManager.loadRepository(getDevStudioReleaseSite(), progress.newChild(1));

    // read meta-data of all available features
    Map<String, EnhancedFeature> allFeaturesInReleaseRepo =
        loadWSO2FeaturesInRepo(artifactRepository, allIUQueryResult, progress.newChild(1));

    Collection<IInstallableUnit> filteredIUs =
        filterInstallableUnits(
            WSO2_FEATURE_PREFIX, FEATURE_GROUP_IU_ID_SFX, allIUQueryResult, progress.newChild(1));
    allAvailableFeatures = new HashMap<String, IInstallableUnit>();
    availableNewFeatures = new HashMap<String, EnhancedFeature>();
    for (IInstallableUnit iInstallableUnit : filteredIUs) {
      allAvailableFeatures.put(iInstallableUnit.getId(), iInstallableUnit);
      if (!installedWSO2FeaturesMap.containsKey(iInstallableUnit.getId())) {
        availableNewFeatures.put(
            iInstallableUnit.getId(), allFeaturesInReleaseRepo.get(iInstallableUnit.getId()));
      } else {
        Version versionInstalled =
            installedWSO2FeaturesMap.get(iInstallableUnit.getId()).getVersion();
        // if the version we have is greater than the installed version view it in the available
        // feature list
        if (versionInstalled != null
            && (iInstallableUnit.getVersion().compareTo(versionInstalled) == 1)) {
          availableNewFeatures.put(
              iInstallableUnit.getId(), allFeaturesInReleaseRepo.get(iInstallableUnit.getId()));
        }
      }
    }
  }