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.richfaces.builder.mojo.AbstractCDKMojo.java

License:Open Source License

protected ClassLoader createProjectClassLoader(MavenProject project, boolean useCCL) {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    try {//ww  w.ja  v a  2  s  . c o m
        List<?> compileClasspathElements = project.getCompileClasspathElements();
        String outputDirectory = project.getBuild().getOutputDirectory();
        URL[] urls = new URL[compileClasspathElements.size() + 1];
        int i = 0;

        urls[i++] = new File(outputDirectory).toURI().toURL();

        for (Iterator<?> iter = compileClasspathElements.iterator(); iter.hasNext();) {
            String element = (String) iter.next();

            urls[i++] = new File(element).toURI().toURL();
        }

        if (useCCL) {
            classLoader = new URLClassLoader(urls, classLoader);
        } else {
            classLoader = new URLClassLoader(urls);
        }
    } catch (MalformedURLException e) {
        getLog().error("Bad URL in classpath", e);
    } catch (DependencyResolutionRequiredException e) {
        getLog().error("Dependencies not resolved ", e);
    }

    return classLoader;
}

From source file:org.scoverage.plugin.SCoverageForkedLifecycleConfigurator.java

License:Apache License

/**
 * Configures project and dependent modules in multi-module project when entering forked {@code scoverage}
 * life cycle./*from w w  w  .j a  v  a2 s .  co m*/
 * 
 * @param project Maven project in {@code scoverage} forked life cycle.
 * @param reactorProjects all reactor Maven projects.
 * @param additionalProjectPropertiesMap additional project properties to set.
 */
public static void afterForkedLifecycleEnter(MavenProject project, List<MavenProject> reactorProjects,
        Map<String, String> additionalProjectPropertiesMap) {
    File classesDirectory = new File(project.getBuild().getOutputDirectory());
    File scoverageClassesDirectory = new File(classesDirectory.getParentFile(),
            "scoverage-" + classesDirectory.getName());

    project.getArtifact().setFile(null);
    project.getBuild().setOutputDirectory(scoverageClassesDirectory.getAbsolutePath());

    if (additionalProjectPropertiesMap != null) {
        for (Map.Entry<String, String> entry : additionalProjectPropertiesMap.entrySet()) {
            project.getProperties().put(entry.getKey(), entry.getValue());
        }
    }

    for (MavenProject reactorProject : reactorProjects) {
        if (reactorProject != project) {
            if (reactorProject.getProperties().containsKey(PROP_FORKED_OUTPUT_DIRECTORY)) {
                String forkedOutputDirectory = (String) reactorProject.getProperties()
                        .remove/* get */(PROP_FORKED_OUTPUT_DIRECTORY);
                reactorProject.getProperties().put(PROP_ORIG_OUTPUT_DIRECTORY,
                        reactorProject.getBuild().getOutputDirectory());
                reactorProject.getBuild().setOutputDirectory(forkedOutputDirectory);
            }

            if (reactorProject.getProperties().containsKey(PROP_FORKED_ARTIFACT_FILE)) {
                String forkedArtifactFilePath = (String) reactorProject.getProperties()
                        .remove/* get */(PROP_FORKED_ARTIFACT_FILE);
                File originalArtifactFile = reactorProject.getArtifact().getFile();
                reactorProject.getProperties().put(PROP_ORIG_ARTIFACT_FILE,
                        originalArtifactFile == null ? "" : originalArtifactFile.getAbsolutePath());
                reactorProject.getArtifact()
                        .setFile("".equals(forkedArtifactFilePath) ? null : new File(forkedArtifactFilePath));
            }
        }
    }
}

From source file:org.scoverage.plugin.SCoverageForkedLifecycleConfigurator.java

License:Apache License

/**
 * Restores original configuration after leaving forked {@code scoverage} life cycle.
 * <br>/*from w  w w .  ja  v a2s.  co  m*/
 * {@code project} is a project in default life cycle, {@code project.getExecutionProject()}
 * is a project in just finished forked {@code scoverage} life cycle.
 * 
 * @param project Maven project in default life cycle.
 * @param reactorProjects all reactor Maven projects.
 */
