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.siddhi.doc.gen.core.MkdocsGitHubPagesDeployMojo.java

License:Open Source License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    // Finding the root maven project
    MavenProject rootMavenProject = mavenProject;
    while (rootMavenProject.getParent() != null && rootMavenProject.getParent().getBasedir() != null) {
        rootMavenProject = rootMavenProject.getParent();
    }//from  ww  w .j  av  a2  s . c om

    // Setting the relevant modules target directory if not set by user
    String moduleTargetPath;
    if (moduleTargetDirectory != null) {
        moduleTargetPath = moduleTargetDirectory.getAbsolutePath();
    } else {
        moduleTargetPath = mavenProject.getBuild().getDirectory();
    }

    // Setting the mkdocs config file path if not set by user
    if (mkdocsConfigFile == null) {
        mkdocsConfigFile = new File(rootMavenProject.getBasedir() + File.separator
                + Constants.MKDOCS_CONFIG_FILE_NAME + Constants.YAML_FILE_EXTENSION);
    }

    // Setting the documentation output directory if not set by user
    String docGenBasePath;
    if (docGenBaseDirectory != null) {
        docGenBasePath = docGenBaseDirectory.getAbsolutePath();
    } else {
        docGenBasePath = rootMavenProject.getBasedir() + File.separator + Constants.DOCS_DIRECTORY;
    }

    // Setting the home page file name if not set by user
    File homePageFile;
    if (homePageFileName == null) {
        homePageFile = new File(docGenBasePath + File.separator + Constants.HOMEPAGE_FILE_NAME
                + Constants.MARKDOWN_FILE_EXTENSION);
    } else {
        homePageFile = new File(docGenBasePath + File.separator + homePageFileName);
    }

    // Setting the readme file name if not set by user
    if (readmeFile == null) {
        readmeFile = new File(rootMavenProject.getBasedir() + File.separator + Constants.README_FILE_NAME
                + Constants.MARKDOWN_FILE_EXTENSION);
    }

    // Setting the home page template file path if not set by user
    if (homePageTemplateFile == null) {
        homePageTemplateFile = new File(rootMavenProject.getBasedir() + File.separator
                + Constants.README_FILE_NAME + Constants.MARKDOWN_FILE_EXTENSION);
    }

    // Retrieving metadata
    List<NamespaceMetaData> namespaceMetaDataList;
    try {
        namespaceMetaDataList = DocumentationUtils.getExtensionMetaData(moduleTargetPath,
                mavenProject.getRuntimeClasspathElements(), getLog());
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoFailureException("Unable to resolve dependencies of the project", e);
    }

    // Generating the documentation
    if (namespaceMetaDataList.size() > 0) {
        DocumentationUtils.generateDocumentation(namespaceMetaDataList, docGenBasePath,
                mavenProject.getVersion(), getLog());
        DocumentationUtils.updateHeadingsInMarkdownFile(homePageTemplateFile, homePageFile,
                rootMavenProject.getArtifactId(), mavenProject.getVersion(), namespaceMetaDataList);
        DocumentationUtils.updateHeadingsInMarkdownFile(readmeFile, readmeFile,
                rootMavenProject.getArtifactId(), mavenProject.getVersion(), namespaceMetaDataList);
    }

    // Delete snapshot files
    DocumentationUtils.removeSnapshotAPIDocs(mkdocsConfigFile, docGenBasePath, getLog());

    // Updating the links in the home page to the mkdocs config
    try {
        updateAPIPagesInMkdocsConfig(mkdocsConfigFile, docGenBasePath);
    } catch (FileNotFoundException e) {
        getLog().warn("Unable to find mkdocs configuration file: " + mkdocsConfigFile.getAbsolutePath()
                + ". Mkdocs configuration file not updated.");
    }
    // Deploying the documentation
    if (DocumentationUtils.generateMkdocsSite(mkdocsConfigFile, getLog())) {
        // Creating the credential provider fot Git
        String scmUsername = System.getenv(Constants.SYSTEM_PROPERTY_SCM_USERNAME_KEY);
        String scmPassword = System.getenv(Constants.SYSTEM_PROPERTY_SCM_PASSWORD_KEY);

        if (scmUsername == null && scmPassword == null) {
            getLog().info("SCM_USERNAME and SCM_PASSWORD not defined!");
        }
        String url = null;
        Scm scm = rootMavenProject.getScm();
        if (scm != null) {
            url = scm.getUrl();
        }
        // Deploying documentation
        DocumentationUtils.updateDocumentationOnGitHub(docGenBasePath, mkdocsConfigFile, readmeFile,
                mavenProject.getVersion(), getLog());
        DocumentationUtils.deployMkdocsOnGitHubPages(mavenProject.getVersion(), rootMavenProject.getBasedir(),
                url, scmUsername, scmPassword, getLog());
    } else {
        getLog().warn("Unable to generate documentation. Skipping documentation deployment.");
    }
}

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 av  a  2  s  .  c om*/
    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:ms.dew.devops.kernel.config.ConfigBuilder.java

