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

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

Introduction

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

Prototype

public Build getBuild() 

Source Link

Usage

From source file:org.libx4j.maven.common.Manifest.java

License:Open Source License

public static Manifest parse(final MavenProject project, final MojoExecution mojoExecution)
        throws MojoFailureException {
    final Plugin plugin = mojoExecution.getPlugin();
    final PluginExecution pluginExecution = MojoUtil.getPluginExecution(mojoExecution);

    final Build build = project.getBuild();
    if (build == null || build.getPlugins() == null)
        throw new MojoFailureException("Configuration is required");

    final Xpp3Dom configuration = plugin.getConfiguration() == null
            ? pluginExecution == null ? null : (Xpp3Dom) pluginExecution.getConfiguration()
            : pluginExecution.getConfiguration() == null ? (Xpp3Dom) plugin.getConfiguration()
                    : Xpp3Dom.mergeXpp3Dom((Xpp3Dom) plugin.getConfiguration(),
                            (Xpp3Dom) pluginExecution.getConfiguration());
    return configuration == null ? null : parse(configuration.getChild("manifest"), plugin, project);
}

From source file:org.libx4j.maven.common.Manifest.java

License:Open Source License

private static Manifest parse(final Xpp3Dom manifest, final Plugin plugin, final MavenProject project)
        throws MojoFailureException {
    if (manifest == null)
        throw new MojoFailureException("Manifest is required");

    File destdir = null;/*from   w  w w.j av  a2  s  .co m*/
    final LinkedHashSet<URL> resources = new LinkedHashSet<URL>();
    boolean overwrite = false;
    boolean compile = false;
    boolean pack = false;

    try {
        for (int j = 0; j < manifest.getChildCount(); j++) {
            final Xpp3Dom element = manifest.getChild(j);
            if ("destdir".equals(element.getName())) {
                destdir = Paths.isAbsolute(element.getValue()) ? new File(element.getValue())
                        : new File(project.getBuild().getDirectory(), element.getValue());
                for (final String attribute : element.getAttributeNames()) {
                    if (attribute.endsWith("overwrite"))
                        overwrite = Boolean.parseBoolean(element.getAttribute(attribute));
                    else if (attribute.endsWith("compile"))
                        compile = Boolean.parseBoolean(element.getAttribute(attribute));
                    else if (attribute.endsWith("package"))
                        pack = Boolean.parseBoolean(element.getAttribute(attribute));
                }
            } else if ("resources".equals(element.getName())) {
                for (int k = 0; k < element.getChildCount(); k++) {
                    final Xpp3Dom schema = element.getChild(k);
                    if ("resource".equals(schema.getName())) {
                        resources.add(buildURL(project.getFile().getParentFile().getAbsoluteFile(),
                                schema.getValue()));
                    }
                }
            }
        }
    } catch (final IOException e) {
        throw new MojoFailureException(e.getMessage(), e);
    }

    if (destdir == null)
        throw new MojoFailureException("Manifest.destdir is required");

    return new Manifest(overwrite, compile, pack, destdir, resources);
}

From source file:org.linuxstuff.mojo.licensing.CollectReportsMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    readLicensingRequirements();//from  ww  w  .j a va 2  s.c  o m

    report = new LicensingReport();

    XStream xstream = new XStream(new StaxDriver());
    xstream.processAnnotations(ArtifactWithLicenses.class);
    xstream.processAnnotations(LicensingReport.class);

    for (MavenProject p : reactorProjects) {

        File licenseXml = new File(p.getBuild().getDirectory(), thirdPartyLicensingFilename);

        if (licenseXml.canRead()) {
            LicensingReport artifactReport = (LicensingReport) xstream.fromXML(licenseXml);
            getLog().debug("Successfully turned " + licenseXml + " into " + artifactReport);
            report.combineWith(artifactReport);
        } else {
            getLog().debug("No report file found at: " + licenseXml.getAbsolutePath());
        }
    }

    File outputFile = new File(project.getBuild().getDirectory(), aggregatedThirdPartyLicensingFilename);
    report.writeReport(outputFile);

    projectHelper.attachArtifact(project, outputFile, "aggregated-third-party-licensing");

}