public static void afterForkedLifecycleExit(MavenProject project, List<MavenProject> reactorProjects) {
    String forkedOutputDirectory = project.getExecutionProject().getBuild().getOutputDirectory();
    project.getProperties().put(PROP_FORKED_OUTPUT_DIRECTORY, forkedOutputDirectory);

    File forkedArtifactFile = project.getExecutionProject().getArtifact().getFile();
    project.getProperties().put(PROP_FORKED_ARTIFACT_FILE,
            forkedArtifactFile != null ? forkedArtifactFile.getAbsolutePath() : "");

    // Restore changed outputDirectory and artifact.file in other reactor projects
    for (MavenProject reactorProject : reactorProjects) {
        if (reactorProject != project) {
            if (reactorProject.getProperties().containsKey(PROP_ORIG_OUTPUT_DIRECTORY)) {
                String originalOutputDirectory = (String) reactorProject.getProperties()
                        .remove(PROP_ORIG_OUTPUT_DIRECTORY);
                forkedOutputDirectory = reactorProject.getBuild().getOutputDirectory();

                reactorProject.getProperties().put(PROP_FORKED_OUTPUT_DIRECTORY, forkedOutputDirectory);
                reactorProject.getBuild().setOutputDirectory(originalOutputDirectory);
            }

            if (reactorProject.getProperties().containsKey(PROP_ORIG_ARTIFACT_FILE)) {
                String originalArtifactFilePath = (String) reactorProject.getProperties()
                        .remove/* get */(PROP_ORIG_ARTIFACT_FILE);
                forkedArtifactFile = reactorProject.getArtifact().getFile();

                reactorProject.getProperties().put(PROP_FORKED_ARTIFACT_FILE,
                        forkedArtifactFile == null ? "" : forkedArtifactFile.getAbsolutePath());
                reactorProject.getArtifact().setFile(
                        "".equals(originalArtifactFilePath) ? null : new File(originalArtifactFilePath));
            }
        }
    }
}

From source file:org.scoverage.plugin.SCoveragePreCompileMojo.java

License:Apache License

/**
 * Configures project for compilation with SCoverage instrumentation.
 * //from w  ww .  java 2 s .c  om
 * @throws MojoExecutionException if unexpected problem occurs
 */
