Example usage for org.apache.maven.project MavenProject getBuildPlugins

List of usage examples for org.apache.maven.project MavenProject getBuildPlugins

Introduction

In this page you can find the example usage for org.apache.maven.project MavenProject getBuildPlugins.

Prototype

public List<Plugin> getBuildPlugins() 

Source Link

Usage

From source file:org.jenkinsci.plugins.pipeline.maven.eventspy.handler.AbstractMavenEventHandler.java

License:Open Source License

/**
 * If the Maven project uses the "flatten-maven-plugin" and defines the config parameter "flattenedPomFilename", get its value.
 *
 * TODO optimize and keep in cache this result
 *
 * @param project//from w  w w .  java2  s.c  om
 * @return the "flattenedPomFilename" defined at the "flatten" execution level or at the plugin definition level. {@code null}
 */
@Nullable
protected String getMavenFlattenPluginFlattenedPomFilename(@Nonnull MavenProject project) {
    for (Plugin buildPlugin : project.getBuildPlugins()) {
        if ("org.codehaus.mojo:flatten-maven-plugin".equals(buildPlugin.getKey())) {
            String mavenConfigurationElement = "flattenedPomFilename";
            for (PluginExecution execution : buildPlugin.getExecutions()) {
                if (execution.getGoals().contains("flatten")) {
                    if (execution.getConfiguration() instanceof Xpp3Dom) {
                        Xpp3Dom configuration = (Xpp3Dom) execution.getConfiguration();
                        Xpp3Dom flattenedPomFilename = configuration.getChild(mavenConfigurationElement);
                        if (flattenedPomFilename != null) {
                            return flattenedPomFilename.getValue();
                        }
                    } else {
                        // unexpected configuration type
                    }
                }
            }
            if (buildPlugin.getConfiguration() instanceof Xpp3Dom) {
                Xpp3Dom configuration = (Xpp3Dom) buildPlugin.getConfiguration();
                Xpp3Dom flattenedPomFilename = configuration.getChild(mavenConfigurationElement);
                if (flattenedPomFilename != null) {
                    return flattenedPomFilename.getValue();
                }
            } else {
                // unexpected configuration type
            }
        } else {

        }
    }
    return null;
}

From source file:org.jetbrains.maven.embedder.MavenEmbedder.java

License:Apache License

@SuppressWarnings({ "unchecked" })
private Map findArtifactTypeHandlers(MavenProject project) {
    // end copied from DefaultLifecycleExecutor.findExtensions
    Map result = new HashMap();
    for (Object each : project.getBuildPlugins()) {
        Plugin eachPlugin = (Plugin) each;

        if (eachPlugin.isExtensions()) {
            try {
                PluginManager pluginManager = getComponent(PluginManager.class);
                pluginManager.verifyPlugin(eachPlugin, project, mySettings, myLocalRepository);
                result.putAll(pluginManager.getPluginComponents(eachPlugin, ArtifactHandler.ROLE));
            } catch (Exception e) {
                MavenEmbedderLog.LOG.info(e);
                continue;
            }/*from   w  ww .java 2  s  . c  o  m*/

            for (Object o : result.values()) {
                ArtifactHandler handler = (ArtifactHandler) o;
                if (project.getPackaging().equals(handler.getPackaging())) {
                    project.getArtifact().setArtifactHandler(handler);
                }
            }
        }
    }
    return result;
}

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  w  w .  j a v  a2s .co  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.johnstonshome.maven.pkgdep.parse.ImportExportParser.java

License:Open Source License

