org.codehaus.plexus.util.FileUtils Java Examples

The following examples show how to use org.codehaus.plexus.util.FileUtils. 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: PluginConfigXmlIT.java    From ci.maven with Apache License 2.0 6 votes vote down vote up
@Test
public void testBootstrapPropertiesFileElements() throws Exception {
    File in = new File(CONFIG_XML);
    FileInputStream input = new FileInputStream(in);
    
    // get input XML Document
    DocumentBuilderFactory inputBuilderFactory = DocumentBuilderFactory.newInstance();
    inputBuilderFactory.setIgnoringComments(true);
    inputBuilderFactory.setCoalescing(true);
    inputBuilderFactory.setIgnoringElementContentWhitespace(true);
    inputBuilderFactory.setValidating(false);
    DocumentBuilder inputBuilder = inputBuilderFactory.newDocumentBuilder();
    Document inputDoc = inputBuilder.parse(input);
    
    // parse input XML Document
    XPath xPath = XPathFactory.newInstance().newXPath();
    String expression = "/liberty-plugin-config/bootstrapPropertiesFile/text()";
    String nodeValue = (String) xPath.compile(expression).evaluate(inputDoc, XPathConstants.STRING);
    File f1 = new File(SOURCE_BOOTSTRAP_PROPERTIES);
    File f2 = new File(nodeValue);
    assertEquals("bootstrapPropertiesFile value", f1.getAbsolutePath(), f2.getAbsolutePath());
    assertEquals("verify target server bootstrap.properties", FileUtils.fileRead(f2),
            FileUtils.fileRead(TARGET_BOOTSTRAP_PROPERTIES));
}
 
Example #2
Source File: ThemeBuilderUtils.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Stores the given properties object in a file named <code>theme-derived.properties</code> within the
 * given theme directory
 *
 * @param themeDirectory directory the properties file should be created in
 * @param themeProperties properties that should be written to the properties file
 * @throws IOException
 */
public static void storeThemeProperties(String themeDirectory, Properties themeProperties) throws IOException {
    File propertiesFile = new File(themeDirectory, ThemeBuilderConstants.THEME_DERIVED_PROPERTIES_FILE);

    // need to remove file if already exists so the new properties will be written
    if (propertiesFile.exists()) {
        FileUtils.forceDelete(propertiesFile);
    }

    FileWriter fileWriter = null;

    try {
        fileWriter = new FileWriter(propertiesFile);

        themeProperties.store(fileWriter, null);
    } finally {
        if (fileWriter != null) {
            fileWriter.close();
        }
    }
}
 
Example #3
Source File: CopyFile.java    From butterfly with MIT License 6 votes vote down vote up
@Override
protected TOExecutionResult execution(File transformedAppFolder, TransformationContext transformationContext) {
    // TODO Validation must be done here!!!

    File fileFrom = getAbsoluteFile(transformedAppFolder, transformationContext);
    File fileTo = getFileTo(transformedAppFolder, transformationContext);
    TOExecutionResult result;

    try {
        if (fileFrom.isDirectory()) {
            IOException ex = new IOException(getRelativePath(transformedAppFolder, fileFrom) + " (Is a directory)");
            result = TOExecutionResult.error(this, new TransformationOperationException("File could not be copied", ex));
        } else {
            String details = String.format("File '%s' has been copied to '%s'", getRelativePath(), getRelativePath(transformedAppFolder, fileTo));
            FileUtils.copyFileToDirectory(fileFrom, fileTo);
            result = TOExecutionResult.success(this, details);
        }
    } catch (IOException e) {
        result = TOExecutionResult.error(this, new TransformationOperationException("File could not be copied", e));
    }

    return result;
}
 
