protected void removeTestFolderLinks(
     IProject project, MavenProject mavenProject, IProgressMonitor monitor, String folder)
     throws CoreException {
   IVirtualComponent component = ComponentCore.createComponent(project);
   if (component != null) {
     IVirtualFolder jsrc = component.getRootFolder().getFolder(folder);
     for (IPath location :
         MavenProjectUtils.getSourceLocations(project, mavenProject.getTestCompileSourceRoots())) {
       jsrc.removeLink(location, 0, monitor);
     }
     for (IPath location :
         MavenProjectUtils.getResourceLocations(project, mavenProject.getTestResources())) {
       jsrc.removeLink(location, 0, monitor);
     }
   }
 }
  private IModuleResource getWebXmlFile(IProject project, IPath modelDeployDirectory) {
    // IDE-110 IDE-648
    IVirtualFolder webappRoot = CoreUtil.getDocroot(project);

    if (webappRoot != null) {
      for (IContainer container : webappRoot.getUnderlyingFolders()) {
        if (container != null && container.exists()) {
          IFile webXml = container.getFile(new Path(WEB_XML_PATH));

          if (webXml.exists()) {
            return new ModuleFile(
                webXml, webXml.getName(), modelDeployDirectory.append(WEB_XML_PATH));
          }
        }
      }
    }

    return null;
  }
  private boolean checkDocrootFileExists(final IPath path) {
    IVirtualFolder webappRoot = CoreUtil.getDocroot(getTargetProject());

    if (webappRoot == null) {
      return false;
    }

    for (IContainer container : webappRoot.getUnderlyingFolders()) {
      if (container != null && container.exists()) {
        IFile file = container.getFile(path);

        if (file.exists()) {
          return true;
        }
      }
    }

    return false;
  }
  public void execute(
      final IProject project,
      final IProjectFacetVersion fv,
      final Object cfg,
      final IProgressMonitor monitor)
      throws CoreException {
    if (monitor != null) {
      monitor.beginTask("", 1); // $NON-NLS-1$
    }

    try {
      IDataModel model = (IDataModel) cfg;

      if (monitor != null) {
        monitor.worked(1);
      }
      // Add WTP natures.

      WtpUtils.addNaturestoEAR(project);

      final IVirtualComponent c = ComponentCore.createComponent(project, false);
      c.create(0, null);

      final IVirtualFolder earroot = c.getRootFolder();
      Path contentDirPath =
          new Path(model.getStringProperty(IEarFacetInstallDataModelProperties.CONTENT_DIR));
      earroot.createLink(contentDirPath, 0, null);
      J2EEModuleVirtualComponent.setDefaultDeploymentDescriptorFolder(
          earroot, contentDirPath, null);

      try {
        ((IDataModelOperation) model.getProperty(FacetDataModelProvider.NOTIFICATION_OPERATION))
            .execute(monitor, null);
      } catch (ExecutionException e) {
        J2EEPlugin.logError(e);
      }

      if (fv == IJ2EEFacetConstants.ENTERPRISE_APPLICATION_70
          || fv == IJ2EEFacetConstants.ENTERPRISE_APPLICATION_60
          || fv == IJ2EEFacetConstants.ENTERPRISE_APPLICATION_50) {
        if (model.getBooleanProperty(IJ2EEFacetInstallDataModelProperties.GENERATE_DD)) {
          // Create the deployment descriptor (application.xml) if one doesn't exist
          IFile appXmlFile =
              earroot.getUnderlyingFolder().getFile(new Path(J2EEConstants.APPLICATION_DD_URI));
          if (!appXmlFile.exists()) {
            try {
              if (!appXmlFile.getParent().exists()
                  && (appXmlFile.getParent().getType() == IResource.FOLDER)) {
                ((IFolder) appXmlFile.getParent()).create(true, true, monitor);
              }
              String appXmlContents = null;
              if (fv == IJ2EEFacetConstants.ENTERPRISE_APPLICATION_70) {
                appXmlContents =
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<application id=\"Application_ID\" version=\"7\" xmlns=\"http://xmlns.jcp.org/xml/ns/javaee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/application_7.xsd\">\n <display-name>"
                        + XMLWriter.getEscaped(project.getName())
                        + "</display-name> \n </application> "; //$NON-NLS-1$ //$NON-NLS-2$
              } else if (fv == IJ2EEFacetConstants.ENTERPRISE_APPLICATION_60) {
                appXmlContents =
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<application id=\"Application_ID\" version=\"6\" xmlns=\"http://java.sun.com/xml/ns/javaee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_6.xsd\">\n <display-name>"
                        + XMLWriter.getEscaped(project.getName())
                        + "</display-name> \n </application> "; //$NON-NLS-1$ //$NON-NLS-2$
              } else {
                appXmlContents =
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<application id=\"Application_ID\" version=\"5\" xmlns=\"http://java.sun.com/xml/ns/javaee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd\">\n <display-name>"
                        + XMLWriter.getEscaped(project.getName())
                        + "</display-name> \n </application> "; //$NON-NLS-1$ //$NON-NLS-2$
              }
              appXmlFile.create(
                  new ByteArrayInputStream(appXmlContents.getBytes("UTF-8")),
                  true,
                  monitor); //$NON-NLS-1$
            } catch (UnsupportedEncodingException e) {
              J2EEPlugin.logError(e);
            }
          }
        }
      } else {
        if (!earroot.getFile(J2EEConstants.APPLICATION_DD_URI).exists()) {
          String ver = model.getStringProperty(IFacetDataModelProperties.FACET_VERSION_STR);
          int nVer = J2EEVersionUtil.convertVersionStringToInt(ver);
          EARArtifactEdit.createDeploymentDescriptor(project, nVer);
        }
      }
    } finally {
      if (monitor != null) {
        monitor.done();
      }
    }
  }
  @Override
  protected void configureJBossAppXml() {
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(earProjectName);
    IVirtualComponent component = ComponentCore.createComponent(project);
    IVirtualFolder folder = component.getRootFolder();
    IFolder rootFolder = (IFolder) folder.getUnderlyingFolder();
    IResource jbossAppXml = rootFolder.findMember("META-INF/jboss-app.xml");
    if (jbossAppXml == null || !(jbossAppXml instanceof IFile) || !jbossAppXml.exists()) {
      return;
    }

    IModelManager manager = StructuredModelManager.getModelManager();
    if (manager == null) {
      return;
    }
    IStructuredModel model = null;
    try {
      model = manager.getModelForEdit((IFile) jbossAppXml);
      if (model instanceof IDOMModel) {
        IDOMModel domModel = (IDOMModel) model;
        IDOMDocument document = domModel.getDocument();
        Element root = document.getDocumentElement();
        if (root == null) {
          return;
        }
        NodeList children = root.getChildNodes();
        boolean strictAdded = false;
        Node firstChild = null;
        for (int i = 0; i < children.getLength(); i++) {
          Node currentNode = children.item(i);
          if (Node.ELEMENT_NODE == currentNode.getNodeType() && firstChild == null) {
            firstChild = currentNode;
          }
          if (Node.ELEMENT_NODE == currentNode.getNodeType()
              && MODULE_ORDER.equals(currentNode.getNodeName())) {
            setValue(document, currentNode, STRICT);
            strictAdded = true;
          }
        }
        if (!strictAdded) {
          Element moduleOrder = document.createElement(MODULE_ORDER);
          setValue(document, moduleOrder, STRICT);
          if (firstChild != null) {
            root.insertBefore(moduleOrder, firstChild);
          } else {
            root.appendChild(moduleOrder);
          }
        }
        model.save();
      }
    } catch (CoreException e) {
      SeamCorePlugin.getDefault().logError(e);
    } catch (IOException e) {
      SeamCorePlugin.getDefault().logError(e);
    } finally {
      if (model != null) {
        model.releaseFromEdit();
      }
    }
    try {
      new FormatProcessorXML().formatFile((IFile) jbossAppXml);
    } catch (IOException e) {
      SeamCorePlugin.getDefault().logError(e);
    } catch (CoreException e) {
      SeamCorePlugin.getDefault().logError(e);
    }
  }
  @Override
  protected boolean createTestProject() {
    if (!(Boolean) model.getProperty(ISeamFacetDataModelProperties.TEST_PROJECT_CREATING)
        || !shouldCopyLibrariesAndTemplates(model)) return false;

    File testProjectDir =
        new File(
            seamWebProject.getLocation().removeLastSegments(1).toFile(),
            testProjectName); //$NON-NLS-1$
    testProjectDir.mkdir();

    IVirtualComponent component = ComponentCore.createComponent(seamWebProject);
    IVirtualFolder webRootVirtFolder =
        component.getRootFolder().getFolder(new Path("/")); // $NON-NLS-1$

    File testLibDir = new File(testProjectDir, "lib"); // $NON-NLS-1$
    File embededEjbDir = new File(testProjectDir, "bootstrap"); // $NON-NLS-1$
    File testSrcDir = new File(testProjectDir, "test-src"); // $NON-NLS-1$
    String seamGenResFolder = seamRuntime.getResourceTemplatesDir();
    File dataSourceFile = new File(seamGenResFolder, "datasource-ds.xml");
    File seamPropertiesFile = new File(seamGenResFolder, "seam.properties");
    // File jbossBeansFile = new File(seamGenResFolder ,"META-INF/jboss-beans.xml"); //$NON-NLS-1$
    FilterSet filterSet = new FilterSet();
    filterSet.addFilter("projectName", seamWebProject.getName()); // $NON-NLS-1$
    filterSet.addFilter("earProjectName", earProjectName); // $NON-NLS-1$
    filterSet.addFilter("ejbProjectName", ejbProjectName); // $NON-NLS-1$
    filterSet.addFilter("testProjectName", testProjectName); // $NON-NLS-1$

    filterSet.addFilter(
        "runtimeName", WtpUtils.getServerRuntimeName(seamWebProject)); // $NON-NLS-1$
    filterSet.addFilter(
        "webRootFolder",
        webRootVirtFolder
            .getUnderlyingFolder()
            .getFullPath()
            .removeFirstSegments(1)
            .toString()); //$NON-NLS-1$

    FilterSet jdbcFilterSet = SeamFacetFilterSetFactory.createJdbcFilterSet(model);
    // TODO: why are these filters not shared!?
    filterSet.addConfiguredFilterSet(
        SeamFacetFilterSetFactory.createHibernateDialectFilterSet(model));

    AntCopyUtils.FileSet includeLibs =
        new AntCopyUtils.FileSet(getJBossTestLibFileset())
            .dir(new File(seamRuntime.getHomeDir(), "lib")); // $NON-NLS-1$
    AntCopyUtils.FileSet secondSetincludeLibs =
        new AntCopyUtils.FileSet(getJBossTestLibFileset())
            .dir(new File(seamRuntime.getHomeDir(), "lib/test")); // $NON-NLS-1$

    File[] firstlibs =
        includeLibs.getDir().listFiles(new AntCopyUtils.FileSetFileFilter(includeLibs));
    File[] secondLibs =
        secondSetincludeLibs
            .getDir()
            .listFiles(new AntCopyUtils.FileSetFileFilter(secondSetincludeLibs));
    Set<String> allLibs =
        new HashSet<String>(); // HACK: needed to be unique because some jboss-*.jars are duplicated
    if (firstlibs != null)
      for (File f : firstlibs) {
        allLibs.add(f.getName());
      }
    if (secondLibs != null)
      for (File f : secondLibs) {
        allLibs.add(f.getName());
      }

    StringBuffer testLibraries = new StringBuffer();

    if (!SeamCorePlugin.getDefault().hasM2Facet(seamWebProject)) {
      for (String file : allLibs) {
        testLibraries.append(
            "\t<classpathentry kind=\"lib\" path=\"lib/"
                + file
                + "\"/>\n"); //$NON-NLS-1$ //$NON-NLS-2$
      }
    }

    StringBuffer requiredProjects = new StringBuffer();
    requiredProjects.append(
        "\t<classpathentry combineaccessrules=\"false\" kind=\"src\" path=\"/"
            + seamWebProject.getName()
            + "\"/>"); //$NON-NLS-1$ //$NON-NLS-2$
    if (!SeamFacetAbstractInstallDelegate.isWarConfiguration(model)) {
      requiredProjects.append(
          "\n\t<classpathentry combineaccessrules=\"false\" kind=\"src\" path=\"/"
              + ejbProjectName
              + "\"/>"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    filterSet.addFilter("testLibraries", testLibraries.toString()); // $NON-NLS-1$
    filterSet.addFilter("requiredProjects", requiredProjects.toString()); // $NON-NLS-1$
    File testTemplateDir = null;
    try {
      testTemplateDir =
          new File(
              SeamFacetInstallDataModelProvider.getTemplatesFolder(), "test-seam2"); // $NON-NLS-1$
    } catch (IOException e) {
      SeamCorePlugin.getPluginLog().logError(e);
      return false;
    }
    AntCopyUtils.FileSet excludeCvsSvn =
        new AntCopyUtils.FileSet(SeamFacetAbstractInstallDelegate.CVS_SVN).dir(testTemplateDir);

    AntCopyUtils.copyFilesAndFolders(
        testTemplateDir,
        testProjectDir,
        new AntCopyUtils.FileSetFileFilter(excludeCvsSvn),
        new FilterSetCollection(filterSet),
        true);

    excludeCvsSvn.dir(new File(seamRuntime.getHomeDir(), "bootstrap")); // $NON-NLS-1$
    AntCopyUtils.copyFilesAndFolders(
        new File(seamRuntime.getHomeDir(), "bootstrap"), // $NON-NLS-1$
        embededEjbDir,
        new AntCopyUtils.FileSetFileFilter(excludeCvsSvn),
        new FilterSetCollection(),
        true);

    //			AntCopyUtils.copyFileToFile(
    //					persistenceFile,
    //					new File(testProjectDir,"test-src/META-INF/persistence.xml"), //$NON-NLS-1$
    //					new FilterSetCollection(filterSet), true);

    FilterSetCollection f = new FilterSetCollection();
    f.addFilterSet(filterSet);
    f.addFilterSet(jdbcFilterSet);

    AntCopyUtils.copyFileToFile(
        dataSourceFile,
        new File(
            testProjectDir,
            "test-src/META-INF/" + seamWebProject.getName() + "-test-ds.xml"), // $NON-NLS-1$
        f,
        true);

    AntCopyUtils.copyFileToFolder(
        seamPropertiesFile,
        testSrcDir, //$NON-NLS-1$
        new FilterSetCollection(filterSet),
        true);

    // Add "org.jboss.seam.core.init.debug=false" for Seam 2.1/2.2/2.3
    // to seam.properties file to avoid https://jira.jboss.org/jira/browse/JBIDE-3623
    if (getVersion() == SeamVersion.SEAM_2_1
        || getVersion() == SeamVersion.SEAM_2_2
        || getVersion() == SeamVersion.SEAM_2_3) {
      Properties seamProperties = new Properties();
      File testSeamPropertiesFile = new File(testSrcDir, "seam.properties");
      FileInputStream inStream = null;
      FileOutputStream out = null;
      try {
        inStream = new FileInputStream(testSeamPropertiesFile);
        seamProperties.load(inStream);
        seamProperties.setProperty(
            "org.jboss.seam.core.init.debug", "false"); // $NON-NLS-1$ //$NON-NLS-2$

        out = new FileOutputStream(testSeamPropertiesFile);
        seamProperties.store(out, "debug is explicitly disabled in test to avoid JBIDE-3623");
      } catch (FileNotFoundException e) {
        SeamCorePlugin.getPluginLog().logError(e);
      } catch (IOException e) {
        SeamCorePlugin.getPluginLog().logError(e);
      } finally {
        if (inStream != null) {
          try {
            inStream.close();
          } catch (IOException e) {
            /** ignore */
          }
        }
        if (out != null) {
          try {
            out.close();
          } catch (IOException e) {
            /** ignore */
          }
        }
      }
    }

    if (!SeamCorePlugin.getDefault().hasM2Facet(seamWebProject) && shouldCopyLibraries(model)) {
      AntCopyUtils.copyFiles(
          new File(seamRuntime.getHomeDir(), "lib"), // $NON-NLS-1$
          testLibDir,
          new AntCopyUtils.FileSetFileFilter(includeLibs));

      // seam2 has a lib/test
      AntCopyUtils.copyFiles(
          new File(seamRuntime.getHomeDir(), "lib/test"), // $NON-NLS-1$
          testLibDir,
          new AntCopyUtils.FileSetFileFilter(includeLibs));
    }

    SeamFacetAbstractInstallDelegate.createComponentsProperties(
        testSrcDir, "", true); // $NON-NLS-1$
    return true;
  }
 protected static IResource[] getUnderlyingResources(IProject project) {
   IVirtualComponent component = ComponentCore.createComponent(project);
   IVirtualFolder root = component.getRootFolder();
   IResource[] underlyingResources = root.getUnderlyingResources();
   return underlyingResources;
 }