private List<Package> parsePomDependencies(final MavenProject project, final String declaration,
        final Artifact defaultArtifact) {
    final List<Package> packages = new LinkedList<Package>();
    if (project.getBuildPlugins() != null) {
        for (final Object plugin : project.getBuildPlugins()) {
            final Plugin realPlugin = (Plugin) plugin;
            if (realPlugin.getGroupId().equals(PLUGIN_GROUP)
                    && realPlugin.getArtifactId().equals(PLUGIN_ARTIFACT)) {
                final Xpp3Dom configuration = (Xpp3Dom) realPlugin.getConfiguration();
                if (configuration != null) {
                    final Xpp3Dom instructions = configuration.getChild(PLUGIN_ELEM_INSTRUCTIONS);
                    if (instructions != null) {
                        final Xpp3Dom[] exports = instructions.getChildren(declaration);
                        if (exports != null) {
                            for (final Xpp3Dom export : exports) {
                                packages.addAll(parseExport(export.getValue(),
                                        project.getBuild().getSourceDirectory(), defaultArtifact));
                            }/*from www .j a v  a2s. c  om*/
                        }
                    }
                }
            }
        }
    }
    return packages;
}

From source file:org.jvnet.hudson.plugins.mavendepsupdate.MavenUpdateChecker.java

License:Apache License

public MavenUpdateCheckerResult call() throws IOException {
    ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();

    try {//w  w  w.ja  va 2s . c  o m

        PluginFirstClassLoader pluginFirstClassLoader = getPluginFirstClassLoader();
        Thread.currentThread().setContextClassLoader(pluginFirstClassLoader);
        String classLoaderName = getClass().getClassLoader().toString();

        mavenUpdateCheckerResult.addDebugLine(classLoaderName);
        PlexusContainer plexusContainer = getPlexusContainer(pluginFirstClassLoader);

        Thread.currentThread().setContextClassLoader(plexusContainer.getContainerRealm());
        mavenUpdateCheckerResult.addDebugLine("ok for new DefaultPlexusContainer( conf ) ");
        mavenUpdateCheckerResult.addDebugLine("Thread.currentThread().getContextClassLoader() "
                + Thread.currentThread().getContextClassLoader());
        mavenUpdateCheckerResult.addDebugLine("Thread.currentThread().getContextClassLoader().parent "
                + (Thread.currentThread().getContextClassLoader().getParent() == null ? "null"
                        : Thread.currentThread().getContextClassLoader().getParent().toString()));
        mavenUpdateCheckerResult.addDebugLine(
                "classLoader  urls " + Arrays.asList(plexusContainer.getContainerRealm().getURLs()));
        ProjectBuilder projectBuilder = plexusContainer.lookup(ProjectBuilder.class);

        // FIXME load userProperties from the job
        Properties userProperties = this.userProperties == null ? new Properties() : this.userProperties;

        userProperties.put("java.home", jdkHome);

        ProjectBuildingRequest projectBuildingRequest = getProjectBuildingRequest(userProperties,
                plexusContainer);

        // check plugins too
        projectBuildingRequest.setProcessPlugins(true);
        // force snapshots update

        projectBuildingRequest.setResolveDependencies(true);

        List<ProjectBuildingResult> projectBuildingResults = projectBuilder
                .build(Arrays.asList(new File(rootPomPath)), true, projectBuildingRequest);

        ProjectDependenciesResolver projectDependenciesResolver = plexusContainer
                .lookup(ProjectDependenciesResolver.class);

        List<MavenProject> mavenProjects = new ArrayList<MavenProject>(projectBuildingResults.size());

        for (ProjectBuildingResult projectBuildingResult : projectBuildingResults) {
            mavenProjects.add(projectBuildingResult.getProject());
        }

        ProjectSorter projectSorter = new ProjectSorter(mavenProjects);

        // use the projects reactor model as a workspaceReader
        // if reactors are not available remotely dependencies resolve will failed
        // due to artifact not found

        final Map<String, MavenProject> projectMap = getProjectMap(mavenProjects);
        WorkspaceReader reactorRepository = new ReactorReader(projectMap);

        MavenRepositorySystemSession mavenRepositorySystemSession = (MavenRepositorySystemSession) projectBuildingRequest
                .getRepositorySession();

        mavenRepositorySystemSession.setUpdatePolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS);

        mavenRepositorySystemSession.setWorkspaceReader(reactorRepository);

        MavenPluginManager mavenPluginManager = plexusContainer.lookup(MavenPluginManager.class);

        for (MavenProject mavenProject : projectSorter.getSortedProjects()) {
            LOGGER.info("resolve dependencies for project " + mavenProject.getId());

            DefaultDependencyResolutionRequest dependencyResolutionRequest = new DefaultDependencyResolutionRequest(
                    mavenProject, mavenRepositorySystemSession);

            try {
                DependencyResolutionResult dependencyResolutionResult = projectDependenciesResolver
                        .resolve(dependencyResolutionRequest);
            } catch (DependencyResolutionException e) {
                mavenUpdateCheckerResult.addDebugLine(e.getMessage());
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);
                mavenUpdateCheckerResult.addDebugLine("skip:" + sw.toString());
            }
            if (checkPlugins) {
                for (Plugin plugin : mavenProject.getBuildPlugins()) {
                    // only for SNAPSHOT
                    if (StringUtils.endsWith(plugin.getVersion(), "SNAPSHOT")) {
                        mavenPluginManager.getPluginDescriptor(plugin,
                                mavenProject.getRemotePluginRepositories(), mavenRepositorySystemSession);
                    }
                }
            }

        }
        SnapshotTransfertListener snapshotTransfertListener = (SnapshotTransfertListener) projectBuildingRequest
                .getRepositorySession().getTransferListener();

        if (snapshotTransfertListener.isSnapshotDownloaded()) {
            mavenUpdateCheckerResult.addFilesUpdatedNames(snapshotTransfertListener.getSnapshots());
        }

    } catch (Exception e) {
        mavenUpdateCheckerResult.addDebugLine(e.getMessage());
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        mavenUpdateCheckerResult.addDebugLine("skip:" + sw.toString());
    } finally {
        Thread.currentThread().setContextClassLoader(originalClassLoader);
    }
    return mavenUpdateCheckerResult;
}

