@SuppressWarnings("restriction")
  @Override
  public ITargetDefinition createDefaultTarget() throws CoreException {

    IPath installPath = getServer().getRuntime().getLocation();

    ITargetDefinition targetDefinition = TargetPlatformService.getDefault().newTarget();
    targetDefinition.setName(getServer().getName());
    IBundleContainer[] containers = getDefaultBundleContainers(installPath);

    targetDefinition.setBundleContainers(containers);
    targetDefinition.resolve(new NullProgressMonitor());

    TargetPlatformService.getDefault().saveTargetDefinition(targetDefinition);
    return targetDefinition;
  }
  private void addBundleContainerToTargetDefinitionIfNotPresent(
      ITargetDefinition directoryTargetDefinition, String folderPath) throws CoreException {
    IBundleContainer bundleContainer =
        findBundleContainerForPath(directoryTargetDefinition, folderPath);

    // Add BundleContainer to target definition if not already present
    if (bundleContainer == null) {
      IBundleContainer[] bundleContainers = directoryTargetDefinition.getBundleContainers();

      IBundleContainer[] newBundleContainers =
          Arrays.copyOf(bundleContainers, bundleContainers.length + 1);

      newBundleContainers[newBundleContainers.length - 1] =
          new DirectoryBundleContainer(folderPath);
      directoryTargetDefinition.setBundleContainers(newBundleContainers);
    }
  }
  /**
   * Set the container to display in the tree or <code>null</code> to disable the tree
   *
   * @param input bundle container or <code>null</code>
   */
  public void setInput(ITargetDefinition input) {
    fTargetDefinition = input;

    // Update the cached data
    fFileBundleMapping = null;
    fAllBundles.clear();

    if (input == null || !input.isResolved()) {
      fTree.setInput(Messages.TargetContentsGroup_10);
      setEnabled(false);
      return;
    }

    IResolvedBundle[] allResolvedBundles = input.getAllBundles();
    if (allResolvedBundles == null || allResolvedBundles.length == 0) {
      fTree.setInput(Messages.TargetContentsGroup_11);
      setEnabled(false);
      return;
    }

    for (int i = 0; i < allResolvedBundles.length; i++) {
      fAllBundles.add(allResolvedBundles[i]);
    }

    boolean isFeatureMode =
        ((TargetDefinition) fTargetDefinition).getUIMode() == TargetDefinition.MODE_FEATURE;
    fFeaureModeButton.setSelection(isFeatureMode);
    fPluginModeButton.setSelection(!isFeatureMode);
    fGroupLabel.setEnabled(!isFeatureMode);

    fTree.getControl().setRedraw(false);
    fTree.setInput(fTargetDefinition);
    fTree.expandAll();
    updateCheckState();
    updateButtons();
    setEnabled(true);
    fTree.getControl().setRedraw(true);
  }
  private IBundleContainer findBundleContainerForPath(
      ITargetDefinition directoryTargetDefinition, String pluginsFolderPath) throws CoreException {
    IBundleContainer returnedBundleContainer = null;

    for (IBundleContainer bundleContainer : directoryTargetDefinition.getBundleContainers()) {
      if (bundleContainer instanceof DirectoryBundleContainer) {
        DirectoryBundleContainer directoryBundleContainer =
            (DirectoryBundleContainer) bundleContainer;

        if (directoryBundleContainer.getLocation(false).equals(pluginsFolderPath)) {
          returnedBundleContainer = bundleContainer;
          break;
        }
      }
    }

    return returnedBundleContainer;
  }
 private void updateCheckState() {
   List result = new ArrayList();
   // Checked error statuses
   if (fMissing != null) {
     result.addAll(fMissing);
   }
   if (fFeaureModeButton.getSelection()) {
     // Checked features and plugins
     result.addAll(((TargetDefinition) fTargetDefinition).getFeaturesAndBundles());
   } else {
     // Bundles with errors are already included from fMissing, do not add twice
     IResolvedBundle[] bundles = fTargetDefinition.getBundles();
     for (int i = 0; i < bundles.length; i++) {
       if (bundles[i].getStatus().isOK()) {
         result.add(bundles[i]);
       }
     }
   }
   fTree.setCheckedElements(result.toArray());
 }
  public ITargetDefinition saveMavenTargetDefinition(
      Shell shell, IProject targetProject, MavenBundleContainer mavenBundleContainer) {
    try {
      ITargetDefinition newTarget = loadMavenTargetDefinition(mavenBundleContainer);

      IFile targetFile = targetProject.getFile(PDE_TARGET_TARGET);

      // Ensure plugins folder is reset
      IFolder pluginsFolder = targetProject.getFolder(PDE_TARGET_PLUGINS);
      if (pluginsFolder.exists()) {
        pluginsFolder.delete(true, null);
      }
      pluginsFolder.create(true, true, null);

      // Ensure otherPlugins folder exists
      IFolder otherPluginsFolder = targetProject.getFolder(PDE_TARGET_OTHER_PLUGINS);
      if (!otherPluginsFolder.exists()) {
        otherPluginsFolder.create(true, true, null);
      }

      File pluginsFolderFile = pluginsFolder.getLocation().toFile();

      // Copy all maven dependencies in pluginsFolder

      // Keep all project artifactIds to ensure they are used instead of any other dependencies
      final HashSet<String> projectArtifactId = new HashSet<String>();
      for (IMavenProjectFacade mavenProject : mavenBundleContainer.getMavenProjects()) {
        projectArtifactId.add(mavenProject.getArtifactKey().getArtifactId());
      }

      Collection<Artifact> mostRecentArtifacts =
          getMostRecentArtifacts(mavenBundleContainer.getArtifacts(null));

      CollectionUtils.filter(
          mostRecentArtifacts,
          new Predicate() {
            @Override
            public boolean evaluate(Object param) {
              Artifact artifact = (Artifact) param;

              return !projectArtifactId.contains(artifact.getArtifactId());
            }
          });

      for (Artifact artifact : mostRecentArtifacts) {
        try {
          File bundleFile = artifact.getFile().getAbsoluteFile();
          if (bundleFile.isFile()) {
            FileUtils.copyFileToDirectory(bundleFile, pluginsFolderFile);
          }
        } catch (IOException e) {
          throw e;
        }
      }

      // Update targetFile with the DirectoryBundelContainer if not already present
      ITargetHandle targetHandle = targetPlatformService.getTarget(targetFile);
      ITargetDefinition directoryTargetDefinition = targetHandle.getTargetDefinition();

      String pluginsFolderPath = pluginsFolderFile.getAbsolutePath();
      String otherPluginsPath = otherPluginsFolder.getLocation().toFile().getAbsolutePath();

      if (targetFile.exists()) {
        // Find already existing DirectoryBundleContainer for maven repository path
        addBundleContainerToTargetDefinitionIfNotPresent(
            directoryTargetDefinition, pluginsFolderPath);
        addBundleContainerToTargetDefinitionIfNotPresent(
            directoryTargetDefinition, otherPluginsPath);
      } else {
        directoryTargetDefinition.setBundleContainers(
            new IBundleContainer[] {
              new DirectoryBundleContainer(pluginsFolderPath),
              new DirectoryBundleContainer(otherPluginsPath)
            });
      }

      // Refresh project folder tree
      NullProgressMonitor monitor = new NullProgressMonitor();
      targetFile.refreshLocal(IResource.DEPTH_INFINITE, monitor);
      pluginsFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);
      otherPluginsFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);
      targetProject.refreshLocal(IResource.DEPTH_INFINITE, monitor);

      // Save target definition
      targetPlatformService.saveTargetDefinition(directoryTargetDefinition);

      LoadTargetDefinitionJob.load(directoryTargetDefinition);
      return newTarget;
    } catch (Exception e) {
      MessageBox msgbox = new MessageBox(shell, SWT.ALPHA);

      msgbox.setMessage(
          "Unable to create PDE Target, delelete file " + PDE_TARGET_TARGET + " in your project");
      msgbox.setText("Error while creating PDE Target");
      msgbox.open();

      e.printStackTrace();

      throw new RuntimeException("Unable to create target", e);
    }
  }
 public ITargetDefinition loadMavenTargetDefinition(MavenBundleContainer mavenBundleContainer) {
   ITargetDefinition newTarget = targetPlatformService.newTarget();
   newTarget.setBundleContainers(new IBundleContainer[] {mavenBundleContainer});
   newTarget.setName(MAVEN_TARGET);
   return newTarget;
 }
  private void updateButtons() {
    if (fTargetDefinition != null && !fTree.getSelection().isEmpty()) {
      Object[] selection = ((IStructuredSelection) fTree.getSelection()).toArray();
      boolean hasResolveBundle = false;
      boolean hasParent = false;
      boolean allSelected = true;
      boolean noneSelected = true;
      for (int i = 0; i < selection.length; i++) {
        if (!hasResolveBundle || !hasParent) {
          if (selection[i] instanceof IResolvedBundle) {
            hasResolveBundle = true;
          } else {
            hasParent = true;
          }
        }
        boolean checked = fTree.getChecked(selection[i]);
        if (checked) {
          noneSelected = false;
        } else {
          allSelected = false;
        }
      }
      // Selection is available if not everything is already selected and not both a parent and
      // child item are selected
      fSelectButton.setEnabled(!allSelected && !(hasResolveBundle && hasParent));
      fDeselectButton.setEnabled(!noneSelected && !(hasResolveBundle && hasParent));
    } else {
      fSelectButton.setEnabled(false);
      fDeselectButton.setEnabled(false);
    }

    int total = fAllBundles.size();
    if (fFeaureModeButton.getSelection()) {
      if (fTargetDefinition == null) {
        total = 0;
      } else {
        total = fTargetDefinition.getAllFeatures().length;
        total += ((TargetDefinition) fTargetDefinition).getOtherBundles().length;
      }
    }
    if (fMissing != null) {
      total += fMissing.size();
    }

    fSelectAllButton.setEnabled(fTargetDefinition != null && fTree.getCheckedLeafCount() != total);
    fDeselectAllButton.setEnabled(fTargetDefinition != null && fTree.getCheckedLeafCount() != 0);
    fSelectRequiredButton.setEnabled(
        fTargetDefinition != null
            && fTree.getCheckedLeafCount() > 0
            && fTree.getCheckedLeafCount() != total);

    if (fTargetDefinition != null) {
      fCountLabel.setText(
          MessageFormat.format(
              Messages.TargetContentsGroup_9,
              new String[] {
                Integer.toString(fTree.getCheckedLeafCount()), Integer.toString(total)
              }));
    } else {
      fCountLabel.setText(""); // $NON-NLS-1$
    }
  }
  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()]));
      }
    }
  }