Example #4
Source File: MoveFile.java    From butterfly with MIT License 6 votes vote down vote up
@Override
protected TOExecutionResult execution(File transformedAppFolder, TransformationContext transformationContext) {
    File fileFrom = getAbsoluteFile(transformedAppFolder, transformationContext);
    File fileTo = getFileTo(transformedAppFolder, transformationContext);
    TOExecutionResult result;

    // TODO
    // Check if it is really a file and if it exists!

    try {
        if (fileFrom.isDirectory()) {
            IOException ex = new IOException(getRelativePath(transformedAppFolder, fileFrom) + " (Is a directory)");
            result = TOExecutionResult.error(this, new TransformationOperationException("File could not be moved", ex));
        } else {
            String details = String.format("File '%s' has been moved to '%s'", getRelativePath(), getRelativePath(transformedAppFolder, fileTo));
            FileUtils.copyFileToDirectory(fileFrom, fileTo);
            FileUtils.fileDelete(fileFrom.getAbsolutePath());
            result = TOExecutionResult.success(this, details);
        }
    } catch (IOException e) {
        result = TOExecutionResult.error(this, new TransformationOperationException("File could not be moved", e));
    }

    return result;
}
 
Example #5
Source File: BuildNumberMojoTest.java    From buildnumber-maven-plugin with MIT License 6 votes vote down vote up
@Test
public void basicItGitTest()
    throws Exception
{
    File projDir = resources.getBasedir( "basic-it-git" );

    MavenExecution mavenExec = maven.forProject( projDir );
    MavenExecutionResult result = mavenExec.execute( "clean" );
    result.assertErrorFreeLog();
    File testDir = result.getBasedir();
    FileUtils.copyDirectoryStructure( new File( testDir, "dotGitDir" ), new File( testDir, ".git" ) );
    result = mavenExec.execute( "clean", "verify" );
    result.assertLogText( "Storing buildNumber: 6d36c746e82f00c5913954f9178f40224497b2f3" );
    result.assertLogText( "Storing buildScmBranch: master" );

    File artifact = new File( testDir, "target/buildnumber-maven-plugin-basic-it-1.0-SNAPSHOT.jar" );
    JarFile jarFile = new JarFile( artifact );
    Attributes manifest = jarFile.getManifest().getMainAttributes();
    jarFile.close();
    String scmRev = manifest.getValue( "SCM-Revision" );
    Assert.assertEquals( "6d36c746e82f00c5913954f9178f40224497b2f3", scmRev );
}
 
Example #6
Source File: RevertMojo.java    From versions-maven-plugin with Apache License 2.0 6 votes vote down vote up
public void execute()
    throws MojoExecutionException, MojoFailureException
{
    File outFile = project.getFile();
    File backupFile = new File( outFile.getParentFile(), outFile.getName() + ".versionsBackup" );

    if ( backupFile.exists() )
    {
        getLog().info( "Restoring " + outFile + " from " + backupFile );
        try
        {
            FileUtils.copyFile( backupFile, outFile );
            FileUtils.forceDelete( backupFile );
        }
        catch ( IOException e )
        {
            throw new MojoExecutionException( e.getMessage(), e );
        }
    }
}
 
Example #7
Source File: AjcHelper.java    From aspectj-maven-plugin with MIT License 6 votes vote down vote up
/**
 * Creates a file that can be used as input to the ajc compiler using the -argdfile flag.
 * Each line in these files should contain one option or filename.
 * Comments, as in Java, start with // and extend to the end of the line.
 *
 * @param arguments All arguments passed to ajc in this run
 * @param fileName the filename of the argfile
 * @param outputDir the build output area.
 * @throws IOException
 */
public static void writeBuildConfigToFile( List<String> arguments, String fileName, File outputDir )
    throws IOException
{
    FileUtils.forceMkdir( outputDir );
    File argFile = new File( outputDir, fileName );
    argFile.getParentFile().mkdirs();
    argFile.createNewFile();
    BufferedWriter writer = new BufferedWriter( new FileWriter( argFile ) );
    for ( String argument : arguments )
    {
        writer.write( argument );
        writer.newLine();
    }
    writer.flush();
    writer.close();
}
 
Example #8
Source File: RawXJC2Mojo.java    From maven-jaxb2-plugin with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected void setupDirectories() {

		final File generateDirectory = getGenerateDirectory();
		if (getRemoveOldOutput() && generateDirectory.exists()) {
			try {
				FileUtils.deleteDirectory(this.getGenerateDirectory());
			} catch (IOException ex) {
				getLog().warn("Failed to remove old generateDirectory [" + generateDirectory + "].", ex);
			}
		}

		// Create the destination path if it does not exist.
		if (generateDirectory != null && !generateDirectory.exists()) {
			generateDirectory.mkdirs();
		}

		final File episodeFile = getEpisodeFile();
		if (getEpisode() && episodeFile != null) {
			final File parentFile = episodeFile.getParentFile();
			parentFile.mkdirs();
		}
	}
 