From source file:org.l2x6.maven.srcdeps.SrcdepsLifecycleParticipant.java

License:Apache License

private Optional<Plugin> findPlugin(MavenProject project, String groupId, String atrifactId) {
    @SuppressWarnings("unchecked")
    List<Plugin> plugins = project.getBuildPlugins();
    if (plugins != null) {
        for (Plugin plugin : plugins) {

            if (SrcdepsPluginConstants.ORG_L2X6_MAVEN_SRCDEPS_GROUP_ID.equals(plugin.getGroupId())
                    && SrcdepsPluginConstants.SRCDEPS_MAVEN_PLUGIN_ADRTIFACT_ID
                            .equals(plugin.getArtifactId())) {
                return Optional.ofNullable(plugin);
            }//from w  w  w.  j a v  a  2s .  com
        }
    }
    return Optional.empty();
}

From source file:org.mobicents.slee.tools.maven.plugins.library.LibraryDescriptorMojo.java

License:Open Source License

/**
 * Obtains the library-name, library-vendor, library-version into a
 * LibraryRef element.//from   w  ww.ja v  a 2  s .  c o m
 * 
 * @param mavenProject
 *            the maven project to obtain it from
 * @return
 */

private LibraryRef getLibraryRef(MavenProject mavenProject) {
    String libraryName;
    String libraryVendor;
    String libraryVersion;

    String libraryDescription = null;

    for (Object pObject : mavenProject.getBuildPlugins()) {
        Plugin plugin = (Plugin) pObject;
        if (plugin.getArtifactId().equals("maven-library-plugin")) {
            Xpp3Dom configuration = (Xpp3Dom) plugin.getConfiguration();

            if (configuration != null) {
                if (configuration.getChildren("library-name").length > 0) {
                    libraryName = configuration.getChildren("library-name")[0].getValue();
                } else {
                    getLog().error("Library Name missing in plugin configuration!");
                    return null;
                }

                if (configuration.getChildren("library-vendor").length > 0) {
                    libraryVendor = configuration.getChildren("library-vendor")[0].getValue();
                } else {
                    getLog().error("Library Vendor missing in plugin configuration!");
                    return null;
                }

                if (configuration.getChildren("library-version").length > 0) {
                    libraryVersion = configuration.getChildren("library-version")[0].getValue();
                } else {
                    getLog().error("Library Version missing in plugin configuration!");
                    return null;
                }

                if (configuration.getChildren("description").length > 0) {
                    libraryDescription = configuration.getChildren("description")[0].getValue();
                }
            } else {
                getLog().error("Configuration missing in plugin!");
                return null;
            }

            return new LibraryRef(libraryName, libraryVendor, libraryVersion, libraryDescription);
        }
    }

    return null;
}

