List of usage examples for org.apache.maven.project MavenProject getArtifacts
public Set<Artifact> getArtifacts()
From source file:org.phpmaven.project.impl.ProjectPhpExecution.java
License:Apache License
/** * Adds project dependencies (/target/classes) for given scope (needed for IDE/multi-pom). * @param execConfig executable config.//from www.j av a2 s. c o m * @param project project. * @param targetScope target scope. * @throws ExpressionEvaluationException thrown on errors. * @since 2.0.1 */ private void addProjectDependencies(IPhpExecutableConfiguration execConfig, MavenProject project, final String targetScope, IDependencyConfiguration depConfig) throws ExpressionEvaluationException { final Set<Artifact> deps = project.getArtifacts(); for (final Artifact dep : deps) { if (!targetScope.equals(dep.getScope())) { continue; } boolean foundDepConfig = false; for (final IDependency depC : depConfig.getDependencies()) { if (depC.getGroupId().equals(dep.getGroupId()) && depC.getArtifactId().equals(dep.getArtifactId())) { foundDepConfig = true; } } if (foundDepConfig) { // was already be performed by addFromDepConfig() continue; } try { final MavenProject depProject = this.getProjectFromArtifact(project, dep); if (depProject.getFile() != null) { // Reference to a local project; should only happen in IDEs or multi-project poms final String depTargetDir = getClassesDirFromProject(depProject); execConfig.getIncludePath().add(depTargetDir); } } catch (ProjectBuildingException ex) { throw new ExpressionEvaluationException("Problems creating maven project from dependency", ex); } } }
From source file:org.rhq.maven.plugins.Utils.java
License:Open Source License
public static Set<File> findParentPlugins(MavenProject agentPluginProject) throws IOException { Set<File> parentPlugins = new HashSet<File>(); Iterator projectArtifacts = agentPluginProject.getArtifacts().iterator(); ScopeArtifactFilter artifactFilter = new ScopeArtifactFilter(Artifact.SCOPE_COMPILE); while (projectArtifacts.hasNext()) { Artifact artifact = (Artifact) projectArtifacts.next(); if (!artifact.isOptional() && artifact.getType().equals("jar") && artifactFilter.include(artifact)) { File artifactFile = artifact.getFile(); if (isAgentPlugin(artifactFile)) { parentPlugins.add(artifactFile); }/* ww w.j a va 2 s . c o m*/ } } return parentPlugins; }
From source file:org.sakaiproject.maven.plugin.component.AbstractComponentMojo.java
License:Apache License
/** * Builds the webapp for the specified project. <p/> Classes, libraries and * tld files are copied to the <tt>webappDirectory</tt> during this phase. * /* w w w.java2 s. co m*/ * @param project * the maven project * @param webappDirectory * @throws java.io.IOException * if an error occured while building the webapp */ public void buildWebapp(MavenProject project, File webappDirectory) throws MojoExecutionException, IOException, MojoFailureException { getLog().info("Assembling webapp " + project.getArtifactId() + " in " + webappDirectory); File webinfDir = new File(webappDirectory, WEB_INF); webinfDir.mkdirs(); File metainfDir = new File(webappDirectory, META_INF); metainfDir.mkdirs(); List webResources = this.webResources != null ? Arrays.asList(this.webResources) : null; if (webResources != null && webResources.size() > 0) { Map filterProperties = getBuildFilterProperties(); for (Iterator it = webResources.iterator(); it.hasNext();) { Resource resource = (Resource) it.next(); copyResources(resource, webappDirectory, filterProperties); } } copyResources(warSourceDirectory, webappDirectory); if (webXml != null && StringUtils.isNotEmpty(webXml.getName())) { if (!webXml.exists()) { throw new MojoFailureException("The specified web.xml file '" + webXml + "' does not exist"); } // rename to web.xml copyFileIfModified(webXml, new File(webinfDir, "/web.xml")); } checkComponentWebXmlExists(new File(webinfDir, "/web.xml")); if (containerConfigXML != null && StringUtils.isNotEmpty(containerConfigXML.getName())) { metainfDir = new File(webappDirectory, META_INF); String xmlFileName = containerConfigXML.getName(); copyFileIfModified(containerConfigXML, new File(metainfDir, xmlFileName)); } File libDirectory = new File(webinfDir, "lib"); File tldDirectory = new File(webinfDir, "tld"); File webappClassesDirectory = new File(webappDirectory, WEB_INF + "/classes"); if (classesDirectory.exists() && !classesDirectory.equals(webappClassesDirectory)) { if (archiveClasses) { createJarArchive(libDirectory); } else { copyDirectoryStructureIfModified(classesDirectory, webappClassesDirectory); } } Set artifacts = project.getArtifacts(); List duplicates = findDuplicates(artifacts); List dependentWarDirectories = new ArrayList(); for (Iterator iter = artifacts.iterator(); iter.hasNext();) { Artifact artifact = (Artifact) iter.next(); String targetFileName = getDefaultFinalName(artifact); getLog().debug("Processing: " + targetFileName); if (duplicates.contains(targetFileName)) { getLog().debug("Duplicate found: " + targetFileName); targetFileName = artifact.getGroupId() + "-" + targetFileName; getLog().debug("Renamed to: " + targetFileName); } // TODO: utilise appropriate methods from project builder ScopeArtifactFilter filter = new ScopeArtifactFilter(Artifact.SCOPE_RUNTIME); if (!artifact.isOptional() && filter.include(artifact)) { String type = artifact.getType(); if ("tld".equals(type)) { copyFileIfModified(artifact.getFile(), new File(tldDirectory, targetFileName)); } else { if ("jar".equals(type) || "ejb".equals(type) || "ejb-client".equals(type)) { copyFileIfModified(artifact.getFile(), new File(libDirectory, targetFileName)); } else { if ("par".equals(type)) { targetFileName = targetFileName.substring(0, targetFileName.lastIndexOf('.')) + ".jar"; getLog().debug("Copying " + artifact.getFile() + " to " + new File(libDirectory, targetFileName)); copyFileIfModified(artifact.getFile(), new File(libDirectory, targetFileName)); } else { if ("war".equals(type)) { dependentWarDirectories.add(unpackWarToTempDirectory(artifact)); } else { getLog().debug("Skipping artifact of type " + type + " for WEB-INF/lib"); } } } } } } if (dependentWarDirectories.size() > 0) { getLog().info("Overlaying " + dependentWarDirectories.size() + " war(s)."); // overlay dependent wars for (Iterator iter = dependentWarDirectories.iterator(); iter.hasNext();) { copyDependentWarContents((File) iter.next(), webappDirectory); } } }
From source file:org.seasar.jsf.selenium.MavenUtil.java
License:Apache License
public static File getArtifactFromPom(File pom, String artifactId) { MavenEmbedder maven = new MavenEmbedder(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); maven.setClassLoader(classLoader);//from w ww . j a v a2s . com MavenEmbedderConsoleLogger logger = new MavenEmbedderConsoleLogger(); logger.setThreshold(MavenEmbedderLogger.LEVEL_ERROR); maven.setLogger(logger); try { maven.start(); MavenProject mavenProject = maven.readProjectWithDependencies(pom); Artifact targetArtifact = null; for (Iterator it = mavenProject.getArtifacts().iterator(); it.hasNext();) { Artifact artifact = (Artifact) it.next(); if (artifactId.equals(artifact.getArtifactId())) { targetArtifact = artifact; } } if (targetArtifact == null) { throw new RuntimeException("[" + artifactId + "] not found. from " + pom); } File targetArtifactFile = targetArtifact.getFile().getCanonicalFile(); maven.stop(); return targetArtifactFile; } catch (MavenEmbedderException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (ArtifactResolutionException e) { throw new RuntimeException(e); } catch (ArtifactNotFoundException e) { throw new RuntimeException(e); } catch (ProjectBuildingException e) { throw new RuntimeException(e); } }
From source file:org.seasar.kvasir.plust.KvasirPlugin.java
@SuppressWarnings("unchecked") public void resolveClasspathEntries(Set<IClasspathEntry> libraryEntries, Set<String> moduleArtifacts, IFile pomFile, boolean recursive, boolean downloadSources, IProgressMonitor monitor) { monitor.beginTask("Reading " + pomFile.getLocation(), IProgressMonitor.UNKNOWN); try {/*from w w w. ja va 2 s. c o m*/ if (monitor.isCanceled()) { throw new OperationCanceledException(); } final MavenProject mavenProject = getMavenProject(pomFile, new SubProgressMonitor(monitor, 1)); if (mavenProject == null) { return; } deleteMarkers(pomFile); // TODO use version? moduleArtifacts.add(mavenProject.getGroupId() + ":" + mavenProject.getArtifactId()); Set artifacts = mavenProject.getArtifacts(); for (Iterator it = artifacts.iterator(); it.hasNext();) { if (monitor.isCanceled()) { throw new OperationCanceledException(); } final Artifact a = (Artifact) it.next(); monitor.subTask("Processing " + a.getId()); if (!"jar".equals(a.getType())) { continue; } // TODO use version? if (!moduleArtifacts.contains(a.getGroupId() + ":" + a.getArtifactId()) && // TODO verify if there is an Eclipse API to check that archive is acceptable ("jar".equals(a.getType()) || "zip".equals(a.getType()))) { String artifactLocation = a.getFile().getAbsolutePath(); // TODO add a lookup through workspace projects Path srcPath = null; File srcFile = new File( artifactLocation.substring(0, artifactLocation.length() - 4) + "-sources.jar"); if (srcFile.exists()) { // XXX ugly hack to do not download any sources srcPath = new Path(srcFile.getAbsolutePath()); } else if (downloadSources && !isSourceChecked(a)) { srcPath = (Path) executeInEmbedder(new MavenEmbedderCallback() { public Object run(MavenEmbedder mavenEmbedder, IProgressMonitor monitor) { monitor.beginTask("Resolve sources " + a.getId(), IProgressMonitor.UNKNOWN); try { Artifact src = mavenEmbedder.createArtifactWithClassifier(a.getGroupId(), a.getArtifactId(), a.getVersion(), "java-source", "sources"); if (src != null) { mavenEmbedder.resolve(src, mavenProject.getRemoteArtifactRepositories(), mavenEmbedder.getLocalRepository()); return new Path(src.getFile().getAbsolutePath()); } } catch (AbstractArtifactResolutionException ex) { String name = ex.getGroupId() + ":" + ex.getArtifactId() + "-" + ex.getVersion() + "." + ex.getType(); getConsole().logMessage(ex.getOriginalMessage() + " " + name); } finally { monitor.done(); } return null; } }, new SubProgressMonitor(monitor, 1)); setSourceChecked(a); } libraryEntries.add(JavaCore.newLibraryEntry(new Path(artifactLocation), srcPath, null)); } } if (recursive) { IContainer parent = pomFile.getParent(); List modules = mavenProject.getModules(); for (Iterator it = modules.iterator(); it.hasNext() && !monitor.isCanceled();) { if (monitor.isCanceled()) { throw new OperationCanceledException(); } String module = (String) it.next(); IResource memberPom = parent.findMember(module + "/" + IKvasirProject.POM_FILE_NAME); if (memberPom != null && memberPom.getType() == IResource.FILE) { resolveClasspathEntries(libraryEntries, moduleArtifacts, (IFile) memberPom, true, downloadSources, new SubProgressMonitor(monitor, 1)); } } } } catch (OperationCanceledException ex) { throw ex; } catch (InvalidArtifactRTException ex) { addMarker(pomFile, ex.getBaseMessage(), 1, IMarker.SEVERITY_ERROR); } catch (Throwable ex) { addMarker(pomFile, ex.toString(), 1, IMarker.SEVERITY_ERROR); } finally { monitor.done(); } }
From source file:org.seasar.teeda.util.MavenUtil.java
License:Apache License
public static File getArtifactFromPom(final File pom, final String artifactId) { final MavenEmbedder maven = new MavenEmbedder(); final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); maven.setClassLoader(classLoader);/*w ww . j a v a 2 s . co m*/ final MavenEmbedderConsoleLogger logger = new MavenEmbedderConsoleLogger(); logger.setThreshold(MavenEmbedderLogger.LEVEL_ERROR); maven.setLogger(logger); try { maven.start(); final MavenProject mavenProject = maven.readProjectWithDependencies(pom); Artifact targetArtifact = null; for (final Iterator it = mavenProject.getArtifacts().iterator(); it.hasNext();) { final Artifact artifact = (Artifact) it.next(); if (artifactId.equals(artifact.getArtifactId())) { targetArtifact = artifact; } } if (targetArtifact == null) { throw new RuntimeException("[" + artifactId + "] not found. from " + pom); } final File targetArtifactFile = targetArtifact.getFile().getCanonicalFile(); maven.stop(); return targetArtifactFile; } catch (final MavenEmbedderException e) { throw new RuntimeException(e); } catch (final IOException e) { throw new RuntimeException(e); } catch (final ArtifactResolutionException e) { throw new RuntimeException(e); } catch (final ArtifactNotFoundException e) { throw new RuntimeException(e); } catch (final ProjectBuildingException e) { throw new RuntimeException(e); } }
From source file:org.sonatype.flexmojos.war.CopyMojo.java
License:Apache License
@SuppressWarnings("unchecked") private List<Artifact> getArtifacts(String type, MavenProject project) { List<Artifact> swfArtifacts = new ArrayList<Artifact>(); Set<Artifact> artifacts = project.getArtifacts(); for (Artifact artifact : artifacts) { if (type.equals(artifact.getType())) { swfArtifacts.add(artifact);//from www. j a v a 2 s . c o m } } return swfArtifacts; }
From source file:org.sonatype.m2e.mavenarchiver.internal.AbstractMavenArchiverConfigurator.java
License:Open Source License
/** * Checks if the MANIFEST.MF needs to be regenerated. That is if : * <ul><li>it doesn't already exist</li> * <li>the maven project configuration changed</li> * <li>the maven project dependencies changed</li> * </ul> /* w w w. java 2 s. c om*/ * Implementations can override this method to add pre-conditions. * @param manifest the MANIFEST.MF file to control * @param oldFacade the old maven facade project configuration * @param newFacade the new maven facade project configuration * @param monitor the progress monitor * @return true if the MANIFEST.MF needs to be regenerated */ protected boolean needsNewManifest(IFile manifest, IMavenProjectFacade oldFacade, IMavenProjectFacade newFacade, IProgressMonitor monitor) { if (!manifest.exists()) { return true; } //Can't compare to a previous state, so assuming it's unchanged //This situation actually occurs during incremental builds, //when called from the buildParticipant if (oldFacade == null || oldFacade.getMavenProject() == null) { return false; } MavenProject newProject = newFacade.getMavenProject(); MavenProject oldProject = oldFacade.getMavenProject(); //Assume Sets of artifacts are actually ordered if (dependenciesChanged( oldProject.getArtifacts() == null ? null : new ArrayList<Artifact>(oldProject.getArtifacts()), newProject.getArtifacts() == null ? null : new ArrayList<Artifact>(newProject.getArtifacts()))) { return true; } Xpp3Dom oldArchiveConfig = getArchiveConfiguration(oldProject); Xpp3Dom newArchiveConfig = getArchiveConfiguration(newProject); if (newArchiveConfig != null && !newArchiveConfig.equals(oldArchiveConfig) || oldArchiveConfig != null) { return true; } //Name always not null if (!newProject.getName().equals(oldProject.getName())) { return true; } String oldOrganizationName = oldProject.getOrganization() == null ? null : oldProject.getOrganization().getName(); String newOrganizationName = newProject.getOrganization() == null ? null : newProject.getOrganization().getName(); if (newOrganizationName != null && !newOrganizationName.equals(oldOrganizationName) || oldOrganizationName != null && newOrganizationName == null) { return true; } return false; }
From source file:org.sonatype.m2e.mavenarchiver.internal.AbstractMavenArchiverConfigurator.java
License:Open Source License
public void generateManifest(IMavenProjectFacade mavenFacade, IFile manifest, IProgressMonitor monitor) throws CoreException { MavenProject mavenProject = mavenFacade.getMavenProject(); Set<Artifact> originalArtifacts = mavenProject.getArtifacts(); boolean parentHierarchyLoaded = false; try {/* w ww .ja v a 2s . c om*/ markerManager.deleteMarkers(mavenFacade.getPom(), MavenArchiverConstants.MAVENARCHIVER_MARKER_ERROR); //Find the mojoExecution MavenSession session = getMavenSession(mavenFacade, monitor); parentHierarchyLoaded = loadParentHierarchy(mavenFacade, monitor); ClassLoader originalTCL = Thread.currentThread().getContextClassLoader(); try { ClassRealm projectRealm = mavenProject.getClassRealm(); if (projectRealm != null && projectRealm != originalTCL) { Thread.currentThread().setContextClassLoader(projectRealm); } MavenExecutionPlan executionPlan = maven.calculateExecutionPlan(session, mavenProject, Collections.singletonList("package"), true, monitor); MojoExecution mojoExecution = getExecution(executionPlan, getExecutionKey()); if (mojoExecution == null) { return; } //Get the target manifest file IFolder destinationFolder = (IFolder) manifest.getParent(); M2EUtils.createFolder(destinationFolder, true, monitor); //Workspace project artifacts don't have a valid getFile(), so won't appear in the manifest //We need to workaround the issue by creating fake files for such artifacts. //We could also use a custom File implementation having "public boolean exists(){return true;}" mavenProject.setArtifacts(fixArtifactFileNames(mavenFacade)); //Invoke the manifest generation API via reflection reflectManifestGeneration(mavenProject, mojoExecution, session, new File(manifest.getLocation().toOSString())); } finally { Thread.currentThread().setContextClassLoader(originalTCL); } } catch (Exception ex) { markerManager.addErrorMarkers(mavenFacade.getPom(), MavenArchiverConstants.MAVENARCHIVER_MARKER_ERROR, ex); } finally { //Restore the project state mavenProject.setArtifacts(originalArtifacts); if (parentHierarchyLoaded) { mavenProject.setParent(null); } } }
From source file:org.sonatype.m2e.webby.internal.config.WarConfigurationExtractor.java
License:Open Source License
public WarConfiguration getConfiguration(IMavenProjectFacade mvnFacade, MavenProject mvnProject, MavenSession mvnSession, IProgressMonitor monitor) throws CoreException { SubMonitor pm = SubMonitor.convert(monitor, "Reading WAR configuration...", 100); try {//from w w w . j a v a 2 s. co m WarConfiguration warConfig = new WarConfiguration(); List<MojoExecution> mojoExecs = mvnFacade.getMojoExecutions(WAR_PLUGIN_GID, WAR_PLUGIN_AID, pm.newChild(90), "war"); IMaven maven = MavenPlugin.getMaven(); String basedir = mvnProject.getBasedir().getAbsolutePath(); String encoding = mvnProject.getProperties().getProperty("project.build.sourceEncoding"); warConfig.setWorkDirectory(getWorkDirectory(mvnProject)); warConfig.setClassesDirectory(resolve(basedir, mvnProject.getBuild().getOutputDirectory())); if (!mojoExecs.isEmpty()) { MojoExecution mojoExec = mojoExecs.get(0); Set<String> overlayKeys = new HashSet<String>(); Object[] overlays = maven.getMojoParameterValue(mvnSession, mojoExec, "overlays", Object[].class); if (overlays != null) { boolean mainConfigured = false; for (Object overlay : overlays) { OverlayConfiguration overlayConfig = new OverlayConfiguration(overlay); if (overlayConfig.isMain()) { if (mainConfigured) { continue; } mainConfigured = true; } warConfig.getOverlays().add(overlayConfig); overlayKeys.add(overlayConfig.getArtifactKey()); } if (!mainConfigured) { warConfig.getOverlays().add(0, new OverlayConfiguration(null, null, null, null)); } } Map<String, Artifact> overlayArtifacts = new LinkedHashMap<String, Artifact>(); for (Artifact artifact : mvnProject.getArtifacts()) { if ("war".equals(artifact.getType())) { overlayArtifacts.put(artifact.getDependencyConflictId(), artifact); } } for (Map.Entry<String, Artifact> e : overlayArtifacts.entrySet()) { if (!overlayKeys.contains(e.getKey())) { Artifact a = e.getValue(); OverlayConfiguration warOverlay = new OverlayConfiguration(a.getGroupId(), a.getArtifactId(), a.getClassifier(), a.getType()); warConfig.getOverlays().add(warOverlay); } } for (OverlayConfiguration overlay : warConfig.getOverlays()) { overlay.setEncoding(encoding); } String warSrcDir = maven.getMojoParameterValue(mvnSession, mojoExec, "warSourceDirectory", String.class); String warSrcInc = maven.getMojoParameterValue(mvnSession, mojoExec, "warSourceIncludes", String.class); String warSrcExc = maven.getMojoParameterValue(mvnSession, mojoExec, "warSourceExcludes", String.class); warConfig.getResources() .add(new ResourceConfiguration(warSrcDir, split(warSrcInc), split(warSrcExc))); ResourceConfiguration[] resources = maven.getMojoParameterValue(mvnSession, mojoExec, "webResources", ResourceConfiguration[].class); if (resources != null) { warConfig.getResources().addAll(Arrays.asList(resources)); } for (ResourceConfiguration resource : warConfig.getResources()) { resource.setDirectory(resolve(basedir, resource.getDirectory())); resource.setEncoding(encoding); } String filenameMapping = maven.getMojoParameterValue(mvnSession, mojoExec, "outputFileNameMapping", String.class); warConfig.setFilenameMapping(filenameMapping); String escapeString = maven.getMojoParameterValue(mvnSession, mojoExec, "escapeString", String.class); warConfig.setEscapeString(escapeString); String webXml = maven.getMojoParameterValue(mvnSession, mojoExec, "webXml", String.class); warConfig.setWebXml(resolve(basedir, webXml)); Boolean webXmlFiltered = maven.getMojoParameterValue(mvnSession, mojoExec, "filteringDeploymentDescriptors", Boolean.class); warConfig.setWebXmlFiltered(webXmlFiltered.booleanValue()); Boolean backslashesEscaped = maven.getMojoParameterValue(mvnSession, mojoExec, "escapedBackslashesInFilePath", Boolean.class); warConfig.setBackslashesInFilePathEscaped(backslashesEscaped.booleanValue()); String[] nonFilteredFileExtensions = maven.getMojoParameterValue(mvnSession, mojoExec, "nonFilteredFileExtensions", String[].class); warConfig.getNonFilteredFileExtensions().addAll(Arrays.asList(nonFilteredFileExtensions)); String[] filters = maven.getMojoParameterValue(mvnSession, mojoExec, "filters", String[].class); for (String filter : filters) { warConfig.getFilters().add(resolve(basedir, filter)); } String packagingIncludes = maven.getMojoParameterValue(mvnSession, mojoExec, "packagingIncludes", String.class); warConfig.setPackagingIncludes(split(packagingIncludes)); String packagingExcludes = maven.getMojoParameterValue(mvnSession, mojoExec, "packagingExcludes", String.class); warConfig.setPackagingExcludes(split(packagingExcludes)); } else { throw WebbyPlugin.newError( "Could not locate configuration for maven-war-plugin in POM for " + mvnProject.getId(), null); } return warConfig; } finally { if (monitor != null) { monitor.done(); } } }