Java Code Examples for org.apache.maven.project.MavenProject#getBasedir()

The following examples show how to use org.apache.maven.project.MavenProject#getBasedir() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DiffFilter.java    From diff-check with GNU Lesser General Public License v2.1 6 votes vote down vote up
public DiffFilter(MavenProject project, File gitDir, List<DiffEntryWrapper> entries) {
    File baseDir = project.getBasedir();
    String baseDirPath = baseDir.getAbsolutePath();
    @SuppressWarnings("unchecked")
    List<String> modules = project.getModules();
    for (DiffEntryWrapper entry : entries) {
        if (!entry.getAbsoluteNewPath().startsWith(baseDirPath)) {
            continue;
        }
        String name = StringUtils.replaceOnce(entry.getAbsoluteNewPath(), baseDirPath, "");
        if (CollectionUtils.isNotEmpty(modules)) {
            for (String module : modules) {
                if (name.startsWith("/" + module)) {
                    name = StringUtils.replaceOnce(name, "/" + module, "");
                    break;
                }
            }
        }
        if (!name.startsWith(SOURCE_PATH_PREFIX)) {
            continue;
        }
        name = StringUtils.replaceOnce(name, SOURCE_PATH_PREFIX, "");
        classPathDiffEntryMap.put(name, entry);
    }
}
 
Example 2
Source File: ValidateApplicationMojoTest.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testRecipe_official_anotherGroupId() throws Exception {

	// Find and execute the mojo
	ValidateApplicationMojo mojo = retriveAndPrepareMojo( "recipe" );
	MavenProject project = (MavenProject) this.rule.getVariableValueFromObject( mojo, "project" );
	this.rule.setVariableValueToObject( mojo, "recipe", true );
	this.rule.setVariableValueToObject( mojo, "official", true );

	project.setGroupId( Constants.OFFICIAL_RECIPES_GROUP_ID + ".database" );
	project.setArtifactId( project.getName());
	Assert.assertTrue( new File( project.getBasedir(), "readme" ).createNewFile());

	mojo.execute();

	// We should not have a result file
	File resultsFile = new File( project.getBasedir(), MavenPluginConstants.VALIDATION_RESULT_PATH );
	Assert.assertFalse( resultsFile.exists());
}
 
Example 3
Source File: ValidateApplicationMojoTest.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testRecipe_official_exactGroupId() throws Exception {

	// Find and execute the mojo
	ValidateApplicationMojo mojo = retriveAndPrepareMojo( "recipe" );
	MavenProject project = (MavenProject) this.rule.getVariableValueFromObject( mojo, "project" );
	this.rule.setVariableValueToObject( mojo, "recipe", true );
	this.rule.setVariableValueToObject( mojo, "official", true );

	project.setGroupId( Constants.OFFICIAL_RECIPES_GROUP_ID );
	project.setArtifactId( project.getName());
	Assert.assertTrue( new File( project.getBasedir(), "readme" ).createNewFile());

	mojo.execute();

	// We should not have a result file
	File resultsFile = new File( project.getBasedir(), MavenPluginConstants.VALIDATION_RESULT_PATH );
	Assert.assertFalse( resultsFile.exists());
}
 
Example 4
Source File: GoogleFormatterMojo.java    From googleformatter-maven-plugin with Apache License 2.0 6 votes vote down vote up
private Set<File> filterUnchangedFiles(Set<File> originalFiles) throws MojoExecutionException {
  MavenProject topLevelProject = session.getTopLevelProject();
  try {
    if (topLevelProject.getScm().getConnection() == null && topLevelProject.getScm().getDeveloperConnection() == null) {
      throw new MojoExecutionException(
          "You must supply at least one of scm.connection or scm.developerConnection in your POM file if you " +
              "specify the filterModified or filter.modified option.");
    }
    String connectionUrl = MoreObjects.firstNonNull(topLevelProject.getScm().getConnection(), topLevelProject.getScm().getDeveloperConnection());
    ScmRepository repository = scmManager.makeScmRepository(connectionUrl);
    ScmFileSet scmFileSet = new ScmFileSet(topLevelProject.getBasedir());
    String basePath = topLevelProject.getBasedir().getAbsoluteFile().getPath();
    List<String> changedFiles =
        scmManager.status(repository, scmFileSet).getChangedFiles().stream()
            .map(f -> new File(basePath, f.getPath()).toString())
            .collect(Collectors.toList());

    return originalFiles.stream().filter(f -> changedFiles.contains(f.getPath())).collect(Collectors.toSet());

  } catch (ScmException e) {
    throw new MojoExecutionException(e.getMessage(), e);
  }
}
 