@Override
public void execute() throws MojoExecutionException {
    if ("pom".equals(project.getPackaging())) {
        getLog().info("Skipping SCoverage execution for project with packaging type 'pom'");
        //for aggragetor mojo - list of submodules: List<MavenProject> modules = project.getCollectedProjects();
        return;
    }

    if (skip) {
        getLog().info("Skipping Scoverage execution");

        Properties projectProperties = project.getProperties();

        // for maven-resources-plugin (testResources), maven-compiler-plugin (testCompile),
        // sbt-compiler-maven-plugin (testCompile), scala-maven-plugin (testCompile),
        // maven-surefire-plugin and scalatest-maven-plugin
        setProperty(projectProperties, "maven.test.skip", "true");
        // for scalatest-maven-plugin and specs2-maven-plugin
        setProperty(projectProperties, "skipTests", "true");

        return;
    }

    long ts = System.currentTimeMillis();

    String scalaMainVersion = null;
    String resolvedScalaVersion = resolveScalaVersion();
    if (resolvedScalaVersion != null) {
        if (resolvedScalaVersion.startsWith("2.10.")) {
            scalaMainVersion = "2.10";
        } else if (resolvedScalaVersion.startsWith("2.11.")) {
            scalaMainVersion = "2.11";
        } else {
            getLog().warn(String.format("Skipping SCoverage execution - unsupported Scala version \"%s\"",
                    resolvedScalaVersion));
            return;
        }
    } else {
        getLog().warn("Skipping SCoverage execution - Scala version not set");
        return;
    }

    File classesDirectory = new File(project.getBuild().getOutputDirectory());
    File scoverageClassesDirectory = new File(classesDirectory.getParentFile(), "scoverage-classes");
    project.getBuild().setOutputDirectory(scoverageClassesDirectory.getAbsolutePath());
    for (MavenProject reactorProject : reactorProjects) {
        if (reactorProject != project) // TODO - how to include only dependent reactor projects?
        {
            classesDirectory = new File(reactorProject.getBuild().getOutputDirectory());
            if (!"scoverage-classes".equals(classesDirectory.getName())) {
                scoverageClassesDirectory = new File(classesDirectory.getParentFile(), "scoverage-classes");
                if (scoverageClassesDirectory.isDirectory()) {
                    reactorProject.getBuild().setOutputDirectory(scoverageClassesDirectory.getAbsolutePath());
                }
                //else
                //{
                // SCoverage probably skipped for that module
                // TODO add info message
                //}
            }
        }
    }

    try {
        Artifact pluginArtifact = getScalaScoveragePluginArtifact(scalaMainVersion);
        Artifact runtimeArtifact = getScalaScoverageRuntimeArtifact(scalaMainVersion);

        if (pluginArtifact == null) {
            return; // scoverage plugin will not be configured
        }

        addScoverageDependenciesToTestClasspath(runtimeArtifact);

        String arg = DATA_DIR_OPTION + dataDirectory.getAbsolutePath();
        String _scalacOptions = quoteArgument(arg);
        String addScalacArgs = arg;

        if (!StringUtils.isEmpty(excludedPackages)) {
            arg = EXCLUDED_PACKAGES_OPTION + excludedPackages.replace("(empty)", "<empty>");
            _scalacOptions = _scalacOptions + SPACE + quoteArgument(arg);
            addScalacArgs = addScalacArgs + PIPE + arg;
        }

        if (!StringUtils.isEmpty(excludedFiles)) {
            arg = EXCLUDED_FILES_OPTION + excludedFiles;
            _scalacOptions = _scalacOptions + SPACE + quoteArgument(arg);
            addScalacArgs = addScalacArgs + PIPE + arg;
        }

        if (highlighting) {
            _scalacOptions = _scalacOptions + SPACE + "-Yrangepos";
            addScalacArgs = addScalacArgs + PIPE + "-Yrangepos";
        }

        String _scalacPlugins = String.format("%s:%s:%s", pluginArtifact.getGroupId(),
                pluginArtifact.getArtifactId(), pluginArtifact.getVersion());

        arg = PLUGIN_OPTION + pluginArtifact.getFile().getAbsolutePath();
        addScalacArgs = addScalacArgs + PIPE + arg;

        Properties projectProperties = project.getProperties();

        // for sbt-compiler-maven-plugin (version 1.0.0-beta5+)
        setProperty(projectProperties, "sbt._scalacOptions", _scalacOptions);
        // for sbt-compiler-maven-plugin (version 1.0.0-beta5+)
        setProperty(projectProperties, "sbt._scalacPlugins", _scalacPlugins);
        // for scala-maven-plugin (version 3.0.0+)
        setProperty(projectProperties, "addScalacArgs", addScalacArgs);
        // for scala-maven-plugin (version 3.1.0+)
        setProperty(projectProperties, "analysisCacheFile",
                "${project.build.directory}/scoverage-analysis/compile");
        // for maven-surefire-plugin and scalatest-maven-plugin
        setProperty(projectProperties, "maven.test.failure.ignore", "true");
        // for maven-jar-plugin
        setProperty(projectProperties, "maven.jar.classifier", "scoverage");
    } catch (ArtifactNotFoundException e) {
        throw new MojoExecutionException("SCoverage preparation failed", e);
    } catch (ArtifactResolutionException e) {
        throw new MojoExecutionException("SCoverage preparation failed", e);
    }

    long te = System.currentTimeMillis();
    getLog().debug(String.format("Mojo execution time: %d ms", te - ts));
}

From source file:org.seasar.kvasir.plust.KvasirPlugin.java

