Java Code Examples for org.codehaus.plexus.util.DirectoryScanner#addDefaultExcludes()

The following examples show how to use org.codehaus.plexus.util.DirectoryScanner#addDefaultExcludes() . 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: AbstractImpSortMojo.java    From impsort-maven-plugin with Apache License 2.0 6 votes vote down vote up
private Stream<File> searchDir(File dir, boolean warnOnBadDir) {
  if (dir == null || !dir.exists() || !dir.isDirectory()) {
    if (warnOnBadDir && dir != null) {
      getLog().warn("Directory does not exist or is not a directory: " + dir);
    }
    return Stream.empty();
  }
  getLog().debug("Adding directory " + dir);
  DirectoryScanner ds = new DirectoryScanner();
  ds.setBasedir(dir);
  ds.setIncludes(includes != null && includes.length > 0 ? includes : DEFAULT_INCLUDES);
  ds.setExcludes(excludes);
  ds.addDefaultExcludes();
  ds.setCaseSensitive(false);
  ds.setFollowSymlinks(false);
  ds.scan();
  return Stream.of(ds.getIncludedFiles()).map(filename -> new File(dir, filename)).parallel();
}
 
Example 2
Source File: FormatterMojo.java    From formatter-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Add source files to the files list.
 *
 */
List<File> addCollectionFiles(File newBasedir) {
    final DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(newBasedir);
    if (this.includes != null && this.includes.length > 0) {
        ds.setIncludes(this.includes);
    } else {
        ds.setIncludes(DEFAULT_INCLUDES);
    }

    ds.setExcludes(this.excludes);
    ds.addDefaultExcludes();
    ds.setCaseSensitive(false);
    ds.setFollowSymlinks(false);
    ds.scan();

    List<File> foundFiles = new ArrayList<>();
    for (String filename : ds.getIncludedFiles()) {
        foundFiles.add(new File(newBasedir, filename));
    }
    return foundFiles;
}
 
Example 3
Source File: ThemeBuilderUtils.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Retrieves a list of file names that are in the given directory, possibly filtered by the list of include
 * patterns or exclude patterns
 *
 * @param baseDirectory directory to retrieve file names from
 * @param includes list of patterns to match against for file names to include, can include Ant patterns
 * @param excludes list of patterns to match for excluded file names, can include Ant patterns
 * @return list of file names within the directory that match all given patterns
 */
public static List<String> getDirectoryFileNames(File baseDirectory, String[] includes, String[] excludes) {
    List<String> files = new ArrayList<String>();

    DirectoryScanner scanner = new DirectoryScanner();

    if (includes != null) {
        scanner.setIncludes(includes);
    }

    if (excludes != null) {
        scanner.setExcludes(excludes);
    }

    scanner.setCaseSensitive(false);
    scanner.addDefaultExcludes();
    scanner.setBasedir(baseDirectory);

    scanner.scan();

    for (String includedFilename : scanner.getIncludedFiles()) {
        files.add(includedFilename);
    }

    return files;
}
 
Example 4
Source File: CreateApplicationBundleMojo.java    From appbundle-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Scan a fileset and get a list of files which it contains.
 *
 * @param fileset
 * @return list of files contained within a fileset.
 * @throws FileNotFoundException
 */
private List<String> scanFileSet(File sourceDirectory, FileSet fileSet) {
    final String[] emptyStringArray = {};

    DirectoryScanner scanner = new DirectoryScanner();

    scanner.setBasedir(sourceDirectory);
    if (fileSet.getIncludes() != null && !fileSet.getIncludes().isEmpty()) {
        scanner.setIncludes(fileSet.getIncludes().toArray(emptyStringArray));
    } else {
        scanner.setIncludes(DEFAULT_INCLUDES);
    }

    if (fileSet.getExcludes() != null && !fileSet.getExcludes().isEmpty()) {
        scanner.setExcludes(fileSet.getExcludes().toArray(emptyStringArray));
    }

    if (fileSet.isUseDefaultExcludes()) {
        scanner.addDefaultExcludes();
    }

    scanner.scan();

    return Arrays.asList(scanner.getIncludedFiles());
}
 
Example 5
Source File: ProjectScanner.java    From wisdom with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the list of packages from {@literal src/main/java}. This method scans for ".class" files in {@literal
 * target/classes}.
 *
 * @return the list of packages, empty if none.
 */