Example #9
Source File: AddProperty.java    From butterfly with MIT License 6 votes vote down vote up
private TOExecutionResult addProperty(File transformedAppFolder, TransformationContext transformationContext) {
    File fileToBeChanged = getAbsoluteFile(transformedAppFolder, transformationContext);
    TOExecutionResult result;
    try {
        String propertyToBeAdded = String.format("%s = %s", propertyName, propertyValue);
        if (fileToBeChanged.length() != 0) {
            FileUtils.fileAppend(fileToBeChanged.getAbsolutePath(), EolHelper.findEolDefaultToOs(fileToBeChanged));
        }
        FileUtils.fileAppend(fileToBeChanged.getAbsolutePath(), propertyToBeAdded);
        String details = String.format("Property '%s' has been added and set to '%s' at '%s'", propertyName, propertyValue, getRelativePath());
        result = TOExecutionResult.success(this, details);
    } catch (IOException e) {
        result = TOExecutionResult.error(this, new TransformationOperationException("Property file could not be modified", e));
    }
    return result;
}
 
Example #10
Source File: ScriptGeneratorBackgroundTest.java    From appassembler with MIT License 6 votes vote down vote up
private void testShellScriptGenerationWithFalseShowConsoleWindow( Platform platform )
    throws Exception
{
    ScriptGenerator generator = (ScriptGenerator) lookup( ScriptGenerator.ROLE );

    Daemon daemon = new Daemon();

    daemon.setShowConsoleWindow( false );
    daemon.setId( "test" );
    daemon.setMainClass( "foo.Bar" );
    daemon.setJvmSettings( new JvmSettings() );
    daemon.getJvmSettings().setExtraArguments( Arrays.asList( new String[] { "Yo", "dude" } ) );
    daemon.setEnvironmentSetupFileName( "setup" );
    daemon.setRepositoryName( "repo" );
    File outputDirectory = getTestFile( "target/test-output/background-shell/" + platform.getName() );

    generator.createBinScript( platform.getName(), daemon, outputDirectory, "bin" );

    File expectedFile =
        getTestFile( PREFIX + "expected-false-showConsoleWindow-" + daemon.getId() + platform.getBinFileExtension() );
    File actualFile = new File( outputDirectory, "bin/" + daemon.getId() + platform.getBinFileExtension() );

    assertEquals( FileUtils.fileRead( expectedFile ), FileUtils.fileRead( actualFile ) );
}
 
Example #11
Source File: RenameMojo.java    From copy-rename-maven-plugin with MIT License 6 votes vote down vote up
private void copy(File srcFile,File destFile) throws MojoExecutionException{

		if(!srcFile.exists()){
			if(ignoreFileNotFoundOnIncremental && buildContext.isIncremental()){
				getLog().warn("sourceFile "+srcFile.getAbsolutePath()+ " not found during incremental build");
			} else {
				getLog().error("sourceFile "+srcFile.getAbsolutePath()+ " does not exist");
			}
		}  else if(destFile == null){
			getLog().error("destinationFile not specified");
		} else if(destFile.exists() && (destFile.isFile() == srcFile.isFile()) && !overWrite){
			getLog().error(destFile.getAbsolutePath()+" already exists and overWrite not set");
		} else{
			try {
				FileUtils.rename(srcFile, destFile);
				getLog().info("Renamed "+ srcFile.getAbsolutePath()+ " to "+ destFile.getAbsolutePath());
				buildContext.refresh(destFile);
			} catch (IOException e) {
				throw new MojoExecutionException("could not rename "+srcFile.getAbsolutePath()+" to "+destFile
                    .getAbsolutePath(),e);
			}
		}


	}
 
