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

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

Introduction

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

Prototype

public File getBasedir() 

Source Link

Usage

From source file:io.fabric8.maven.AbstractFabric8Mojo.java

License:Apache License

/**
 * Tries to default some environment variables if they are not already defined.
 *
 * This can happen if using Jenkins Workflow which doens't seem to define BUILD_URL or GIT_URL for example
 *
 * @return the value of the environment variable name if it can be found or calculated
 *//*from  w  ww  . jav  a 2  s  .  c om*/
protected String tryDefaultAnnotationEnvVar(String envVarName) {
    // only do this if enabled
    if (extendedMetadata != null && !extendedMetadata) {
        return null;
    }

    MavenProject rootProject = getRootProject();
    File basedir = rootProject.getBasedir();
    if (basedir == null) {
        basedir = getProject().getBasedir();
    }
    if (basedir == null) {
        basedir = new File(System.getProperty("basedir", "."));
    }
    ProjectConfig projectConfig = ProjectConfigs.loadFromFolder(basedir);
    String repoName = rootProject.getArtifactId();

    String userEnvVar = "JENKINS_GOGS_USER";
    String username = Systems.getEnvVarOrSystemProperty(userEnvVar);

    if (Objects.equal("BUILD_URL", envVarName)) {
        String jobUrl = projectConfig.getLink("Job");
        if (Strings.isNullOrBlank(jobUrl)) {
            String name = projectConfig.getBuildName();
            if (Strings.isNullOrBlank(name)) {
                // lets try deduce the jenkins build name we'll generate
                if (Strings.isNotBlank(repoName)) {
                    name = repoName;
                    if (Strings.isNotBlank(username)) {
                        name = ProjectRepositories.createBuildName(username, repoName);
                    } else {
                        warnIfInCDBuild("Cannot auto-default BUILD_URL as there is no environment variable `"
                                + userEnvVar + "` defined so we can't guess the Jenkins build URL");
                    }
                }
            }
            if (Strings.isNotBlank(name)) {
                try {
                    // this requires online access to kubernetes so we should silently fail if no connection
                    String jenkinsUrl = KubernetesHelper.getServiceURLInCurrentNamespace(getKubernetes(),
                            ServiceNames.JENKINS, "http", null, true);
                    jobUrl = URLUtils.pathJoin(jenkinsUrl, "/job", name);
                } catch (Throwable e) {
                    Throwable cause = e;

                    boolean notFound = false;
                    boolean connectError = false;
                    Iterable<Throwable> it = createExceptionIterable(e);
                    for (Throwable t : it) {
                        connectError = t instanceof ConnectException
                                || "No route to host".equals(t.getMessage());
                        notFound = t instanceof IllegalArgumentException || t.getMessage() != null
                                && t.getMessage().startsWith("No kubernetes service could be found for name");
                        if (connectError || notFound) {
                            cause = t;
                            break;
                        }
                    }

                    if (connectError) {
                        warnIfInCDBuild("Cannot connect to Kubernetes to find jenkins service URL: "
                                + cause.getMessage());
                    } else if (notFound) {
                        // the message from the exception is good as-is
                        warnIfInCDBuild(cause.getMessage());
                    } else {
                        warnIfInCDBuild("Cannot find jenkins service URL: " + cause, cause);
                    }
                }
            }
        }
        if (Strings.isNotBlank(jobUrl)) {
            String buildId = Systems.getEnvVarOrSystemProperty("BUILD_ID");
            if (Strings.isNotBlank(buildId)) {
                jobUrl = URLUtils.pathJoin(jobUrl, buildId);
            } else {
                warnIfInCDBuild(
                        "Cannot find BUILD_ID to create a specific jenkins build URL. So using: " + jobUrl);
            }
        }
        return jobUrl;
    } else if (Objects.equal("GIT_URL", envVarName)) {
        if (Strings.isNotBlank(repoName) && Strings.isNotBlank(username)) {
            try {
                // this requires online access to kubernetes so we should silently fail if no connection
                String gogsUrl = KubernetesHelper.getServiceURLInCurrentNamespace(getKubernetes(),
                        ServiceNames.GOGS, "http", null, true);
                String rootGitUrl = URLUtils.pathJoin(gogsUrl, username, repoName);
                String gitCommitId = getGitCommitId(envVarName, basedir);
                if (Strings.isNotBlank(gitCommitId)) {
                    rootGitUrl = URLUtils.pathJoin(rootGitUrl, "commit", gitCommitId);
                }
                return rootGitUrl;
            } catch (Throwable e) {
                Throwable cause = e;

                boolean notFound = false;
                boolean connectError = false;
                Iterable<Throwable> it = createExceptionIterable(e);
                for (Throwable t : it) {
                    notFound = t instanceof IllegalArgumentException || t.getMessage() != null
                            && t.getMessage().startsWith("No kubernetes service could be found for name");
                    connectError = t instanceof ConnectException || "No route to host".equals(t.getMessage());
                    if (connectError) {
                        cause = t;
                        break;
                    }
                }

                if (connectError) {
                    warnIfInCDBuild(
                            "Cannot connect to Kubernetes to find gogs service URL: " + cause.getMessage());
                } else if (notFound) {
                    // the message from the exception is good as-is
                    warnIfInCDBuild(cause.getMessage());
                } else {
                    warnIfInCDBuild("Cannot find gogs service URL: " + cause, cause);
                }
            }
        } else {
            warnIfInCDBuild("Cannot auto-default GIT_URL as there is no environment variable `" + userEnvVar
                    + "` defined so we can't guess the Gogs build URL");
        }
        /*
                    TODO this is the git clone url; while we could try convert from it to a browse URL its probably too flaky?
                
                    try {
        url = GitHelpers.extractGitUrl(basedir);
                    } catch (IOException e) {
        warnIfInCDBuild("Failed to find git url in directory " + basedir + ". " + e, e);
                    }
                    if (Strings.isNotBlank(url)) {
        // for gogs / github style repos we trim the .git suffix for browsing
        return Strings.stripSuffix(url, ".git");
                    }
        */
    } else if (Objects.equal("GIT_COMMIT", envVarName)) {
        return getGitCommitId(envVarName, basedir);
    } else if (Objects.equal("GIT_BRANCH", envVarName)) {
        Repository repository = getGitRepository(basedir, envVarName);
        try {
            if (repository != null) {
                return repository.getBranch();
            }
        } catch (IOException e) {
            warnIfInCDBuild("Failed to find git commit id. " + e, e);
        } finally {
            if (repository != null) {
                repository.close();
            }
        }
    }
    return null;
}

