protected void handleAdd() {
    ElementListSelectionDialog dialog =
        new ElementListSelectionDialog(getShell(), new StyledBundleLabelProvider(false, false));

    try {
      dialog.setElements(getValidBundles());
    } catch (CoreException e) {
      dialog.setMessage(e.getMessage());
    }

    dialog.setTitle(PDEUIMessages.PluginSelectionDialog_title);
    dialog.setMessage(PDEUIMessages.PluginSelectionDialog_message);
    dialog.setMultipleSelection(true);
    if (dialog.open() == Window.OK) {

      Object[] models = dialog.getResult();
      ArrayList<NameVersionDescriptor> pluginsToAdd = new ArrayList<NameVersionDescriptor>();
      for (int i = 0; i < models.length; i++) {
        BundleInfo desc = ((BundleInfo) models[i]);
        pluginsToAdd.add(new NameVersionDescriptor(desc.getSymbolicName(), null));
      }
      Set<NameVersionDescriptor> allDependencies = new HashSet<NameVersionDescriptor>();
      allDependencies.addAll(pluginsToAdd);
      NameVersionDescriptor[] currentBundles = getTargetDefinition().getImplicitDependencies();
      if (currentBundles != null) {
        allDependencies.addAll(Arrays.asList(currentBundles));
      }
      getTargetDefinition()
          .setImplicitDependencies(
              allDependencies.toArray(new NameVersionDescriptor[allDependencies.size()]));
      fElementViewer.refresh();
      updateImpButtons();
    }
  }
  /**
   * Gets a list of all the bundles that can be added as implicit dependencies
   *
   * @return list of possible dependencies
   */
  protected BundleInfo[] getValidBundles() throws CoreException {
    NameVersionDescriptor[] current = getTargetDefinition().getImplicitDependencies();
    Set<String> currentBundles = new HashSet<String>();
    if (current != null) {
      for (int i = 0; i < current.length; i++) {
        if (!currentBundles.contains(current[i].getId())) {
          currentBundles.add(current[i].getId());
        }
      }
    }

    List<BundleInfo> targetBundles = new ArrayList<BundleInfo>();
    TargetBundle[] allTargetBundles = getTargetDefinition().getAllBundles();
    if (allTargetBundles == null || allTargetBundles.length == 0) {
      throw new CoreException(
          new Status(
              IStatus.WARNING,
              PDEPlugin.getPluginId(),
              PDEUIMessages.ImplicitDependenciesSection_0));
    }
    for (int i = 0; i < allTargetBundles.length; i++) {
      BundleInfo bundleInfo = allTargetBundles[i].getBundleInfo();
      if (!currentBundles.contains(bundleInfo.getSymbolicName())) {
        currentBundles.add(bundleInfo.getSymbolicName()); // to avoid duplicate entries
        targetBundles.add(bundleInfo);
      }
    }

    return targetBundles.toArray(new BundleInfo[targetBundles.size()]);
  }
  public XMLComparePreferencePage() {
    super();

    fIdMaps = new HashMap();
    XMLPlugin plugin = XMLPlugin.getDefault();
    HashMap PluginIdMaps = plugin.getIdMaps();
    Set keySet = PluginIdMaps.keySet();
    for (Iterator iter = keySet.iterator(); iter.hasNext(); ) {
      String key = (String) iter.next();
      fIdMaps.put(key, ((HashMap) PluginIdMaps.get(key)).clone());
    }
    fIdMapsInternal = plugin.getIdMapsInternal();

    fIdExtensionToName = new HashMap();
    HashMap PluginIdExtensionToName = plugin.getIdExtensionToName();
    keySet = PluginIdExtensionToName.keySet();
    for (Iterator iter = keySet.iterator(); iter.hasNext(); ) {
      String key = (String) iter.next();
      fIdExtensionToName.put(key, PluginIdExtensionToName.get(key));
    }

    fOrderedElements = new HashMap();
    HashMap PluginOrderedElements = plugin.getOrderedElements();
    keySet = PluginOrderedElements.keySet();
    for (Iterator iter = keySet.iterator(); iter.hasNext(); ) {
      String key = (String) iter.next();
      fOrderedElements.put(key, ((ArrayList) PluginOrderedElements.get(key)).clone());
    }

    fOrderedElementsInternal = plugin.getOrderedElementsInternal();
  }
 private void computeSelected(Collection initialSelection) {
   if (initialSelection == null || initialSelection.size() == 0) return;
   Set selected = new HashSet();
   Iterator iter = initialSelection.iterator();
   while (iter.hasNext()) {
     Object obj = iter.next();
     if (obj instanceof IProject) {
       IMonitorModelBase model = MonitorRegistry.findModel((IProject) obj);
       if (model != null) {
         selected.add(model);
       }
     }
   }
   fSelected = (IMonitorModelBase[]) selected.toArray(new IMonitorModelBase[selected.size()]);
 }
 @Override
 protected void refreshPage() {
   fAvailableListViewer.addFilter(fSourceFilter);
   fImportListViewer.getTable().removeAll();
   fSelected.clear();
   fAvailableFilter.setPattern("*"); // $NON-NLS-1$
   fSourceFilter.setState(fPage1.getState());
   fVersionFilter.setModel(fModels);
   fAvailableListViewer.refresh();
   pageChanged();
 }
  protected void fillIdMapsTable() {
    // fill user idmaps from plugin.xml
    fillIdMaps(true);

    // fill user idmaps from Preference Store
    fillIdMaps(false);

    // add user idmaps that have ordered entries but no id mappings
    // they do not appear in the preference store with name IDMAP_PREFERENCE_NAME
    Set OrderedKeys = fOrderedElements.keySet();
    Set IdMapKeys = fIdMaps.keySet();
    for (Iterator iter_orderedElements = OrderedKeys.iterator(); iter_orderedElements.hasNext(); ) {
      String IdMapName = (String) iter_orderedElements.next();
      if (!IdMapKeys.contains(IdMapName)) {
        IdMap idmap = new IdMap(IdMapName, false);
        ArrayList idmapOrdered = (ArrayList) fOrderedElements.get(IdMapName);
        setOrdered(idmap, idmapOrdered);
        newIdMapsTableItem(idmap, false);
      }
    }
  }
  private boolean handleRemove() {
    IStructuredSelection ssel = (IStructuredSelection) fCategoryViewer.getSelection();
    Iterator<?> iterator = ssel.iterator();
    boolean success = true;
    Set<?> removedCategories = new HashSet<Object>();
    while (iterator.hasNext()) {
      Object object = iterator.next();
      if (object == null) continue;
      if (object instanceof ISiteCategoryDefinition) {
        if (!handleRemoveCategoryDefinition((ISiteCategoryDefinition) object)) {
          success = false;
        }
      } else {
        // check if some of features was not removed during category removal
        SiteFeatureAdapter fa = (SiteFeatureAdapter) object;
        if (removedCategories.contains(fa.category)) continue;

        if (!handleRemoveSiteFeatureAdapter(fa)) {
          success = false;
        }
      }
    }
    return success;
  }
 private void fillIdMaps(boolean internal) {
   HashMap IdMaps = (internal) ? fIdMapsInternal : fIdMaps;
   HashMap OrderedElements = (internal) ? fOrderedElementsInternal : fOrderedElements;
   Set IdMapKeys = IdMaps.keySet();
   for (Iterator iter_internal = IdMapKeys.iterator(); iter_internal.hasNext(); ) {
     String IdMapName = (String) iter_internal.next();
     Vector Mappings = new Vector();
     IdMap idmap = new IdMap(IdMapName, internal, Mappings);
     // create mappings of internal idmaps
     HashMap idmapHM = (HashMap) IdMaps.get(IdMapName);
     Set idmapKeys = idmapHM.keySet();
     for (Iterator iter_idmap = idmapKeys.iterator(); iter_idmap.hasNext(); ) {
       Mapping mapping = new Mapping();
       String signature = (String) iter_idmap.next();
       int end_of_signature = signature.lastIndexOf(SIGN_SEPARATOR, signature.length() - 2);
       if (end_of_signature < XMLStructureCreator.ROOT_ID.length() + 1)
         mapping.setSignature(""); // $NON-NLS-1$
       else
         mapping.setSignature(
             signature.substring(XMLStructureCreator.ROOT_ID.length() + 1, end_of_signature));
       mapping.setElement(signature.substring(end_of_signature + 1, signature.length() - 1));
       mapping.setIdAttribute((String) idmapHM.get(signature));
       Mappings.add(mapping);
     }
     // create ordered mappings
     ArrayList idmapOrdered = (ArrayList) OrderedElements.get(IdMapName);
     if (idmapOrdered != null) {
       setOrdered(idmap, idmapOrdered);
     }
     // set extension
     if (fIdExtensionToName.containsValue(IdMapName)) {
       Set keySet = fIdExtensionToName.keySet();
       String extension = new String();
       for (Iterator iter = keySet.iterator(); iter.hasNext(); ) {
         extension = (String) iter.next();
         if (((String) fIdExtensionToName.get(extension)).equals(IdMapName)) break;
       }
       idmap.setExtension(extension);
     }
     newIdMapsTableItem(idmap, false);
   }
 }
 private void doRemove(List<Object> items) {
   fSelected.removeAll(items);
   fImportListViewer.remove(items.toArray());
   fAvailableListViewer.add(items.toArray());
 }
 /**
  * Delimits a comma separated preference and add the items to the given set
  *
  * @param set
  * @param preference
  */
 private void addExtraChoices(Set<String> set, String preference) {
   StringTokenizer tokenizer = new StringTokenizer(preference, ","); // $NON-NLS-1$
   while (tokenizer.hasMoreTokens()) {
     set.add(tokenizer.nextToken().trim());
   }
 }
  /**
   * Uses the target state to determine all bundles required by the currently checked bundles and
   * returns them so they can be checked in the tree.
   *
   * @param allBundles list of all bundles to search requirements in
   * @param checkedBundles list of bundles to get requirements for
   * @return list of resolved bundles from the collection to be checked
   */
  private Object[] getRequiredPlugins(final Collection allBundles, final Object[] checkedBundles) {
    final Set dependencies = new HashSet();
    IRunnableWithProgress op =
        new IRunnableWithProgress() {
          public void run(IProgressMonitor monitor) {
            try {
              monitor.beginTask(Messages.TargetContentsGroup_5, 150);

              // Get all the bundle locations
              List allLocations = new ArrayList(allBundles.size());
              for (Iterator iterator = allBundles.iterator(); iterator.hasNext(); ) {
                IResolvedBundle current = (IResolvedBundle) iterator.next();
                try {
                  // Some bundles, such as those with errors, may not have locations
                  URI location = current.getBundleInfo().getLocation();
                  if (location != null) {
                    allLocations.add(new File(location).toURL());
                  }
                } catch (MalformedURLException e) {
                  PDEPlugin.log(e);
                  monitor.setCanceled(true);
                  return;
                }
              }
              if (monitor.isCanceled()) {
                return;
              }
              monitor.worked(20);

              // Create a PDE State containing all of the target bundles
              PDEState state =
                  new PDEState(
                      (URL[]) allLocations.toArray(new URL[allLocations.size()]),
                      true,
                      new SubProgressMonitor(monitor, 50));
              if (monitor.isCanceled()) {
                return;
              }

              // Figure out which of the models have been checked
              IPluginModelBase[] models = state.getTargetModels();
              List checkedModels = new ArrayList(checkedBundles.length);
              for (int i = 0; i < checkedBundles.length; i++) {
                if (checkedBundles[i] instanceof IResolvedBundle) {
                  BundleInfo bundle = ((IResolvedBundle) checkedBundles[i]).getBundleInfo();
                  for (int j = 0; j < models.length; j++) {
                    if (models[j]
                            .getBundleDescription()
                            .getSymbolicName()
                            .equals(bundle.getSymbolicName())
                        && models[j]
                            .getBundleDescription()
                            .getVersion()
                            .toString()
                            .equals(bundle.getVersion())) {
                      checkedModels.add(models[j]);
                      break;
                    }
                  }
                }
              }
              monitor.worked(20);
              if (monitor.isCanceled()) {
                return;
              }

              // Get implicit dependencies as a list of strings
              // This is wasteful since the dependency calculation puts them back into BundleInfos
              NameVersionDescriptor[] implicitDependencies =
                  fTargetDefinition.getImplicitDependencies();
              List implicitIDs = new ArrayList();
              if (implicitDependencies != null) {
                for (int i = 0; i < implicitDependencies.length; i++) {
                  implicitIDs.add(implicitDependencies[i].getId());
                }
              }
              monitor.worked(10);

              // Get all dependency bundles
              // exclude "org.eclipse.ui.workbench.compatibility" - it is only needed for pre-3.0
              // bundles
              dependencies.addAll(
                  DependencyManager.getDependencies(
                      checkedModels.toArray(),
                      (String[]) implicitIDs.toArray(new String[implicitIDs.size()]),
                      state.getState(),
                      new String[] {"org.eclipse.ui.workbench.compatibility"})); // $NON-NLS-1$
              monitor.worked(50);

            } finally {
              monitor.done();
            }
          }
        };
    try {
      // Calculate the dependencies
      new ProgressMonitorDialog(fTree.getControl().getShell()).run(true, true, op);

      // We want to check the dependents, the source of the dependents, and the source of the
      // originally checked
      Set checkedNames = new HashSet(checkedBundles.length);
      for (int i = 0; i < checkedBundles.length; i++) {
        if (checkedBundles[i] instanceof IResolvedBundle) {
          checkedNames.add(((IResolvedBundle) checkedBundles[i]).getBundleInfo().getSymbolicName());
        }
      }

      List toCheck = new ArrayList();
      for (Iterator iterator = fAllBundles.iterator(); iterator.hasNext(); ) {
        IResolvedBundle bundle = (IResolvedBundle) iterator.next();
        if (bundle.isSourceBundle()) {
          String name = bundle.getSourceTarget().getSymbolicName();
          if (name != null && (dependencies.contains(name) || checkedNames.contains(name))) {
            toCheck.add(bundle);
          }
        } else if (dependencies.contains(bundle.getBundleInfo().getSymbolicName())) {
          toCheck.add(bundle);
        }
      }
      return toCheck.toArray();
    } catch (InvocationTargetException e) {
      PDEPlugin.log(e);
    } catch (InterruptedException e) {
    }

    return new Object[0];
  }
  public void saveIncludedBundleState() {
    if (fFeaureModeButton.getSelection()) {
      // Create a list of checked bundle infos
      List included = new ArrayList();
      int missingCount = 0;
      Object[] checked = fTree.getCheckedLeafElements();
      for (int i = 0; i < checked.length; i++) {
        if (checked[i] instanceof IFeatureModel) {
          included.add(
              new NameVersionDescriptor(
                  ((IFeatureModel) checked[i]).getFeature().getId(),
                  null,
                  NameVersionDescriptor.TYPE_FEATURE));
        }
        if (checked[i] instanceof IResolvedBundle) {
          // Missing features are included as IResolvedBundles, save them as features instead
          if (((IResolvedBundle) checked[i]).getStatus().getCode()
              == IResolvedBundle.STATUS_PLUGIN_DOES_NOT_EXIST) {
            included.add(
                new NameVersionDescriptor(
                    ((IResolvedBundle) checked[i]).getBundleInfo().getSymbolicName(),
                    null,
                    NameVersionDescriptor.TYPE_PLUGIN));
            missingCount++;
          } else if (((IResolvedBundle) checked[i]).getStatus().getCode()
              == IResolvedBundle.STATUS_FEATURE_DOES_NOT_EXIST) {
            included.add(
                new NameVersionDescriptor(
                    ((IResolvedBundle) checked[i]).getBundleInfo().getSymbolicName(),
                    null,
                    NameVersionDescriptor.TYPE_FEATURE));
            missingCount++;
          } else {
            included.add(
                new NameVersionDescriptor(
                    ((IResolvedBundle) checked[i]).getBundleInfo().getSymbolicName(), null));
          }
        }
      }

      if (included.size() == 0) {
        fTargetDefinition.setIncluded(new NameVersionDescriptor[0]);
      } else if (included.size() == 0
          || included.size() - missingCount
              == fTargetDefinition.getAllFeatures().length
                  + ((TargetDefinition) fTargetDefinition).getOtherBundles().length) {
        fTargetDefinition.setIncluded(null);
      } else {
        fTargetDefinition.setIncluded(
            (NameVersionDescriptor[]) included.toArray(new NameVersionDescriptor[included.size()]));
      }
    } else {
      // Figure out if there are multiple bundles sharing the same id
      Set multi = new HashSet(); // BSNs of bundles with multiple versions available
      Set all = new HashSet();
      for (Iterator iterator = fAllBundles.iterator(); iterator.hasNext(); ) {
        IResolvedBundle rb = (IResolvedBundle) iterator.next();
        if (!all.add(rb.getBundleInfo().getSymbolicName())) {
          multi.add(rb.getBundleInfo().getSymbolicName());
        }
      }

      // Create a list of checked bundle infos
      List included = new ArrayList();
      Object[] checked = fTree.getCheckedLeafElements();
      for (int i = 0; i < checked.length; i++) {
        if (checked[i] instanceof IResolvedBundle) {
          // Create the bundle info object
          String bsn = ((IResolvedBundle) checked[i]).getBundleInfo().getSymbolicName();
          NameVersionDescriptor info = null;
          if (multi.contains(bsn)) {
            // include version info
            info =
                new NameVersionDescriptor(
                    bsn, ((IResolvedBundle) checked[i]).getBundleInfo().getVersion());
          } else {
            // don't store version info
            info = new NameVersionDescriptor(bsn, null);
          }
          included.add(info);
        }
      }

      if (included.size() == 0) {
        fTargetDefinition.setIncluded(new NameVersionDescriptor[0]);
      } else if (included.size() == fAllBundles.size() + fMissing.size()) {
        fTargetDefinition.setIncluded(null);
      } else {
        fTargetDefinition.setIncluded(
            (NameVersionDescriptor[]) included.toArray(new NameVersionDescriptor[included.size()]));
      }
    }
  }