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.ZipMojo.java

License:Apache License

protected void generateAggregatedZip(MavenProject rootProject, List<MavenProject> reactorProjects,
        Set<MavenProject> pomZipProjects) throws IOException, MojoExecutionException {
    File projectBaseDir = rootProject.getBasedir();
    String rootProjectGroupId = rootProject.getGroupId();
    String rootProjectArtifactId = rootProject.getArtifactId();
    String rootProjectVersion = rootProject.getVersion();

    String aggregatedZipFileName = "target/" + rootProjectArtifactId + "-" + rootProjectVersion + "-app.zip";
    File projectOutputFile = new File(projectBaseDir, aggregatedZipFileName);
    getLog().info("Generating " + projectOutputFile.getAbsolutePath() + " from root project "
            + rootProjectArtifactId);/*from w w w . ja  v  a2  s .co  m*/
    File projectBuildDir = new File(projectBaseDir, reactorProjectOutputPath);

    if (projectOutputFile.exists()) {
        projectOutputFile.delete();
    }
    createAggregatedZip(projectBaseDir, projectBuildDir, reactorProjectOutputPath, projectOutputFile,
            includeReadMe, pomZipProjects);
    if (rootProject.getAttachedArtifacts() != null) {
        // need to remove existing as otherwise we get a WARN
        Artifact found = null;
        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
    List<String> activeProfileIds = new ArrayList<>();
    List<Profile> activeProfiles = rootProject.getActiveProfiles();
    if (activeProfiles != null) {
        for (Profile profile : activeProfiles) {
            String id = profile.getId();
            if (Strings.isNotBlank(id)) {
                activeProfileIds.add(id);
            }
        }
    }
    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);
        request.setProfiles(activeProfileIds);

        Properties props = new Properties();
        props.setProperty("file", aggregatedZipFileName);
        props.setProperty("groupId", rootProjectGroupId);
        props.setProperty("artifactId", rootProjectArtifactId);
        props.setProperty("version", rootProjectVersion);
        props.setProperty("classifier", "app");
        props.setProperty("packaging", "zip");
        props.setProperty("generatePom", "false");
        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);
        }
    }

    if (rootProject.hasLifecyclePhase("deploy")) {

        if (deploymentRepository == null && Strings.isNullOrBlank(altDeploymentRepository)) {
            String msg = "Cannot run deploy phase as Maven project has no <distributionManagement> with the maven url to use for deploying the aggregated zip file, neither an altDeploymentRepository property.";
            getLog().warn(msg);
            throw new MojoExecutionException(msg);
        }

        getLog().info("Deploying aggregated zip " + projectOutputFile + " to root project "
                + rootProject.getArtifactId());
        getLog().info("Using deploy goal: " + deployFileGoal + " with active profiles: " + activeProfileIds);

        InvocationRequest request = new DefaultInvocationRequest();
        request.setBaseDirectory(rootProject.getBasedir());
        request.setPomFile(new File("./pom.xml"));
        request.setGoals(Collections.singletonList(deployFileGoal));
        request.setRecursive(false);
        request.setInteractive(false);
        request.setProfiles(activeProfileIds);
        request.setProperties(getProjectAndFabric8Properties(getProject()));

        Properties props = new Properties();
        props.setProperty("file", aggregatedZipFileName);
        props.setProperty("groupId", rootProjectGroupId);
        props.setProperty("artifactId", rootProjectArtifactId);
        props.setProperty("version", rootProjectVersion);
        props.setProperty("classifier", "app");
        props.setProperty("packaging", "zip");
        String deployUrl = null;

        if (!Strings.isNullOrBlank(deployFileUrl)) {
            deployUrl = deployFileUrl;
        } else if (altDeploymentRepository != null && altDeploymentRepository.contains("::")) {
            deployUrl = altDeploymentRepository.substring(altDeploymentRepository.lastIndexOf("::") + 2);
        } else {
            deployUrl = deploymentRepository.getUrl();
        }

        props.setProperty("url", deployUrl);
        props.setProperty("repositoryId", deploymentRepository.getId());
        props.setProperty("generatePom", "false");
        request.setProperties(props);

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

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

License:Apache License

protected static String getChildProjectRelativePath(File projectBaseDir, MavenProject pomProject)
        throws IOException {
    // must include first dir as prefix
    String root = projectBaseDir.getName();
    String relativePath = Files.getRelativePath(projectBaseDir, pomProject.getBasedir());
    relativePath = root + File.separator + relativePath;
    return relativePath;
}

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

License:Apache License

protected static void combineAppFilesToFolder(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;// w w  w.j  av a2 s .  c o  m
    }
    File outDir = new File(basedir, reactorProjectOutputPath);
    if (!outDir.exists()) {
        log.warn("No app output dir at: " + outDir.getAbsolutePath() + " for project + " + reactorProject
                + " so ignoring this project.");
        return;
    }
    log.info("Copying apps from " + outDir.getAbsolutePath() + " into the output directory: " + buildDir);

    File[] files = outDir.listFiles();
    if (files != null) {
        for (File file : files) {
            if (file.isDirectory()) {
                appendAppConfigFiles(file, buildDir);
            }
        }
    }
}