From source file:io.fabric8.maven.AbstractNamespacedMojo.java

License:Apache License

/**
 * Returns the configuration of the project in the <code>fabric8.yml</code> file in the root project or current directory
 * or returns an empty configuraiton/*from ww w  .j av  a 2s  .  co  m*/
 */
protected ProjectConfig findProjectConfig() {
    MavenProject rootProject = getRootProject();
    File basedir = null;
    if (rootProject != null) {
        basedir = rootProject.getBasedir();
    }
    if (basedir == null) {
        MavenProject project = getProject();
        if (project != null) {
            basedir = project.getBasedir();
        }
    }
    if (basedir == null) {
        basedir = new File(System.getProperty("basedir", "."));
    }
    return ProjectConfigs.loadFromFolder(basedir);
}

From source file:io.fabric8.maven.AbstractNamespacedMojo.java

License:Apache License

/**
 * Returns the root project folder//  w w w  .ja  v a 2  s .  c o  m
 */
protected File getRootProjectFolder() {
    File answer = null;
    MavenProject project = getProject();
    while (project != null) {
        File basedir = project.getBasedir();
        if (basedir != null) {
            answer = basedir;
        }
        project = project.getParent();
    }
    return answer;
}

From source file:io.fabric8.maven.AbstractProfileMojo.java