public void updateOuterLibrariesProperties(IProject project, Artifact[] artifacts, IProgressMonitor monitor)
        throws CoreException {
    monitor.beginTask("Updating outerLibraries' information", IProgressMonitor.UNKNOWN);
    IFile pomFile = null;//w  w w  .jav a2s  . c o m
    try {
        Properties prop = new Properties();
        do {
            if (artifacts == null) {
                break;
            }
            pomFile = project.getFile(IKvasirProject.POM_FILE_NAME);
            if (!pomFile.exists()) {
                pomFile = null;
                break;
            }
            KvasirPlugin.getDefault().deleteMarkers(pomFile);
            MavenProject pom = getMavenProject(pomFile, monitor);
            if (pom == null) {
                break;
            }
            Build build = pom.getBuild();
            if (build == null) {
                break;
            }
            Plugin plugin = (Plugin) build.getPluginsAsMap()
                    .get("org.seasar.kvasir.maven.plugin:maven-kvasir-plugin");
            if (plugin == null) {
                break;
            }
            Xpp3Dom configuration = (Xpp3Dom) plugin.getConfiguration();
            Xpp3Dom[] children = configuration.getChildren();
            String outerLibraries = null;
            for (int i = 0; i < children.length; i++) {
                if ("pluginOuterLibraries".equals(children[i].getName())) {
                    outerLibraries = children[i].getValue();
                    break;
                }
            }
            if (outerLibraries == null) {
                break;
            }
            prop = KvasirPluginUtils.getOuterLibrariesProperties(null, outerLibraries,
                    new HashSet<Artifact>(Arrays.asList(artifacts)));
        } while (false);
        storeProperties(prop, project.getFile(IKvasirProject.OUTERLIBRARIES_FILE_PATH));

        IFile custom = project.getFile(IKvasirProject.CUSTOM_XPROPERTIES_FILE_PATH);
        Properties customProp = loadProperties(custom);
        String value = prop.getProperty("outerLibraries");
        if (value != null) {
            customProp.setProperty(PROP_SYSTEM_DEVELOPEDPLUGIN_ADDITIONALJARS, value);
        } else {
            customProp.remove(PROP_SYSTEM_DEVELOPEDPLUGIN_ADDITIONALJARS);
        }
        storeProperties(customProp, custom);
    } catch (IOException ex) {
        KvasirPlugin.getDefault().log("Can't update outerLibraries' information", ex);
    } catch (ArtifactNotFoundException ex) {
        if (pomFile != null) {
            ArtifactPattern[] patterns = ex.getArtifactPatterns();
            if (patterns != null) {
                for (int i = 0; i < patterns.length; i++) {
                    createMarker(pomFile, patterns[i].toString());
                }
            } else {
                createMarker(pomFile, null);
            }
        }
    } finally {
        monitor.done();
    }
}

From source file:org.seasar.uruma.eclipath.classpath.CompilerConfiguration.java

License:Apache License

private static Plugin findCompilerPlugin(MavenProject project) {
    Build build = project.getBuild();
    List<Plugin> plugins = build.getPlugins();
    for (Plugin plugin : plugins) {
        if (COMPILER_PLUGIN_GROUP_ID.equals(plugin.getGroupId())
                && COMPILER_PLUGIN_ARTIFACT_ID.equals(plugin.getArtifactId())) {
            return plugin;
        }/*from  w  ww  .j a v  a2 s .  c  o  m*/
    }
    return null;
}

From source file:org.sonar.api.batch.maven.MavenPlugin.java

License:Open Source License

/**
 * Registers a plugin in a project pom//w w w.j a v a 2 s .com
 * <p/>
 * <p>Adds the plugin if it does not exist or amend its version if it does exist and specified</p>
 *
 * @param pom the project pom
 * @param groupId the plugin group id
 * @param artifactId the plugin artifact id
 * @param version the plugin version
 * @param overrideVersion whether to override the version if the plugin is already registered
 * @return the registered plugin
 */
public static MavenPlugin registerPlugin(MavenProject pom, String groupId, String artifactId, String version,
        boolean overrideVersion) {
    MavenPlugin plugin = getPlugin(pom, groupId, artifactId);
    if (plugin == null) {
        plugin = new MavenPlugin(groupId, artifactId, version);

    } else if (overrideVersion) {
        plugin.setVersion(version);
    }

    // remove from pom
    unregisterPlugin(pom, groupId, artifactId);

    // register
    pom.getBuild().addPlugin(plugin.getPlugin());

    return plugin;
}

From source file:org.sonar.api.test.MavenTestUtils.java