License:Apache License

private static FinalProjectConfig doBuildProject(DewConfig dewConfig, AppKindPlugin appKindPlugin,
        DeployPlugin deployPlugin, MavenProject mavenProject, String inputProfile, String inputDockerHost,
        String inputDockerRegistryUrl, String inputDockerRegistryUserName, String inputDockerRegistryPassword,
        String inputKubeBase64Config, Optional<String> dockerHostAppendOpt,
        Optional<String> dockerRegistryUrlAppendOpt, Optional<String> dockerRegistryUserNameAppendOpt,
        Optional<String> dockerRegistryPasswordAppendOpt, Optional<String> kubeBase64ConfigAppendOpt)
        throws InvocationTargetException, IllegalAccessException {
    FinalProjectConfig finalProjectConfig = new FinalProjectConfig();
    if (inputProfile.equalsIgnoreCase(FLAG_DEW_DEVOPS_DEFAULT_PROFILE)) {
        $.bean.copyProperties(finalProjectConfig, dewConfig);
    } else {/*www  .  ja va 2 s  .c  o m*/
        $.bean.copyProperties(finalProjectConfig, dewConfig.getProfiles().get(inputProfile));
    }
    // setting basic
    finalProjectConfig.setId(mavenProject.getId());
    finalProjectConfig.setAppKindPlugin(appKindPlugin);
    finalProjectConfig.setDeployPlugin(deployPlugin);
    finalProjectConfig.setProfile(inputProfile);
    finalProjectConfig.setAppGroup(mavenProject.getGroupId());
    finalProjectConfig.setAppName(mavenProject.getArtifactId());
    finalProjectConfig.setSkip(false);
    if (mavenProject.getName() != null && !mavenProject.getName().trim().isEmpty()) {
        finalProjectConfig.setAppShowName(mavenProject.getName());
    } else {
        finalProjectConfig.setAppShowName(mavenProject.getArtifactId());
    }
    // ?
    if (inputDockerHost != null && !inputDockerHost.trim().isEmpty()) {
        finalProjectConfig.getDocker().setHost(inputDockerHost.trim());
    }
    if (inputDockerRegistryUrl != null && !inputDockerRegistryUrl.trim().isEmpty()) {
        finalProjectConfig.getDocker().setRegistryUrl(inputDockerRegistryUrl.trim());
    }
    if (inputDockerRegistryUserName != null && !inputDockerRegistryUserName.trim().isEmpty()) {
        finalProjectConfig.getDocker().setRegistryUserName(inputDockerRegistryUserName.trim());
    }
    if (inputDockerRegistryPassword != null && !inputDockerRegistryPassword.trim().isEmpty()) {
        finalProjectConfig.getDocker().setRegistryPassword(inputDockerRegistryPassword.trim());
    }
    if (inputKubeBase64Config != null && !inputKubeBase64Config.trim().isEmpty()) {
        finalProjectConfig.getKube().setBase64Config(inputKubeBase64Config.trim());
    }

    // setting path
    finalProjectConfig.setDirectory(mavenProject.getBasedir().getPath() + File.separator);
    finalProjectConfig.setTargetDirectory(finalProjectConfig.getDirectory() + "target" + File.separator);

    // setting git info
    finalProjectConfig.setScmUrl(GitHelper.inst().getScmUrl());
    finalProjectConfig.setGitCommit(GitHelper.inst().getCurrentCommit());
    finalProjectConfig.setImageVersion(finalProjectConfig.getGitCommit());
    finalProjectConfig.setAppVersion(finalProjectConfig.getGitCommit());

    // setting custom config by app kind
    finalProjectConfig.getAppKindPlugin().customConfig(finalProjectConfig);
    // setting reuse version
    fillReuseVersionInfo(finalProjectConfig, dewConfig, dockerHostAppendOpt, dockerRegistryUrlAppendOpt,
            dockerRegistryUserNameAppendOpt, dockerRegistryPasswordAppendOpt, kubeBase64ConfigAppendOpt);
    return finalProjectConfig;
}