License:Apache License

public static void combineProfileFilesToFolder(MavenProject reactorProject, File buildDir, Log log,
        String reactorProjectOutputPath) throws IOException {
    File basedir = reactorProject.getBasedir();
    if (!basedir.exists()) {
        log.warn("No basedir " + basedir.getAbsolutePath() + " for project + " + reactorProject);
        return;/*from w w  w.  j a v a  2 s.  co m*/
    }
    File outDir = new File(basedir, reactorProjectOutputPath);
    if (!outDir.exists()) {
        log.warn("No profile output dir at: " + outDir.getAbsolutePath() + " for project + " + reactorProject
                + " so ignoring this project.");
        return;
    }
    log.info("Copying profiles from " + outDir.getAbsolutePath() + " into the output directory: " + buildDir);
    appendProfileConfigFiles(outDir, buildDir);
}

From source file:io.fabric8.maven.AbstractProfileMojo.java

License:Apache License

protected void createAggregatedZip(List<MavenProject> reactorProjectList, File projectBaseDir,
        File projectBuildDir, String reactorProjectOutputPath, File projectOutputFile, boolean includeReadMe,
        List<MavenProject> pomZipProjects) throws IOException {
    projectBuildDir.mkdirs();//ww w  .j a  v a  2  s. c  o  m

    for (MavenProject reactorProject : reactorProjectList) {
        // ignoreProject the execution root which just aggregates stuff
        if (!reactorProject.isExecutionRoot()) {
            Log log = getLog();
            combineProfileFilesToFolder(reactorProject, projectBuildDir, log, reactorProjectOutputPath);
        }
    }

    // we may want to include readme files for pom projects
    if (includeReadMe) {

        Map<String, File> pomNames = new HashMap<String, File>();

        for (MavenProject pomProjects : pomZipProjects) {
            File src = pomProjects.getFile().getParentFile();

            // must include first dir as prefix
            String root = projectBaseDir.getName();

            String relativePath = Files.getRelativePath(projectBaseDir, pomProjects.getBasedir());
            relativePath = root + File.separator + relativePath;

            // we must use dot instead of dashes in profile paths
            relativePath = pathToProfilePath(relativePath);

            File outDir = new File(projectBuildDir, relativePath);
            File copiedFile = copyReadMe(src, outDir);

            if (copiedFile != null) {
                String key = getReadMeFileKey(relativePath);
                pomNames.put(key, copiedFile);
            }
        }

        if (replaceReadmeLinksPrefix != null) {

            // now parse each readme file and replace github links
            for (Map.Entry<String, File> entry : pomNames.entrySet()) {
                File file = entry.getValue();
                String key = entry.getKey();

                boolean changed = false;
                List<String> lines = Files.readLines(file);
                for (int i = 0; i < lines.size(); i++) {
                    String line = lines.get(i);
                    String newLine = replaceGithubLinks(pomNames.keySet(), key, line);
                    if (newLine != null) {
                        lines.set(i, newLine);
                        changed = true;
                    }
                }
                if (changed) {
                    Files.writeLines(file, lines);
                    getLog().info("Replaced github links to fabric profiles in reaadme file: " + file);
                }
            }
        }
    }

    Zips.createZipFile(getLog(), projectBuildDir, projectOutputFile);
    String relativePath = Files.getRelativePath(projectBaseDir, projectOutputFile);
    while (relativePath.startsWith("/")) {
        relativePath = relativePath.substring(1);
    }
    getLog().info("Created profile zip file: " + relativePath);
}

From source file:io.fabric8.maven.core.util.GitUtil.java

License:Apache License