License:Open Source License

public static MavenProject loadPom(String pomUrlInClasspath) {
    FileReader fileReader = null;
    try {//from   w  ww.  j  ava  2 s .c  o  m
        File pomFile = new File(MavenTestUtils.class.getResource(pomUrlInClasspath).toURI());
        MavenXpp3Reader pomReader = new MavenXpp3Reader();
        fileReader = new FileReader(pomFile);
        Model model = pomReader.read(fileReader);
        MavenProject project = new MavenProject(model);
        project.setFile(pomFile);
        project.getBuild().setDirectory(pomFile.getParentFile().getPath());
        project.addCompileSourceRoot(pomFile.getParentFile().getPath() + "/src/main/java");
        project.addTestCompileSourceRoot(pomFile.getParentFile().getPath() + "/src/test/java");
        return project;
    } catch (Exception e) {
        throw new SonarException("Failed to read Maven project file : " + pomUrlInClasspath, e);

    } finally {
        IOUtils.closeQuietly(fileReader);
    }
}

From source file:org.sonar.batch.InMemoryPomCreator.java

License:Open Source License

public MavenProject create() {
    File workDir = project.getWorkDir();
    String buildDirectory = workDir.getAbsolutePath() + "/target";
    Properties properties = project.getProperties();

    if (project.getBinaries().size() == 0) {
        project.addBinaryDir(buildDirectory + "/classes");
    }/*from   w w  w . ja  v  a 2 s .co m*/

    final MavenProject pom = new MavenProject() {
        /**
         * This allows to specify base directory without specifying location of a pom.xml
         */
        @Override
        public File getBasedir() {
            return project.getBaseDir();
        };

        /**
         * This allows to specify project classpath (binaries + libraries).
         */
        @Override
        public List<String> getCompileClasspathElements() throws DependencyResolutionRequiredException {
            List<String> cp = new ArrayList<String>();
            cp.addAll(project.getBinaries());
            cp.addAll(project.getLibraries());
            return cp;
        }
    };

    String key = getPropertyOrDie(properties, CoreProperties.PROJECT_KEY_PROPERTY);
    String[] keys = key.split(":");
    pom.setGroupId(keys[0]);
    pom.setArtifactId(keys[1]);
    pom.setVersion(getPropertyOrDie(properties, CoreProperties.PROJECT_VERSION_PROPERTY));

    pom.setName(properties.getProperty(CoreProperties.PROJECT_NAME_PROPERTY, "Unnamed - " + key));
    pom.setDescription(properties.getProperty(CoreProperties.PROJECT_DESCRIPTION_PROPERTY, ""));

    pom.getModel().setProperties(properties);

    pom.setArtifacts(Collections.EMPTY_SET);

    // Configure fake directories
    pom.getBuild().setDirectory(buildDirectory);
    pom.getBuild().setOutputDirectory(project.getBinaries().get(0));
    Reporting reporting = new Reporting();
    String reportingOutputDirectory = buildDirectory + "/site";
    reporting.setOutputDirectory(reportingOutputDirectory);
    pom.setReporting(reporting);

    // Configure source directories
    for (String dir : project.getSourceDirs()) {
        pom.addCompileSourceRoot(dir);
    }

    // Configure test directories
    for (String dir : project.getTestDirs()) {
        pom.addTestCompileSourceRoot(dir);
    }

    return pom;
}

From source file:org.sonar.batch.maven.MavenProjectConverter.java

License:Open Source License

public void synchronizeFileSystem(MavenProject pom, ProjectDefinition into) {
    into.setBaseDir(pom.getBasedir());/* w  ww  .  jav  a 2s .co m*/
    File buildDir = getBuildDir(pom);
    if (buildDir != null) {
        into.setBuildDir(buildDir);
        into.setWorkDir(getSonarWorkDir(pom));
    }
    into.setSourceDirs(toPaths(mainDirs(pom)));
    into.setTestDirs(toPaths(testDirs(pom)));
    File binaryDir = resolvePath(pom.getBuild().getOutputDirectory(), pom.getBasedir());
    if (binaryDir != null) {
        into.addBinaryDir(binaryDir);
    }
}