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

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

Introduction

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

Prototype

public File getFile() 

Source Link

Usage

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);//from  w  w  w .j  a va2s  .  co  m
        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.github.wanghuayao.maven.plugin.oaktree.CreateTreeMojo.java

License:Apache License

public void execute() throws MojoExecutionException {
    log = getLog();/*from   ww  w .j a va2s  .co m*/
    try {
        OakProperties properties = new OakProperties();
        dependencyArtifacts = "io.github.wanghuayao:maven-plugin-oaktree:" + properties.getVersion()
                + ":dependency-artifacts";

        filter = new ProcessingFilter(likePatten, hitePatten, deep);

        MavenProject mp = (MavenProject) this.getPluginContext().get("project");
        String mavenHomeStr = removeUnusedCharInPath(mavenHome.getPath());
        File mvnExecFile = new File(mavenHomeStr + "/bin/mvn");
        mvnExec = mvnExecFile.getPath();
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {
            mvnExec = mvnExec + ".cmd";
            isWindwos = true;
        }

        File okaBaseDir = new File(outputDirectory, "oaktree");
        File okadependencyDir = new File(okaBaseDir, "dependency");
        if (!okadependencyDir.exists()) {
            okadependencyDir.mkdirs();
        }
        okadependencyOutputDir = okadependencyDir.getPath();

        ArtifactItem rootItem = new ArtifactItem(mp.getGroupId(), mp.getArtifactId(), mp.getPackaging(),
                mp.getVersion());

        File rootPom = mp.getFile();
        int startDeep = 2;
        for (Object obj : mp.getDependencyArtifacts()) {
            DefaultArtifact artifact = (DefaultArtifact) obj;
            ArtifactItem chieldern = ArtifactItem.valueOf(artifact);
            if (filter.isGoOnProcessing(chieldern, startDeep)) {
                calcDependancy(chieldern, startDeep);
                rootItem.addChildren(chieldern);
            }
        }

        FileWriter w = null;
        try {
            File okaFile = new File(okaBaseDir, "okatree.txt");
            if (okaFile.exists()) {
                okaFile.delete();
            }
            w = new FileWriter(okaFile);
            log.info("writing file :  " + okaFile.getPath());
            printArtifactItem(w, rootItem, "");
            log.info("writing complete.");
        } finally {
            StreamUtils.quiteClose(w);
        }
    } catch (Exception ex) {
        getLog().error(ex.getMessage(), ex);
        throw new MojoExecutionException(ex.getMessage(), ex);
    }
}

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

License:Apache License

void backGroundBuild(MavenProject project) throws MojoExecutionException {
    MavenExecutionRequest executionRequest = session.getRequest();

    InvocationRequest request = new DefaultInvocationRequest();
    request.setBaseDirectory(project.getBasedir());
    request.setPomFile(project.getFile());
    request.setGoals(executionRequest.getGoals());
    request.setRecursive(false);//from ww w .j ava2  s.c  o  m
    request.setInteractive(false);

    request.setProfiles(executionRequest.getActiveProfiles());
    request.setProperties(executionRequest.getUserProperties());
    Invoker invoker = new DefaultInvoker();
    try {
        InvocationResult result = invoker.execute(request);
        if (result.getExitCode() != 0) {
            throw new IllegalStateException(
                    "Error invoking Maven goals:[" + StringUtils.join(executionRequest.getGoals(), ", ") + "]",
                    result.getExecutionException());
        }
    } catch (MavenInvocationException e) {
        throw new IllegalStateException(
                "Error invoking Maven goals:[" + StringUtils.join(executionRequest.getGoals(), ", ") + "]", e);
    }
}

From source file:io.takari.maven.plugins.Deploy.java

License:Open Source License