Example #12
Source File: PrepareFrontendMojoTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void writeTokenFile_devModePropertiesAreWritten()
        throws IOException, MojoExecutionException, MojoFailureException {

    mojo.execute();

    String json = org.apache.commons.io.FileUtils
            .readFileToString(tokenFile, StandardCharsets.UTF_8);
    JsonObject buildInfo = JsonUtil.parse(json);

    Assert.assertTrue(
            Constants.SERVLET_PARAMETER_ENABLE_PNPM
                    + "should have been written",
            buildInfo.getBoolean(Constants.SERVLET_PARAMETER_ENABLE_PNPM));
    Assert.assertTrue(
            Constants.REQUIRE_HOME_NODE_EXECUTABLE
                    + "should have been written",
            buildInfo.getBoolean(Constants.REQUIRE_HOME_NODE_EXECUTABLE));

    Assert.assertFalse(buildInfo
            .hasKey(Constants.SERVLET_PARAMETER_DEVMODE_OPTIMIZE_BUNDLE));
}
 
Example #13
Source File: NativeLinkMojo.java    From maven-native with MIT License 6 votes vote down vote up
private File getDependencyFile( Artifact artifact, boolean doCopy )
    throws MojoExecutionException
{

    File newLocation = new File( this.externalLibDirectory,
            artifact.getArtifactId() + "." + artifact.getArtifactHandler().getExtension() );

    try
    {
        if ( doCopy && !artifact.getFile().isDirectory()
                && ( !newLocation.exists() || newLocation.lastModified() <= artifact.getFile().lastModified() ) )
        {
            FileUtils.copyFile( artifact.getFile(), newLocation );
        }
    }
    catch ( IOException ioe )
    {
        throw new MojoExecutionException( "Unable to copy dependency to staging area.  Could not copy "
                + artifact.getFile() + " to " + newLocation, ioe );
    }

    return newLocation;
}
 
Example #14
Source File: AjcHelper.java    From aspectj-maven-plugin with MIT License 6 votes vote down vote up
/**
 * Reads a build config file, and returns the List of all compiler arguments.
 *
 * @param fileName the filename of the argfile
 * @param outputDir the build output area
 * @return
 * @throws IOException
 */
public static List<String> readBuildConfigFile( String fileName, File outputDir )
    throws IOException
{
    List<String> arguments = new ArrayList<String>();
    File argFile = new File( outputDir, fileName );
    if ( FileUtils.fileExists( argFile.getAbsolutePath() ) )
    {
        FileReader reader = new FileReader( argFile );
        BufferedReader bufRead = new BufferedReader( reader );
        String line = null;
        do
        {
            line = bufRead.readLine();
            if ( null != line )
            {
                arguments.add( line );
            }
        }
        while ( null != line );
    }
    return arguments;
}
 
Example #15
Source File: CommitMojo.java    From versions-maven-plugin with Apache License 2.0 6 votes vote down vote up
public void execute()
    throws MojoExecutionException, MojoFailureException
{
    File outFile = project.getFile();
    File backupFile = new File( outFile.getParentFile(), outFile.getName() + ".versionsBackup" );

    if ( backupFile.exists() )
    {
        getLog().info( "Accepting all changes to " + outFile );
        try
        {
            FileUtils.forceDelete( backupFile );
        }
        catch ( IOException e )
        {
            throw new MojoExecutionException( e.getMessage(), e );
        }
    }
}
 
Example #16
Source File: MonkeyTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Test
public void run() throws Exception {
    final File tomee = prepareProject();
    try {
        invoke(tomee); // invalid, should fail
    } catch (final ClassFormatError cfe) {
        // ok, we created an invalid jar
    }

    new Monkey(tomee).run();
    final File[] libs = new File(tomee, "lib").listFiles(new FilenameFilter() {
        @Override
        public boolean accept(final File dir, final String name) {
            return name.endsWith(".jar");
        }
    });
    assertEquals(1, libs.length);
    final File jar = libs[0];
    assertTrue(jar.getName().contains("tomee-monkey-"));
    assertEquals(2, invoke(tomee));

    FileUtils.deleteDirectory(tomee.getParentFile().getParentFile());
}
 
Example #17
Source File: TransformMojoTest.java    From xml-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Builds the it7 test project.
 * @throws Exception The test failed.
 */
