private void writeComponents(XMLWriter w, List componentDescriptors)
      throws ComponentDescriptorCreatorException, PlexusConfigurationException {
    w.startElement("components");

    for (Iterator i = componentDescriptors.iterator(); i.hasNext(); ) {
      w.startElement("component");

      ComponentDescriptor cd = (ComponentDescriptor) i.next();

      element(w, "alias", cd.getAlias());

      element(w, "role", cd.getRole());

      element(w, "role-hint", cd.getRoleHint());

      element(w, "implementation", cd.getImplementation());

      element(w, "version", cd.getVersion());

      element(w, "instantiation-strategy", cd.getInstantiationStrategy());

      element(w, "lifecycle-handler", cd.getLifecycleHandler());

      element(w, "description", cd.getDescription());

      writeRequirements(w, cd.getRequirements());

      writeConfiguration(w, cd.getConfiguration());

      w.endElement();
    }

    w.endElement();
  }
 /** Writes the .classpath file for Eclipse. */
 public void write(String projectName) throws Exception {
   final File projectFile = this.getFile(".project");
   final FileWriter fileWriter = new FileWriter(projectFile);
   final XMLWriter writer = new PrettyPrintXMLWriter(fileWriter, "UTF-8", null);
   writer.startElement("projectDescription");
   writer.startElement("name");
   writer.writeText(projectName);
   writer.endElement();
   writer.startElement("comment");
   writer.endElement();
   writer.startElement("projects");
   writer.endElement();
   writer.startElement("buildSpec");
   writer.startElement("buildCommand");
   writer.startElement("name");
   writer.writeText("org.eclipse.jdt.core.javabuilder");
   writer.endElement();
   writer.startElement("arguments");
   writer.endElement();
   writer.endElement();
   writer.endElement();
   writer.startElement("natures");
   writer.startElement("nature");
   writer.writeText("org.eclipse.jdt.core.javanature");
   writer.endElement();
   writer.endElement();
   writer.endElement();
   IOUtil.close(fileWriter);
   this.logger.info("Project file written --> '" + projectFile + "'");
 }
  private void element(XMLWriter w, String name, String value) {
    if (value == null) {
      return;
    }

    w.startElement(name);

    w.writeText(value);

    w.endElement();
  }
  private void writeRequirements(XMLWriter w, List requirements) {
    if (requirements == null || requirements.size() == 0) {
      return;
    }

    w.startElement("requirements");

    for (Iterator j = requirements.iterator(); j.hasNext(); ) {
      ComponentRequirement cr = (ComponentRequirement) j.next();

      w.startElement("requirement");

      element(w, "role", cr.getRole());

      element(w, "role-hint", cr.getRoleHint());

      element(w, "field-name", cr.getFieldName());

      w.endElement();
    }

    w.endElement();
  }
  /**
   * Writes out any additional project facets specified in the plugin configuration
   *
   * @param writer
   * @param packaging
   */
  private void writeAdditionalProjectFacets(XMLWriter writer) {
    if (config.getProjectFacets() == null) {
      return;
    }

    Iterator facetIterator = config.getProjectFacets().entrySet().iterator();
    while (facetIterator.hasNext()) {
      Entry facetEntry = (Entry) facetIterator.next();

      writer.startElement(ELT_INSTALLED);
      writer.addAttribute(ATTR_FACET, (String) facetEntry.getKey());
      writer.addAttribute(ATTR_VERSION, (String) facetEntry.getValue());
      writer.endElement(); // installed
    }
  }
  public void writeDependencies(XMLWriter w, ComponentSetDescriptor componentSetDescriptor) {
    List deps = componentSetDescriptor.getDependencies();

    if (deps == null || deps.size() == 0) {
      return;
    }

    w.startElement("dependencies");

    for (int i = 0; i < deps.size(); i++) {
      writeDependencyElement((ComponentDependency) deps.get(i), w);
    }

    w.endElement();
  }
  private void writePlexusConfiguration(XMLWriter xmlWriter, PlexusConfiguration c)
      throws PlexusConfigurationException {
    if (c.getAttributeNames().length == 0 && c.getChildCount() == 0 && c.getValue() == null) {
      return;
    }

    xmlWriter.startElement(c.getName());

    // ----------------------------------------------------------------------
    // Write the attributes
    // ----------------------------------------------------------------------

    String[] attributeNames = c.getAttributeNames();

    for (int i = 0; i < attributeNames.length; i++) {
      String attributeName = attributeNames[i];

      xmlWriter.addAttribute(attributeName, c.getAttribute(attributeName));
    }

    // ----------------------------------------------------------------------
    // Write the children
    // ----------------------------------------------------------------------

    PlexusConfiguration[] children = c.getChildren();

    if (children.length > 0) {
      for (int i = 0; i < children.length; i++) {
        writePlexusConfiguration(xmlWriter, children[i]);
      }
    } else {
      String value = c.getValue();

      if (value != null) {
        xmlWriter.writeText(value);
      }
    }

    xmlWriter.endElement();
  }
  private void writeDependencyElement(ComponentDependency dependency, XMLWriter w) {
    w.startElement("dependency");

    String groupId = dependency.getGroupId();

    element(w, "groupId", groupId);

    String artifactId = dependency.getArtifactId();

    element(w, "artifactId", artifactId);

    String type = dependency.getType();

    if (type != null) {
      element(w, "type", type);
    }

    String version = dependency.getVersion();

    element(w, "version", version);

    w.endElement();
  }
 /**
  * Writes a facet <code>installed</code> element with attribute <code>facet</code> set to the
  * value of argument <code>facetName</code>, and attribute <code>version</code> set to the value
  * of argument <code>facetVersion</code> .
  *
  * @param writer
  * @param facetName
  * @param facetVersion
  */
 private void writeFacetInstalledElement(XMLWriter writer, String facetName, String facetVersion) {
   writer.startElement(ELT_INSTALLED);
   writer.addAttribute(ATTR_FACET, facetName);
   writer.addAttribute(ATTR_VERSION, facetVersion);
   writer.endElement();
 }
 /**
  * Writes facet <code>fixed</code> element with attribute <code>facet</code> set to the value of
  * argument <code>facetName</code>.
  *
  * @param writer
  * @param facetName
  */
 private void writeFacetFixedElement(XMLWriter writer, String facetName) {
   writer.startElement(ELT_FIXED);
   writer.addAttribute(ATTR_FACET, facetName);
   writer.endElement();
 }
  /**
   * Writes out the facet info for a faceted-project based on the packaging.
   *
   * @param writer
   * @param packaging
   */
  private void writeModuleTypeFacetCore(XMLWriter writer, String packaging) {
    writer.startElement(ELT_FACETED_PROJECT);
    if (Constants.PROJECT_PACKAGING_WAR.equalsIgnoreCase(packaging)) // $NON-NLS-1$
    {
      writeFacetFixedElement(writer, FACET_JST_JAVA); // fixed
      writeFacetFixedElement(writer, FACET_JST_WEB); // fixed
      String servletVersion;
      if (config.getJeeVersion() != null) {
        servletVersion =
            JeeUtils.getJeeDescriptorFromJeeVersion(config.getJeeVersion()).getServletVersion();
      } else {
        servletVersion = JeeUtils.resolveServletVersion(config.getProject());
      }
      writeFacetInstalledElement(writer, FACET_JST_WEB, servletVersion); // installed
      writeFacetInstalledElement(
          writer, FACET_JST_JAVA, IdeUtils.resolveJavaVersion(config.getProject())); // installed
    } else if (Constants.PROJECT_PACKAGING_EJB.equalsIgnoreCase(packaging)) // $NON-NLS-1$
    {
      writeFacetFixedElement(writer, FACET_JST_JAVA); // fixed
      writeFacetFixedElement(writer, FACET_JST_EJB); // fixed

      String ejbVersion;
      if (config.getJeeVersion() != null) {
        ejbVersion =
            JeeUtils.getJeeDescriptorFromJeeVersion(config.getJeeVersion()).getEjbVersion();
      } else {
        ejbVersion = JeeUtils.resolveEjbVersion(config.getProject());
      }
      writeFacetInstalledElement(writer, FACET_JST_EJB, ejbVersion); // installed
      writeFacetInstalledElement(
          writer, FACET_JST_JAVA, IdeUtils.resolveJavaVersion(config.getProject())); // installed
    } else if (Constants.PROJECT_PACKAGING_EAR.equalsIgnoreCase(packaging)) // $NON-NLS-1$
    {
      if (this.config.getWorkspaceConfiguration().getWebsphereVersion() != null) {
        writer.startElement("runtime");
        writer.addAttribute(
            "name", config.getWorkspaceConfiguration().getDefaultDeployServerName());
        writer.endElement(); // runtime

        writeFacetInstalledElement(
            writer,
            FACET_COM_IBM_WEBSPHERE_EXTENDED_EAR,
            this.config.getWorkspaceConfiguration().getWebsphereVersion()); // installed
        writeFacetInstalledElement(
            writer,
            FACET_COM_IBM_WEBSPHERE_COEXISTENCE_EAR,
            this.config.getWorkspaceConfiguration().getWebsphereVersion()); // installed
      }
      writeFacetFixedElement(writer, FACET_JST_EAR); // fixed
      String jeeVersion;
      if (config.getJeeVersion() != null) {
        jeeVersion =
            JeeUtils.getJeeDescriptorFromJeeVersion(config.getJeeVersion()).getJeeVersion();
      } else {
        jeeVersion = JeeUtils.resolveJeeVersion(config.getProject());
      }
      writeFacetInstalledElement(writer, FACET_JST_EAR, jeeVersion); // installed
    } else if (Constants.PROJECT_PACKAGING_JAR.equalsIgnoreCase(packaging)) // $NON-NLS-1$
    {
      writeFacetFixedElement(writer, FACET_JST_JAVA); // fixed
      writeFacetFixedElement(writer, FACET_JST_UTILITY); // fixed
      writeFacetInstalledElement(writer, FACET_JST_UTILITY, "1.0"); // $NON-NLS-1$
      writeFacetInstalledElement(
          writer, FACET_JST_JAVA, IdeUtils.resolveJavaVersion(config.getProject())); // installed
      // installed
    }

    writeAdditionalProjectFacets(writer);

    writer.endElement(); // faceted-project
  }
  /**
   * Writer entry point
   *
   * @throws MojoExecutionException
   */
  public void write() throws MojoExecutionException {
    String packaging = config.getProject().getPackaging();

    if (!Constants.PROJECT_PACKAGING_EAR.equalsIgnoreCase(packaging)
        && !Constants.PROJECT_PACKAGING_WAR.equalsIgnoreCase(packaging)
        && !Constants.PROJECT_PACKAGING_EJB.equalsIgnoreCase(packaging)) {
      return;
    }

    FileWriter w;

    try {
      w =
          new FileWriter(
              new File(config.getEclipseProjectDirectory(), MYECLIPSE_MYMETADATA_FILENAME));
    } catch (IOException ex) {
      throw new MojoExecutionException(
          Messages.getString("EclipsePlugin.erroropeningfile"), ex); // $NON-NLS-1$
    }

    XMLWriter writer = new PrettyPrintXMLWriter(w, "UTF-8", null);

    writer.startElement(MYECLIPSE_METADATA_PROJECT);
    writer.addAttribute(MYECLIPSE_METADATA_PROJECT_TYPE, getMyEclipseProjectType(packaging));
    writer.addAttribute(MYECLIPSE_METADATA_PROJECT_NAME, config.getEclipseProjectName());
    writer.addAttribute(MYECLIPSE_METADATA_PROJECT_ID, config.getEclipseProjectName());

    if (Constants.PROJECT_PACKAGING_WAR.equalsIgnoreCase(packaging)) {
      // Find web application context root from maven-war-plugin configuration.
      // ArtifactId is used as the default value
      String warContextRoot =
          IdeUtils.getPluginSetting(
              config.getProject(),
              JeeUtils.ARTIFACT_MAVEN_WAR_PLUGIN,
              "warContextRoot",
              //$NON-NLS-1$
              "/" + config.getProject().getArtifactId());

      writer.addAttribute(MYECLIPSE_METADATA_PROJECT_CONTEXT_ROOT, warContextRoot);

      writer.addAttribute(MYECLIPSE_METADATA_PROJECT_J2EE_SPEC, getJeeVersion());
      // TODO : use maven final name
      writer.addAttribute(
          MYECLIPSE_METADATA_PROJECT_ARCHIVE, config.getEclipseProjectName() + ".war");
    }

    if (Constants.PROJECT_PACKAGING_EAR.equalsIgnoreCase(packaging)) {
      // TODO : use maven final name
      writer.addAttribute(
          MYECLIPSE_METADATA_PROJECT_ARCHIVE, config.getEclipseProjectName() + ".ear");
    }

    writer.startElement(MYECLIPSE_METADATA_PROJECT_ATTRIBUTES);
    if (Constants.PROJECT_PACKAGING_WAR.equalsIgnoreCase(packaging)) {
      writer.startElement(MYECLIPSE_METADATA_PROJECT_ATTRIBUTE);
      writer.addAttribute("name", "webrootdir");
      // TODO : retrieve this from project configuration
      writer.addAttribute("value", "src/main/webapp");
      writer.endElement();
    }
    // Close <attributes>
    writer.endElement();

    // Close <project-module>
    writer.endElement();

    IOUtil.close(w);
  }
  public void processSources(
      File[] sourceDirectories,
      File outputFile,
      boolean containerDescriptor,
      ComponentDescriptor[] roleDefaults)
      throws ComponentDescriptorCreatorException {
    // ----------------------------------------------------------------------
    // Check and register all directories to scan
    // ----------------------------------------------------------------------

    JavaSource[] javaSources;

    JavaDocBuilder builder = new JavaDocBuilder();

    getLogger().debug("Source directories: ");

    for (int it = 0; it < sourceDirectories.length; it++) {
      File sourceDirectory = sourceDirectories[it];

      if (!sourceDirectory.isDirectory()) {
        getLogger()
            .debug(
                "Specified source directory isn't a directory: "
                    + "'"
                    + sourceDirectory.getAbsolutePath()
                    + "'.");
      }

      getLogger().debug(" - " + sourceDirectory.getAbsolutePath());

      builder.addSourceTree(sourceDirectory);
    }

    // ----------------------------------------------------------------------
    // Scan the sources
    // ----------------------------------------------------------------------

    javaSources = builder.getSources();

    Map defaultsByRole = new HashMap();
    if (roleDefaults != null) {
      for (int i = 0; i < roleDefaults.length; i++) {
        // TODO: fail if role is null
        defaultsByRole.put(roleDefaults[i].getRole(), roleDefaults[i]);
      }
    }

    List componentDescriptors = new ArrayList();

    for (int i = 0; i < javaSources.length; i++) {
      JavaClass javaClass = getJavaClass(javaSources[i]);

      ComponentDescriptor componentDescriptor = gleaner.glean(builder, javaClass);

      if (componentDescriptor != null && !javaClass.isAbstract()) {
        // TODO: better merge, perhaps pass it into glean as the starting point instead
        if (defaultsByRole.containsKey(componentDescriptor.getRole())) {
          ComponentDescriptor desc =
              (ComponentDescriptor) defaultsByRole.get(componentDescriptor.getRole());

          if (componentDescriptor.getInstantiationStrategy() == null) {
            componentDescriptor.setInstantiationStrategy(desc.getInstantiationStrategy());
          }
        }
        componentDescriptors.add(componentDescriptor);
      }
    }

    ComponentSetDescriptor componentSetDescriptor = new ComponentSetDescriptor();

    componentSetDescriptor.setComponents(componentDescriptors);

    // ----------------------------------------------------------------------
    // Convert the Maven dependencies to Plexus component dependencies
    // ----------------------------------------------------------------------

    //        List componentDependencies = convertDependencies( mavenProject.getDependencies() );
    //
    //        componentSetDescriptor.setDependencies( componentDependencies );

    // TODO: for now
    componentSetDescriptor.setDependencies(Collections.EMPTY_LIST);

    // ----------------------------------------------------------------------
    //
    // ----------------------------------------------------------------------

    validateConfiguration(componentSetDescriptor);

    // ----------------------------------------------------------------------
    // Write out the component descriptor
    // ----------------------------------------------------------------------

    if (componentDescriptors.size() == 0 && componentSetDescriptor.getDependencies().size() == 0) {
      getLogger().debug("No components or dependencies found, not writing components.xml");

      return;
    }

    File parentFile = outputFile.getParentFile();
    if (!parentFile.exists()) {
      if (!parentFile.mkdirs()) {
        throw new ComponentDescriptorCreatorException(
            "Could not make parent directory: '" + parentFile.getAbsolutePath() + "'.");
      }
    }

    try {
      FileWriter writer = new FileWriter(outputFile);

      XMLWriter w = new PrettyPrintXMLWriter(writer);

      w.startElement(containerDescriptor ? "plexus" : "component-set");

      writeComponents(w, componentDescriptors);

      writeDependencies(w, componentSetDescriptor);

      w.endElement();

      writer.write(LS);

      writer.close();
    } catch (PlexusConfigurationException e) {
      throw new ComponentDescriptorCreatorException(
          "Internal error while writing out the configuration", e);
    } catch (IOException e) {
      throw new ComponentDescriptorCreatorException(
          "Error while writing the component descriptor to: "
              + "'"
              + outputFile.getAbsolutePath()
              + "'.",
          e);
    }
  }