public Set<String> getPackagesFromMainSources() {
    Set<String> packages = new LinkedHashSet<>();
    File classes = getClassesDirectory();
    if (classes.isDirectory()) {
        DirectoryScanner scanner = new DirectoryScanner();
        scanner.setBasedir(classes);
        scanner.setIncludes(new String[]{"**/*.class"});
        scanner.addDefaultExcludes();
        scanner.scan();

        for (int i = 0; i < scanner.getIncludedFiles().length; i++) {
            packages.add(Packages.getPackageName(scanner.getIncludedFiles()[i]));
        }
    }

    return packages;
}
 
Example 6
Source File: ProjectScanner.java    From wisdom with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the list of packages from {@literal src/test/java}. This method scans for ".class" files in {@literal
 * target/test-classes}.
 *
 * @return the list of packages, empty if none.
 */
public Set<String> getPackagesFromTestSources() {
    Set<String> packages = new LinkedHashSet<>();
    File classes = new File(basedir, "target/test-classes");
    if (classes.isDirectory()) {
        DirectoryScanner scanner = new DirectoryScanner();
        scanner.setBasedir(classes);
        scanner.setIncludes(new String[]{"**/*.class"});
        scanner.addDefaultExcludes();
        scanner.scan();

        for (int i = 0; i < scanner.getIncludedFiles().length; i++) {
            packages.add(Packages.getPackageName(scanner.getIncludedFiles()[i]));
        }
    }

    return packages;
}
 
Example 7
Source File: FormatMojo.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
private List<File> scan(File directory) {
	DirectoryScanner scanner = new DirectoryScanner();
	scanner.setBasedir(directory);
	scanner.setIncludes(hasLength(this.includes) ? this.includes : DEFAULT_INCLUDES);
	scanner.setExcludes(this.excludes);
	scanner.addDefaultExcludes();
	scanner.setCaseSensitive(false);
	scanner.setFollowSymlinks(false);
	scanner.scan();
	return Arrays.asList(scanner.getIncludedFiles()).stream().map(name -> new File(directory, name))
			.collect(Collectors.toList());
}
 