public void testIt7()
    throws Exception
{
    final File dir = new File( "src/test/it7" );
    final File target = new File( dir, "target/generated-resources/xml/xslt/doc1.xml" );
    TransformMojo mojo = (TransformMojo) newMojo( dir.getPath() );
    FileUtils.fileDelete( target.getPath() );
    mojo.execute();
    String result = read( target );
    assertFalse( result.startsWith( "<?xml" ) );
    mojo = (TransformMojo) newMojo( "src/test/it7" );
    TransformationSet[] transformationSets =
        (TransformationSet[]) getVariableValueFromObject( mojo, "transformationSets" );
    transformationSets[0].getOutputProperties()[0].setValue( "no" );
    FileUtils.fileDelete( target.getPath() );
    mojo.execute();
    result = read( target );
    assertTrue( result.startsWith( "<?xml" ) );
}
 
Example #18
Source File: BuildNumberMojoTest.java    From buildnumber-maven-plugin with MIT License 6 votes vote down vote up
@Test
public void basicItSvnJavaTest()
    throws Exception
{
    Assume.assumeTrue( isSvn18() );

    File projDir = resources.getBasedir( "basic-it-svnjava" );

    MavenExecution mavenExec = maven.forProject( projDir );
    MavenExecutionResult result = mavenExec.execute( "clean" );
    result.assertErrorFreeLog();
    File testDir = result.getBasedir();
    FileUtils.copyDirectoryStructure( new File( testDir, "dotSvnDir" ), new File( testDir, ".svn" ) );
    result = mavenExec.execute( "clean", "verify" );
    result.assertLogText( "Storing buildNumber: 19665" );
    result.assertLogText( "Storing buildScmBranch: trunk" );

    File artifact = new File( testDir, "target/buildnumber-maven-plugin-basic-it-svnjava-1.0-SNAPSHOT.jar" );
    JarFile jarFile = new JarFile( artifact );
    Attributes manifest = jarFile.getManifest().getMainAttributes();
    jarFile.close();
    String scmRev = manifest.getValue( "SCM-Revision" );
    Assert.assertEquals( "19665", scmRev );
}
 
Example #19
Source File: ApiTestMojoTest.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Clean configured output directory.
 */
private void clean( ApiTestMojo apiMojo)
  {
  File outDir = apiMojo.getOutDirFile();
  if( outDir.exists())
    {
    try
      {
      FileUtils.cleanDirectory( outDir);
      }
    catch( Exception e)
      {
      throw new RuntimeException( "Can't clear outDir=" + outDir, e);
      }
    }
  }
 
Example #20
Source File: AjcHelper.java    From aspectj-maven-plugin with MIT License 6 votes vote down vote up
/**
 * Based on a set of weavedirs returns a set of all the files to be weaved.
 *
 * @return
 * @throws MojoExecutionException
 */
public static Set<String> getWeaveSourceFiles( String[] weaveDirs )
    throws MojoExecutionException
{
    Set<String> result = new HashSet<String>();

    for ( int i = 0; i < weaveDirs.length; i++ )
    {
        String weaveDir = weaveDirs[i];
        if ( FileUtils.fileExists( weaveDir ) )
        {
            try
            {
                result.addAll( FileUtils.getFileNames( new File( weaveDir ), "**/*.class", DEFAULT_EXCLUDES, true ) );
            }
            catch ( IOException e )
            {
                throw new MojoExecutionException( "IO Error resolving weavedirs", e );
            }
        }
    }
    return result;
}
 
Example #21
Source File: JavaServiceWrapperDaemonGeneratorTest.java    From appassembler with MIT License 6 votes vote down vote up
public void testGenerationWithChkConfig()
    throws Exception
{
    runTest( "jsw", "src/test/resources/project-12/pom.xml", "src/test/resources/project-12/descriptor.xml",
             "target/output-12-jsw" );

    File jswDir = getTestFile( "target/output-12-jsw/app" );
    File wrapper = new File( jswDir, "conf/wrapper.conf" );

    String wrapperContents = FileUtils.fileRead( wrapper );

    assertFalse( "Wrapper conf contains chkconfig.start", wrapperContents.contains( "chkconfig.start" ) );
    assertFalse( "Wrapper conf contains chkconfig.stop", wrapperContents.contains( "chkconfig.stop" ) );

    File script = new File( jswDir, "bin/app" );
    String scriptContents = FileUtils.fileRead( script );

    assertTrue( "Chkconfig replace did not work", scriptContents.contains( "chkconfig: 3 21 81" ) );
}
 