private void installProject(MavenProject project) throws MojoExecutionException {

    DeployRequest deployRequest = new DeployRequest();

    if ("pom".equals(project.getPackaging())) {
        ////from   w  ww  . j a v  a  2 s .c o  m
        // POM-project primary artifact
        //
        Artifact artifact = AetherUtils.toArtifact(project.getArtifact());
        artifact = artifact.setFile(project.getFile());
        deployRequest.addArtifact(artifact);

    } else {
        //
        // Primary artifact
        //
        Artifact artifact = AetherUtils.toArtifact(project.getArtifact());
        deployRequest.addArtifact(artifact);

        //
        // POM
        //
        Artifact pomArtifact = new SubArtifact(artifact, "", "pom");
        pomArtifact = pomArtifact.setFile(project.getFile());
        deployRequest.addArtifact(pomArtifact);
    }

    //
    // Attached artifacts
    //
    for (org.apache.maven.artifact.Artifact attachedArtifact : project.getAttachedArtifacts()) {
        deployRequest.addArtifact(AetherUtils.toArtifact(attachedArtifact));
    }

    deployRequest.setRepository(remoteRepository(project));

    try {
        repositorySystem.deploy(repositorySystemSession, deployRequest);
    } catch (DeploymentException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:io.takari.maven.plugins.Install.java

License:Open Source License

private void installProject(MavenProject project) throws MojoExecutionException {

    InstallRequest installRequest = new InstallRequest();

    if ("pom".equals(project.getPackaging())) {
        ////  w  w w.  ja v  a  2  s  .  c o m
        // POM-project primary artifact
        //
        Artifact artifact = AetherUtils.toArtifact(project.getArtifact());
        artifact = artifact.setFile(project.getFile());
        installRequest.addArtifact(artifact);

    } else {
        //
        // Primary artifact
        //
        Artifact artifact = AetherUtils.toArtifact(project.getArtifact());
        installRequest.addArtifact(artifact);

        //
        // POM
        //
        Artifact pomArtifact = new SubArtifact(artifact, "", "pom");
        pomArtifact = pomArtifact.setFile(project.getFile());
        installRequest.addArtifact(pomArtifact);
    }

    //
    // Attached artifacts
    //
    for (org.apache.maven.artifact.Artifact attachedArtifact : project.getAttachedArtifacts()) {
        installRequest.addArtifact(AetherUtils.toArtifact(attachedArtifact));
    }

    try {
        repositorySystem.install(repositorySystemSession, installRequest);
    } catch (InstallationException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:io.takari.maven.workspace.GenerationsWorkspaceReader.java

License:Apache License

private File find(MavenProject project, Artifact artifact) {
    File file = null;// w  w w .  j a v a  2 s . c  o  m

    if ("pom".equals(artifact.getExtension())) {
        return project.getFile();
    }

    //
    // project = project where we will find artifact, this may be the primary artifact or any of the 
    // secondary artifacts
    //
    Artifact projectArtifact = findMatchingArtifact(project, artifact);

    if (hasArtifactFileFromPackagePhase(projectArtifact)) {
        //
        // We have gone far enough in the lifecycle to produce a JAR, WAR, or other file-based artifact
        //
        if (isTestArtifact(artifact)) {
            //
            // We are looking for a test JAR foo-1.0-test.jar
            //
            file = new File(project.getBuild().getDirectory(),
                    String.format("%s-%s-tests.jar", project.getArtifactId(), project.getVersion()));
        } else {
            //
            // We are looking for an application JAR foo-1.0.jar
            //
            file = projectArtifact.getFile();
        }
    } else if (!hasBeenPackaged(project)) {
        //
        // Here no file has been produced so we fallback to loose class files only if artifacts haven't been packaged yet
        // and only for plain old jars. Not war files, not ear files, not anything else.
        //                    
        String type = artifact.getProperty("type", "");

        if (isTestArtifact(artifact)) {
            if (project.hasLifecyclePhase("test-compile")) {
                file = new File(project.getBuild().getTestOutputDirectory());
            }
        } else if (project.hasLifecyclePhase("compile") && COMPILE_PHASE_TYPES.contains(type)) {
            file = new File(project.getBuild().getOutputDirectory());
        }
        if (file == null && allowArtifactsWithoutAFileToBeResolvedInTheReactor) {
            //
            // There is no elegant way to signal that the Artifact's representation is actually present in the 
            // reactor but that it has no file-based representation during this execution and may, in fact, not
            // require one. The case this accounts for something I am doing with Eclipse project file
            // generation where I can perform dependency resolution, but cannot run any lifecycle phases.
            // I need the in-reactor references to work correctly. The WorkspaceReader interface needs
            // to be changed to account for this. This is not exactly elegant, but it's turned on
            // with a property and should not interfere.
            //
            // We have made a slight change in that we don't want to return "." because it confuses the 
            // compiler plugin for special cases that we have where we are running the compiler in the
            // process-resources phase.
            //
            file = new File(project.getBuild().getOutputDirectory());
            //if (file.exists() == false) {
            //  file = new File(".");
            //}
        }
    }

    //
    // The fall-through indicates that the artifact cannot be found;
    // for instance if package produced nothing or classifier problems.
    //
    return file;
}

From source file:io.takari.maven.workspace.GenerationsWorkspaceReader.java

License:Apache License

private File findWorkspaceArtifact(MavenProject project, Artifact artifact) {
    File file = null;/*from   w  ww  .j  a va2s . co m*/

    if ("pom".equals(artifact.getExtension())) {
        return project.getFile();
    }

    //
    // project = project where we will find artifact, this may be the primary artifact or any of the 
    // secondary artifacts
    //
    Artifact projectArtifact = findMatchingArtifact(project, artifact);

    if (hasArtifactFileFromPackagePhase(projectArtifact)) {
        //
        // We have gone far enough in the lifecycle to produce a JAR, WAR, or other file-based artifact
        //
        if (isTestArtifact(artifact)) {
            //
            // We are looking for a test JAR foo-1.0-test.jar
            //
            file = new File(project.getBuild().getDirectory(),
                    String.format("%s-%s-tests.jar", project.getArtifactId(), project.getVersion()));
        } else {
            //
            // We are looking for an application JAR foo-1.0.jar
            //
            file = projectArtifact.getFile();
        }
    } else if (!hasBeenPackaged(project)) {
        //
        // Here no file has been produced so we fallback to loose class files only if artifacts haven't been packaged yet
        // and only for plain old jars. Not war files, not ear files, not anything else.
        //                    
        String type = artifact.getProperty("type", "");

        if (isTestArtifact(artifact)) {
            if (project.hasLifecyclePhase("test-compile")) {
                file = new File(project.getBuild().getTestOutputDirectory());
            }
        } else if (project.hasLifecyclePhase("compile") && COMPILE_PHASE_TYPES.contains(type)) {
            file = new File(project.getBuild().getOutputDirectory());
        }
        if (file == null && allowArtifactsWithoutAFileToBeResolvedInTheReactor) {
            //
            // There is no elegant way to signal that the Artifact's representation is actually present in the 
            // reactor but that it has no file-based representation during this execution and may, in fact, not
            // require one. The case this accounts for something I am doing with Eclipse project file
            // generation where I can perform dependency resolution, but cannot run any lifecycle phases.
            // I need the in-reactor references to work correctly. The WorkspaceReader interface needs
            // to be changed to account for this. This is not exactly elegant, but it's turned on
            // with a property and should not interfere.
            // 

            /*
                    
            Turn off resolving for now
                    
            file = new File(project.getBuild().getOutputDirectory());
            if (file.exists() == false) {
              file = new File(".");
            }
                    
            */
        }
    }

    //
    // The fall-through indicates that the artifact cannot be found;
    // for instance if package produced nothing or classifier problems.
    //
    return file;
}

From source file:io.takari.maven.workspace.GenerationsWorkspaceReader.java

License:Apache License

private Map<String, MavenProject> getProjectMap(Collection<MavenProject> projects) {
    Map<String, MavenProject> index = new LinkedHashMap<String, MavenProject>();
    Map<String, List<File>> collisions = new LinkedHashMap<String, List<File>>();

    for (MavenProject project : projects) {
        String projectId = ArtifactUtils.key(project.getGroupId(), project.getArtifactId(),
                project.getVersion());/*from  w  w  w. j a v a  2  s .  com*/

        MavenProject collision = index.get(projectId);

        if (collision == null) {
            index.put(projectId, project);
        } else {
            List<File> pomFiles = collisions.get(projectId);

            if (pomFiles == null) {
                pomFiles = new ArrayList<File>(Arrays.asList(collision.getFile(), project.getFile()));
                collisions.put(projectId, pomFiles);
            } else {
                pomFiles.add(project.getFile());
            }
        }
    }

    /*
     * 
     * We'll assume there is no collisions
     * 
     * if (!collisions.isEmpty()) { throw new DuplicateProjectException("Two or more projects in the reactor" + " have the same identifier, please make sure that <groupId>:<artifactId>:<version>" +
     * " is unique for each project: " + collisions, collisions); }
     */

    return index;
}

From source file:io.teecube.t3.GenericReplacerMojo.java

License:Apache License

@Override
public void execute(ExecutionContext context) throws MojoExecutionException, MojoFailureException {
    this.log.info("Perform replacement in POMs.");

    // prepare for rollback
    this.cachedPOMs = Maps.newHashMap();
    for (MavenProject p : this.reactorProjects) {
        this.cachedPOMs.put(p, PomUtil.parsePOM(p).get());
    }//from  w  w w .j  a  v a2 s .  c o  m

    // retrieve qualifier (for instance the 1 in genericReplacer[1])
    String _qualifier = context.getQualifier() != null ? context.getQualifier() : "1";
    String _signGPG = "false";
    if (_qualifier.contains(",")) {
        _signGPG = _qualifier.substring(_qualifier.indexOf(",") + 1).trim();
        _qualifier = _qualifier.substring(0, _qualifier.indexOf(",")).trim();
    }
    qualifier = Integer.parseInt(_qualifier); // TODO: handle parse error
    signGPG = new Boolean(_signGPG);
    this.log.info("Step number is " + qualifier);

    try {
        for (MavenProject p : this.reactorProjects) {
            if (qualifier == 2) {
                for (String profile : profiles) {
                    session.getSettings().addActiveProfile(profile);
                }
                p.getModel().getProperties().put("ecosystemVersion", p.getVersion());
            }
            propertiesManager = CommonMojo.propertiesManager(session, p);

            if (doReplace(p.getFile(), RegexpUtil.asOptions(""))) {
                if (signGPG) {
                    signGPG(p);
                }
            }
        }
    } catch (Throwable t) {
        throw new MojoFailureException("Could not perform replacement in POMs.", t);
    } finally {
        deleteTempSettings();
    }
}

From source file:io.teecube.t3.GenericReplacerMojo.java

License:Apache License

private void signGPG(MavenProject p)
        throws MojoExecutionException, MavenInvocationException, MojoFailureException, IOException {
    InvocationRequest request = getInvocationRequest(p);
    Invoker invoker = getInvoker();

    InvocationResult result = invoker.execute(request);
    if (result.getExitCode() != 0) {
        CommandLineException executionException = result.getExecutionException();
        if (executionException != null) {
            throw new MojoFailureException("Error during project build: " + executionException.getMessage(),
                    executionException);
        } else {//from   ww w . j  a va  2  s.  c o m
            throw new MojoFailureException("Error during project build: " + result.getExitCode());
        }
    }
    if (!p.isExecutionRoot() || p.getModel().getModules().isEmpty()) {
        File gpgTempDirectory = null;
        try {
            URL gpgTempDirectoryURL = new URL(request.getProperties().get("url").toString());
            gpgTempDirectory = new File(gpgTempDirectoryURL.getFile());
            File pomGpgSignature = new File(gpgTempDirectory,
                    p.getGroupId().replaceAll("\\.", "/") + "/" + p.getArtifactId() + "/" + p.getVersion() + "/"
                            + p.getArtifactId() + "-" + p.getVersion() + ".pom.asc");
            File gpgSignatureDest = new File(p.getBuild().getDirectory(), pomGpgSignature.getName());
            pomGpgSignature = new File(p.getFile().getParentFile(), "pom.xml.asc");
            org.apache.commons.io.FileUtils.copyFile(pomGpgSignature, gpgSignatureDest);
        } finally {
            if (gpgTempDirectory != null && gpgTempDirectory.exists()) {
                org.apache.commons.io.FileUtils.deleteDirectory(gpgTempDirectory);
            }
            File ascFile = new File(p.getFile().getParentFile(), "pom.xml.asc");
            if (ascFile.exists()) {
                ascFile.delete();
            }
        }
    }
}