private String getDefaultFinalName(final Artifact artifact) { return artifact.getArtifactId() + "-" + artifact.getVersion() + "." + artifact.getArtifactHandler().getExtension(); }
/** * Filters the specified {@link Artifact}s to those that match the following criteria: * * <ul> * <li>{@link Artifact#isResolved()} is <code>true</code> * <li>{@link Artifact#getArtifactHandler().getExtension()} equals "jar" * <li>{@link Artifact#getScope()} equals {@link Artifact#SCOPE_COMPILE} * <li>{@link Artifact#getFile()} returns a {@link File} where {@link File#isFile()} is <code> * true</code> * </ul> * * @param artifacts the {@link Set} of {@link Artifact}s to filter * @return the actual JAR {@link File}s available from the specified {@link Artifact}s */ public static List<File> filterToResolvedJars(List<Artifact> artifacts) { List<File> resolvedJarArtifacts = new ArrayList<File>(); ScopeArtifactFilter filter = new ScopeArtifactFilter(Artifact.SCOPE_COMPILE_PLUS_RUNTIME); for (Artifact artifact : artifacts) { // Ensure that this Artifact should be included if (!artifact.isResolved()) continue; if (artifact.getArtifactHandler() == null || !"jar".equalsIgnoreCase(artifact.getArtifactHandler().getExtension())) continue; if (!filter.include(artifact)) continue; // Ensure that the Artifact resolves to a File that we can use File artifactJarFile = artifact.getFile(); if (!artifactJarFile.isFile()) continue; resolvedJarArtifacts.add(artifactJarFile); } return resolvedJarArtifacts; }
public String mapFileName(Artifact artifact) { StringBuilder fileName = new StringBuilder(artifact.getArtifactId()); String classifier = artifact.getClassifier(); if (classifier != null) { fileName.append("-").append(classifier); } if (!isRemoveDependencyVersions()) { fileName.append("-").append(artifact.getVersion()); } fileName.append(".").append(artifact.getArtifactHandler().getExtension()); return fileName.toString(); }
/** * Builds the string to be entered in the href attribute of the jar resource element in the * generated JNLP file. This will be equal to the artifact file name with the version number * stripped out. * * @param artifact The underlying artifact of the jar resource. * @return The href string for the given artifact, never null. */ private String buildHrefValue(Artifact artifact) { StringBuffer sbuf = new StringBuffer(); sbuf.append(artifact.getArtifactId()); if (StringUtils.isNotEmpty(artifact.getClassifier())) { sbuf.append("-").append(artifact.getClassifier()); } sbuf.append(".").append(artifact.getArtifactHandler().getExtension()); return sbuf.toString(); }
public boolean isExcluded(Artifact artifact) { if (isExcludeAll() || !artifact.getArtifactHandler().isAddedToClasspath()) { return true; } if (getExcludes() != null) { for (String groupIdArtifactId : excludes) { if (groupIdArtifactId.equals(artifact.getGroupId() + ":" + artifact.getArtifactId())) { return true; } } } return false; }
private void logArtifacts(Collection<Artifact> collection) { List<Artifact> artifacts = new ArrayList<Artifact>(collection); Collections.sort( artifacts, new Comparator<Artifact>() { public int compare(Artifact o1, Artifact o2) { return o1.getArtifactId().compareTo(o2.getArtifactId()); } }); for (Artifact artifact : artifacts) { getLog() .debug( " " + artifact.getArtifactId() + "-" + artifact.getVersion() + "." + artifact.getArtifactHandler().getExtension()); } }
private String artifactToMvn(Artifact artifact) throws MojoExecutionException { String uri; String groupId = artifact.getGroupId(); String artifactId = artifact.getArtifactId(); String version = artifact.getBaseVersion(); String type = artifact.getArtifactHandler().getExtension(); String classifier = artifact.getClassifier(); if (MavenUtil.isEmpty(classifier)) { if ("jar".equals(type)) { uri = String.format("mvn:%s/%s/%s", groupId, artifactId, version); } else { uri = String.format("mvn:%s/%s/%s/%s", groupId, artifactId, version, type); } } else { uri = String.format("mvn:%s/%s/%s/%s/%s", groupId, artifactId, version, type, classifier); } return uri; }
private void addDependencies(Archiver archiver) throws ArchiverException, MojoExecutionException { Log log = getLog(); AndArtifactFilter filter = new AndArtifactFilter(); filter.add(new ScopeArtifactFilter(Artifact.SCOPE_RUNTIME)); filter.add( new ArtifactFilter() { public boolean include(Artifact artifact) { return !artifact.isOptional(); } }); filter.add(new TypeArtifactFilter("jar")); filter.add(buildSynapseRuntimeArtifactFilter()); for (Artifact artifact : filterArtifacts((Set<Artifact>) project.getArtifacts(), filter)) { String targetFileName = artifact.getArtifactId() + "-" + artifact.getVersion() + "." + artifact.getArtifactHandler().getExtension(); log.info("Adding " + targetFileName + " (scope " + artifact.getScope() + ")"); archiver.addFile(artifact.getFile(), "lib/" + targetFileName); } }
/** * Generate the test classpath. * * @return List containing the classpath elements * @throws MojoFailureException when it happens */ public Set<URL> getUrlsForCustomClasspath() throws MojoFailureException, MojoExecutionException { Set<URL> classpath = new HashSet<URL>(2 + getProject().getArtifacts().size()); try { classpath.add(getTestClassesDirectory().getAbsoluteFile().toURI().toURL()); classpath.add(getClassesDirectory().getAbsoluteFile().toURI().toURL()); @SuppressWarnings("unchecked") Set<Artifact> classpathArtifacts = getProject().getArtifacts(); for (Artifact artifact : classpathArtifacts) { if (artifact.getArtifactHandler().isAddedToClasspath() && !artifact.getGroupId().startsWith("org.apache.maven")) { File file = artifact.getFile(); if (file != null) { classpath.add(file.toURI().toURL()); } } } } catch (MalformedURLException e) { getLog().error(e.getMessage(), e); } return classpath; }
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); } } }
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 } } } }
/** * Resolve project dependencies. Manual resolution is needed in order to avoid resoltion of * multiproject artifacts (if projects will be linked each other an installed jar is not needed) * and to avoid a failure when a jar is missing. * * @throws MojoExecutionException if dependencies can't be resolved * @return resoved IDE dependencies, with attached jars for non-reactor dependencies */ protected IdeDependency[] doDependencyResolution() throws MojoExecutionException { MavenProject project = getProject(); ArtifactRepository localRepo = getLocalRepository(); List dependencies = getProject().getDependencies(); // Collect the list of resolved IdeDependencies. List dependencyList = new ArrayList(); if (dependencies != null) { Map managedVersions = createManagedVersionMap( getArtifactFactory(), project.getId(), project.getDependencyManagement()); ArtifactResolutionResult artifactResolutionResult = null; try { List listeners = new ArrayList(); if (logger.isDebugEnabled()) { listeners.add(new DebugResolutionListener(logger)); } listeners.add(new WarningResolutionListener(logger)); artifactResolutionResult = artifactCollector.collect( getProjectArtifacts(), project.getArtifact(), managedVersions, localRepo, project.getRemoteArtifactRepositories(), getArtifactMetadataSource(), null, listeners); } catch (ArtifactResolutionException e) { getLog().debug(e.getMessage(), e); getLog() .error( Messages.getString( "artifactresolution", new Object[] { // $NON-NLS-1$ e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage() })); // if we are here artifactResolutionResult is null, create a project without dependencies // but don't fail // (this could be a reactor projects, we don't want to fail everything) return new IdeDependency[0]; } // keep track of added reactor projects in order to avoid duplicates Set emittedReactorProjectId = new HashSet(); for (Iterator i = artifactResolutionResult.getArtifactResolutionNodes().iterator(); i.hasNext(); ) { ResolutionNode node = (ResolutionNode) i.next(); Artifact art = node.getArtifact(); boolean isReactorProject = getUseProjectReferences() && isAvailableAsAReactorProject(art); // don't resolve jars for reactor projects if (!isReactorProject) { try { artifactResolver.resolve(art, node.getRemoteRepositories(), localRepository); } catch (ArtifactNotFoundException e) { getLog().debug(e.getMessage(), e); getLog() .warn( Messages.getString( "artifactdownload", new Object[] { // $NON-NLS-1$ e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage() })); } catch (ArtifactResolutionException e) { getLog().debug(e.getMessage(), e); getLog() .warn( Messages.getString( "artifactresolution", new Object[] { // $NON-NLS-1$ e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage() })); } } if (!isReactorProject || emittedReactorProjectId.add(art.getGroupId() + '-' + art.getArtifactId())) { IdeDependency dep = new IdeDependency( art.getGroupId(), art.getArtifactId(), art.getVersion(), isReactorProject, Artifact.SCOPE_TEST.equals(art.getScope()), Artifact.SCOPE_SYSTEM.equals(art.getScope()), Artifact.SCOPE_PROVIDED.equals(art.getScope()), art.getArtifactHandler().isAddedToClasspath(), art.getFile(), art.getType()); dependencyList.add(dep); } } // @todo a final report with the list of missingArtifacts? } IdeDependency[] deps = (IdeDependency[]) dependencyList.toArray(new IdeDependency[dependencyList.size()]); return deps; }
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); IPackagingConfiguration opts = new PackagingConfiguration(config.getPackagingIncludes(), config.getPackagingExcludes()); /* * 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>(); FileNameMapping fileNameMapping = config.getFileNameMapping(); String targetDir = mavenProject.getBuild().getDirectory(); // 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.toClasspathEntry(); String scope = descriptor.getScope(); Artifact artifact = ArtifactHelper.getArtifact(mavenProject.getArtifacts(), descriptor.getArtifactKey()); ArtifactHelper.fixArtifactHandler(artifact.getArtifactHandler()); String deployedName = fileNameMapping.mapFileName(artifact); boolean isDeployed = (Artifact.SCOPE_COMPILE.equals(scope) || Artifact.SCOPE_RUNTIME.equals(scope)) && !descriptor.isOptionalDependency() && opts.isPackaged("WEB-INF/lib/" + deployedName) && !isWorkspaceProject(artifact); // add non-dependency attribute if this classpathentry is not meant to be deployed // or if it's a workspace project (projects already have a reference created in configure()) if (!isDeployed) { descriptor.setClasspathAttribute( NONDEPENDENCY_ATTRIBUTE.getName(), NONDEPENDENCY_ATTRIBUTE.getValue()); } // If custom fileName is used, then copy the artifact and rename the artifact under the build // dir String fileName = entry.getPath().lastSegment(); if (!deployedName.equals(fileName)) { IPath newPath = renameArtifact(targetDir, entry.getPath(), deployedName); if (newPath != null) { descriptor.setPath(newPath); } } if (!names.add(deployedName)) { dups.add(deployedName); } } // second pass disambiguates colliding entry file names iter = classpath.getEntryDescriptors().iterator(); while (iter.hasNext()) { IClasspathEntryDescriptor descriptor = iter.next(); IClasspathEntry entry = descriptor.toClasspathEntry(); if (dups.contains(entry.getPath().lastSegment())) { String newName = descriptor.getGroupId() + "-" + entry.getPath().lastSegment(); IPath newPath = renameArtifact(targetDir, entry.getPath(), newName); if (newPath != null) { descriptor.setPath(newPath); } } } }
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 } } } }