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

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

Introduction

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

Prototype

public void setFile(File file) 

Source Link

Usage

From source file:ch.rotscher.maven.plugins.InstallWithVersionOverrideMojo.java

License:Apache License

public void execute() throws MojoExecutionException {
    try {//from  w  w w . ja  v  a  2  s.c  o  m

        String versionOverride = System.getProperty("version.override");
        if (versionOverride != null) {
            MavenProject project = getMavenProject();
            if (project != null) {
                getLog().info(
                        "version.override: rewrite the version in the original pom.xom in target/pom.xml");

                //it's very important to set the absolute file name as some classes are using File.equals for comparing
                //to file instances
                File targetDir = new File(project.getBasedir(), "target");
                if (!targetDir.exists()) {
                    targetDir.mkdir();
                }
                File newPomFile = new File(targetDir, "pom.xml");
                newPomFile.createNewFile();
                replaceVersion(project.getFile(), newPomFile, versionOverride);
                project.setFile(newPomFile);
            } else {
                getLog().warn(
                        "could not access the project in InstallMojo: install with version.override did not work!");
            }
        }

    } catch (IOException e) {
        getLog().warn(e);
    } catch (JDOMException e) {
        getLog().warn(e);
    }

    super.execute();
}

From source file:com.datacoper.maven.util.MavenUtil.java

public static MavenProject startNewProject(File folderProject) {
    try {/*from   w w  w.jav  a 2  s . c  o m*/
        File pomFile = getPomFile(folderProject);

        FileReader reader = new FileReader(pomFile);
        Model model = new MavenXpp3Reader().read(reader);
        model.setPomFile(pomFile);

        MavenProject project = new MavenProject(model);
        project.setFile(folderProject);

        return project;
    } catch (IOException | XmlPullParserException ex) {
        throw new DcRuntimeException(ex.getMessage());
    }
}

From source file:com.oracle.istack.maven.PropertyResolver.java

License:Open Source License

/**
 *
 * @param project maven project/*ww w  .  ja  v  a  2s  . co  m*/
 * @throws FileNotFoundException properties not found
 * @throws IOException IO error
 * @throws XmlPullParserException error parsing xml
 */