Example 5
Source File: MavenUtilsTest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
@Test
public void testDumpEmptyDependencies() throws Exception {
    Model model = new Model();
    model.setPomFile(new File("target/test-classes/maven/test/minimal.xml"));
    MavenProject project = new MavenProject(model);
    project.setFile(new File("target/test-classes/maven/test/minimal.xml"));

    Classpath.store(project);

    File deps = new File(project.getBasedir(), Constants.DEPENDENCIES_FILE);
    assertThat(deps).isFile();
    ObjectMapper mapper = new ObjectMapper();
    ProjectDependencies dependencies = mapper.readValue(deps, ProjectDependencies.class);
    System.out.println(dependencies.getDirectDependencies());

    assertThat(Classpath.load(project.getBasedir()).getDirectDependencies()).isEmpty();
    assertThat(Classpath.load(project.getBasedir()).getTransitiveDependencies()).isEmpty();
}
 
Example 6
Source File: ApplyMojo.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns the root project folder
 */
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;
}
 
Example 7
Source File: ValidateApplicationMojoTest.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
private void findAndExecuteMojo( String projectName, boolean expectTextFile ) throws Exception {

		ValidateApplicationMojo mojo = retriveAndPrepareMojo( projectName );
		MavenProject project = (MavenProject) this.rule.getVariableValueFromObject( mojo, "project" );

		// Execute the mojo
		mojo.execute();

		// Should we have a result file?
		File resultsFile = new File( project.getBasedir(), MavenPluginConstants.VALIDATION_RESULT_PATH );
		Assert.assertEquals( expectTextFile, resultsFile.exists());
	}
 
Example 8
Source File: Analyzer.java    From revapi with Apache License 2.0 5 votes vote down vote up
private static Artifact findProjectArtifact(MavenProject project) {
    String extension = project.getArtifact().getArtifactHandler().getExtension();

    String fileName = project.getModel().getBuild().getFinalName() + "." + extension;
    File f = new File(new File(project.getBasedir(), "target"), fileName);
    if (f.exists()) {
        Artifact ret = RepositoryUtils.toArtifact(project.getArtifact());
        return ret.setFile(f);
    } else {
        return null;
    }
}
 
Example 9
Source File: RootLocationMojo.java    From build-helper-maven-plugin with MIT License 5 votes vote down vote up
private Set<String> getChildModuleCanoncialPath( MavenProject project, List<String> modules ) throws IOException {
    Set<String> paths = new TreeSet<>();
    for (String module : modules) {
        File file = new File( project.getBasedir(), module );
        paths.add(file.getCanonicalPath());
    }
    return paths;
}
 
Example 10
Source File: ShrinkWrapFatJarPackageService.java    From vertx-maven-plugin with Apache License 2.0 5 votes vote down vote up
private void embedFileSet(Log log, MavenProject project, FileSet fs, JavaArchive jar) {
    File directory = new File(fs.getDirectory());
    if (!directory.isAbsolute()) {
        directory = new File(project.getBasedir(), fs.getDirectory());
    }

    if (!directory.isDirectory()) {
        log.warn("File set root directory (" + directory.getAbsolutePath() + ") does not exist " +
            "- skipping");
        return;
    }

    DirectoryScanner scanner = new DirectoryScanner();
    scanner.setBasedir(directory);
    if (fs.getOutputDirectory() == null) {
        fs.setOutputDirectory("/");
    } else if (!fs.getOutputDirectory().startsWith("/")) {
        fs.setOutputDirectory("/" + fs.getOutputDirectory());
    }
    List<String> excludes = fs.getExcludes();
    if (fs.isUseDefaultExcludes()) {
        excludes.addAll(FileUtils.getDefaultExcludesAsList());
    }
    if (!excludes.isEmpty()) {
        scanner.setExcludes(excludes.toArray(new String[0]));
    }
    if (!fs.getIncludes().isEmpty()) {
        scanner.setIncludes(fs.getIncludes().toArray(new String[0]));
    }
    scanner.scan();
    String[] files = scanner.getIncludedFiles();
    for (String path : files) {
        File file = new File(directory, path);
        log.debug("Adding " + fs.getOutputDirectory() + path + " to the archive");
        jar.addAsResource(file, fs.getOutputDirectory() + path);
    }
}
 
Example 11
Source File: GenerateDocumentationMojoTest.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
private File findAndExecuteMojo( List<String> renderers, List<String> locales, Map<String,String> options ) throws Exception {

		// Find the mojo.
		GenerateDocumentationMojo docMojo = (GenerateDocumentationMojo) super.findMojo( "project--valid", "documentation" );
		MavenProject project = (MavenProject) this.rule.getVariableValueFromObject( docMojo, "project" );
		Assert.assertNotNull( project );

		this.rule.setVariableValueToObject( docMojo, "locales", locales );
		this.rule.setVariableValueToObject( docMojo, "renderers", renderers );
		this.rule.setVariableValueToObject( docMojo, "options", options );

		// Copy the resources
		Utils.copyDirectory(
				new File( project.getBasedir(), MavenPluginConstants.SOURCE_MODEL_DIRECTORY ),
				new File( project.getBuild().getOutputDirectory()));

		// Initial check
		File docDirectory = new File( project.getBasedir(), MavenPluginConstants.TARGET_DOC_DIRECTORY );
		Assert.assertFalse( docDirectory.exists());

		// Execute the mojo
		docMojo.execute();

		// Should we have a result file?
		Assert.assertTrue( docDirectory.exists());
		return docDirectory;
	}
 
