Example usage for org.apache.maven.project ProjectBuildingRequest setProject

List of usage examples for org.apache.maven.project ProjectBuildingRequest setProject

Introduction

In this page you can find the example usage for org.apache.maven.project ProjectBuildingRequest setProject.

Prototype

void setProject(MavenProject mavenProject);

Source Link

Usage

From source file:com.github.wcy123.maven.launcher.RunnerMojo.java

License:Apache License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (isSkip()) {
        getLog().info("Skipping plugin execution");
        return;/* w  w  w.  j  a va  2s .  co m*/
    }

    if (coordinate.getArtifactId() == null && artifact == null) {
        throw new MojoFailureException("You must specify an artifact, "
                + "e.g. -Dartifact=org.apache.maven.plugins:maven-downloader-plugin:1.0");
    }
    if (artifact != null) {
        String[] tokens = StringUtils.split(artifact, ":");
        if (tokens.length < 3 || tokens.length > 5) {
            throw new MojoFailureException(
                    "Invalid artifact, you must specify groupId:artifactId:version[:packaging[:classifier]] "
                            + artifact);
        }
        coordinate.setGroupId(tokens[0]);
        coordinate.setArtifactId(tokens[1]);
        coordinate.setVersion(tokens[2]);
        if (tokens.length >= 4) {
            coordinate.setType(tokens[3]);
        }
        if (tokens.length == 5) {
            coordinate.setClassifier(tokens[4]);
        }
    }

    ArtifactRepositoryPolicy always = new ArtifactRepositoryPolicy(true,
            ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN);

    List<ArtifactRepository> repoList = new ArrayList<ArtifactRepository>();

    if (pomRemoteRepositories != null) {
        repoList.addAll(pomRemoteRepositories);
    }

    if (remoteRepositories != null) {
        // Use the same format as in the deploy plugin id::layout::url
        List<String> repos = Arrays.asList(StringUtils.split(remoteRepositories, ","));
        for (String repo : repos) {
            repoList.add(parseRepository(repo, always));
        }
    }

    try {
        ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(
                session.getProjectBuildingRequest());
        buildingRequest.setProject(session.getCurrentProject());
        buildingRequest.setRemoteRepositories(repoList);

        getLog().info("Resolving " + coordinate + " with transitive dependencies");

        // FIXME
        // artifactResolver.resolveArtifact( buildingRequest, coordinate );

        final Iterable<ArtifactResult> artifactResults = dependencyResolver.resolveDependencies(buildingRequest,
                coordinate, null);

        // start from here
        if (!artifactResults.iterator().hasNext()) {
            getLog().error("cannot find the first artifcat");
            return;
        }
        List<Artifact> listOfArtifacts = new ArrayList<>();
        for (ArtifactResult artifactResult : artifactResults) {
            getLog().info("artifacts " + artifactResult.getArtifact());
            listOfArtifacts.add(artifactResolver.resolveArtifact(buildingRequest, artifactResult.getArtifact())
                    .getArtifact());

        }
        URL[] urls = new URL[listOfArtifacts.size()];
        for (int i = 0; i < urls.length; ++i) {
            urls[i] = listOfArtifacts.get(i).getFile().toURI().toURL();
        }
        final SharedUrlClassLoader classLoader = SharedUrlClassLoader.create(urls);

        final JarFile jarFile = new JarFile(urls[0].getFile());
        final Manifest manifest = jarFile.getManifest();
        String value = manifest.getMainAttributes().getValue("Main-Class");
        // final String charSequence = "cannot find Main-Class: " +
        // manifest.getMainAttributes().entrySet().stream().map(e -> e.getKey() + ":" +
        // e.getValue()).collect(Collectors.joining("\n"));
        if (value == null) {
            throw new MojoFailureException("cannot find Main-Class " + classLoader.getURLs());
        }
        value = "com.wcy123.HelloWorldApplication";
        System.out.println("value is value " + value);
        final Class<?> aClass = Class.forName(value, true, classLoader);
        final Method main = aClass.getMethod("main", String[].class);
        Thread runnerThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    main.invoke(null, new Object[] { new String[] { "hello", "world" } });
                } catch (IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        });
        runnerThread.setContextClassLoader(classLoader);
        runnerThread.start();
        runnerThread.join();
    } catch (DependencyResolverException e) {
        throw new MojoExecutionException("Couldn't download artifact: " + e.getMessage(), e);
    } catch (IOException e) {
        getLog().error("cannot create class loader", e);
        throw new MojoFailureException("cannot create class loader");
    } catch (ArtifactResolverException e) {
        getLog().error("cannot resolve artifact", e);
        throw new MojoFailureException("cannot resolve artifact");
    } catch (ClassNotFoundException e) {
        getLog().error("cannot load Main-Class", e);
        throw new MojoFailureException("cannot load Main-Class");
    } catch (NoSuchMethodException e) {
        getLog().error("cannot get main method", e);
        throw new MojoFailureException("cannot get main method");
    } catch (InterruptedException e) {
        getLog().error("interrupted", e);
    }
}