From source file:org.maven.ide.eclipse.embedder.BuildPathManager.java

License:Apache License

public void updateSourceFolders(IProject project, ResolverConfiguration configuration,
        IProgressMonitor monitor) {//from w  ww.j a  v  a2s  .  com
    IFile pom = project.getFile(Maven2Plugin.POM_FILE_NAME);
    if (!pom.exists()) {
        return;
    }

    monitor.beginTask("Updating sources " + project.getName(), IProgressMonitor.UNKNOWN);
    long t1 = System.currentTimeMillis();
    try {
        Set sources = new LinkedHashSet();
        List entries = new ArrayList();

        MavenProject mavenProject = collectSourceEntries(project, entries, sources, configuration, monitor);

        monitor.subTask("Configuring Build Path");
        IJavaProject javaProject = JavaCore.create(project);

        if (mavenProject != null) {
            Map options = collectOptions(mavenProject);
            setOption(javaProject, options, JavaCore.COMPILER_COMPLIANCE);
            setOption(javaProject, options, JavaCore.COMPILER_SOURCE);
            setOption(javaProject, options, JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM);

            String source = (String) options.get(JavaCore.COMPILER_SOURCE);
            if (source == null) {
                entries.add(JavaRuntime.getDefaultJREContainerEntry());
            } else {
                entries.add(getJREContainer(source));
            }
        }

        IClasspathEntry[] currentClasspath = javaProject.getRawClasspath();
        for (int i = 0; i < currentClasspath.length; i++) {
            // Delete all non container (e.g. JRE library) entries. See MNGECLIPSE-9 
            IClasspathEntry entry = currentClasspath[i];
            if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
                if (!JavaRuntime.JRE_CONTAINER.equals(entry.getPath().segment(0))) {
                    entries.add(entry);
                }
            }
        }

        if (mavenProject != null) {
            String outputDirectory = toRelativeAndFixSeparator(project.getLocation().toFile(), //
                    mavenProject.getBuild().getOutputDirectory());
            IFolder outputFolder = project.getFolder(outputDirectory);
            Util.createFolder(outputFolder);
            javaProject.setRawClasspath(
                    (IClasspathEntry[]) entries.toArray(new IClasspathEntry[entries.size()]),
                    outputFolder.getFullPath(), monitor);
        } else {
            javaProject.setRawClasspath(
                    (IClasspathEntry[]) entries.toArray(new IClasspathEntry[entries.size()]), monitor);
        }

        long t2 = System.currentTimeMillis();
        console.logMessage(
                "Updated source folders for project " + project.getName() + " " + (t2 - t1) / 1000 + "sec");

    } catch (Exception ex) {
        String msg = "Unable to update source folders " + project.getName() + "; " + ex.toString();
        console.logMessage(msg);
        Maven2Plugin.log(msg, ex);

    } finally {
        monitor.done();
    }
}

From source file:org.maven.ide.eclipse.embedder.BuildPathManager.java

License:Apache License

private void addDirs(IContainer project, Set sources, List sourceEntries, MavenProject mavenProject,
        File basedir, File projectBaseDir) {
    addSourceDirs(project, sources, sourceEntries, mavenProject.getCompileSourceRoots(), basedir,
            projectBaseDir);/* ww w.  jav  a2s .  c  o m*/
    addSourceDirs(project, sources, sourceEntries, mavenProject.getTestCompileSourceRoots(), basedir,
            projectBaseDir);

    addResourceDirs(project, sources, sourceEntries, mavenProject.getBuild().getResources(), basedir,
            projectBaseDir);
    addResourceDirs(project, sources, sourceEntries, mavenProject.getBuild().getTestResources(), basedir,
            projectBaseDir);

    // HACK to support xmlbeans generated classes MNGECLIPSE-374
    File generatedClassesDir = new File(mavenProject.getBuild().getDirectory(),
            "generated-classes" + File.separator + "xmlbeans");
    IResource generatedClasses = project.findMember(toRelativeAndFixSeparator(projectBaseDir, //
            generatedClassesDir.getAbsolutePath()));
    if (generatedClasses != null && generatedClasses.isAccessible()
            && generatedClasses.getType() == IResource.FOLDER) {
        sourceEntries.add(JavaCore.newLibraryEntry(generatedClasses.getFullPath(), null, null));
    }
}