public static Repository getGitRepository(MavenProject project) throws IOException {
    MavenProject rootProject = MavenUtil.getRootProject(project);
    File baseDir = rootProject.getBasedir();
    if (baseDir == null) {
        baseDir = project.getBasedir();/*from w w  w.j ava  2  s.  c  o m*/
    }
    if (baseDir == null) {
        // TODO: Why is this check needed ?
        baseDir = new File(System.getProperty("basedir", "."));
    }
    File gitFolder = findGitFolder(baseDir);
    if (gitFolder == null) {
        // No git repository found
        return null;
    }
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = builder.readEnvironment().setGitDir(gitFolder).build();
    return repository;
}

From source file:io.fabric8.maven.CreateProfileZipMojo.java

License:Apache License

protected void generateAggregatedZip(MavenProject rootProject, List<MavenProject> reactorProjects,
        List<MavenProject> pomZipProjects) throws IOException, MojoExecutionException {
    File projectBaseDir = rootProject.getBasedir();
    File projectOutputFile = new File(projectBaseDir, "target/profile.zip");
    getLog().info("Generating " + projectOutputFile.getAbsolutePath() + " from root project "
            + rootProject.getArtifactId());
    File projectBuildDir = new File(projectBaseDir, reactorProjectOutputPath);

    createAggregatedZip(reactorProjects, projectBaseDir, projectBuildDir, reactorProjectOutputPath,
            projectOutputFile, includeReadMe, pomZipProjects);
    if (rootProject.getAttachedArtifacts() != null) {
        // need to remove existing as otherwise we get a WARN
        Artifact found = null;//w ww .  j  a  v a2 s. c  o  m
        for (Artifact artifact : rootProject.getAttachedArtifacts()) {
            if (artifactClassifier != null && artifact.hasClassifier()
                    && artifact.getClassifier().equals(artifactClassifier)) {
                found = artifact;
                break;
            }
        }
        if (found != null) {
            rootProject.getAttachedArtifacts().remove(found);
        }
    }

    getLog().info("Attaching aggregated zip " + projectOutputFile + " to root project "
            + rootProject.getArtifactId());
    projectHelper.attachArtifact(rootProject, artifactType, artifactClassifier, projectOutputFile);

    // if we are doing an install goal, then also install the aggregated zip manually
    // as maven will install the root project first, and then build the reactor projects, and at this point
    // it does not help to attach artifact to root project, as those artifacts will not be installed
    // so we need to install manually
    if (rootProject.hasLifecyclePhase("install")) {
        getLog().info("Installing aggregated zip " + projectOutputFile);
        InvocationRequest request = new DefaultInvocationRequest();
        request.setBaseDirectory(rootProject.getBasedir());
        request.setPomFile(new File("./pom.xml"));
        request.setGoals(Collections.singletonList("install:install-file"));
        request.setRecursive(false);
        request.setInteractive(false);

        Properties props = new Properties();
        props.setProperty("file", "target/profile.zip");
        props.setProperty("groupId", rootProject.getGroupId());
        props.setProperty("artifactId", rootProject.getArtifactId());
        props.setProperty("version", rootProject.getVersion());
        props.setProperty("classifier", "profile");
        props.setProperty("packaging", "zip");
        request.setProperties(props);

        getLog().info(
                "Installing aggregated zip using: mvn install:install-file" + serializeMvnProperties(props));
        Invoker invoker = new DefaultInvoker();
        try {
            InvocationResult result = invoker.execute(request);
            if (result.getExitCode() != 0) {
                throw new IllegalStateException("Error invoking Maven goal install:install-file");
            }
        } catch (MavenInvocationException e) {
            throw new MojoExecutionException("Error invoking Maven goal install:install-file", e);
        }
    }
}

From source file:io.fabric8.maven.enricher.api.util.GitUtil.java

License:Apache License

