Пример #1
0
 public static int convertVersionStringToInt(IVirtualComponent comp) {
   String version = J2EEProjectUtilities.getJ2EEProjectVersion(comp.getProject());
   if (JavaEEProjectUtilities.isDynamicWebProject(comp.getProject()))
     return convertWebVersionStringToJ2EEVersionID(version);
   if (JavaEEProjectUtilities.isEJBProject(comp.getProject()))
     return convertEJBVersionStringToJ2EEVersionID(version);
   if (JavaEEProjectUtilities.isEARProject(comp.getProject()))
     return convertVersionStringToInt(version);
   if (JavaEEProjectUtilities.isJCAProject(comp.getProject()))
     return convertConnectorVersionStringToJ2EEVersionID(version);
   if (JavaEEProjectUtilities.isApplicationClientProject(comp.getProject()))
     return convertAppClientVersionStringToJ2EEVersionID(version);
   return 0;
 }
  protected void configure(IProject project, MavenProject mavenProject, IProgressMonitor monitor)
      throws CoreException {
    IFacetedProject facetedProject = ProjectFacetsManager.create(project, true, monitor);

    // make sure to update the main deployment folder
    WarPluginConfiguration config = new WarPluginConfiguration(mavenProject, project);
    String warSourceDirectory = config.getWarSourceDirectory();
    IFile defaultWebXml = project.getFolder(warSourceDirectory).getFile("WEB-INF/web.xml");
    IFolder libDir = project.getFolder(warSourceDirectory).getFolder("WEB-INF/lib");

    boolean alreadyHasWebXml = defaultWebXml.exists();
    boolean alreadyHasLibDir = libDir.exists();

    Set<Action> actions = new LinkedHashSet<Action>();

    installJavaFacet(actions, project, facetedProject);

    IVirtualComponent component = ComponentCore.createComponent(project);
    if (component != null && warSourceDirectory != null) {
      IPath warPath = new Path(warSourceDirectory);
      // remove the old links (if there is one) before adding the new one.
      component.getRootFolder().removeLink(warPath, IVirtualResource.NONE, monitor);
      component.getRootFolder().createLink(warPath, IVirtualResource.NONE, monitor);
    }

    // MNGECLIPSE-2279 get the context root from the final name of the project, or artifactId by
    // default.
    String contextRoot = getContextRoot(mavenProject);

    IProjectFacetVersion webFv = config.getWebFacetVersion(project);
    if (!facetedProject.hasProjectFacet(WebFacetUtils.WEB_FACET)) {
      installWebFacet(mavenProject, warSourceDirectory, contextRoot, actions, webFv);
    } else {
      IProjectFacetVersion projectFacetVersion =
          facetedProject.getProjectFacetVersion(WebFacetUtils.WEB_FACET);
      if (webFv.getVersionString() != null
          && !webFv.getVersionString().equals(projectFacetVersion.getVersionString())) {
        try {
          Action uninstallAction =
              new IFacetedProject.Action(
                  IFacetedProject.Action.Type.UNINSTALL,
                  facetedProject.getInstalledVersion(WebFacetUtils.WEB_FACET),
                  null);
          facetedProject.modify(Collections.singleton(uninstallAction), monitor);
        } catch (Exception ex) {
          MavenLogger.log("Error removing WEB facet", ex);
        }
        installWebFacet(mavenProject, warSourceDirectory, contextRoot, actions, webFv);
      }
    }

    if (!actions.isEmpty()) {
      facetedProject.modify(actions, monitor);
    }

    // MNGECLIPSE-632 remove test sources/resources from WEB-INF/classes
    removeTestFolderLinks(project, mavenProject, monitor, "/WEB-INF/classes");

    addContainerAttribute(project, DEPENDENCY_ATTRIBUTE, monitor);

    // MNGECLIPSE-2279 change the context root if needed
    if (!contextRoot.equals(J2EEProjectUtilities.getServerContextRoot(project))) {
      J2EEProjectUtilities.setServerContextRoot(project, contextRoot);
    }

    // MNGECLIPSE-2357 support custom location of web.xml
    String customWebXml = config.getCustomWebXml(project);
    // If we have a custom web.xml but WTP created one against our will, we delete it
    if (customWebXml != null && !alreadyHasWebXml && defaultWebXml.exists()) {
      defaultWebXml.delete(true, monitor);
    }
    // Maven /m2eclipse doesn't need a new lib dir.
    if (!alreadyHasLibDir && libDir.exists()) {
      libDir.delete(true, monitor);
    }
    linkFile(project, customWebXml, "WEB-INF/web.xml", monitor);

    IPath filteredFolder = WebResourceFilteringConfiguration.getTargetFolder(mavenProject, project);
    if (component != null) {
      ProjectUtils.hideM2eclipseWtpFolder(mavenProject, project);
      component.getRootFolder().removeLink(filteredFolder, IVirtualResource.NONE, monitor);
      if (config.getWebResources() != null && config.getWebResources().length > 0) {
        component.getRootFolder().createLink(filteredFolder, IVirtualResource.NONE, monitor);
      }
    }
  }
  public void configureClasspath(
      IProject project,
      MavenProject mavenProject,
      IClasspathDescriptor classpath,
      IProgressMonitor monitor)
      throws CoreException {

    // Improve skinny war support by generating the manifest classpath
    // similar to mvn eclipse:eclipse
    // http://maven.apache.org/plugins/maven-war-plugin/examples/skinny-wars.html
    WarPluginConfiguration config = new WarPluginConfiguration(mavenProject, project);
    WarPackagingOptions opts = new WarPackagingOptions(config);

    StringBuilder manifestCp = new StringBuilder();

    /*
     * Need to take care of three separate cases
     *
     * 1. remove any project dependencies (they are represented as J2EE module dependencies)
     * 2. add non-dependency attribute for entries originated by artifacts with
     *    runtime, system, test scopes or optional dependencies (not sure about the last one)
     * 3. make sure all dependency JAR files have unique file names, i.e. artifactId/version collisions
     */

    Set<String> dups = new LinkedHashSet<String>();
    Set<String> names = new HashSet<String>();

    // first pass removes projects, adds non-dependency attribute and collects colliding filenames
    Iterator<IClasspathEntryDescriptor> iter = classpath.getEntryDescriptors().iterator();
    while (iter.hasNext()) {
      IClasspathEntryDescriptor descriptor = iter.next();
      IClasspathEntry entry = descriptor.getClasspathEntry();
      String scope = descriptor.getScope();
      String key =
          ArtifactUtils.versionlessKey(descriptor.getGroupId(), descriptor.getArtifactId());
      Artifact artifact = mavenProject.getArtifactMap().get(key);
      String extension = artifact.getArtifactHandler().getExtension();

      if (IClasspathEntry.CPE_PROJECT == entry.getEntryKind()
          && Artifact.SCOPE_COMPILE.equals(scope)) {
        // get deployed name for project dependencies
        // TODO can this be done somehow more elegantly?
        IProject p =
            (IProject) ResourcesPlugin.getWorkspace().getRoot().findMember(entry.getPath());

        IVirtualComponent component = ComponentCore.createComponent(p);

        boolean usedInEar = opts.isReferenceFromEar(component, extension);
        if (opts.isSkinnyWar() && usedInEar) {
          if (manifestCp.length() > 0) {
            manifestCp.append(" ");
          }
          // MNGECLIPSE-2393 prepend ManifestClasspath prefix
          if (config.getManifestClasspathPrefix() != null
              && !JEEPackaging.isJEEPackaging(artifact.getType())) {
            manifestCp.append(config.getManifestClasspathPrefix());
          }

          manifestCp.append(component.getDeployedName()).append(".").append(extension);
        }

        if (!descriptor.isOptionalDependency() || usedInEar) {
          // remove mandatory project dependency from classpath
          iter.remove();
          continue;
        } // else : optional dependency not used in ear -> need to trick ClasspathAttribute with
          // NONDEPENDENCY_ATTRIBUTE
      }

      if (opts.isSkinnyWar() && opts.isReferenceFromEar(descriptor)) {

        if (manifestCp.length() > 0) {
          manifestCp.append(" ");
        }
        if (config.getManifestClasspathPrefix() != null
            && !JEEPackaging.isJEEPackaging(artifact.getType())) {
          manifestCp.append(config.getManifestClasspathPrefix());
        }
        manifestCp.append(entry.getPath().lastSegment());

        // ear references aren't kept in the Maven Dependencies
        iter.remove();
        continue;
      }

      // add non-dependency attribute
      // Check the scope & set WTP non-dependency as appropriate
      // Optional artifact shouldn't be deployed
      if (Artifact.SCOPE_PROVIDED.equals(scope)
          || Artifact.SCOPE_TEST.equals(scope)
          || Artifact.SCOPE_SYSTEM.equals(scope)
          || descriptor.isOptionalDependency()) {
        descriptor.addClasspathAttribute(NONDEPENDENCY_ATTRIBUTE);
      }

      // collect duplicate file names
      if (!names.add(entry.getPath().lastSegment())) {
        dups.add(entry.getPath().lastSegment());
      }
    }

    String targetDir = mavenProject.getBuild().getDirectory();

    // second pass disambiguates colliding entry file names
    iter = classpath.getEntryDescriptors().iterator();
    while (iter.hasNext()) {
      IClasspathEntryDescriptor descriptor = iter.next();
      IClasspathEntry entry = descriptor.getClasspathEntry();

      if (dups.contains(entry.getPath().lastSegment())) {
        File src = new File(entry.getPath().toOSString());
        String groupId = descriptor.getGroupId();
        File dst = new File(targetDir, groupId + "-" + entry.getPath().lastSegment());
        try {
          if (src.canRead()) {
            if (isDifferent(src, dst)) { // uses lastModified
              FileUtils.copyFile(src, dst);
              dst.setLastModified(src.lastModified());
            }
            descriptor.setClasspathEntry(
                JavaCore.newLibraryEntry(
                    Path.fromOSString(dst.getCanonicalPath()), //
                    entry.getSourceAttachmentPath(), //
                    entry.getSourceAttachmentRootPath(), //
                    entry.getAccessRules(), //
                    entry.getExtraAttributes(), //
                    entry.isExported()));
          }
        } catch (IOException ex) {
          MavenLogger.log("File copy failed", ex);
        }
      }
    }

    if (opts.isSkinnyWar()) {

      // writing the manifest only works when the project has been properly created
      // placing this check on the top of the method broke 2 other tests
      // thats why its placed here now.
      if (ComponentCore.createComponent(project) == null) {
        return;
      }

      // write manifest, using internal API - seems ok for 3.4/3.5, though
      ArchiveManifest mf = J2EEProjectUtilities.readManifest(project);
      if (mf == null) {
        mf = new ArchiveManifestImpl();
      }
      mf.addVersionIfNecessary();
      mf.setClassPath(manifestCp.toString());

      try {
        J2EEProjectUtilities.writeManifest(project, mf);
      } catch (Exception ex) {
        MavenLogger.log("Could not write web module manifest file", ex);
      }
    }
  }
  protected void configure(IProject project, MavenProject mavenProject, IProgressMonitor monitor)
      throws CoreException {
    IFacetedProject facetedProject = ProjectFacetsManager.create(project, true, monitor);
    IMavenProjectFacade facade =
        MavenPlugin.getMavenProjectRegistry()
            .create(project.getFile(IMavenConstants.POM_FILE_NAME), true, monitor);

    // make sure to update the main deployment folder
    WarPluginConfiguration config = new WarPluginConfiguration(mavenProject, project);
    String warSourceDirectory = config.getWarSourceDirectory();

    IFolder contentFolder = project.getFolder(warSourceDirectory);

    Set<Action> actions = new LinkedHashSet<Action>();

    installJavaFacet(actions, project, facetedProject);

    IVirtualComponent component = ComponentCore.createComponent(project, true);

    // MNGECLIPSE-2279 get the context root from the final name of the project, or artifactId by
    // default.
    String contextRoot = getContextRoot(mavenProject, config.getWarName());

    IProjectFacetVersion webFv = config.getWebFacetVersion(project);
    IDataModel webModelCfg = getWebModelConfig(warSourceDirectory, contextRoot);
    if (!facetedProject.hasProjectFacet(WebFacetUtils.WEB_FACET)) {
      removeConflictingFacets(facetedProject, webFv, actions);
      actions.add(
          new IFacetedProject.Action(IFacetedProject.Action.Type.INSTALL, webFv, webModelCfg));
    } else {
      IProjectFacetVersion projectFacetVersion =
          facetedProject.getProjectFacetVersion(WebFacetUtils.WEB_FACET);
      if (webFv.getVersionString() != null
          && !webFv.getVersionString().equals(projectFacetVersion.getVersionString())) {
        actions.add(
            new IFacetedProject.Action(
                IFacetedProject.Action.Type.VERSION_CHANGE, webFv, webModelCfg));
      }
    }

    String customWebXml = config.getCustomWebXml(project);

    if (!actions.isEmpty()) {
      ResourceCleaner fileCleaner = new ResourceCleaner(project);
      try {
        addFilesToClean(fileCleaner, facade.getResourceLocations());
        addFilesToClean(fileCleaner, facade.getCompileSourceLocations());
        IFolder libDir = project.getFolder(warSourceDirectory).getFolder("WEB-INF/lib");
        fileCleaner.addFiles(
            contentFolder.getFile("META-INF/MANIFEST.MF").getProjectRelativePath());
        fileCleaner.addFolder(libDir, false);
        if (customWebXml != null) {
          IFile defaultWebXml = project.getFolder(warSourceDirectory).getFile("WEB-INF/web.xml");
          fileCleaner.addFiles(defaultWebXml.getProjectRelativePath());
        }

        facetedProject.modify(actions, monitor);
      } finally {
        // Remove any unwanted MANIFEST.MF the Facet installation has created
        fileCleaner.cleanUp();
      }
    }

    // MECLIPSEWTP-41 Fix the missing moduleCoreNature
    fixMissingModuleCoreNature(project, monitor);

    // MNGECLIPSE-632 remove test sources/resources from WEB-INF/classes
    removeTestFolderLinks(project, mavenProject, monitor, "/WEB-INF/classes");

    addContainerAttribute(project, DEPENDENCY_ATTRIBUTE, monitor);

    // MNGECLIPSE-2279 change the context root if needed
    if (!contextRoot.equals(J2EEProjectUtilities.getServerContextRoot(project))) {
      J2EEProjectUtilities.setServerContextRoot(project, contextRoot);
    }

    // If we have a custom web.xml but WTP created one against our will, we delete it
    if (customWebXml != null) {
      linkFileFirst(project, customWebXml, "/WEB-INF/web.xml", monitor);
    }

    component = ComponentCore.createComponent(project, true);
    if (component != null) {
      IPath warPath = new Path("/").append(contentFolder.getProjectRelativePath());
      List<IPath> sourcePaths = new ArrayList<IPath>();
      sourcePaths.add(warPath);
      if (!WTPProjectsUtil.hasLink(project, ROOT_PATH, warPath, monitor)) {
        component.getRootFolder().createLink(warPath, IVirtualResource.NONE, monitor);
      }
      // MECLIPSEWTP-22 support web filtered resources. Filtered resources directory must be
      // declared BEFORE
      // the regular web source directory. First resources discovered take precedence on deployment
      IPath filteredFolder =
          new Path("/")
              .append(WebResourceFilteringConfiguration.getTargetFolder(mavenProject, project));

      boolean useBuildDir =
          MavenWtpPlugin.getDefault()
              .getMavenWtpPreferencesManager()
              .getPreferences(project)
              .isWebMavenArchiverUsesBuildDirectory();
      boolean useWebresourcefiltering =
          config.getWebResources() != null && config.getWebResources().length > 0
              || config.isFilteringDeploymentDescriptorsEnabled();

      if (useBuildDir || useWebresourcefiltering) {

        if (!useBuildDir && useWebresourcefiltering) {
          mavenMarkerManager.addMarker(
              project,
              MavenWtpConstants.WTP_MARKER_CONFIGURATION_ERROR_ID,
              Messages.markers_mavenarchiver_output_settings_ignored_warning,
              -1,
              IMarker.SEVERITY_WARNING);
        }
        sourcePaths.add(filteredFolder);
        WTPProjectsUtil.insertLinkBefore(project, filteredFolder, warPath, new Path("/"), monitor);
      } else {
        component.getRootFolder().removeLink(filteredFolder, IVirtualResource.NONE, monitor);
      }

      WTPProjectsUtil.deleteLinks(project, ROOT_PATH, sourcePaths, monitor);

      WTPProjectsUtil.setDefaultDeploymentDescriptorFolder(
          component.getRootFolder(), warPath, monitor);

      addComponentExclusionPatterns(component, config);
    }

    WTPProjectsUtil.removeWTPClasspathContainer(project);

    // MECLIPSEWTP-214 : add (in|ex)clusion patterns as .component metadata
  }