From source file:org.maven.ide.eclipse.embedder.BuildPathManager.java

License:Apache License

private static String getBuildOption(MavenProject project, String artifactId, String optionName) {
    String option = getBuildOption(project.getBuild().getPlugins(), artifactId, optionName);
    if (option != null) {
        return option;
    }//from   ww w. ja  v a  2  s  .com
    PluginManagement pluginManagement = project.getBuild().getPluginManagement();
    if (pluginManagement != null) {
        return getBuildOption(pluginManagement.getPlugins(), artifactId, optionName);
    }
    return null;
}

From source file:org.maven.ide.eclipse.wtp.EarProjectConfiguratorDelegate.java

License:Open Source License

protected void configure(IProject project, MavenProject mavenProject, IProgressMonitor monitor)
        throws CoreException {

    monitor.setTaskName("Configuring EAR project " + project.getName());

    IFacetedProject facetedProject = ProjectFacetsManager.create(project, true, monitor);
    IMavenProjectFacade facade = MavenPlugin.getMavenProjectRegistry()
            .create(project.getFile(IMavenConstants.POM_FILE_NAME), true, monitor);

    EarPluginConfiguration config = new EarPluginConfiguration(mavenProject);
    Set<Action> actions = new LinkedHashSet<Action>();

    String contentDir = config.getEarContentDirectory(project);
    IFolder contentFolder = project.getFolder(contentDir);

    ResourceCleaner fileCleaner = new ResourceCleaner(project);
    addFilesToClean(fileCleaner, facade.getResourceLocations());
    fileCleaner.addFiles(contentFolder.getFile("META-INF/application.xml").getProjectRelativePath());

    IProjectFacetVersion earFv = config.getEarFacetVersion();
    if (!facetedProject.hasProjectFacet(WTPProjectsUtil.EAR_FACET)) {
        removeConflictingFacets(facetedProject, earFv, actions);
        actions.add(new IFacetedProject.Action(IFacetedProject.Action.Type.INSTALL, earFv,
                getEarModel(contentDir)));
    } else {//from ww  w. j  av a2s  .  c  om
        //MECLIPSEWTP-37 : don't uninstall the EAR Facet, as it causes constraint failures when used with RAD
        IProjectFacetVersion projectFacetVersion = facetedProject
                .getProjectFacetVersion(WTPProjectsUtil.EAR_FACET);
        if (earFv.getVersionString() != null
                && !earFv.getVersionString().equals(projectFacetVersion.getVersionString())) {
            actions.add(new IFacetedProject.Action(IFacetedProject.Action.Type.VERSION_CHANGE, earFv,
                    getEarModel(contentDir)));
        }
    }

    try {
        if (!actions.isEmpty()) {
            facetedProject.modify(actions, monitor);
        }
    } finally {
        try {
            //Remove any WTP created files (extras application.xml and manifest) 
            fileCleaner.cleanUp();
        } catch (CoreException cex) {
            LOG.error("Error while cleaning up WTP's created files", cex);
        }
    }
    //MECLIPSEWTP-41 Fix the missing moduleCoreNature
    fixMissingModuleCoreNature(project, monitor);

    IVirtualComponent earComponent = ComponentCore.createComponent(project);
    IPath contentDirPath = new Path((contentDir.startsWith("/")) ? contentDir : "/" + contentDir);
    //Ensure the EarContent link has been created
    if (!WTPProjectsUtil.hasLink(project, ROOT_PATH, contentDirPath, monitor)) {
        earComponent.getRootFolder().createLink(contentDirPath, IVirtualResource.NONE, monitor);
    }
    WTPProjectsUtil.setDefaultDeploymentDescriptorFolder(earComponent.getRootFolder(), contentDirPath, monitor);

    //MECLIPSEWTP-56 : application.xml should not be generated in the source directory
    boolean useBuildDirectory = MavenWtpPlugin.getDefault().getMavenWtpPreferencesManager()
            .getPreferences(project).isApplicationXmGeneratedInBuildDirectory();

    List<IPath> sourcePaths = new ArrayList<IPath>();
    sourcePaths.add(contentDirPath);

    if (useBuildDirectory) {
        IPath m2eclipseWtpFolderPath = new Path("/")
                .append(ProjectUtils.getM2eclipseWtpFolder(mavenProject, project));
        ProjectUtils.hideM2eclipseWtpFolder(mavenProject, project);
        IPath generatedResourcesPath = m2eclipseWtpFolderPath
                .append(Path.SEPARATOR + MavenWtpConstants.EAR_RESOURCES_FOLDER);
        sourcePaths.add(generatedResourcesPath);
        if (!WTPProjectsUtil.hasLink(project, ROOT_PATH, generatedResourcesPath, monitor)) {
            WTPProjectsUtil.insertLinkBefore(project, generatedResourcesPath, contentDirPath, ROOT_PATH,
                    monitor);
        }
    }

    //MECLIPSEWTP-161 remove stale source paths
    WTPProjectsUtil.deleteLinks(project, ROOT_PATH, sourcePaths, monitor);

    removeTestFolderLinks(project, mavenProject, monitor, "/");

    ProjectUtils.removeNature(project, JavaCore.NATURE_ID, monitor);

    String finalName = mavenProject.getBuild().getFinalName();
    if (!finalName.endsWith(".ear")) {
        finalName += ".ear";
    }
    configureDeployedName(project, finalName);
    project.refreshLocal(IResource.DEPTH_INFINITE, monitor);

    //MECLIPSEWTP-221 : add (in|ex)clusion patterns as .component metadata
    addComponentExclusionPatterns(earComponent, config);
}