public static Repository getGitRepository(MavenProject project) throws IOException {
    MavenProject rootProject = MavenUtil.getRootProject(project);
    File baseDir = rootProject.getBasedir();
    if (baseDir == null) {
        baseDir = project.getBasedir();/*  ww w.j  ava  2s  .c o  m*/
    }
    if (baseDir == null) {
        // TODO: Why is this check needed ?
        baseDir = new File(System.getProperty("basedir", "."));
    }
    File gitFolder = GitHelpers.findGitFolder(baseDir);
    if (gitFolder == null) {
        // No git repository found
        return null;
    }
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = builder.readEnvironment().setGitDir(gitFolder).build();
    return repository;
}

From source file:io.fabric8.maven.generator.javaexec.JavaExecGenerator.java

License:Apache License

protected void addAssembly(AssemblyConfiguration.Builder builder) throws MojoExecutionException {
    String assemblyRef = getConfig(Config.assemblyRef);
    if (assemblyRef != null) {
        builder.descriptorRef(assemblyRef);
    } else {//ww w .jav  a  2s  .com
        if (isFatJar()) {
            FatJarDetector.Result fatJar = detectFatJar();
            Assembly assembly = new Assembly();
            MavenProject project = getProject();
            if (fatJar == null) {
                DependencySet dependencySet = new DependencySet();
                dependencySet.addInclude(project.getGroupId() + ":" + project.getArtifactId());
                assembly.addDependencySet(dependencySet);
            } else {
                FileSet fileSet = new FileSet();
                File buildDir = new File(project.getBuild().getDirectory());
                fileSet.setDirectory(toRelativePath(buildDir, project.getBasedir()));
                fileSet.addInclude(toRelativePath(fatJar.getArchiveFile(), buildDir));
                fileSet.setOutputDirectory(".");
                assembly.addFileSet(fileSet);
            }
            assembly.addFileSet(createFileSet("src/main/fabric8-includes/bin", "bin", "0755", "0755"));
            assembly.addFileSet(createFileSet("src/main/fabric8-includes", ".", "0644", "0755"));
            builder.assemblyDef(assembly);
        } else {
            builder.descriptorRef("artifact-with-dependencies");
        }
    }
    ;
}

From source file:io.fabric8.maven.HelmMojo.java

License:Apache License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    File yaml = getKubernetesYaml();
    if (Files.isFile(yaml)) {
        getLog().info("Creating Helm Chart for kubernetes yaml file: " + yaml);

        File outputDir = getOutputDir();
        if (outputDir != null) {
            File manifestsDir = new File(outputDir, "manifests");
            // lets delete all the manifests in case there are some existing ones with different names
            if (Files.isDirectory(manifestsDir)) {
                Files.recursiveDelete(manifestsDir);
            }//from ww  w  .  j a  v a  2s  . co m
            manifestsDir.mkdirs();
            File outputYamlFile = new File(manifestsDir, chartName + HELM_YAML_EXTENSION);
            try {
                Files.copy(yaml, outputYamlFile);
            } catch (IOException e) {
                throw new MojoExecutionException("Failed to copy file " + yaml + " to chart manifest file: "
                        + outputYamlFile + ". Reason: " + e, e);
            }

            File outputChartFile = new File(outputDir, "Chart" + HELM_YAML_EXTENSION);
            Chart chart = createChart();
            try {
                KubernetesHelper.saveYaml(chart, outputChartFile);
            } catch (IOException e) {
                throw new MojoExecutionException("Failed to save chart " + outputChartFile + ". Reason: " + e,
                        e);
            }

            MavenProject project = getProject();
            if (project != null) {
                File basedir = project.getBasedir();
                if (basedir != null) {
                    String outputReadMeFileName = "README.md";
                    try {
                        copyReadMe(basedir, outputDir, outputReadMeFileName);
                    } catch (IOException e) {
                        throw new MojoExecutionException(
                                "Failed to save " + outputReadMeFileName + ". Reason: " + e, e);
                    }
                }
            }

            getLog().info("Generated Helm Chart " + chartName + " at " + outputDir);
        }
    }
}