List of usage examples for org.apache.maven.project MavenProject setArtifacts
public void setArtifacts(Set<Artifact> artifacts)
From source file:org.jetbrains.maven.embedder.MavenEmbedder.java
License:Apache License
@Nonnull public MavenExecutionResult resolveProject(@Nonnull final File file, @Nonnull final List<String> activeProfiles, @Nonnull final List<String> inactiveProfiles, List<ResolutionListener> listeners) { MavenExecutionRequest request = createRequest(file, activeProfiles, inactiveProfiles, Collections.<String>emptyList()); ProjectBuilderConfiguration config = request.getProjectBuilderConfiguration(); request.getGlobalProfileManager().loadSettingsProfiles(mySettings); ProfileManager globalProfileManager = request.getGlobalProfileManager(); globalProfileManager.loadSettingsProfiles(request.getSettings()); List<Exception> exceptions = new ArrayList<Exception>(); MavenProject project = null; try {/*from www. j a v a 2 s. c o m*/ // copied from DefaultMavenProjectBuilder.buildWithDependencies MavenProjectBuilder builder = getComponent(MavenProjectBuilder.class); project = builder.build(new File(file.getPath()), config); builder.calculateConcreteState(project, config, false); // copied from DefaultLifecycleExecutor.execute findExtensions(project); // end copied from DefaultLifecycleExecutor.execute Artifact projectArtifact = project.getArtifact(); Map managedVersions = project.getManagedVersionMap(); ArtifactMetadataSource metadataSource = getComponent(ArtifactMetadataSource.class); project.setDependencyArtifacts( project.createArtifacts(getComponent(ArtifactFactory.class), null, null)); ArtifactResolver resolver = getComponent(ArtifactResolver.class); ArtifactResolutionResult result = resolver.resolveTransitively(project.getDependencyArtifacts(), projectArtifact, managedVersions, myLocalRepository, project.getRemoteArtifactRepositories(), metadataSource, null, listeners); project.setArtifacts(result.getArtifacts()); // end copied from DefaultMavenProjectBuilder.buildWithDependencies } catch (Exception e) { return handleException(e); } return new MavenExecutionResult(project, exceptions); }
From source file:org.jfrog.jade.plugins.idea.AbstractIdeaMojo.java
License:Apache License
protected void doDependencyResolution() throws InvalidDependencyVersionException, ProjectBuildingException, InvalidVersionSpecificationException { // If the execution root project is not a parent (meaning it is last one in reactor list) // Then the mojo will inherit manually its configuration if (reactorProjects != null) { int nbProjects = reactorProjects.size(); // Get the last project it contains the specific ideaj configuration if (nbProjects > 1) { MavenProject lastproject = reactorProjects.get(nbProjects - 1); if (lastproject.isExecutionRoot()) { //noinspection unchecked List<Plugin> plugins = lastproject.getBuildPlugins(); fillPluginSettings(plugins, "jade-idea-plugin", this, null); }/*from w ww . ja v a2 s . c o m*/ } } MavenProject project = getExecutedProject(); ArtifactRepository localRepo = getLocalRepository(); Map managedVersions = createManagedVersionMap(); try { ArtifactResolutionResult result = getArtifactResolver().resolveTransitively(getProjectArtifacts(), project.getArtifact(), managedVersions, localRepo, project.getRemoteArtifactRepositories(), artifactMetadataSource); project.setArtifacts(result.getArtifacts()); } catch (ArtifactNotFoundException e) { getLog().debug(e.getMessage(), e); StringBuffer msg = new StringBuffer(); msg.append("An error occurred during dependency resolution.\n\n"); msg.append(" Failed to retrieve ").append(e.getDownloadUrl()).append("\n"); msg.append("from the following repositories:"); for (Iterator repositories = e.getRemoteRepositories().iterator(); repositories.hasNext();) { ArtifactRepository repository = (ArtifactRepository) repositories.next(); msg.append("\n ").append(repository.getId()).append("(").append(repository.getUrl()).append(")"); } msg.append("\nCaused by: ").append(e.getMessage()); getLog().warn(msg); } catch (ArtifactResolutionException e) { getLog().debug(e.getMessage(), e); StringBuffer msg = new StringBuffer(); msg.append("An error occurred during dependency resolution of the following artifact:\n\n"); msg.append(" ").append(e.getGroupId()).append(":").append(e.getArtifactId()).append(e.getVersion()) .append("\n\n"); msg.append("Caused by: ").append(e.getMessage()); getLog().warn(msg); } }
From source file:org.jszip.maven.RunMojo.java
License:Apache License
public void execute() throws MojoExecutionException, MojoFailureException { if (runPackages == null || runPackages.length == 0) { runPackages = new String[] { "war" }; }/*from w w w .j a v a 2s . c o m*/ injectMissingArtifacts(project, executedProject); if (!Arrays.asList(runPackages).contains(project.getPackaging())) { getLog().info("Skipping JSZip run: module " + ArtifactUtils.versionlessKey(project.getGroupId(), project.getArtifactId()) + " as not specified in runPackages"); return; } if (StringUtils.isNotBlank(runModule) && !project.getArtifactId().equals(runModule) && !ArtifactUtils.versionlessKey(project.getGroupId(), project.getArtifactId()).equals(runModule)) { getLog().info("Skipping JSZip run: module " + ArtifactUtils.versionlessKey(project.getGroupId(), project.getArtifactId()) + " as requested runModule is " + runModule); return; } getLog().info("Starting JSZip run: module " + ArtifactUtils.versionlessKey(project.getGroupId(), project.getArtifactId())); MavenProject project = this.project; long lastResourceChange = System.currentTimeMillis(); long lastClassChange = System.currentTimeMillis(); long lastPomChange = getPomsLastModified(); Server server = new Server(); if (connectors == null || connectors.length == 0) { SelectChannelConnector selectChannelConnector = new SelectChannelConnector(); selectChannelConnector.setPort(8080); connectors = new Connector[] { selectChannelConnector }; } server.setConnectors(connectors); ContextHandlerCollection contexts = new ContextHandlerCollection(); HandlerCollection handlerCollection = new HandlerCollection(true); DefaultHandler defaultHandler = new DefaultHandler(); handlerCollection.setHandlers(new Handler[] { contexts, defaultHandler }); server.setHandler(handlerCollection); try { server.start(); } catch (Exception e) { throw new MojoExecutionException(e.getMessage(), e); } List<MavenProject> reactorProjects = this.reactorProjects; WebAppContext webAppContext; Resource webXml; List<Resource> resources; try { resources = new ArrayList<Resource>(); addCssEngineResources(project, reactorProjects, mappings, resources); for (Artifact a : getOverlayArtifacts(project, scope)) { addOverlayResources(reactorProjects, resources, a); } if (warSourceDirectory == null) { warSourceDirectory = new File(project.getBasedir(), "src/main/webapp"); } if (warSourceDirectory.isDirectory()) { resources.add(Resource.newResource(warSourceDirectory)); } Collections.reverse(resources); getLog().debug("Overlays:"); int index = 0; for (Resource r : resources) { getLog().debug(" [" + index++ + "] = " + r); } final ResourceCollection resourceCollection = new ResourceCollection( resources.toArray(new Resource[resources.size()])); webAppContext = new JettyWebAppContext(); webAppContext.setWar(warSourceDirectory.getAbsolutePath()); webAppContext.setBaseResource(resourceCollection); WebAppClassLoader classLoader = new WebAppClassLoader(webAppContext); for (String s : getClasspathElements(project, scope)) { classLoader.addClassPath(s); } webAppContext.setClassLoader(classLoader); contexts.setHandlers(new Handler[] { webAppContext }); contexts.start(); webAppContext.start(); Resource webInf = webAppContext.getWebInf(); webXml = webInf != null ? webInf.getResource("web.xml") : null; } catch (MojoExecutionException e) { throw e; } catch (MojoFailureException e) { throw e; } catch (ArtifactFilterException e) { throw new MojoExecutionException(e.getMessage(), e); } catch (MalformedURLException e) { throw new MojoExecutionException(e.getMessage(), e); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } catch (Exception e) { throw new MojoExecutionException(e.getMessage(), e); } long webXmlLastModified = webXml == null ? 0L : webXml.lastModified(); try { getLog().info("Context started. Will restart if changes to poms detected."); long nextClasspathCheck = System.currentTimeMillis() + classpathCheckInterval; while (true) { long nextCheck = System.currentTimeMillis() + 500; long pomsLastModified = getPomsLastModified(); boolean pomsChanged = lastPomChange < pomsLastModified; boolean overlaysChanged = false; boolean classPathChanged = webXmlLastModified < (webXml == null ? 0L : webXml.lastModified()); if (nextClasspathCheck < System.currentTimeMillis()) { long classChange = classpathLastModified(project); if (classChange > lastClassChange) { classPathChanged = true; lastClassChange = classChange; } nextClasspathCheck = System.currentTimeMillis() + classpathCheckInterval; } if (!classPathChanged && !overlaysChanged && !pomsChanged) { try { lastResourceChange = processResourceSourceChanges(reactorProjects, project, lastResourceChange); } catch (ArtifactFilterException e) { getLog().debug("Couldn't process resource changes", e); } try { Thread.sleep(Math.max(100L, nextCheck - System.currentTimeMillis())); } catch (InterruptedException e) { getLog().debug("Interrupted", e); } continue; } if (pomsChanged) { getLog().info("Change in poms detected, re-parsing to evaluate impact..."); // we will now process this change, // so from now on don't re-process // even if we have issues processing lastPomChange = pomsLastModified; List<MavenProject> newReactorProjects; try { newReactorProjects = buildReactorProjects(); } catch (ProjectBuildingException e) { getLog().info("Re-parse aborted due to malformed pom.xml file(s)", e); continue; } catch (CycleDetectedException e) { getLog().info("Re-parse aborted due to dependency cycle in project model", e); continue; } catch (DuplicateProjectException e) { getLog().info("Re-parse aborted due to duplicate projects in project model", e); continue; } catch (Exception e) { getLog().info("Re-parse aborted due a problem that prevented sorting the project model", e); continue; } if (!buildPlanEqual(newReactorProjects, this.reactorProjects)) { throw new BuildPlanModifiedException("A pom.xml change has impacted the build plan."); } MavenProject newProject = findProject(newReactorProjects, this.project); if (newProject == null) { throw new BuildPlanModifiedException("A pom.xml change appears to have removed " + this.project.getId() + " from the build plan."); } newProject.setArtifacts(resolve(newProject, "runtime")); getLog().debug("Comparing effective classpath of new and old models"); try { classPathChanged = classPathChanged || classpathsEqual(project, newProject, scope); } catch (DependencyResolutionRequiredException e) { getLog().info("Re-parse aborted due to dependency resolution problems", e); continue; } if (classPathChanged) { getLog().info("Effective classpath of " + project.getId() + " has changed."); } else { getLog().debug("Effective classpath is unchanged."); } getLog().debug("Comparing effective overlays of new and old models"); try { overlaysChanged = overlaysEqual(project, newProject); } catch (OverConstrainedVersionException e) { getLog().info("Re-parse aborted due to dependency resolution problems", e); continue; } catch (ArtifactFilterException e) { getLog().info("Re-parse aborted due to overlay resolution problems", e); continue; } if (overlaysChanged) { getLog().info("Overlay modules of " + project.getId() + " have changed."); } else { getLog().debug("Overlay modules are unchanged."); } getLog().debug("Comparing overlays paths of new and old models"); try { List<Resource> newResources = new ArrayList<Resource>(); // TODO newMappings addCssEngineResources(newProject, newReactorProjects, mappings, resources); for (Artifact a : getOverlayArtifacts(project, scope)) { addOverlayResources(newReactorProjects, newResources, a); } if (warSourceDirectory.isDirectory()) { newResources.add(Resource.newResource(warSourceDirectory)); } Collections.reverse(newResources); getLog().debug("New overlays:"); int index = 0; for (Resource r : newResources) { getLog().debug(" [" + index++ + "] = " + r); } boolean overlayPathsChanged = !resources.equals(newResources); if (overlayPathsChanged) { getLog().info("Overlay module paths of " + project.getId() + " have changed."); } else { getLog().debug("Overlay module paths are unchanged."); } overlaysChanged = overlaysChanged || overlayPathsChanged; } catch (ArtifactFilterException e) { getLog().info("Re-parse aborted due to overlay evaluation problems", e); continue; } catch (PluginConfigurationException e) { getLog().info("Re-parse aborted due to overlay evaluation problems", e); continue; } catch (PluginContainerException e) { getLog().info("Re-parse aborted due to overlay evaluation problems", e); continue; } catch (IOException e) { getLog().info("Re-parse aborted due to overlay evaluation problems", e); continue; } project = newProject; reactorProjects = newReactorProjects; } if (!overlaysChanged && !classPathChanged) { continue; } getLog().info("Restarting context to take account of changes..."); try { webAppContext.stop(); } catch (Exception e) { throw new MojoExecutionException(e.getMessage(), e); } if (classPathChanged) { getLog().info("Updating classpath..."); try { WebAppClassLoader classLoader = new WebAppClassLoader(webAppContext); for (String s : getClasspathElements(project, scope)) { classLoader.addClassPath(s); } webAppContext.setClassLoader(classLoader); } catch (Exception e) { throw new MojoExecutionException(e.getMessage(), e); } } if (overlaysChanged || classPathChanged) { getLog().info("Updating overlays..."); try { resources = new ArrayList<Resource>(); addCssEngineResources(project, reactorProjects, mappings, resources); for (Artifact a : getOverlayArtifacts(project, scope)) { addOverlayResources(reactorProjects, resources, a); } if (warSourceDirectory.isDirectory()) { resources.add(Resource.newResource(warSourceDirectory)); } Collections.reverse(resources); getLog().debug("Overlays:"); int index = 0; for (Resource r : resources) { getLog().debug(" [" + index++ + "] = " + r); } final ResourceCollection resourceCollection = new ResourceCollection( resources.toArray(new Resource[resources.size()])); webAppContext.setBaseResource(resourceCollection); } catch (Exception e) { throw new MojoExecutionException(e.getMessage(), e); } } try { webAppContext.start(); } catch (Exception e) { throw new MojoExecutionException(e.getMessage(), e); } webXmlLastModified = webXml == null ? 0L : webXml.lastModified(); getLog().info("Context restarted."); } } finally { try { server.stop(); } catch (Exception e) { throw new MojoExecutionException(e.getMessage(), e); } } }
From source file:org.sonar.batch.InMemoryPomCreator.java
License:Open Source License
public MavenProject create() { File workDir = project.getWorkDir(); String buildDirectory = workDir.getAbsolutePath() + "/target"; Properties properties = project.getProperties(); if (project.getBinaries().size() == 0) { project.addBinaryDir(buildDirectory + "/classes"); }//from w ww. j av a 2 s . c o m final MavenProject pom = new MavenProject() { /** * This allows to specify base directory without specifying location of a pom.xml */ @Override public File getBasedir() { return project.getBaseDir(); }; /** * This allows to specify project classpath (binaries + libraries). */ @Override public List<String> getCompileClasspathElements() throws DependencyResolutionRequiredException { List<String> cp = new ArrayList<String>(); cp.addAll(project.getBinaries()); cp.addAll(project.getLibraries()); return cp; } }; String key = getPropertyOrDie(properties, CoreProperties.PROJECT_KEY_PROPERTY); String[] keys = key.split(":"); pom.setGroupId(keys[0]); pom.setArtifactId(keys[1]); pom.setVersion(getPropertyOrDie(properties, CoreProperties.PROJECT_VERSION_PROPERTY)); pom.setName(properties.getProperty(CoreProperties.PROJECT_NAME_PROPERTY, "Unnamed - " + key)); pom.setDescription(properties.getProperty(CoreProperties.PROJECT_DESCRIPTION_PROPERTY, "")); pom.getModel().setProperties(properties); pom.setArtifacts(Collections.EMPTY_SET); // Configure fake directories pom.getBuild().setDirectory(buildDirectory); pom.getBuild().setOutputDirectory(project.getBinaries().get(0)); Reporting reporting = new Reporting(); String reportingOutputDirectory = buildDirectory + "/site"; reporting.setOutputDirectory(reportingOutputDirectory); pom.setReporting(reporting); // Configure source directories for (String dir : project.getSourceDirs()) { pom.addCompileSourceRoot(dir); } // Configure test directories for (String dir : project.getTestDirs()) { pom.addTestCompileSourceRoot(dir); } return pom; }
From source file:org.sonatype.flexmojos.war.CopyMojo.java
License:Apache License
private void performSubArtifactsCopy(Artifact artifact) throws MojoExecutionException { MavenProject artifactProject = getProject(artifact); if (artifactProject != null) { try {/*from ww w.j a va 2 s . c om*/ artifactProject.setArtifacts(artifactProject.createArtifacts(artifactFactory, null, null)); } catch (InvalidDependencyVersionException e) { throw new MojoExecutionException("Error resolving artifacts " + artifact, e); } if (copyRSL) { performRslCopy(artifactProject); } if (copyRuntimeLocales) { performRuntimeLocalesCopy(artifactProject); } } }
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 {//from w ww. ja v a 2 s.c o m 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); } } }