From source file:org.mobicents.slee.tools.maven.plugins.library.LibraryDescriptorMojo.java

License:Open Source License

private String getRefs(MavenProject mavenProject, String refName) {

    for (Object pObject : mavenProject.getBuildPlugins()) {

        Plugin plugin = (Plugin) pObject;

        if (!plugin.getArtifactId().equals("maven-library-plugin")) {
            continue;
        }//from   w  ww. j  av  a2  s . c  o  m

        Xpp3Dom configuration = (Xpp3Dom) plugin.getConfiguration();

        if (configuration != null) {
            String result = null;
            for (Xpp3Dom child : configuration.getChildren(refName + "-ref")) {
                String childXml = "\t\t<" + refName + "-ref>";
                try {
                    childXml += "\n\t\t\t<" + refName + "-name>" + child.getChild(refName + "-name").getValue()
                            + "</" + refName + "-name>";
                    childXml += "\n\t\t\t<" + refName + "-vendor>"
                            + child.getChild(refName + "-vendor").getValue() + "</" + refName + "-vendor>";
                    childXml += "\n\t\t\t<" + refName + "-version>"
                            + child.getChild(refName + "-version").getValue() + "</" + refName + "-version>";
                    childXml += "\n\t\t</" + refName + "-ref>";
                } catch (Exception e) {
                    getLog().error("Failed to load ref of type " + refName, e);
                    throw new RuntimeException(e);
                }
                if (result == null) {
                    result = childXml;
                } else {
                    result += "\r\n" + childXml;
                }
            }
            return result;
        } else {
            getLog().info("Configuration missing in plugin!");
            return null;
        }
    }

    return null;
}

From source file:org.mobicents.slee.tools.maven.plugins.library.LibraryDescriptorMojo.java

License:Open Source License

private String getSecurityPermission(MavenProject mavenProject) {
    for (Object pObject : mavenProject.getBuildPlugins()) {
        Plugin plugin = (Plugin) pObject;
        if (!plugin.getArtifactId().equals("maven-library-plugin")) {
            continue;
        }//w  ww .  j  av  a 2  s. c o  m
        Xpp3Dom configuration = (Xpp3Dom) plugin.getConfiguration();
        if (configuration == null) {
            getLog().info("Configuration missing in plugin!");
            return null;
        }
        String result = null;
        Xpp3Dom child = configuration.getChild("security-permissions");
        if (child != null) {
            result = "\t<security-permissions>\r\n";
            Xpp3Dom description = child.getChild("description");
            if (description != null && description.getValue() != null) {
                result += "\t\t<description>\r\n\t\t\t" + description.getValue() + "\r\n\t\t</description>\r\n";
            }
            Xpp3Dom securityPermissionSpec = child.getChild("security-permission-spec");
            if (securityPermissionSpec != null && securityPermissionSpec.getValue() != null) {
                result += "\t\t<security-permission-spec>\r\n\t\t\t" + securityPermissionSpec.getValue()
                        + "\r\n\t\t</security-permission-spec>\r\n";
            }
            result += "\t</security-permissions>\r\n";
        }
        return result;
    }

    return null;
}

From source file:org.nbheaven.sqe.core.maven.utils.MavenUtilities.java

License:Open Source License

/**
 * try to collect the plugin's dependency artifacts
 * as defined in <dependencies> section within <plugin>. Will only
 * return files currently in local repository
 *
 * @return list of files in local repository
 *//*w w w. j a va 2  s .  c o m*/