From source file:com.xwikisas.xcs.tools.dependenciespackager.PackageExtensionsMojo.java

License:Open Source License

private Collection<Artifact> getMainWikiArtifacts() throws DependencyGraphBuilderException {
    // Get main UI
    Artifact mainWikiUI = mavenProject.getArtifactMap().get(extensionOnMainWiki);
    // If no artifact was configured for main wiki, return an empty list of artifacts to mark as installed
    if (mainWikiUI == null) {
        return Collections.<Artifact>emptyList();
    }/*  w  ww.j  av a2s . co m*/

    ProjectBuildingRequest request = new DefaultProjectBuildingRequest();
    request.setRepositorySession(session.getRepositorySession());
    request.setProject(mavenProject);

    DependencyNode rootNode = graphBuilder.buildDependencyGraph(request, null);

    Collection<Artifact> artifactsToInstall = new ArrayList<>();
    walk(rootNode, mainWikiUI, false, artifactsToInstall);

    return artifactsToInstall;
}

From source file:org.apifocal.maven.plugins.bom.AbstractBomMojo.java

License:Apache License

protected void importProperties(Dependency artifactMetadata) throws MojoExecutionException {
    try {/*from w  ww  . j a  v a 2 s. co  m*/
        Artifact artifact = repoSystem.createDependencyArtifact(artifactMetadata);
        getLog().info("Importing properties from " + artifact);

        ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(
                session.getProjectBuildingRequest());
        buildingRequest.setProject(null);
        buildingRequest.setResolveDependencies(false);
        MavenProject bomProject = projectBuilder.build(artifact, buildingRequest).getProject();

        bomProject.getProperties()
                .forEach((Object key, Object value) -> project.getProperties().putIfAbsent(key, value));
    } catch (ProjectBuildingException ex) {
        getLog().error("Failed to resolve artifact", ex);
        throw new MojoExecutionException("Could not read artifact " + artifactMetadata.toString(), ex);
    }
}

From source file:org.eclipse.m2e.core.internal.project.registry.DefaultMavenDependencyResolver.java

License:Open Source License