From source file:ms.dew.devops.maven.function.AppKindPluginSelector.java

License:Apache License

/**
 * Select app kind plugin./*from   w  ww  . j a v  a 2  s  . c  o m*/
 *
 * @param mavenProject the maven project
 * @return the optional
 */
public static Optional<AppKindPlugin> select(MavenProject mavenProject) {
    if (mavenProject.getPackaging().equalsIgnoreCase("maven-plugin")) {
        return Optional.empty();
    }
    if (new File(mavenProject.getBasedir().getPath() + File.separator + "package.json").exists()) {
        return Optional.of(new FrontendNodeAppKindPlugin());
    }
    if (mavenProject.getPackaging().equalsIgnoreCase("jar")
            && new File(mavenProject.getBasedir().getPath() + File.separator + "src" + File.separator + "main"
                    + File.separator + "resources").exists()
            && Arrays
                    .stream(new File(mavenProject.getBasedir().getPath() + File.separator + "src"
                            + File.separator + "main" + File.separator + "resources").listFiles())
                    .anyMatch((res -> res.getName().toLowerCase().contains("application")
                            || res.getName().toLowerCase().contains("bootstrap")))
            && mavenProject.getArtifacts().stream()
                    .map(artifact -> artifact.getGroupId() + ":" + artifact.getArtifactId())
                    .anyMatch("org.springframework.boot:spring-boot-starter-web"::equalsIgnoreCase)) {
        return Optional.of(new JvmServiceSpringBootAppKindPlugin());
    }
    if (mavenProject.getPackaging().equalsIgnoreCase("jar")) {
        return Optional.of(new JvmLibAppKindPlugin());
    }
    if (mavenProject.getPackaging().equalsIgnoreCase("pom")) {
        return Optional.of(new PomAppKindPlugin());
    }
    return Optional.empty();
}

From source file:net.java.javabuild.SourceFoldersUtils.java

License:Apache License

private static Resource toResource(String folderString, MavenProject project) {
    File folder = new File(project.getBasedir(), folderString);
    Resource resource = new Resource();
    resource.setDirectory(folder.getAbsolutePath());
    return resource;
}

From source file:net.java.jpatch.maven.common.AbstractPatchMojo.java

License:Apache License

/**
 * Check the SCM status of the project.//www  .j a va  2s  .  co m
 *
 * @param project the MAVEN project.
 * @param begin the SCM ID.
 * @param end the SCM ID.
 *
 * @return
 *
 * @throws MojoExecutionException if the method fails.
 */