Example #22
Source File: EmoStartMojo.java    From emodb with Apache License 2.0 6 votes vote down vote up
private void copyEmoServiceArtifactToWorkingDirectory() throws MojoExecutionException, MojoFailureException {
    // NOTE: this emo service artifact is an "uberjar" created by the maven-shade-plugin
    final ArtifactItem emoServiceArtifact = new ArtifactItem();
    emoServiceArtifact.setGroupId("com.bazaarvoice.emodb");
    emoServiceArtifact.setArtifactId("emodb-web");
    emoServiceArtifact.setVersion(pluginVersion());

    resolveArtifactItems(asList(emoServiceArtifact));
    final File emoServiceJar = emoServiceArtifact.getResolvedArtifact().getArtifact().getFile();
    try {
        // copy to "emodb.jar" so that we always overwrite any prior
        FileUtils.copyFile(emoServiceJar, new File(emoProcessWorkingDirectory(), "emodb.jar"));
    } catch (IOException e) {
        throw new MojoFailureException("failed to copy: " + emoServiceArtifact, e);
    }
}
 
Example #23
Source File: AbstractAppAssemblerMojo.java    From appassembler with MIT License 6 votes vote down vote up
protected void removeDirectory( File directory )
    throws MojoExecutionException
{
    if ( directory.exists() )
    {
        try
        {
            this.getLog().info( "Removing " + directory );
            FileUtils.deleteDirectory( directory );
        }
        catch ( IOException e )
        {
            throw new MojoExecutionException( e.getMessage(), e );
        }
    }
}
 
Example #24
Source File: FileSystemUtilities.java    From jaxb2-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Convenience method to successfully create a directory - or throw an exception if failing to create it.
 *
 * @param aDirectory        The directory to create.
 * @param cleanBeforeCreate if {@code true}, the directory and all its content will be deleted before being
 *                          re-created. This will ensure that the created directory is really clean.
 * @throws MojoExecutionException if the aDirectory could not be created (and/or cleaned).
 */
public static void createDirectory(final File aDirectory, final boolean cleanBeforeCreate)
        throws MojoExecutionException {

    // Check sanity
    Validate.notNull(aDirectory, "aDirectory");
    validateFileOrDirectoryName(aDirectory);

    // Clean an existing directory?
    if (cleanBeforeCreate) {
        try {
            FileUtils.deleteDirectory(aDirectory);
        } catch (IOException e) {
            throw new MojoExecutionException("Could not clean directory [" + getCanonicalPath(aDirectory) + "]", e);
        }
    }

    // Now, make the required directory, if it does not already exist as a directory.
    final boolean existsAsFile = aDirectory.exists() && aDirectory.isFile();
    if (existsAsFile) {
        throw new MojoExecutionException("[" + getCanonicalPath(aDirectory) + "] exists and is a file. "
                + "Cannot make directory");
    } else if (!aDirectory.exists() && !aDirectory.mkdirs()) {
        throw new MojoExecutionException("Could not create directory [" + getCanonicalPath(aDirectory) + "]");
    }
}
 
Example #25
Source File: NativeLinkMojo.java    From maven-native with MIT License 6 votes vote down vote up
private List<String> getLibFileNames()
    throws MojoExecutionException
{
    List<String> libList = new ArrayList<>();

    Set<Artifact> artifacts = this.project.getArtifacts();

    for ( Iterator<Artifact> iter = artifacts.iterator(); iter.hasNext(); )
    {
        Artifact artifact = iter.next();

        if ( INCZIP_TYPE.equals( artifact.getType() ) )
        {
            continue;
        }

        String libFileName = FileUtils.filename( this.getDependencyFile( artifact, true ).getPath() );

        libList.add( libFileName );
    }

    libList = this.reorderLibDependencies( libList );

    return libList;
}
 