@Override
public void resolveProjectDependencies(final IMavenProjectFacade facade, Set<Capability> capabilities,
        Set<RequiredCapability> requirements, final IProgressMonitor monitor) throws CoreException {
    long start = System.currentTimeMillis();
    log.debug("Resolving dependencies for {}", facade.toString()); //$NON-NLS-1$

    markerManager.deleteMarkers(facade.getPom(), IMavenConstants.MARKER_DEPENDENCY_ID);

    ProjectBuildingRequest configuration = getMaven().getExecutionContext().newProjectBuildingRequest();
    configuration.setProject(facade.getMavenProject()); // TODO do we need this?
    configuration.setResolveDependencies(true);
    MavenExecutionResult mavenResult = getMaven().readMavenProject(facade.getPomFile(), configuration);

    markerManager.addMarkers(facade.getPom(), IMavenConstants.MARKER_DEPENDENCY_ID, mavenResult);

    if (!facade.getResolverConfiguration().shouldResolveWorkspaceProjects()) {
        return;/*from   w w w.  j av a2 s .c om*/
    }

    MavenProject mavenProject = facade.getMavenProject();

    // dependencies

    // resolved dependencies
    for (Artifact artifact : mavenProject.getArtifacts()) {
        requirements.add(MavenRequiredCapability.createMavenArtifact(new ArtifactKey(artifact),
                artifact.getScope(), artifact.isOptional()));
    }

    // extension plugins (affect packaging type calculation)
    for (Plugin plugin : mavenProject.getBuildPlugins()) {
        if (plugin.isExtensions()) {
            ArtifactKey artifactKey = new ArtifactKey(plugin.getGroupId(), plugin.getArtifactId(),
                    plugin.getVersion(), null);
            requirements.add(MavenRequiredCapability.createMavenArtifact(artifactKey, "plugin", false)); //$NON-NLS-1$
        }
    }

    // missing dependencies
    DependencyResolutionResult resolutionResult = mavenResult.getDependencyResolutionResult();
    if (resolutionResult != null && resolutionResult.getUnresolvedDependencies() != null) {
        for (Dependency dependency : resolutionResult.getUnresolvedDependencies()) {
            org.sonatype.aether.artifact.Artifact artifact = dependency.getArtifact();
            ArtifactKey dependencyKey = new ArtifactKey(artifact.getGroupId(), artifact.getArtifactId(),
                    artifact.getVersion(), null);
            requirements.add(MavenRequiredCapability.createMavenArtifact(dependencyKey, dependency.getScope(),
                    dependency.isOptional()));
        }
    }

    log.debug("Resolved dependencies for {} in {} ms", facade.toString(), System.currentTimeMillis() - start); //$NON-NLS-1$
}

From source file:org.sourcepit.maven.dependency.model.aether.AetherDependencyModelResolver.java

License:Apache License

private ProjectBuildingRequest newProjectBuildingRequest(boolean resolveDeps, boolean processPlugins) {
    final ProjectBuildingRequest request = new DefaultProjectBuildingRequest(
            buildContext.getSession().getProjectBuildingRequest());
    request.setResolveDependencies(resolveDeps);
    request.setProcessPlugins(processPlugins);
    request.setProject(null);

    final MavenProject project = buildContext.getSession().getCurrentProject();
    if (project != null) {
        @SuppressWarnings("unchecked")
        List<ArtifactRepository> artifactRepos = combine(project.getRemoteArtifactRepositories(),
                request.getRemoteRepositories());

        @SuppressWarnings("unchecked")
        List<ArtifactRepository> pluginRepos = combine(project.getPluginArtifactRepositories(),
                request.getPluginArtifactRepositories());

        request.setRemoteRepositories(artifactRepos);
        request.setPluginArtifactRepositories(pluginRepos);
    }/*from   w  w  w.j  a  v a 2  s.c o  m*/

    return request;
}

From source file:org.sourcepit.osgifier.maven.OsgifyArtifactsMojo.java

License:Apache License

private ProjectBuildingResult buildMavenProject(final MavenArtifact artifact) throws ProjectBuildingException {
    final ProjectBuildingRequest request = new DefaultProjectBuildingRequest(
            buildContext.getSession().getProjectBuildingRequest());
    request.setProject(null);
    request.setResolveDependencies(false);
    request.setProcessPlugins(false);/*from   w  w  w. j ava2s.co  m*/

    final org.apache.maven.artifact.Artifact projectArtifact = RepositoryUtils.toArtifact(artifactFactory
            .createArtifact(artifactFactory.createArtifact(artifact.getArtifactKey()), null, "pom"));

    return projectBuilder.build(projectArtifact, true, request);
}

From source file:org.sourcepit.osgifier.maven.resolve.MavenModelContentAppenderParticipant.java

License:Apache License

private Model buildMavenModel(final ArtifactKey pomKey) {
    final Artifact pomArtifact = RepositoryUtils.toArtifact(artifactFactory.createArtifact(pomKey));

    final ProjectBuildingRequest request = new DefaultProjectBuildingRequest(
            buildContext.getSession().getProjectBuildingRequest());
    request.setProject(null);
    request.setResolveDependencies(false);
    request.setProcessPlugins(false);//from   w ww .j  a v  a  2 s .  co  m
    request.setValidationLevel(VALIDATION_LEVEL_MINIMAL);

    try {
        final ProjectBuildingResult result = projectBuilder.build(pomArtifact, true, request);
        return result.getProject().getModel();
    } catch (ProjectBuildingException e) {
        throw pipe(e);
    }
}