private boolean checkSCM(MavenProject project, String revision, File diffDirectory)
        throws MojoExecutionException {

    getLog().info("Check SCM for the project " + project.getId());

    boolean result = false;
    boolean ignoreUnknown = true;

    DiffScmResult scmResult = null;
    try {
        ScmRepository repository = scmManager.makeScmRepository(project.getScm().getConnection());
        scmResult = scmManager.diff(repository, new ScmFileSet(project.getBasedir()), new ScmRevision(revision),
                null);
    } catch (Exception e) {
        getLog().error("Error check SCM status for project " + project.getId());
        throw new MojoExecutionException("Couldn't configure SCM repository: " + e.getLocalizedMessage(), e);
    }

    if (scmResult != null && scmResult.getChangedFiles() != null) {
        List<ScmFile> changedFiles = scmResult.getChangedFiles();
        for (ScmFile changedScmFile : changedFiles) {
            ScmFileStatus status = changedScmFile.getStatus();
            if (!status.isStatus()) {
                getLog().debug("Not a diff: " + status);
                continue;
            }
            if (ignoreUnknown && ScmFileStatus.UNKNOWN.equals(status)) {
                getLog().debug("Ignoring unknown");
                continue;
            }

            getLog().info(changedScmFile.getStatus().toString() + " " + changedScmFile.getPath());
            result = true;
        }

        if (result) {
            File diffFile = new File(diffDirectory, project.getArtifactId() + project.getVersion() + ".diff");
            try {
                getLog().info("Create new diff file: " + diffFile.getAbsolutePath());
                diffFile.createNewFile();
                FileUtils.fileWrite(diffFile.getAbsolutePath(), scmResult.getPatch());
            } catch (IOException ex) {
                Logger.getLogger(AbstractPatchMojo.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    getLog().info("");
    return result;
}

From source file:net.java.jpatch.maven.ReleaseMojo.java

License:Apache License

/**
 * Gets the SCM status from the repository.
 * /*from w w  w  . j ava2 s  .co m*/
 * @param project the MAVEN project.
 * 
 * @return the SCM status.
 * 
 * @throws MojoExecutionException if the method fails.
 * 
 * TODO: rewrite this method. Exception handling.
 */
private String scmRevision(MavenProject project) throws MojoExecutionException {
    String result = null;
    try {
        ScmRepository repository = scmManager.makeScmRepository(project.getScm().getConnection());
        ChangeLogScmResult scmResult = scmManager.changeLog(repository, new ScmFileSet(project.getBasedir()),
                null, null, null);
        if (scmResult != null) {
            ChangeLogSet log = scmResult.getChangeLog();
            if (log != null) {
                if (log.getChangeSets() != null) {
                    List<ChangeSet> changes = log.getChangeSets();
                    if (!changes.isEmpty()) {
                        ChangeSet change = changes.get(0);
                        if (!change.getFiles().isEmpty()) {
                            List<ChangeFile> files = change.getFiles();
                            ChangeFile file = files.get(0);
                            result = file.getRevision();
                        } else {
                            throw new MojoExecutionException("No revision found! Project: " + project.getId());
                        }
                    } else {
                        throw new MojoExecutionException(
                                "Missing changes in the repository! Project: " + project.getId());
                    }
                }
            } else {
                throw new MojoExecutionException("Missing the SCM log! Project: " + project.getId());
            }
        } else {
            throw new MojoExecutionException("Missing the SCM result! Project: " + project.getId());
        }
    } catch (Exception e) {
        getLog().error("Error check SCM status for project " + project.getId());
        throw new MojoExecutionException("Couldn't configure SCM repository: " + e.getLocalizedMessage(), e);
    }
    return result;
}

From source file:net.oneandone.stool.stage.SourceStage.java

License:Apache License

public List<FileNode> artifacts() throws IOException {
    List<FileNode> result;//ww w. jav a  2s .  co  m
    FileNode basedir;
    Filter filter;

    filter = directory.getWorld().filter();
    filter.include("target/*.war");
    result = new ArrayList<>();
    for (MavenProject project : wars()) {
        basedir = directory.getWorld().file(project.getBasedir());
        result.addAll(basedir.find(filter));
    }
    return result;
}

From source file:net.oneandone.stool.stage.SourceStage.java

License:Apache License

private FileNode docroot(World world, MavenProject project) throws IOException {
    FileNode directory;//  w  w w  . ja va2  s.  c  o m
    List<FileNode> result;
    Filter filter;

    directory = world.file(project.getBasedir());
    filter = directory.getWorld().filter();
    filter.include("target/*/WEB-INF");
    filter.predicate((node, b) -> node.isDirectory()
            && (node.join("lib").isDirectory() || node.join("classes").isDirectory()));
    filter.exclude("target/test-classes/**/*");
    result = (List) directory.find(filter);
    switch (result.size()) {
    case 0:
        throw new IOException("No web application found. Did you build the project?");
    case 1:
        return result.get(0).getParent();
    default:
        throw new FileNotFoundException("web.xml ambiguous: " + result);
    }
}

From source file:net.oneandone.stool.stage.Stage.java

License:Apache License

private void warProjects(FileNode pomXml, Properties userProperties, List<String> profiles,
        List<MavenProject> result) throws IOException {
    MavenProject root;
    FileNode modulePom;//  w  ww .j av a2 s .c  o m

    try {
        root = maven().loadPom(pomXml, false, userProperties, profiles, null);
    } catch (ProjectBuildingException | RepositoryException e) {
        throw new IOException("cannot parse " + pomXml + ": " + e.getMessage(), e);
    }
    session.console.verbose.println("loading " + pomXml);
    if ("war".equals(root.getPackaging())) {
        result.add(root);
    } else {
        for (String module : root.getModules()) {
            modulePom = session.world.file(root.getBasedir()).join(module);
            if (modulePom.isDirectory()) {
                modulePom = modulePom.join("pom.xml");
            }
            warProjects(modulePom, userProperties, profiles, result);
        }
    }
}