From source file:org.maven.ide.eclipse.wtp.WebProjectConfiguratorDelegate.java

License:Open Source License

public void configureClasspath(IProject project, MavenProject mavenProject, IClasspathDescriptor classpath,
        IProgressMonitor monitor) throws CoreException {

    //Improve skinny war support by generating the manifest classpath
    //similar to mvn eclipse:eclipse 
    //http://maven.apache.org/plugins/maven-war-plugin/examples/skinny-wars.html
    WarPluginConfiguration config = new WarPluginConfiguration(mavenProject, project);
    IPackagingConfiguration opts = new PackagingConfiguration(config.getPackagingIncludes(),
            config.getPackagingExcludes());

    /*/*from w  w  w  . j  av  a 2 s.c  o m*/
     * Need to take care of three separate cases
     * 
     * 1. remove any project dependencies (they are represented as J2EE module dependencies)
     * 2. add non-dependency attribute for entries originated by artifacts with
     *    runtime, system, test scopes or optional dependencies (not sure about the last one)
     * 3. make sure all dependency JAR files have unique file names, i.e. artifactId/version collisions
     */

    Set<String> dups = new LinkedHashSet<String>();
    Set<String> names = new HashSet<String>();
    FileNameMapping fileNameMapping = config.getFileNameMapping();
    String targetDir = mavenProject.getBuild().getDirectory();

    // first pass removes projects, adds non-dependency attribute and collects colliding filenames
    Iterator<IClasspathEntryDescriptor> iter = classpath.getEntryDescriptors().iterator();
    while (iter.hasNext()) {
        IClasspathEntryDescriptor descriptor = iter.next();
        IClasspathEntry entry = descriptor.toClasspathEntry();
        String scope = descriptor.getScope();
        Artifact artifact = ArtifactHelper.getArtifact(mavenProject.getArtifacts(),
                descriptor.getArtifactKey());

        ArtifactHelper.fixArtifactHandler(artifact.getArtifactHandler());

        String deployedName = fileNameMapping.mapFileName(artifact);

        boolean isDeployed = (Artifact.SCOPE_COMPILE.equals(scope) || Artifact.SCOPE_RUNTIME.equals(scope))
                && !descriptor.isOptionalDependency() && opts.isPackaged("WEB-INF/lib/" + deployedName)
                && !isWorkspaceProject(artifact);

        // add non-dependency attribute if this classpathentry is not meant to be deployed
        // or if it's a workspace project (projects already have a reference created in configure())
        if (!isDeployed) {
            descriptor.setClasspathAttribute(NONDEPENDENCY_ATTRIBUTE.getName(),
                    NONDEPENDENCY_ATTRIBUTE.getValue());
        }

        //If custom fileName is used, then copy the artifact and rename the artifact under the build dir
        String fileName = entry.getPath().lastSegment();
        if (!deployedName.equals(fileName)) {
            IPath newPath = renameArtifact(targetDir, entry.getPath(), deployedName);
            if (newPath != null) {
                descriptor.setPath(newPath);
            }
        }

        if (!names.add(deployedName)) {
            dups.add(deployedName);
        }
    }

    // second pass disambiguates colliding entry file names
    iter = classpath.getEntryDescriptors().iterator();
    while (iter.hasNext()) {
        IClasspathEntryDescriptor descriptor = iter.next();
        IClasspathEntry entry = descriptor.toClasspathEntry();

        if (dups.contains(entry.getPath().lastSegment())) {
            String newName = descriptor.getGroupId() + "-" + entry.getPath().lastSegment();
            IPath newPath = renameArtifact(targetDir, entry.getPath(), newName);
            if (newPath != null) {
                descriptor.setPath(newPath);
            }
        }
    }
}