Example 12
Source File: LooseEarApplication.java    From ci.maven with Apache License 2.0 5 votes vote down vote up
public File getRarSourceDirectory(MavenProject proj) throws Exception {
    String dir = MavenProjectUtil.getPluginConfiguration(proj, "org.apache.maven.plugins", "maven-rar-plugin",
            "rarSourceDirectory");
    if (dir != null) {
        return new File(dir);
    } else {
        return new File(proj.getBasedir(), "src/main/rar");
    }
}
 
Example 13
Source File: Classpath.java    From wisdom with Apache License 2.0 5 votes vote down vote up
/**
 * Stores the dependencies from the given project into the 'dependencies.json' file.
 *
 * @param project the project
 * @throws IOException if the file cannot be created.
 */
public static void store(MavenProject project) throws IOException {
    final File output = new File(project.getBasedir(), Constants.DEPENDENCIES_FILE);
    output.getParentFile().mkdirs();
    ProjectDependencies dependencies = new ProjectDependencies(project);
    mapper.writer()
            .withDefaultPrettyPrinter()
            .writeValue(
                    output,
                    dependencies
            );
}
 
Example 14
Source File: MavenProjectSettingsConfigurator.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
private List<File> getSearchFolders(ProjectConfigurationRequest request) {
	List<File> files = new ArrayList<>();
	MavenProject project = request.getMavenProject();
	while (project != null && project.getBasedir() != null) {
		files.add(project.getBasedir());
		project = project.getParent();
	}
	return files;
}
 
Example 15
Source File: ValidateApplicationMojoTest.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testRecipe_nonOfficial_withWarnings_2() throws Exception {

	// Find and execute the mojo
	ValidateApplicationMojo mojo = retriveAndPrepareMojo( "recipe-with-instances" );
	MavenProject project = (MavenProject) this.rule.getVariableValueFromObject( mojo, "project" );
	this.rule.setVariableValueToObject( mojo, "recipe", true );

	mojo.execute();

	// We should have a result file
	File resultsFile = new File( project.getBasedir(), MavenPluginConstants.VALIDATION_RESULT_PATH );
	Assert.assertTrue( resultsFile.exists());
}
 
Example 16
Source File: ApplicationSecretGenerator.java    From wisdom with Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether the application configuration file as the application secret.
 * If not generates one.
 *
 * @param project the Maven Project
 * @param log     the logger
 * @throws java.io.IOException if the application file cannot be read, or rewritten
 */
public static void ensureOrGenerateSecret(MavenProject project, Log log) throws IOException {
    File conf = new File(project.getBasedir(), "src/main/configuration/application.conf");
    if (conf.isFile()) {
        List<String> lines = FileUtils.readLines(conf);

        boolean changed = false;
        for (int i = 0; i < lines.size(); i++) {
            String line = lines.get(i);
            Matcher matcher = OLD_SECRET_LINE_PATTERN.matcher(line);
            if (matcher.matches()) {
                if (matcher.group(1).length() == 0) {
                    lines.set(i, "application.secret=\"" + generate() + "\"");
                    changed = true;
                }
            } else {
                matcher = SECRET_LINE_PATTERN.matcher(line);
                if (matcher.matches()) {
                    if (matcher.group(2).trim().length() == 0) {
                        lines.set(i, "  secret = \"" + generate() + "\"");
                        changed = true;
                    }
                }
            }

        }

        if (changed) {
            FileUtils.writeLines(conf, lines);
            log.info("Application Secret generated - the configuration file was updated.");
        }

    }
}
 
Example 17
Source File: SetupTemplateUtils.java    From vertx-maven-plugin with Apache License 2.0 4 votes vote down vote up
public static void createVerticle(MavenProject project, String verticle, Log log) throws MojoExecutionException {
    if (Strings.isNullOrEmpty(verticle)) {
        return;
    }
    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);
    }

}
 
