/**
  * return what the suggested archiveName is
  *
  * @param ref
  * @return
  */
 public String getDefaultArchiveName(IVirtualReference ref) {
   if (!ref.getReferencedComponent().isBinary()) {
     return getDefaultProjectArchiveName(ref.getReferencedComponent());
   }
   // binary
   return new Path(ref.getReferencedComponent().getDeployedName()).lastSegment();
 }
  protected String toString(IVirtualReference[] references) {
    StringBuilder sb = new StringBuilder("[");

    String sep = "";
    for (IVirtualReference reference : references) {
      IVirtualComponent component = reference.getReferencedComponent();
      sb.append(sep).append(reference.getRuntimePath() + " - ");
      sb.append(component.getName());
      sb.append(" " + component.getMetaProperties());
      sep = ", ";
    }

    return sb.append(']').toString();
  }
  protected boolean hasChanged(IVirtualReference[] existingRefs, IVirtualReference[] refArray) {

    if (existingRefs == refArray) {
      return false;
    }
    if (existingRefs == null || existingRefs.length != refArray.length) {
      return true;
    }
    for (int i = 0; i < existingRefs.length; i++) {
      IVirtualReference existingRef = existingRefs[i];
      IVirtualReference newRef = refArray[i];
      if ((existingRef.getArchiveName() != null
              && !existingRef.getArchiveName().equals(newRef.getArchiveName()))
          || !existingRef.getReferencedComponent().equals(newRef.getReferencedComponent())
          || !existingRef.getRuntimePath().equals(newRef.getRuntimePath())) {
        return true;
      }
    }
    return false;
  }
  public void setModuleDependencies(
      IProject project, MavenProject mavenProject, IProgressMonitor monitor) throws CoreException {
    IVirtualComponent component = ComponentCore.createComponent(project);
    // if the attempt to create dependencies happens before the project is actually created, abort.
    // this will be created again when the project exists.
    if (component == null) {
      return;
    }

    WarPluginConfiguration config = new WarPluginConfiguration(mavenProject, project);
    WarPackagingOptions opts = new WarPackagingOptions(config);

    List<AbstractDependencyConfigurator> depConfigurators =
        ExtensionReader.readDependencyConfiguratorExtensions(
            projectManager,
            MavenPlugin.getDefault().getMavenRuntimeManager(),
            mavenMarkerManager,
            MavenPlugin.getDefault().getConsole());

    Set<IVirtualReference> references = new LinkedHashSet<IVirtualReference>();
    List<IMavenProjectFacade> exportedDependencies =
        getWorkspaceDependencies(project, mavenProject);
    for (IMavenProjectFacade dependency : exportedDependencies) {
      String depPackaging = dependency.getPackaging();
      if ("pom".equals(depPackaging))
        continue; // MNGECLIPSE-744 pom dependencies shouldn't be deployed

      preConfigureDependencyProject(dependency, monitor);
      MavenProject depMavenProject = dependency.getMavenProject(monitor);

      IVirtualComponent depComponent = ComponentCore.createComponent(dependency.getProject());

      String artifactKey = ArtifactUtils.versionlessKey(depMavenProject.getArtifact());
      Artifact artifact = mavenProject.getArtifactMap().get(artifactKey);
      // in a skinny war the dependency modules are referenced by manifest classpath
      // see also <code>configureClasspath</code> the dependeny project is handled in the skinny
      // case
      if (opts.isSkinnyWar()
          && opts.isReferenceFromEar(depComponent, artifact.getArtifactHandler().getExtension())) {
        continue;
      }

      // an artifact in mavenProject.getArtifacts() doesn't have the "optional" value as
      // depMavenProject.getArtifact();
      if (!artifact.isOptional()) {
        IVirtualReference reference = ComponentCore.createReference(component, depComponent);
        reference.setRuntimePath(new Path("/WEB-INF/lib"));
        references.add(reference);
      }
    }

    IVirtualReference[] newRefs = references.toArray(new IVirtualReference[references.size()]);
    if (hasChanged(component.getReferences(), newRefs)) {
      // Only write in the .component file if necessary
      component.setReferences(newRefs);
    }

    // TODO why a 2nd loop???
    for (IMavenProjectFacade dependency : exportedDependencies) {
      MavenProject depMavenProject = dependency.getMavenProject(monitor);
      Iterator<AbstractDependencyConfigurator> configurators = depConfigurators.iterator();
      while (configurators.hasNext()) {
        try {
          configurators
              .next()
              .configureDependency(
                  mavenProject, project, depMavenProject, dependency.getProject(), monitor);
        } catch (MarkedException ex) {
          // XXX handle this
        }
      }
    }
  }
  public void setModuleDependencies(
      IProject project, MavenProject mavenProject, IProgressMonitor monitor) throws CoreException {
    IVirtualComponent component = ComponentCore.createComponent(project);
    // if the attempt to create dependencies happens before the project is actually created, abort.
    // this will be created again when the project exists.
    if (component == null) {
      return;
    }
    // MECLIPSEWTP-41 Fix the missing moduleCoreNature
    fixMissingModuleCoreNature(project, monitor);

    DebugUtilities.debug(
        "==============Processing " + project.getName() + " dependencies ===============");
    WarPluginConfiguration config = new WarPluginConfiguration(mavenProject, project);
    IPackagingConfiguration opts =
        new PackagingConfiguration(config.getPackagingIncludes(), config.getPackagingExcludes());
    FileNameMapping fileNameMapping = config.getFileNameMapping();

    List<AbstractDependencyConfigurator> depConfigurators =
        ExtensionReader.readDependencyConfiguratorExtensions(
            projectManager, MavenPlugin.getMavenRuntimeManager(), mavenMarkerManager);

    Set<IVirtualReference> references = new LinkedHashSet<IVirtualReference>();
    List<IMavenProjectFacade> exportedDependencies =
        getWorkspaceDependencies(project, mavenProject);
    for (IMavenProjectFacade dependency : exportedDependencies) {
      String depPackaging = dependency.getPackaging();
      if ("pom".equals(depPackaging) // MNGECLIPSE-744 pom dependencies shouldn't be deployed
          || "war".equals(depPackaging) // Overlays are dealt with the overlay configurator
          || "zip".equals(depPackaging)) {
        continue;
      }

      try {
        preConfigureDependencyProject(dependency, monitor);

        if (!ModuleCoreNature.isFlexibleProject(dependency.getProject())) {
          // Projects unsupported by WTP (ex. adobe flex projects) should not be added as references
          continue;
        }
        MavenProject depMavenProject = dependency.getMavenProject(monitor);

        IVirtualComponent depComponent = ComponentCore.createComponent(dependency.getProject());

        ArtifactKey artifactKey = ArtifactHelper.toArtifactKey(depMavenProject.getArtifact());
        // Get artifact using the proper classifier
        Artifact artifact = ArtifactHelper.getArtifact(mavenProject.getArtifacts(), artifactKey);
        if (artifact == null) {
          // could not map key to artifact
          artifact = depMavenProject.getArtifact();
        }
        ArtifactHelper.fixArtifactHandler(artifact.getArtifactHandler());
        String deployedName = fileNameMapping.mapFileName(artifact);

        boolean isDeployed =
            !artifact.isOptional() && opts.isPackaged("WEB-INF/lib/" + deployedName);

        // an artifact in mavenProject.getArtifacts() doesn't have the "optional" value as
        // depMavenProject.getArtifact();
        if (isDeployed) {
          IVirtualReference reference = ComponentCore.createReference(component, depComponent);
          IPath path = new Path("/WEB-INF/lib");
          reference.setArchiveName(deployedName);
          reference.setRuntimePath(path);
          references.add(reference);
        }
      } catch (RuntimeException ex) {
        // Should probably be NPEs at this point
        String dump =
            DebugUtilities.dumpProjectState(
                "An error occured while configuring a dependency of  "
                    + project.getName()
                    + DebugUtilities.SEP,
                dependency.getProject());
        LOG.error(dump);
        throw ex;
      }
    }

    IVirtualReference[] oldRefs = WTPProjectsUtil.extractHardReferences(component, false);

    IVirtualReference[] newRefs = references.toArray(new IVirtualReference[references.size()]);

    if (WTPProjectsUtil.hasChanged(oldRefs, newRefs)) {
      // Only write in the .component file if necessary
      IVirtualReference[] overlayRefs = WTPProjectsUtil.extractHardReferences(component, true);
      IVirtualReference[] allRefs = new IVirtualReference[overlayRefs.length + newRefs.length];
      System.arraycopy(newRefs, 0, allRefs, 0, newRefs.length);
      System.arraycopy(overlayRefs, 0, allRefs, newRefs.length, overlayRefs.length);
      component.setReferences(allRefs);
    }

    // TODO why a 2nd loop???
    for (IMavenProjectFacade dependency : exportedDependencies) {
      MavenProject depMavenProject = dependency.getMavenProject(monitor);
      Iterator<AbstractDependencyConfigurator> configurators = depConfigurators.iterator();
      while (configurators.hasNext()) {
        try {
          configurators
              .next()
              .configureDependency(
                  mavenProject, project, depMavenProject, dependency.getProject(), monitor);
        } catch (MarkedException ex) {
          // XXX handle this
        }
      }
    }
  }