public void resolveProperties(MavenProject project)
        throws FileNotFoundException, IOException, XmlPullParserException {
    logger.info("Resolving properties for " + project.getGroupId() + ":" + project.getArtifactId());

    Model model = null;
    FileReader reader;
    try {
        reader = new FileReader(project.getFile());
        model = mavenreader.read(reader);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ImportPropertiesMojo.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ImportPropertiesMojo.class.getName()).log(Level.SEVERE, null, ex);
    }
    MavenProject loadedProject = new MavenProject(model);

    DependencyManagement dm = loadedProject.getDependencyManagement();
    if (dm == null) {
        logger.warn("No dependency management section found in: " + loadedProject.getGroupId() + ":"
                + loadedProject.getArtifactId());
        return;
    }

    List<Dependency> depList = dm.getDependencies();

    DependencyResult result;
    for (Dependency d : depList) {
        if ("import".equals(d.getScope())) {
            try {
                String version = d.getVersion();
                logger.info("Imported via import-scope: " + d.getGroupId() + ":" + d.getArtifactId() + ":"
                        + version);
                if (version.contains("$")) {
                    version = properties
                            .getProperty(version.substring(version.indexOf('{') + 1, version.lastIndexOf('}')));
                    logger.info("Imported version resolved to: " + version);
                }
                d.setVersion(version);
                d.setType("pom");
                d.setClassifier("pom");
                result = DependencyResolver.resolve(d, pluginRepos, repoSystem, repoSession);
                Artifact a = result.getArtifactResults().get(0).getArtifact();
                reader = new FileReader(a.getFile());
                Model m = mavenreader.read(reader);
                MavenProject p = new MavenProject(m);
                p.setFile(a.getFile());
                for (Map.Entry<Object, Object> e : p.getProperties().entrySet()) {
                    logger.info("Setting property: " + (String) e.getKey() + ":" + (String) e.getValue());
                    properties.setProperty((String) e.getKey(), (String) e.getValue());
                }

                resolveProperties(p);
            } catch (DependencyResolutionException ex) {
                Logger.getLogger(ImportPropertiesMojo.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:com.thoughtworks.gauge.maven.tests.GaugeExecutionMojoTestCase.java

License:Open Source License

public void testGetCommandWithDirProjectBaseDir() throws Exception {
    File testPom = getPomFile("simple-config.xml");

    MavenProject project = new MavenProject();
    project.setFile(testPom);

    GaugeExecutionMojo mojo = (GaugeExecutionMojo) lookupConfiguredMojo(project,
            GaugeExecutionMojo.GAUGE_EXEC_MOJO_NAME);

    ArrayList<String> actual = mojo.createGaugeCommand();
    String directory = testPom.getParentFile().getAbsolutePath();
    List<String> expected = Arrays.asList("gauge", "--dir=" + directory, "specs");
    assertEquals(expected, actual);//  w  w w  .j a v a2  s.c o m
}

From source file:fr.brouillard.oss.jgitver.JGitverUtils.java

License:Apache License

/**
 * Changes the pom file of the given project.
 * @param project the project to change the pom
 * @param newPom the pom file to set on the project
 * @param logger a logger to use /* w w w. ja  va 2  s  .  c  om*/
 */
public static void setProjectPomFile(MavenProject project, File newPom, Logger logger) {
    try {
        project.setPomFile(newPom);
    } catch (Throwable unused) {
        logger.warn("maven version might be <= 3.2.4, changing pom file using old mechanism");
        File initialBaseDir = project.getBasedir();
        project.setFile(newPom);
        File newBaseDir = project.getBasedir();
        try {
            if (!initialBaseDir.getCanonicalPath().equals(newBaseDir.getCanonicalPath())) {
                changeBaseDir(project, initialBaseDir);
            }
        } catch (Exception ex) {
            GAV gav = GAV.from(project);
            logger.warn("cannot reset basedir of project " + gav.toString(), ex);
        }
    }
}

From source file:io.github.stephenc.rfmm.ResourcesMojo.java

License:Apache License

public void execute() throws MojoExecutionException, MojoFailureException {
    if (resources == null || resources.isEmpty()) {
        resources = new ArrayList<Resource>(1);
        final Resource resource = new Resource();
        resource.setDirectory("src/secret/resources");
        resource.setFiltering(false);/*www  .j  a  v  a 2 s  . com*/
        resources.add(resource);
    }
    if (!outputDirectory.isDirectory()) {
        outputDirectory.mkdirs();
    }
    File sessionExecutionRoot;
    try {
        sessionExecutionRoot = new File(session.getExecutionRootDirectory()).getCanonicalFile();
    } catch (IOException e) {
        sessionExecutionRoot = new File(session.getExecutionRootDirectory());
    }
    getLog().debug("Session execution root: " + sessionExecutionRoot);
    final File sessionBaseDir = project.getBasedir();
    final String relativePath = getRelativePath(sessionBaseDir, sessionExecutionRoot);
    getLog().debug("Project path relative to root: " + relativePath);
    File candidateExecutionRoot;
    try {
        candidateExecutionRoot = new File(sessionExecutionRoot, offset).getCanonicalFile();
    } catch (IOException e) {
        candidateExecutionRoot = new File(sessionExecutionRoot, offset).getAbsoluteFile();
    }
    getLog().debug("Candidate execution root: " + candidateExecutionRoot);
    File candidateBaseDir = null;
    if (candidateExecutionRoot.equals(sessionExecutionRoot)) {
        getLog().debug(
                "Execution root is sufficiently close to the root of the filesystem that we cannot be a release "
                        + "build");
    } else {
        candidateBaseDir = new File(candidateExecutionRoot, relativePath);
        getLog().debug("Candidate project directory: " + candidateBaseDir);
        if (!candidateBaseDir.isDirectory()) {
            getLog().debug("As there is no directory at the candidate path, we cannot be a release build");
            candidateBaseDir = null;
        }
    }
    File candidateProjectFile;
    if (candidateBaseDir == null) {
        candidateProjectFile = project.getFile();
    } else {
        candidateProjectFile = new File(candidateBaseDir, project.getFile().getName());
        if (!isGroupIdArtifactIdMatch(candidateProjectFile)) {
            candidateProjectFile = project.getFile();
        }
    }

    try {

        if (StringUtils.isEmpty(encoding) && isFilteringEnabled(getResources())) {
            getLog().warn("File encoding has not been set, using platform encoding "
                    + ReaderFactory.FILE_ENCODING + ", i.e. build is platform dependent!");
        }

        List<String> filters = getCombinedFiltersList();

        MavenProject project = null;
        try {
            project = (MavenProject) this.project.clone();
            project.setFile(candidateProjectFile);
        } catch (CloneNotSupportedException e) {
            throw new MojoExecutionException("Could not clone project");
        }

        MavenResourcesExecution mavenResourcesExecution = new MavenResourcesExecution(getResources(),
                getOutputDirectory(), project, encoding, filters, Collections.<String>emptyList(), session);

        mavenResourcesExecution.setEscapeWindowsPaths(escapeWindowsPaths);

        // never include project build filters in this call, since we've already accounted for the POM build filters
        // above, in getCombinedFiltersList().
        mavenResourcesExecution.setInjectProjectBuildFilters(false);

        mavenResourcesExecution.setEscapeString(escapeString);
        mavenResourcesExecution.setOverwrite(overwrite);
        mavenResourcesExecution.setIncludeEmptyDirs(includeEmptyDirs);
        mavenResourcesExecution.setSupportMultiLineFiltering(supportMultiLineFiltering);

        // if these are NOT set, just use the defaults, which are '${*}' and '@'.
        if (delimiters != null && !delimiters.isEmpty()) {
            LinkedHashSet<String> delims = new LinkedHashSet<String>();
            if (useDefaultDelimiters) {
                delims.addAll(mavenResourcesExecution.getDelimiters());
            }

            for (String delim : delimiters) {
                if (delim == null) {
                    // FIXME: ${filter:*} could also trigger this condition. Need a better long-term solution.
                    delims.add("${*}");
                } else {
                    delims.add(delim);
                }
            }

            mavenResourcesExecution.setDelimiters(delims);
        }

        if (nonFilteredFileExtensions != null) {
            mavenResourcesExecution.setNonFilteredFileExtensions(nonFilteredFileExtensions);
        }
        mavenResourcesFiltering.filterResources(mavenResourcesExecution);

        executeUserFilterComponents(mavenResourcesExecution);
    } catch (MavenFilteringException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:io.sundr.maven.AbstractSundrioMojo.java

License:Apache License

MavenProject readProject(File pomFile) throws IOException {
    MavenXpp3Reader mavenReader = new MavenXpp3Reader();
    FileReader fileReader = null;
    try {/*  w w  w. j a  v  a 2s  .  c  om*/
        fileReader = new FileReader(pomFile);
        Model model = mavenReader.read(fileReader);
        model.setPomFile(pomFile);
        MavenProject project = new MavenProject(model);
        project.setFile(pomFile);
        project.setArtifact(createArtifact(pomFile, model.getGroupId(), model.getArtifactId(),
                model.getVersion(), "compile", model.getPackaging(), ""));
        return project;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (fileReader != null) {
            fileReader.close();
        }
    }
}

From source file:io.sundr.maven.GenerateBomMojo.java

License:Apache License

/**
 * Returns the generated {@link org.apache.maven.project.MavenProject} to build.
 * This version of the project contains all the stuff needed for building (parents, profiles, properties etc).
 *
 * @param project The source {@link org.apache.maven.project.MavenProject}.
 * @param config  The {@link io.sundr.maven.BomConfig}.
 * @return The build {@link org.apache.maven.project.MavenProject}.
 *///from   w  w  w .  j  a  v a  2  s .  c om
private static MavenProject toBuild(MavenProject project, BomConfig config) {
    File outputDir = new File(project.getBuild().getOutputDirectory());
    File bomDir = new File(outputDir, config.getArtifactId());
    File generatedBom = new File(bomDir, BOM_NAME);

    MavenProject toBuild = project.clone();
    //we want to avoid recursive "generate-bom".
    toBuild.setExecutionRoot(false);
    toBuild.setFile(generatedBom);
    toBuild.getModel().setPomFile(generatedBom);
    toBuild.setModelVersion(project.getModelVersion());

    toBuild.setArtifact(new DefaultArtifact(project.getGroupId(), config.getArtifactId(), project.getVersion(),
            project.getArtifact().getScope(), project.getArtifact().getType(),
            project.getArtifact().getClassifier(), project.getArtifact().getArtifactHandler()));

    toBuild.setParent(project.getParent());
    toBuild.getModel().setParent(project.getModel().getParent());

    toBuild.setGroupId(project.getGroupId());
    toBuild.setArtifactId(config.getArtifactId());
    toBuild.setVersion(project.getVersion());
    toBuild.setPackaging("pom");
    toBuild.setName(config.getName());
    toBuild.setDescription(config.getDescription());

    toBuild.setUrl(project.getUrl());
    toBuild.setLicenses(project.getLicenses());
    toBuild.setScm(project.getScm());
    toBuild.setDevelopers(project.getDevelopers());
    toBuild.setDistributionManagement(project.getDistributionManagement());
    toBuild.getModel().setProfiles(project.getModel().getProfiles());

    //We want to avoid having the generated stuff wiped.
    toBuild.getProperties().put("clean.skip", "true");
    toBuild.getModel().getBuild().setDirectory(bomDir.getAbsolutePath());
    toBuild.getModel().getBuild().setOutputDirectory(new File(bomDir, "target").getAbsolutePath());
    for (String key : config.getProperties().stringPropertyNames()) {
        toBuild.getProperties().put(key, config.getProperties().getProperty(key));
    }
    return toBuild;
}

From source file:org.codehaus.cargo.documentation.ConfluenceContainerDocumentationGenerator.java

License:Apache License

/**
 * Returns the download URL used for testing the given container.
 * @param containerId Container ID.//www.java2s  .  co  m
 * @return Download URL for testing <code>containerId</code>, <code>null</code> if no download
 * URL is set.
 */
public String getContainerServerDownloadUrl(String containerId) {
    File pom = new File(SAMPLES_DIRECTORY, POM).getAbsoluteFile();

    Model model = new Model();
    try {
        model = POM_READER.read(new FileReader(pom));
    } catch (Exception e) {
        throw new IllegalStateException("Caught Exception reading pom.xml", e);
    }

    MavenProject project = new MavenProject(model);
    project.setFile(pom);

    Map<String, Plugin> plugins = project.getPluginManagement().getPluginsAsMap();
    Plugin surefire = plugins.get(SUREFIRE_PLUGIN);
    if (surefire == null) {
        throw new IllegalStateException("Cannot find plugin " + SUREFIRE_PLUGIN + " in pom file " + pom
                + ". Found plugins: " + plugins.keySet());
    }

    Xpp3Dom configuration = (Xpp3Dom) surefire.getConfiguration();
    if (configuration == null) {
        throw new IllegalStateException(
                "Plugin " + SUREFIRE_PLUGIN + " in pom file " + pom + " does not have any configuration.");
    }
    Xpp3Dom systemProperties = configuration.getChild(SYSTEM_PROPERTIES);
    if (systemProperties == null) {
        throw new IllegalStateException("Plugin " + SUREFIRE_PLUGIN + " in pom file " + pom
                + " does not have any " + SYSTEM_PROPERTIES + " in its configuration.");
    }

    String urlName = "cargo." + containerId + ".url";
    for (Xpp3Dom property : systemProperties.getChildren()) {
        Xpp3Dom nameChild = property.getChild("name");
        Xpp3Dom valueChild = property.getChild("value");
        if (nameChild == null || valueChild == null) {
            throw new IllegalStateException("One of the " + SUREFIRE_PLUGIN
                    + "'s configuration options in pom file " + pom + " is incomplete:\n" + property);
        }

        if (urlName.equals(nameChild.getValue())) {
            return valueChild.getValue();
        }
    }

    return null;
}

From source file:org.codehaus.cargo.documentation.ConfluenceProjectStructureDocumentationGenerator.java

License:Apache License

/**
 * Creates a MavenProject from a given POM.XML file.
 * @param pom the POM.XML file to create a MavenProject from.
 * @return a MavenProject represented by the given POM.XML file.
 *///  w  ww .j  a va2s  . c om
private MavenProject createProjectFromPom(File pom) {
    Model model = new Model();
    try {
        model = POM_READER.read(new FileReader(pom));
    } catch (Exception e) {
        throw new IllegalStateException("Caught Exception reading pom.xml", e);
    }

    MavenProject project = new MavenProject(model);
    project.setFile(pom);

    return project;
}