public static List<File> findDependencyArtifacts(Project project, String pluginGroupId, String pluginArtifactId,
        boolean includePluginArtifact) {
    List<File> cpFiles = new ArrayList<File>();
    final NbMavenProject p = project.getLookup().lookup(NbMavenProject.class);
    final MavenEmbedder online = EmbedderFactory.getOnlineEmbedder();
    MavenProject mp = p.getMavenProject();
    if (includePluginArtifact) {
        Set<Artifact> arts = new HashSet<Artifact>();
        arts.addAll(mp.getReportArtifacts());
        arts.addAll(mp.getPluginArtifacts());
        for (Artifact a : arts) {
            if (pluginArtifactId.equals(a.getArtifactId()) && pluginGroupId.equals(a.getGroupId())) {
                File f = a.getFile();
                if (f == null) {
                    //somehow the report plugins are not resolved, we need to workaround that..
                    f = FileUtil.normalizeFile(new File(new File(online.getLocalRepository().getBasedir()),
                            online.getLocalRepository().pathOf(a)));
                }
                if (!f.exists()) {
                    try {
                        online.resolve(a, mp.getRemoteArtifactRepositories(), online.getLocalRepository());
                    } catch (ArtifactResolutionException ex) {
                        Exceptions.printStackTrace(ex);
                    } catch (ArtifactNotFoundException ex) {
                        Exceptions.printStackTrace(ex);
                    }
                }
                if (f.exists()) {
                    cpFiles.add(f);
                    try {
                        ProjectBuildingRequest req = new DefaultProjectBuildingRequest();
                        req.setRemoteRepositories(mp.getRemoteArtifactRepositories());
                        req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
                        req.setSystemProperties(online.getSystemProperties());
                        ProjectBuildingResult res = online.buildProject(a, req);
                        MavenProject mp2 = res.getProject();
                        if (mp2 != null) {
                            // XXX this is not really right, but mp.dependencyArtifacts = null for some reason
                            for (Dependency dep : mp2.getDependencies()) {
                                Artifact a2 = online.createArtifact(dep.getGroupId(), dep.getArtifactId(),
                                        dep.getVersion(), "jar");
                                online.resolve(a2, mp.getRemoteArtifactRepositories(),
                                        online.getLocalRepository());
                                File df = a2.getFile();
                                if (df.exists()) {
                                    cpFiles.add(df);
                                }
                            }
                        }
                    } catch (Exception x) {
                        Exceptions.printStackTrace(x);
                    }
                }
            }
        }

    }
    List<Plugin> plugins = mp.getBuildPlugins();
    for (Plugin plug : plugins) {
        if (pluginArtifactId.equals(plug.getArtifactId()) && pluginGroupId.equals(plug.getGroupId())) {
            try {
                List<Dependency> deps = plug.getDependencies();
                ArtifactFactory artifactFactory = online.getPlexus().lookup(ArtifactFactory.class);
                for (Dependency d : deps) {
                    final Artifact projectArtifact = artifactFactory.createArtifactWithClassifier(
                            d.getGroupId(), d.getArtifactId(), d.getVersion(), d.getType(), d.getClassifier());
                    String localPath = online.getLocalRepository().pathOf(projectArtifact);
                    File f = FileUtil
                            .normalizeFile(new File(online.getLocalRepository().getBasedir(), localPath));
                    if (!f.exists()) {
                        try {
                            online.resolve(projectArtifact, mp.getRemoteArtifactRepositories(),
                                    online.getLocalRepository());
                        } catch (ArtifactResolutionException ex) {
                            ex.printStackTrace();
                            //                                        Exceptions.printStackTrace(ex);
                        } catch (ArtifactNotFoundException ex) {
                            ex.printStackTrace();
                            //                            Exceptions.printStackTrace(ex);
                        }
                    }
                    if (f.exists()) {
                        cpFiles.add(f);
                    }
                }
            } catch (ComponentLookupException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }
    return cpFiles;
}