From source file:io.fabric8.vertx.maven.plugin.util.GitUtil.java

License:Apache License

/**
 * Get the git {@link Repository} if the the project has one
 *
 * @param project - the {@link MavenProject} whose Git repo needs to be returned in {@link Repository}
 * @return Repository  - the Git Repository of the project
 * @throws IOException - any error that might occur finding the Git folder
 *//*from   ww  w. j a va  2s .c  om*/
public static Repository getGitRepository(MavenProject project) throws IOException {

    MavenProject rootProject = getRootProject(project);

    File baseDir = rootProject.getBasedir();

    if (baseDir == null) {
        baseDir = project.getBasedir();
    }

    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.vertx.maven.plugin.utils.SetupTemplateUtils.java

License:Apache License

public static void createVerticle(MavenProject project, String verticle, Log log)
        throws MojoExecutionException {
    if (Strings.isNullOrEmpty(verticle)) {
        return;//from www .  j  a v  a2 s  .  co m
    }
    log.info("Creating verticle " + verticle);

    File root = new File(project.getBasedir(), "src/main/java");

    String packageName = null;
    String className;
    if (verticle.endsWith(".java")) {
        verticle = verticle.substring(0, verticle.length() - ".java".length());
    }

    if (verticle.contains(".")) {
        int idx = verticle.lastIndexOf('.');
        packageName = verticle.substring(0, idx);
        className = verticle.substring(idx + 1);
    } else {
        className = verticle;
    }

    if (packageName != null) {
        File packageDir = new File(root, packageName.replace('.', '/'));
        if (!packageDir.exists()) {
            packageDir.mkdirs();
            log.info("Creating directory " + packageDir.getAbsolutePath());
        }
        root = packageDir;
    }

    File classFile = new File(root, className + ".java");
    Map<String, String> context = new HashMap<>();
    context.put("className", className);
    if (packageName != null) {
        context.put("packageName", packageName);
    }
    try {
        Template temp = cfg.getTemplate("templates/verticle-template.ftl");
        Writer out = new FileWriter(classFile);
        temp.process(context, out);
    } catch (Exception e) {
        throw new MojoExecutionException("Unable to generate verticle", e);
    }

}

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  ww  . j  a v  a  2  s .  c o 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.sarl.maven.compiler.AbstractSarlBatchCompilerMojo.java

License:Apache License

/** Run compilation.
 *
 * @param classPath the classpath/* ww  w .ja va 2s .c  o m*/
 * @param sourcePaths the source paths.
 * @param outputPath the output path.
 * @throws MojoExecutionException if error.
 * @throws MojoFailureException if failure.
 */
protected void compile(List<File> classPath, List<File> sourcePaths, File outputPath)
        throws MojoExecutionException, MojoFailureException {
    final SarlBatchCompiler compiler = getBatchCompiler();
    final MavenProject project = getProject();
    compiler.setResourceSetProvider(new MavenProjectResourceSetProvider(project));
    final Iterable<File> filtered = Iterables.filter(sourcePaths, (input) -> input.isDirectory());
    if (Iterables.isEmpty(filtered)) {
        final String dir = Iterables.toString(sourcePaths);
        getLog().info(Locale.getString(AbstractSarlBatchCompilerMojo.class, "ERROR_0", dir)); //$NON-NLS-1$
        return;
    }
    final String baseDir = project.getBasedir().getAbsolutePath();
    compiler.setJavaPostCompilationEnable(getPostRunningOfJavaCompiler());
    compiler.setClassOutputPath(makeAbsolute(new File(getProject().getBuild().getOutputDirectory())));
    compiler.setJavaSourceVersion(getSourceVersion());
    compiler.setBasePath(baseDir);
    compiler.setTempDirectory(getTempDirectory());
    compiler.setDeleteTempDirectory(false);
    compiler.setClassPath(classPath);
    final String bootClassPath = getBootClassPath();
    compiler.setBootClassPath(bootClassPath);
    final List<File> filteredSourcePaths = Lists.newArrayList(filtered);
    compiler.setSourcePath(filteredSourcePaths);
    compiler.setOutputPath(outputPath);
    compiler.setFileEncoding(getEncoding());
    compiler.setWriteTraceFiles(getGenerateTraceFiles());
    compiler.setWriteStorageFiles(getGenerateStorageFiles());
    compiler.setGenerateInlineAnnotation(getGenerateInlines());
    final Logger logger = Logger.getLogger(getClass().getName(), new MavenLoggerFactory(getLog()));
    compiler.setLogger(logger);
    compiler.setIssueMessageFormatter((issue, uriToProblem) -> {
        final String filename;
        if (uriToProblem != null) {
            filename = uriToProblem.toFileString();
        } else {
            filename = Locale.getString(AbstractSarlBatchCompilerMojo.class, "NO_FILE_NAME"); //$NON-NLS-1$
        }
        return Locale.getString(AbstractSarlBatchCompilerMojo.class, "ISSUE_MESSAGE", //$NON-NLS-1$
                filename, issue.getLineNumber(), issue.getColumn(), issue.getMessage());
    });
    if (!compiler.compile()) {
        final StringBuilder dir = new StringBuilder();
        for (final File file : filtered) {
            if (dir.length() > 0) {
                dir.append(File.pathSeparator);
            }
            dir.append(file.getAbsolutePath());
        }
        throw new MojoFailureException(Locale.getString(AbstractSarlBatchCompilerMojo.class, "ERROR_1")); //$NON-NLS-1$
    }
}

From source file:io.sarl.maven.docs.AbstractDocumentationMojo.java

License:Apache License

private Properties createProjectProperties() {
    final Properties props = new Properties();
    final MavenProject prj = this.session.getCurrentProject();
    props.put("project.groupId", prj.getGroupId()); //$NON-NLS-1$
    props.put("project.artifactId", prj.getArtifactId()); //$NON-NLS-1$
    props.put("project.basedir", prj.getBasedir()); //$NON-NLS-1$
    props.put("project.description", prj.getDescription()); //$NON-NLS-1$
    props.put("project.id", prj.getId()); //$NON-NLS-1$
    props.put("project.inceptionYear", prj.getInceptionYear()); //$NON-NLS-1$
    props.put("project.name", prj.getName()); //$NON-NLS-1$
    props.put("project.version", prj.getVersion()); //$NON-NLS-1$
    props.put("project.url", prj.getUrl()); //$NON-NLS-1$
    props.put("project.encoding", this.encoding); //$NON-NLS-1$
    return props;
}

From source file:io.siddhi.doc.gen.core.ExtensionsIndexGenerationMojo.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   w  w  w  . java 2 s. c o  m*/

    // Checking if extension repositories and repository owner had been added in the configuration
    if (extensionRepositories == null || extensionRepositories.size() == 0) {
        throw new MojoExecutionException(
                "extensionRepositories configuration is required to use goal " + "generate-extensions-index");
    }

    // Setting the extension repository owner if not set by the user
    if (extensionRepositoryOwner == null) {
        extensionRepositoryOwner = Constants.GITHUB_OWNER_WSO2_EXTENSIONS;
    }

    // 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 extension index output file name if not set by user
    if (indexGenFileName == null) {
        indexGenFileName = Constants.MARKDOWN_EXTENSIONS_INDEX_TEMPLATE;
    }

    // Creating a extensions index
    DocumentationUtils.createExtensionsIndex(extensionRepositories, extensionRepositoryOwner, docGenBasePath,
            mavenProject.getBasedir().toString(), indexGenFileName);
}

From source file:io.siddhi.doc.gen.core.MarkdownDocumentationGenerationMojo.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 w  ww .ja  v  a 2 s .c  o  m*/

    // 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 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 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);
    //        }

    // 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 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);
    }

    // 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);
    }
}