Example 8
Source File: MainClassesCoSSkipper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public boolean skip(RunConfig config, boolean includingTests, long timeStamp) {
    if (includingTests) {
        if (!RunUtils.hasApplicationCompileOnSaveEnabled(config) && RunUtils.hasTestCompileOnSaveEnabled(config)) {
            //in case when only tests are enabled for CoS, the main source root is not compiled on the fly.
            // we need to checkif something was changed there and if so, recompile manually.
            
            //TODO is there a way to figure if there is a modified java file in a simpler way?
            File dirFile = FileUtilities.convertStringToFile(config.getMavenProject().getBuild().getSourceDirectory());
            if (dirFile == null || !dirFile.exists()) { //#223461
                return false;
            }
            DirectoryScanner ds = new DirectoryScanner();
            ds.setBasedir(dirFile);
            //includes/excludes
            ds.setIncludes(new String[]{"**/*.java"});
            ds.addDefaultExcludes();
            ds.scan();
            String[] inclds = ds.getIncludedFiles();
            for (String inc : inclds) {
                File f = new File(dirFile, inc);
                if (f.lastModified() >= timeStamp) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 9
Source File: FilteredResourcesCoSSkipper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean hasChangedResources(Resource r, long stamp) {
        String dir = r.getDirectory();
        File dirFile = FileUtil.normalizeFile(new File(dir));
  //      System.out.println("checkresource dirfile =" + dirFile);
        if (dirFile.exists()) {
            List<File> toCopy = new ArrayList<File>();
            DirectoryScanner ds = new DirectoryScanner();
            ds.setBasedir(dirFile);
            //includes/excludes
            String[] incls = r.getIncludes().toArray(new String[0]);
            if (incls.length > 0) {
                ds.setIncludes(incls);
            } else {
                ds.setIncludes(DEFAULT_INCLUDES);
            }
            String[] excls = r.getExcludes().toArray(new String[0]);
            if (excls.length > 0) {
                ds.setExcludes(excls);
            }
            ds.addDefaultExcludes();
            ds.scan();
            String[] inclds = ds.getIncludedFiles();
//            System.out.println("found=" + inclds.length);
            for (String inc : inclds) {
                File f = new File(dirFile, inc);
                if (f.lastModified() >= stamp) { 
                    toCopy.add(FileUtil.normalizeFile(f));
                }
            }
            if (toCopy.size() > 0) {
                    //the case of filtering source roots, here we want to return false
                    //to skip CoS altogether.
                return true;
            }
        }
        return false;
    }
 
Example 10
Source File: ProjectUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static Set<Path> collectBinaries(IPath projectDir, Set<String> include, Set<String> exclude, IProgressMonitor monitor) throws CoreException {
	Set<Path> binaries = new LinkedHashSet<>();
	Map<IPath, Set<String>> includeByPrefix = groupGlobsByPrefix(projectDir, include);
	Set<IPath> excludeResolved = exclude.stream().map(glob -> resolveGlobPath(projectDir, glob)).collect(Collectors.toSet());
	for (IPath baseDir: includeByPrefix.keySet()) {
		Path base = baseDir.toFile().toPath();
		if (monitor.isCanceled()) {
			return binaries;
		}
		if (Files.isRegularFile(base)) {
			if (isBinary(base))	{
				binaries.add(base);
			}
			continue; // base is a regular file path
		}
		if (!Files.isDirectory(base)) {
			continue; // base does not exist
		}
		Set<String> subInclude = includeByPrefix.get(baseDir);
		Set<String> subExclude = excludeResolved.stream().map(glob -> glob.makeRelativeTo(baseDir).toOSString()).collect(Collectors.toSet());
		DirectoryScanner scanner = new DirectoryScanner();
		try {
			scanner.setIncludes(subInclude.toArray(new String[subInclude.size()]));
			scanner.setExcludes(subExclude.toArray(new String[subExclude.size()]));
			scanner.addDefaultExcludes();
			scanner.setBasedir(base.toFile());
			scanner.scan();
		} catch (IllegalStateException e) {
			throw new CoreException(StatusFactory.newErrorStatus("Unable to collect binaries", e));
		}
		for (String result: scanner.getIncludedFiles()) {
			Path file = base.resolve(result);
			if (isBinary(file))	{
				binaries.add(file);
			}
		}
	}
	return binaries;
}
 
Example 11
Source File: CompileMojo.java    From twirl-maven-plugin with Apache License 2.0 5 votes vote down vote up
private static String[] findFiles(File dir, Set<String> includes, Set<String> excludes) {
  if (!dir.exists()) {
    return new String[0];
  }

  DirectoryScanner scanner = new DirectoryScanner();
  scanner.setBasedir(dir);
  scanner.setIncludes(includes.toArray(new String[includes.size()]));
  scanner.setExcludes(excludes.toArray(new String[excludes.size()]));
  scanner.addDefaultExcludes();
  scanner.scan();
  return scanner.getIncludedFiles();
}
 
Example 12
Source File: ThemeBuilderUtils.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Retrieves a list of files and directories that are in the given directory, possibly filtered by the
 * list of include patterns or exclude patterns
 *
 * @param baseDirectory directory to retrieve files and directories from
 * @param includes list of patterns to match against for files to include, can include Ant patterns
 * @param excludes list of patterns to match for excluded files, can include Ant patterns
 * @return list of files within the directory that match all given patterns
 */
public static List<String> getDirectoryContents(File baseDirectory, String[] includes, String[] excludes) {
    List<String> contents = new ArrayList<String>();

    DirectoryScanner scanner = new DirectoryScanner();

    if (includes != null) {
        scanner.setIncludes(includes);
    }

    if (excludes != null) {
        scanner.setExcludes(excludes);
    }

    scanner.setCaseSensitive(false);
    scanner.addDefaultExcludes();
    scanner.setBasedir(baseDirectory);

    scanner.scan();

    for (String includedDirectory : scanner.getIncludedDirectories()) {
        contents.add(includedDirectory);
    }

    for (String includedFilename : scanner.getIncludedFiles()) {
        contents.add(includedFilename);
    }

    return contents;
}
 
Example 13
Source File: AggregateJsMojo.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
private void doExecute() throws Exception {
  // build scanner to find files to aggregate
  DirectoryScanner files = new DirectoryScanner();
  files.setBasedir(sourceDirectory);
  if (includes == null || includes.length == 0) {
    files.setIncludes(DEFAULT_INCLUDES);
  }
  else {
    files.setIncludes(includes);
  }
  files.setExcludes(excludes);
  files.addDefaultExcludes();

  // build the list of ordered classes to include
  ClassDefScanner scanner = new ClassDefScanner(getLog());
  scanner.setWarnings(warnings);
  if (namespace == null) {
    getLog().warn("Namespace is not configured; will be unable to detect and resolve MVC references");
  }
  else {
    scanner.setNamespace(namespace);
  }
  List<ClassDef> classes = scanner.scan(files);

  // aggregate all class sources
  getLog().info("Writing: " + outputFile);
  Writer output = new BufferedWriter(new FileWriter(outputFile));
  try {
    FileAppender appender;
    if (omit) {
      appender = new OmissionFileAppender(getLog(), output, omitFlags);
    }
    else {
      appender = new FileAppender(getLog(), output);
    }

    for (ClassDef def : classes) {
      appender.append(def.getSource());
    }
  }
  finally {
    output.close();
  }
}
 
Example 14
Source File: RequireEncoding.java    From extra-enforcer-rules with Apache License 2.0 4 votes vote down vote up
public void execute( EnforcerRuleHelper helper )
    throws EnforcerRuleException
{
    try
    {
        if ( StringUtils.isBlank( encoding ) )
        {
            encoding = (String) helper.evaluate( "${project.build.sourceEncoding}" );
        }
        Log log = helper.getLog();

        Set< String > acceptedEncodings = new HashSet< String >( Arrays.asList( encoding ) );
        if ( encoding.equals( StandardCharsets.US_ASCII.name() ) )
        {
            log.warn( "Encoding US-ASCII is hard to detect. Use UTF-8 or ISO-8859-1" );
        }

        if ( acceptAsciiSubset && ( encoding.equals( StandardCharsets.ISO_8859_1.name() ) || encoding.equals( StandardCharsets.UTF_8.name() ) ) )
        {
            acceptedEncodings.add( StandardCharsets.US_ASCII.name() );
        }

        String basedir = (String) helper.evaluate( "${basedir}" );
        DirectoryScanner ds = new DirectoryScanner();
        ds.setBasedir( basedir );
        if ( StringUtils.isNotBlank( includes ) )
        {
            ds.setIncludes( includes.split( "[,\\|]" ) );
        }
        if ( StringUtils.isNotBlank( excludes ) )
        {
            ds.setExcludes( excludes.split( "[,\\|]" ) );
        }
        if ( useDefaultExcludes )
        {
            ds.addDefaultExcludes();
        }
        ds.scan();
        StringBuilder filesInMsg = new StringBuilder();
        for ( String file : ds.getIncludedFiles() )
        {
            String fileEncoding = getEncoding( encoding, new File( basedir, file ), log );
            if ( log.isDebugEnabled() )
            {
                log.debug( file + "==>" + fileEncoding );
            }
            if ( fileEncoding != null && !acceptedEncodings.contains( fileEncoding ) )
            {
                filesInMsg.append( file );
                filesInMsg.append( "==>" );
                filesInMsg.append( fileEncoding );
                filesInMsg.append( "\n" );
                if ( failFast )
                {
                    throw new EnforcerRuleException( filesInMsg.toString() );
                }
            }
        }
        if ( filesInMsg.length() > 0 )
        {
            throw new EnforcerRuleException( "Files not encoded in " + encoding + ":\n" + filesInMsg );
        }
    }
    catch ( IOException ex )
    {
        throw new EnforcerRuleException( "Reading Files", ex );
    }
    catch ( ExpressionEvaluationException e )
    {
        throw new EnforcerRuleException( "Unable to lookup an expression " + e.getLocalizedMessage(), e );
    }
}
 
Example 15
Source File: NativeSources.java    From maven-native with MIT License 4 votes vote down vote up
public List<File> getFiles()
{
    String[] filePaths = new String[0];

    if ( includes != null || excludes != null )
    {
        DirectoryScanner scanner = new DirectoryScanner();
        scanner.setBasedir( this.directory );
        scanner.setIncludes( includes );
        scanner.setExcludes( excludes );
        scanner.addDefaultExcludes();

        scanner.scan();

        filePaths = scanner.getIncludedFiles();
    }

    List<File> files = new ArrayList<>( filePaths.length + this.fileNames.length );
    for ( int i = 0; i < filePaths.length; ++i )
    {
        files.add( new File( this.directory, filePaths[i] ) );
    }

    // remove duplicate files
    for ( int i = 0; i < this.fileNames.length; ++i )
    {
        File file = new File( this.directory, this.fileNames[i] );

        boolean found = false;

        for ( int k = 0; k < filePaths.length; ++k )
        {
            if ( files.get( k ).equals( file ) )
            {
                found = true;
                break;
            }
        }

        if ( !found )
        {
            files.add( file );
        }
    }

    return files;

}