Example 18
Source File: SCMManifestCustomizer.java    From vertx-maven-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public Map<String, String> getEntries(PackageMojo mojo, MavenProject project) {
    Map<String, String> attributes = new HashMap<>();

    if (mojo.isSkipScmMetadata()) {
        return attributes;
    }

    //Add SCM Metadata only when <scm> is configured in the pom.xml
    if (project.getScm() != null) {
        Scm scm = project.getScm();
        String connectionUrl = scm.getConnection() == null ? scm.getDeveloperConnection() : scm.getConnection();

        if (scm.getUrl() != null) {
            attributes.put("Scm-Url", scm.getUrl());
        }

        if (scm.getTag() != null) {
            attributes.put("Scm-Tag", scm.getTag());
        }
        if (mojo.getScmManager() != null && connectionUrl != null) {
            try {
                //SCM metadata
                File baseDir = project.getBasedir();
                ScmSpy scmSpy = new ScmSpy(mojo.getScmManager());

                Map<String, String> scmChangeLogMap = scmSpy.getChangeLog(connectionUrl, baseDir);

                if (!scmChangeLogMap.isEmpty()) {
                    attributes.put("Scm-Type",
                        scmChangeLogMap.get(ExtraManifestKeys.scmType.name()));
                    attributes.put("Scm-Revision",
                        scmChangeLogMap.get(ExtraManifestKeys.scmRevision.name()));
                    attributes.put("Last-Commit-Timestamp",
                        scmChangeLogMap.get(ExtraManifestKeys.lastCommitTimestamp.name()));
                    attributes.put("Author",
                        scmChangeLogMap.get(ExtraManifestKeys.author.name()));
                }

            } catch (Exception e) {
                mojo.getLog().warn("Error while getting SCM Metadata `" + e.getMessage() + "`");
                mojo.getLog().warn("SCM metadata ignored");
                mojo.getLog().debug(e);
            }
        }
    }
    return attributes;
}
 
Example 19
Source File: SetupTemplateUtils.java    From vertx-maven-plugin with Apache License 2.0 4 votes vote down vote up
public static void createVerticle(MavenProject project, String verticle, Log log) throws MojoExecutionException {
    if (Strings.isNullOrEmpty(verticle)) {
        return;
    }
    log.info("Creating verticle " + verticle);

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

    String packageName = null;
    String className;
    if (verticle.endsWith(JAVA_EXTENSION)) {
        verticle = verticle.substring(0, verticle.length() - JAVA_EXTENSION.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_EXTENSION);
    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);
    }

}
 
Example 20
Source File: JCasGenMojoTest.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
public void test(String projectName, String... types) throws Exception {

    File projectSourceDirectory = getTestFile("src/test/resources/" + projectName);
    File projectDirectory = getTestFile("target/project-" + projectName + "-test");

    // Stage project to target folder
    FileUtils.copyDirectoryStructure(projectSourceDirectory, projectDirectory);
    
    File pomFile = new File(projectDirectory, "/pom.xml");
    assertNotNull(pomFile);
    assertTrue(pomFile.exists());

    // create the MavenProject from the pom.xml file
    MavenExecutionRequest executionRequest = new DefaultMavenExecutionRequest();
    ProjectBuildingRequest buildingRequest = executionRequest.getProjectBuildingRequest();
    ProjectBuilder projectBuilder = this.lookup(ProjectBuilder.class);
    MavenProject project = projectBuilder.build(pomFile, buildingRequest).getProject();
    assertNotNull(project);

    // copy resources
    File source = new File(projectDirectory, "src/main/resources");
    if (source.exists()) {
      FileUtils.copyDirectoryStructure(source, new File(project.getBuild().getOutputDirectory()));
    }
    
    // load the Mojo
    JCasGenMojo generate = (JCasGenMojo) this.lookupConfiguredMojo(project, "generate");
    assertNotNull(generate);

    // set the MavenProject on the Mojo (AbstractMojoTestCase does not do this by default)
    setVariableValueToObject(generate, "project", project);

    // execute the Mojo
    generate.execute();

    // check that the Java files have been generated
    File jCasGenDirectory = new File(project.getBasedir(), "target/generated-sources/jcasgen");
    
    // Record all the files that were generated
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(jCasGenDirectory);
    ds.setIncludes(new String[] { "**/*.java" });
    ds.scan();
    List<File> files = new ArrayList<>();
    for (String scannedFile : ds.getIncludedFiles()) {
      files.add(new File(ds.getBasedir(), scannedFile));
    }
    
    for (String type : types) {
      File wrapperFile = new File(jCasGenDirectory + "/" + type.replace('.', '/') + ".java");
      // no _type files in v3
//      File typeFile = new File(jCasGenDirectory + "/" + type.replace('.', '/') + "_Type.java");
      
      Assert.assertTrue(files.contains(wrapperFile));
      // no _type files in v3
//      Assert.assertTrue(files.contains(typeFile));
      
      files.remove(wrapperFile);
//      files.remove(typeFile);
    }
    
    // check that no extra files were generated
    Assert.assertTrue(files.isEmpty());

    // check that the generated sources are on the compile path
    Assert.assertTrue(project.getCompileSourceRoots().contains(jCasGenDirectory.getAbsolutePath()));
  }