Example #26
Source File: AbstractHelmMojo.java    From helm-maven-plugin with MIT License 6 votes vote down vote up
List<String> getChartDirectories(String path) throws MojoExecutionException {
	List<String> exclusions = new ArrayList<>();

	if (getExcludes() != null) {
		exclusions.addAll(Arrays.asList(getExcludes()));
	}

	exclusions.addAll(FileUtils.getDefaultExcludesAsList());

	MatchPatterns exclusionPatterns = MatchPatterns.from(exclusions);

	try (Stream<Path> files = Files.walk(Paths.get(path), FileVisitOption.FOLLOW_LINKS)) {
		List<String> chartDirs = files.filter(p -> p.getFileName().toString().equalsIgnoreCase("chart.yaml"))
				.map(p -> p.getParent().toString())
				.filter(shouldIncludeDirectory(exclusionPatterns))
				.collect(Collectors.toList());

		if (chartDirs.isEmpty()) {
			getLog().warn("No Charts detected - no Chart.yaml files found below " + path);
		}

		return chartDirs;
	} catch (IOException e) {
		throw new MojoExecutionException("Unable to scan chart directory at " + path, e);
	}
}
 
Example #27
Source File: BuildFrontendMojoTest.java    From flow with Apache License 2.0 5 votes vote down vote up
static JsonObject getPackageJson(String packageJson) throws IOException {
    if (FileUtils.fileExists(packageJson)) {
        return Json.parse(FileUtils.fileRead(packageJson));

    } else {
        return Json.createObject();
    }
}
 
Example #28
Source File: AjcHelper.java    From aspectj-maven-plugin with MIT License 5 votes vote down vote up
/**
 * Helper method to find all .java or .aj files specified by the
 * includeString. The includeString is a comma separated list over files, or
 * directories relative to the specified basedir. Examples of correct
 * listings
 *
 * <pre>
 *         src/main/java/
 *         src/main/java
 *         src/main/java/com/project/AClass.java
 *         src/main/java/com/project/AnAspect.aj
 *         src/main/java/com/project/AnAspect.java
 * </pre>
 *
 * @param input
 * @param basedir the baseDirectory
 * @return a list over all files inn the include string
 * @throws IOException
 */
protected static Set<String> resolveIncludeExcludeString( String input, File basedir )
    throws MojoExecutionException
{
    Set<String> inclExlSet = new LinkedHashSet<String>();
    try
    {
        if ( null == input || input.trim().equals( "" ) )
        {
            return inclExlSet;
        }
        String[] elements = input.split( "," );
        if ( null != elements )
        {

            for ( int i = 0; i < elements.length; i++ )
            {
                String element = elements[i];
                if ( element.endsWith( ".java" ) || element.endsWith( ".aj" ) )
                {
                    inclExlSet.addAll( FileUtils.getFileNames( basedir, element, "", true ) );
                }
                else
                {
                    File lookupBaseDir = new File( basedir, element );
                    if ( FileUtils.fileExists( lookupBaseDir.getAbsolutePath() ) )
                    {
                        inclExlSet.addAll( FileUtils.getFileNames( lookupBaseDir, DEFAULT_INCLUDES, "",
                                                               true ) );
                    }
                }
            }
        }
    }
    catch ( IOException e )
    {
        throw new MojoExecutionException( "Could not resolve java or aspect sources to compile", e );
    }
    return inclExlSet;
}
 
Example #29
Source File: AbstractPitAggregationReportMojo.java    From pitest with Apache License 2.0 5 votes vote down vote up
private List<File> getProjectFilesByFilter(final File projectBaseDir,
                                           final String filter) throws IOException {

  File reportsDir = projectBaseDir.toPath().resolve(REPORT_DIR_RELATIVE_TO_PROJECT).toFile();
  if (!reportsDir.exists()) {
    return new ArrayList<>();
  }

  File latestReportDir = reportSourceLocator.locate(reportsDir, getLog());

  final List<File> files = FileUtils.getFiles(latestReportDir, filter, "");
  return files == null ? new ArrayList<>() : files;
}
 
Example #30
Source File: AbstractVersionsDisplayMojo.java    From versions-maven-plugin with Apache License 2.0 5 votes vote down vote up
protected void logLine( boolean error, String line )
{
    if ( logOutput )
    {
        if ( error )
        {
            getLog().error( line );
        }
        else
        {
            getLog().info( line );
        }
    }
    if ( outputFile != null && !outputFileError )
    {
        try
        {
            FileUtils.fileAppend( outputFile.getAbsolutePath(), outputEncoding,
                                  error ? "> " + line + System.getProperty( "line.separator" )
                                                  : line + System.getProperty( "line.separator" ) );
        }
        catch ( IOException e )
        {
            getLog().error( "Cannot send output to " + outputFile, e );
            outputFileError = true;
        }
    }
}