/* * Build Maven Project from Source using Out and Err PrintStreams for getting the output */ private void buildMavenProject(Source source, PrintStream out, PrintStream err) throws org.uberfire.java.nio.IOException, InvalidPathException, SecurityException, UnsupportedOperationException, IllegalArgumentException { List<String> goals = new ArrayList<>(); goals.add("package"); Properties p = new Properties(); p.setProperty("failIfNoTests", "false"); final InputStream pomStream = org.uberfire.java.nio.file.Files.newInputStream( source.getPath().resolve("drools-webapp-example").resolve("pom.xml")); MavenProject project = MavenProjectLoader.parseMavenPom(pomStream); final String expectedBinary = project.getArtifact().getArtifactId() + "-" + project.getArtifact().getVersion() + "." + project.getArtifact().getType(); final org.guvnor.ala.build.maven.model.MavenProject mavenProject = new MavenProjectImpl( project.getId(), project.getArtifact().getType(), project.getName(), expectedBinary, source.getPath(), source.getPath().resolve("drools-webapp-example"), source.getPath().resolve("target").resolve(expectedBinary).toAbsolutePath(), null, null); final File pom = new File(getRepositoryVisitor(mavenProject).getRoot(), "pom.xml"); MavenBuildExecutor.executeMaven(pom, out, err, p, goals.toArray(new String[0])); }
private Map<String, Artifact> createManagedVersionMap() throws MojoExecutionException { Map<String, Artifact> map = new HashMap<String, Artifact>(); DependencyManagement dependencyManagement = project.getDependencyManagement(); if (dependencyManagement != null && dependencyManagement.getDependencies() != null) { for (Dependency d : dependencyManagement.getDependencies()) { try { VersionRange versionRange = VersionRange.createFromVersionSpec(d.getVersion()); Artifact artifact = artifactFactory.createDependencyArtifact( d.getGroupId(), d.getArtifactId(), versionRange, d.getType(), d.getClassifier(), d.getScope(), d.isOptional()); handleExclusions(artifact, d); map.put(d.getManagementKey(), artifact); } catch (InvalidVersionSpecificationException e) { throw new MojoExecutionException( String.format( "%1s: unable to parse version '%2s' for dependency '%3s': %4s", project.getId(), d.getVersion(), d.getManagementKey(), e.getMessage()), e); } } } return map; }
private void process( MavenProject node, DirectedGraph graph, Map<Artifact, ArtifactVertex> processed, final MyArtifactFilter artifactFilter) { abstractMojo.getLog().debug("DependencyProcessor: Processing: " + node.getId()); process(resolveProject(node, artifactFilter), graph, processed, artifactFilter); }
private DependencyNode resolveProject(MavenProject project, final MyArtifactFilter filter) { try { abstractMojo.getLog().debug("DependencyProcessor: Resolving project: " + project.getId()); return dependencyTreeBuilder.buildDependencyTree( project, localRepository, factory, artifactMetadataSource, filter, collector); } catch (DependencyTreeBuilderException e) { abstractMojo.getLog().error("DependencyProcessor: Unable to build dependency tree.", e); return null; } }
private AgentProjectInfo processProject(MavenProject project) { long startTime = System.currentTimeMillis(); log.info(WssUtils.logMsg(LOG_COMPONENT, "processing Maven project " + project.getId())); AgentProjectInfo projectInfo = new AgentProjectInfo(); // project token if (project.equals(mavenParser.getMavenProject())) { projectInfo.setProjectToken(projectToken); } else { projectInfo.setProjectToken(moduleTokens.get(project.getArtifactId())); } // project coordinates projectInfo.setCoordinates(extractCoordinates(project)); Parent parent = project.getModel().getParent(); // parent coordinates if (parent != null) { projectInfo.setParentCoordinates(extractParentCoordinates(parent)); } // dependencies Map<Dependency, Artifact> lut = createLookupTable(project); for (Dependency dependency : mavenParser.getDependencies(project)) { DependencyInfo dependencyInfo = getDependencyInfo(dependency); Artifact artifact = lut.get(dependency); if (artifact != null) { File artifactFile = artifact.getFile(); if (artifactFile != null && artifactFile.exists()) { try { dependencyInfo.setSha1(ChecksumUtils.calculateSHA1(artifactFile)); } catch (IOException e) { log.warn(WssUtils.logMsg(LOG_COMPONENT, ERROR_SHA1 + " for " + artifact.getId())); } } } projectInfo.getDependencies().add(dependencyInfo); } log.info( WssUtils.logMsg( LOG_COMPONENT, "Total Maven project processing time is " + (System.currentTimeMillis() - startTime) + " [msec]")); return projectInfo; }
private void addTargetEnvironments( TargetPlatformConfiguration result, MavenProject project, Xpp3Dom configuration) { TargetEnvironment deprecatedTargetEnvironmentSpec = getDeprecatedTargetEnvironment(configuration); if (deprecatedTargetEnvironmentSpec != null) { result.addEnvironment(deprecatedTargetEnvironmentSpec); } Xpp3Dom environmentsDom = configuration.getChild("environments"); if (environmentsDom != null) { if (deprecatedTargetEnvironmentSpec != null) { String message = "Deprecated target-platform-configuration <environment> element must not be combined with new <environments> element; check the (inherited) configuration of " + project.getId(); throw new RuntimeException(message); } for (Xpp3Dom environmentDom : environmentsDom.getChildren("environment")) { result.addEnvironment(newTargetEnvironment(environmentDom)); } } }
public void execute(final Archiver archiver, final AssemblerConfigurationSource configSource) throws ArchiveCreationException, AssemblyFormattingException, InvalidAssemblerConfigurationException { if ((dependencySets == null) || dependencySets.isEmpty()) { logger.debug("No dependency sets specified."); return; } @SuppressWarnings("unchecked") final List<Dependency> deps = project.getDependencies(); if ((deps == null) || deps.isEmpty()) { logger.debug( "Project " + project.getId() + " has no dependencies. Skipping dependency set addition."); } for (final Iterator<DependencySet> i = dependencySets.iterator(); i.hasNext(); ) { final DependencySet dependencySet = i.next(); addDependencySet(dependencySet, archiver, configSource); } }
public void testDependencyManagementOverridesTransitiveDependencyVersion() throws Exception { File localRepo = getLocalRepositoryPath(); File pom0 = new File(localRepo, "p0/pom.xml"); File pom0Basedir = pom0.getParentFile(); File pom1 = new File(pom0Basedir, "p1/pom.xml"); // load the child project, which inherits from p0... MavenProject project0 = getProjectWithDependencies(pom0); MavenProject project1 = getProjectWithDependencies(pom1); assertEquals(pom0Basedir, project1.getParent().getBasedir()); System.out.println("Project " + project1.getId() + " " + project1); Map map = project1.getArtifactMap(); assertNotNull("No artifacts", map); assertTrue("No Artifacts", map.size() > 0); assertTrue("Set size should be 3, is " + map.size(), map.size() == 3); Artifact a = (Artifact) map.get("maven-test:t10-a"); Artifact b = (Artifact) map.get("maven-test:t10-b"); Artifact c = (Artifact) map.get("maven-test:t10-c"); assertNotNull(a); assertNotNull(b); assertNotNull(c); // inherited from depMgmt System.out.println(a.getScope()); assertTrue("Incorrect scope for " + a.getDependencyConflictId(), a.getScope().equals("test")); // transitive dep, overridden b depMgmt assertTrue( "Incorrect scope for " + b.getDependencyConflictId(), b.getScope().equals("runtime")); // direct dep, overrides depMgmt assertTrue( "Incorrect scope for " + c.getDependencyConflictId(), c.getScope().equals("runtime")); }
@Override public Collection<AgentProjectInfo> extract() { log.info(WssUtils.logMsg(LOG_COMPONENT, "Collection started")); mavenParser = configureMavenParser(checkoutDirectory); Collection<MavenProject> projects = new ArrayList<MavenProject>(); MavenProject mavenProject = mavenParser.getMavenProject(); projects.add(mavenProject); projects.addAll(mavenParser.getModules(mavenProject)); Collection<AgentProjectInfo> projectInfos = new ArrayList<AgentProjectInfo>(); // Collect OSS usage information for (MavenProject project : projects) { if (shouldProcess(project)) { projectInfos.add(processProject(project)); } else { log.info(WssUtils.logMsg(LOG_COMPONENT, "skipping " + project.getId())); } } logAgentProjectInfos(projectInfos); return projectInfos; }
@SuppressWarnings("unchecked") public void execute() throws MojoExecutionException { ArtifactVersion currentVersion = ri.getApplicationVersion(); ArtifactVersion maxUsageVersion = new DefaultArtifactVersion("2.2.0"); if (maxUsageVersion.compareTo(currentVersion) < 0) { getLog() .debug( "This version of Maven does not require injection of custom ArtifactHandlers using this code. Skipping."); return; } Map<String, ?> handlerDescriptors = session.getContainer().getComponentDescriptorMap(ArtifactHandler.ROLE); if (handlerDescriptors != null) { getLog().debug("Registering all unregistered ArtifactHandlers..."); if (artifactHandlerManager instanceof DefaultArtifactHandlerManager) { Set<String> existingHints = ((DefaultArtifactHandlerManager) artifactHandlerManager).getHandlerTypes(); if (existingHints != null) { for (String hint : existingHints) { handlerDescriptors.remove(hint); } } } if (handlerDescriptors.isEmpty()) { getLog().debug("All ArtifactHandlers are registered. Continuing..."); } else { Map<String, ArtifactHandler> unregisteredHandlers = new HashMap<String, ArtifactHandler>(handlerDescriptors.size()); for (String hint : handlerDescriptors.keySet()) { try { unregisteredHandlers.put( hint, (ArtifactHandler) session.lookup(ArtifactHandler.ROLE, hint)); getLog().info("Adding ArtifactHandler for: " + hint); } catch (ComponentLookupException e) { getLog() .warn( "Failed to lookup ArtifactHandler with hint: " + hint + ". Reason: " + e.getMessage(), e); } } artifactHandlerManager.addHandlers(unregisteredHandlers); } } getLog() .debug("...done.\nSetting ArtifactHandler on project-artifact: " + project.getId() + "..."); Set<Artifact> artifacts = new HashSet<Artifact>(); artifacts.add(project.getArtifact()); Set<Artifact> dependencyArtifacts = project.getDependencyArtifacts(); if (dependencyArtifacts != null && !dependencyArtifacts.isEmpty()) { artifacts.addAll(dependencyArtifacts); } for (Artifact artifact : artifacts) { String type = artifact.getType(); ArtifactHandler handler = artifactHandlerManager.getArtifactHandler(type); getLog() .debug( "Artifact: " + artifact.getId() + "\nType: " + type + "\nArtifactHandler extension: " + handler.getExtension()); artifact.setArtifactHandler(handler); } getLog().debug("...done."); }
protected Set<Artifact> resolveDependencyArtifacts(final DependencySet dependencySet) throws InvalidAssemblerConfigurationException { final Set<Artifact> dependencyArtifacts = new LinkedHashSet<Artifact>(); if (resolvedArtifacts != null) { dependencyArtifacts.addAll(resolvedArtifacts); } if (dependencySet.isUseProjectArtifact()) { final Artifact projectArtifact = project.getArtifact(); if ((projectArtifact != null) && (projectArtifact.getFile() != null)) { dependencyArtifacts.add(projectArtifact); } else { logger.warn( "Cannot include project artifact: " + projectArtifact + "; it doesn't have an associated file or directory."); } } if (dependencySet.isUseProjectAttachments()) { @SuppressWarnings("unchecked") final List<Artifact> attachments = project.getAttachedArtifacts(); if (attachments != null) { for (final Iterator<Artifact> attachmentIt = attachments.iterator(); attachmentIt.hasNext(); ) { final Artifact attachment = attachmentIt.next(); if (attachment.getFile() != null) { dependencyArtifacts.add(attachment); } else { logger.warn( "Cannot include attached artifact: " + project.getId() + " for project: " + project.getId() + "; it doesn't have an associated file or directory."); } } } } if (dependencySet.isUseTransitiveFiltering()) { logger.debug("Filtering dependency artifacts USING transitive dependency path information."); } else { logger.debug( "Filtering dependency artifacts WITHOUT transitive dependency path information."); } final ScopeArtifactFilter filter = new ScopeArtifactFilter(dependencySet.getScope()); FilterUtils.filterArtifacts( dependencyArtifacts, dependencySet.getIncludes(), dependencySet.getExcludes(), dependencySet.isUseStrictFiltering(), dependencySet.isUseTransitiveFiltering(), logger, filter); return dependencyArtifacts; }
/** * 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; }
/** Validate Mojo parameters. */ private void validateParameters() { if (artifact == null) { // using project if found or super-pom getLog().info("No artifact parameter specified, using '" + project.getId() + "' as project."); } }