public MavenLoader(final String m2Home) { setMavenHome(m2Home); try { loadMaven(); final ProjectBuilder projectBuilder = new DefaultProjectBuilder(); for (final URL pomUrl : lookupPomFiles()) { info("URL: %s", pomUrl); setMavenProject(projectBuilder.build(new File(pomUrl.getFile()), new DefaultProjectBuildingRequest()).getProject()); // mavenProjectClass.getMethod("setPomFile", new Class[] { File.class }).invoke(mavenProject, new File(pomUrl.getFile())); } } catch (MalformedURLException mue) { mue.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } setDependencyHandler(new MavenDependencyHandler(mavenProject)); }
private void buildProjects() throws MojoExecutionException { final ProjectBuildingRequest request = new DefaultProjectBuildingRequest(); request.setProcessPlugins(false); request.setSystemProperties(System.getProperties()); request.setRemoteRepositories(this.project.getRemoteArtifactRepositories()); request.setRepositorySession(this.repositorySystemSession); request.setResolveDependencies(true); try { PROBABLE_FRACTIONS = this.projectBuilder .build(Collections.singletonList(findRoot(this.project).getFile()), true, request) .stream() .filter(this::isNotArquillianArtifact) .map(ProjectBuildingResult::getProject) .collect(Collectors.toList()); } catch (ProjectBuildingException e) { throw new MojoExecutionException("Error generating list of PROBABLE_FRACTIONS", e); } }
public DependencyNode getRootDependencyNode(final DependencyGraphBuilder dependencyGraphBuilder, final MavenSession session, final MavenProject project, final String projectName, final String versionName) throws MojoExecutionException { org.apache.maven.shared.dependency.graph.DependencyNode rootNode = null; final ProjectBuildingRequest buildRequest = new DefaultProjectBuildingRequest( session.getProjectBuildingRequest()); buildRequest.setProject(project); buildRequest.setResolveDependencies(true); try { rootNode = dependencyGraphBuilder.buildDependencyGraph(buildRequest, null); } catch (final DependencyGraphBuilderException ex) { throw new MojoExecutionException(EXCEPTION_MSG_NO_DEPENDENCY_GRAPH, ex); } final String groupId = project.getGroupId(); final String artifactId = project.getArtifactId(); final String version = versionName; final MavenExternalId projectGav = new MavenExternalId(groupId, artifactId, version); final Set<DependencyNode> children = new LinkedHashSet<>(); final DependencyNode root = new DependencyNode(projectName, versionName, projectGav, children); for (final org.apache.maven.shared.dependency.graph.DependencyNode child : rootNode.getChildren()) { if (includedScopes.contains(child.getArtifact().getScope())) { children.add(createCommonDependencyNode(child)); } } for (final MavenProject moduleProject : project.getCollectedProjects()) { if (!excludedModules.contains(moduleProject.getArtifactId())) { final DependencyNode moduleRootNode = getRootDependencyNode(dependencyGraphBuilder, session, moduleProject, moduleProject.getArtifactId(), moduleProject.getVersion()); children.addAll(moduleRootNode.children); } } return root; }
private ProjectBuildingRequest getProjectBuildingRequest(Properties properties) throws NoLocalRepositoryManagerException { DefaultProjectBuildingRequest projectBuildingRequest = new DefaultProjectBuildingRequest(); DefaultRepositorySystemSession session = createSession(properties); projectBuildingRequest.setRepositoryMerging(RepositoryMerging.REQUEST_DOMINANT); projectBuildingRequest.setRemoteRepositories(mavenRepositories(properties)); projectBuildingRequest.getRemoteRepositories() .addAll(mavenRepositories(settings)); projectBuildingRequest.setRepositorySession(session); projectBuildingRequest.setProcessPlugins(false); projectBuildingRequest.setBuildStartTime(new Date()); projectBuildingRequest.setUserProperties(properties); projectBuildingRequest.setSystemProperties(System.getProperties()); return projectBuildingRequest; }
/** * Tests method to create effective POM. * * @throws Exception if something goes wrong. */ @Test public void testCreateEffectivePom() throws Exception { String magicValue = "magic-value"; Properties userProperties = new Properties(); userProperties.setProperty( "cmd.test.property", magicValue ); File pomFile = new File( "src/test/resources/cmdpropertysubstituion/pom.xml" ); ArtifactRepository localRepository = new MavenArtifactRepository(); localRepository.setLayout( new DefaultRepositoryLayout() ); ArtifactFactory artifactFactory = new DefaultArtifactFactory(); ArtifactHandlerManager artifactHandlerManager = new DefaultArtifactHandlerManager(); setDeclaredField( artifactFactory, "artifactHandlerManager", artifactHandlerManager ); Map<String, ArtifactHandler> artifactHandlers = new HashMap<String, ArtifactHandler>(); setDeclaredField( artifactHandlerManager, "artifactHandlers", artifactHandlers ); DefaultDependencyResolver depencencyResolver = new DefaultDependencyResolver(); DefaultProjectBuildingRequest projectBuildingRequest = new DefaultProjectBuildingRequest(); FlattenModelResolver resolver = new FlattenModelResolver( localRepository, artifactFactory, depencencyResolver, projectBuildingRequest, Collections.<MavenProject>emptyList() ); ModelBuildingRequest buildingRequest = new DefaultModelBuildingRequest().setPomFile( pomFile ).setModelResolver( resolver ).setUserProperties( userProperties ); Model effectivePom = FlattenMojo.createEffectivePom( buildingRequest, false ); assertThat( effectivePom.getName() ).isEqualTo( magicValue ); }
protected MavenSession createMavenSession( File pom, Properties executionProperties ) throws Exception { MavenExecutionRequest request = createMavenExecutionRequest( pom ); ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest() .setLocalRepository( request.getLocalRepository() ) .setRemoteRepositories( request.getRemoteRepositories() ) .setPluginArtifactRepositories( request.getPluginArtifactRepositories() ) .setSystemProperties( executionProperties ); MavenProject project = null; if ( pom != null ) { project = projectBuilder.build( pom, configuration ).getProject(); } else { project = createStubMavenProject(); project.setRemoteArtifactRepositories( request.getRemoteRepositories() ); project.setPluginArtifactRepositories( request.getPluginArtifactRepositories() ); } initRepoSession( configuration ); MavenSession session = new MavenSession( getContainer(), configuration.getRepositorySession(), request, new DefaultMavenExecutionResult() ); session.setProjects( Arrays.asList( project ) ); return session; }
private PomTestWrapper buildPom( String pomPath ) throws Exception { File pomFile = new File( testDirectory + File.separator + pomPath, "pom.xml" ); File settingsFile = new File( testDirectory + File.separator + pomPath, "settings.xml" ); Settings settings = readSettingsFile( settingsFile ); ProjectBuildingRequest config = new DefaultProjectBuildingRequest(); for ( org.apache.maven.settings.Profile rawProfile : settings.getProfiles() ) { Profile profile = SettingsUtils.convertFromSettingsProfile( rawProfile ); config.addProfile( profile ); } String localRepoUrl = System.getProperty( "maven.repo.local", System.getProperty( "user.home" ) + "/.m2/repository" ); localRepoUrl = "file://" + localRepoUrl; config.setLocalRepository( repositorySystem.createArtifactRepository( "local", localRepoUrl, new DefaultRepositoryLayout(), null, null ) ); config.setActiveProfileIds( settings.getActiveProfiles() ); MavenRepositorySystemSession repoSession = new MavenRepositorySystemSession( true ); repoSession.setLocalRepositoryManager( new SimpleLocalRepositoryManager( new File( config.getLocalRepository().getBasedir() ) ) ); config.setRepositorySession( repoSession ); return new PomTestWrapper( pomFile, projectBuilder.build( pomFile, config ).getProject() ); }
@Override @SuppressWarnings("PMD.EmptyCatchBlock") public void execute() throws MojoExecutionException, MojoFailureException { ArrayNode root = new ArrayNode(JsonNodeFactory.instance); URLClassLoader classLoader = null; try { PluginDescriptor desc = (PluginDescriptor) getPluginContext().get("pluginDescriptor"); List<Artifact> artifacts = desc.getArtifacts(); ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest()); buildingRequest.setRemoteRepositories(remoteRepositories); for (Artifact artifact : artifacts) { ArtifactResult result = artifactResolver.resolveArtifact(buildingRequest, artifact); File jar = result.getArtifact().getFile(); classLoader = createClassLoader(jar); if (classLoader == null) { throw new IOException("Can not create classloader for " + jar); } ObjectNode entry = new ObjectNode(JsonNodeFactory.instance); addConnectorMeta(entry, classLoader); addComponentMeta(entry, classLoader); if (entry.size() > 0) { addGav(entry, artifact); root.add(entry); } } if (root.size() > 0) { saveCamelMetaData(root); } } catch (ArtifactResolverException | IOException e) { throw new MojoExecutionException(e.getMessage(), e); } finally { if (classLoader != null) { try { classLoader.close(); } catch (IOException ignored) { } } } }
/** * Find the SCM URL for the given {@code g, a, v} triple and store the association for the later retrieval via * {@link #createSortedScmRepositoryMap()}. * * @param g * {@code groupId} * @param a * {@code artifactId} * @param v * {@code version} * @param failOnUnresolvable * see {@link SrcdepsInitMojo#failOnUnresolvable} * @throws MojoExecutionException */ public void addGav(String g, String a, String v, boolean failOnUnresolvable) throws MojoExecutionException { final Gav gav = new Gav(g, a, v); if (!seenGavs.contains(gav)) { seenGavs.add(gav); final Ga ga = new Ga(g, a); log.debug("Adding GA: {}", ga); ProjectBuildingRequest projectBuildingRequest = new DefaultProjectBuildingRequest(); projectBuildingRequest.setLocalRepository(session.getLocalRepository()); projectBuildingRequest .setRemoteRepositories(session.getProjectBuildingRequest().getRemoteRepositories()); projectBuildingRequest.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL); projectBuildingRequest.setProcessPlugins(false); projectBuildingRequest.setRepositoryMerging(ProjectBuildingRequest.RepositoryMerging.REQUEST_DOMINANT); projectBuildingRequest.setSystemProperties(session.getSystemProperties()); projectBuildingRequest.setRepositorySession(repoSession); Artifact pomArtifact = repositorySystem.createProjectArtifact(g, a, v, "compile"); try { ProjectBuildingResult result = projectBuilder.build(pomArtifact, projectBuildingRequest); MavenProject dependencyProject = result.getProject(); ScmUrlAncestry ancestry = ScmUrlAncestry.of(dependencyProject); if (!ancestry.hasUrl()) { log.warn("No SCM connection for artifact [{}]", ga); } else { final String url = ancestry.getUrl(); if (unsupportedUrls.contains(url)) { /* was reported once already */ } else if (isScmUrlSupported(url)) { log.debug("Found SCM URL [{}] for GA [{}]", url, ga); int len = ancestry.getLength(); for (int i = 0; i < len; i++) { this.add(url, ancestry.getGaAt(i)); } Set<Ga> rootGas = urlRootGasMap.get(url); if (rootGas == null) { rootGas = new TreeSet<>(); urlRootGasMap.put(url, rootGas); } rootGas.add(ancestry.getRootGa()); } else { log.warn("Unsupported SCM URL [{}] for GAV [{}]", url, ga); unsupportedUrls.add(url); } } } catch (ProjectBuildingException e) { final String msg = String.format("Could not resolve [%s] using remote repositories [%s]", pomArtifact, remoteRepos); if (failOnUnresolvable) { throw new MojoExecutionException(msg, e); } else { log.warn(msg); } } } }
/** * We run the EvoSuite that is provided with the plugin * * @return */ private List<String> getCommandToRunEvoSuite(){ logger.debug("EvoSuite Maven Plugin Artifacts: "+Arrays.toString(artifacts.toArray())); Artifact evosuite = null; for(Artifact art : artifacts){ //first find the main EvoSuite jar among the dependencies if(art.getArtifactId().equals("evosuite-master")){ evosuite = art; break; } } if(evosuite==null){ logger.error("CRITICAL ERROR: plugin can detect EvoSuite executable"); return null; } logger.debug("EvoSuite located at: "+evosuite.getFile()); /* * now, build a project descriptor for evosuite, which is needed to * query all of its dependencies */ DefaultProjectBuildingRequest req = new DefaultProjectBuildingRequest(); req.setRepositorySession(repoSession); req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL); req.setSystemProperties(System.getProperties()); req.setResolveDependencies(true); ProjectBuildingResult res; try { res = projectBuilder.build(evosuite, req); } catch (ProjectBuildingException e) { logger.error("Failed: "+e.getMessage(),e); return null; } //build the classpath to run EvoSuite String cp = evosuite.getFile().getAbsolutePath(); for(Artifact dep : res.getProject().getArtifacts()){ cp += File.pathSeparator+dep.getFile().getAbsolutePath(); } logger.debug("EvoSuite classpath: "+cp); String entryPoint = EvoSuite.class.getName(); List<String> cmd = new ArrayList<>(); cmd.add(JavaExecCmdUtil.getJavaBinExecutablePath()/*"java"*/); cmd.add("-D" + LoggingUtils.USE_DIFFERENT_LOGGING_XML_PARAMETER + "=logback-ctg-entry.xml"); cmd.add("-Dlogback.configurationFile=logback-ctg-entry.xml"); cmd.add("-cp"); cmd.add(cp); cmd.add(entryPoint); return cmd; }
@Override public void execute() throws MojoExecutionException, MojoFailureException { try { // find the nar dependency Artifact narArtifact = null; for (final Artifact artifact : project.getDependencyArtifacts()) { if (NAR.equals(artifact.getType())) { // ensure the project doesn't have two nar dependencies if (narArtifact != null) { throw new MojoExecutionException("Project can only have one NAR dependency."); } // record the nar dependency narArtifact = artifact; } } // ensure there is a nar dependency if (narArtifact == null) { throw new MojoExecutionException("Project does not have any NAR dependencies."); } // build the project for the nar artifact final ProjectBuildingRequest narRequest = new DefaultProjectBuildingRequest(); narRequest.setRepositorySession(repoSession); narRequest.setSystemProperties(System.getProperties()); final ProjectBuildingResult narResult = projectBuilder.build(narArtifact, narRequest); // get the artifact handler for excluding dependencies final ArtifactHandler narHandler = excludesDependencies(narArtifact); narArtifact.setArtifactHandler(narHandler); // nar artifacts by nature includes dependencies, however this prevents the // transitive dependencies from printing using tools like dependency:tree. // here we are overriding the artifact handler for all nars so the // dependencies can be listed. this is important because nar dependencies // will be used as the parent classloader for this nar and seeing what // dependencies are provided is critical. final Map<String, ArtifactHandler> narHandlerMap = new HashMap<>(); narHandlerMap.put(NAR, narHandler); artifactHandlerManager.addHandlers(narHandlerMap); // get the dependency tree final DependencyNode root = dependencyTreeBuilder.buildDependencyTree(narResult.getProject(), localRepository, null); // write the appropriate output DependencyNodeVisitor visitor = null; if ("tree".equals(mode)) { visitor = new TreeWriter(); } else if ("pom".equals(mode)) { visitor = new PomWriter(); } // ensure the mode was specified correctly if (visitor == null) { throw new MojoExecutionException("The specified mode is invalid. Supported options are 'tree' and 'pom'."); } // visit and print the results root.accept(visitor); getLog().info("--- Provided NAR Dependencies ---\n\n" + visitor.toString()); } catch (DependencyTreeBuilderException | ProjectBuildingException e) { throw new MojoExecutionException("Cannot build project dependency tree", e); } }