From source file:org.mobicents.maven.plugin.EclipseMojo.java

License:Open Source License

/**
 * Processes the project compile source roots (adds all appropriate ones to the projects)
 * so that they're avialable to the eclipse mojos.
 *
 * @param projects the projects to process.
 * @return the source roots./* w  ww .j  a  v a2s  . c o m*/
 * @throws Exception
 */
private void processCompileSourceRoots(final List projects) throws Exception {
    for (final Iterator iterator = projects.iterator(); iterator.hasNext();) {
        final MavenProject project = (MavenProject) iterator.next();
        final Set compileSourceRoots = new LinkedHashSet(project.getCompileSourceRoots());
        compileSourceRoots.addAll(this.getExtraSourceDirectories(project));
        final String testSourceDirectory = project.getBuild().getTestSourceDirectory();
        if (testSourceDirectory != null && testSourceDirectory.trim().length() > 0) {
            compileSourceRoots.add(testSourceDirectory);
        }
        project.getCompileSourceRoots().clear();
        project.getCompileSourceRoots().addAll(compileSourceRoots);
    }
}

From source file:org.mobicents.maven.plugin.EclipseMojo.java

License:Open Source License

/**
 * Retrieves any additional source directories which are defined within the andromda-multi-source-plugin.
 *
 * @param project the maven project from which to retrieve the extra source directories.
 * @return the list of extra source directories.
 *//*from   w ww .ja  v  a 2s .  co m*/
private List getExtraSourceDirectories(final MavenProject project) {
    final List sourceDirectories = new ArrayList();
    final Build build = project.getBuild();
    if (build != null) {
        final PluginManagement pluginManagement = build.getPluginManagement();
        if (pluginManagement != null && !pluginManagement.getPlugins().isEmpty()) {
            Plugin multiSourcePlugin = null;
            for (final Iterator iterator = pluginManagement.getPlugins().iterator(); iterator.hasNext();) {
                final Plugin plugin = (Plugin) iterator.next();
                if (MULTI_SOURCE_PLUGIN_ARTIFACT_ID.equals(plugin.getArtifactId())) {
                    multiSourcePlugin = plugin;
                    break;
                }
            }
            final Xpp3Dom configuration = this.getConfiguration(multiSourcePlugin);
            if (configuration != null && configuration.getChildCount() > 0) {
                final Xpp3Dom directories = configuration.getChild(0);
                if (directories != null) {
                    final int childCount = directories.getChildCount();
                    if (childCount > 0) {
                        final String baseDirectory = PathNormalizer
                                .normalizePath(ObjectUtils.toString(project.getBasedir()) + '/');
                        final Xpp3Dom[] children = directories.getChildren();
                        for (int ctr = 0; ctr < childCount; ctr++) {
                            final Xpp3Dom child = children[ctr];
                            if (child != null) {
                                String directoryValue = PathNormalizer.normalizePath(child.getValue());
                                if (directoryValue != null) {
                                    if (!directoryValue.startsWith(baseDirectory)) {
                                        directoryValue = PathNormalizer
                                                .normalizePath(baseDirectory + directoryValue.trim());
                                    }
                                    sourceDirectories.add(directoryValue);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return sourceDirectories;
}