Java Code Examples for org.codehaus.plexus.util.DirectoryScanner

The following examples show how to use org.codehaus.plexus.util.DirectoryScanner. These examples are extracted from open source projects. 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 Project: vertx-maven-plugin   Source File: AbstractRunMojo.java    License: Apache License 2.0 6 votes vote down vote up
private File lookForConfiguration(String filename) {
    File confBaseDir = new File(project.getBasedir(), DEFAULT_CONF_DIR);
    if (!confBaseDir.isDirectory()) {
        return null;
    }
    DirectoryScanner directoryScanner = new DirectoryScanner();
    directoryScanner.setBasedir(confBaseDir);
    String[] includes = Stream.concat(Stream.of(JSON_EXTENSION), YAML_EXTENSIONS.stream())
        .map(ext -> filename + ext)
        .toArray(String[]::new);
    directoryScanner.setIncludes(includes);
    directoryScanner.scan();
    return Arrays.stream(directoryScanner.getIncludedFiles())
        .map(found -> new File(confBaseDir, found))
        .findFirst()
        .orElse(null);
}
 
Example 2
Source Project: impsort-maven-plugin   Source File: AbstractImpSortMojo.java    License: 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 3
public File[] getFiles(final File basedir) {
    final DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(basedir);
    if (includes != null && includes.length > 0) {
        ds.setIncludes(includes);
    }
    if (excludes != null && excludes.length > 0) {
        ds.setExcludes(excludes);
    }
    ds.scan();
    final String[] filePaths = ds.getIncludedFiles();
    final File[] files = new File[filePaths.length];

    for (int i = 0; i < filePaths.length; i++) {
        files[i] = new File(basedir, filePaths[i]);
    }

    return files;
}
 
Example 4
private String scanBootclasspath(String javaHome, String[] includes, String[] excludes) {
	getLog().debug(
			"Scanning bootClassPath:\n" + "\tjavaHome = " + javaHome + "\n" + "\tincludes = "
					+ Arrays.toString(includes) + "\n" + "\texcludes = " + Arrays.toString(excludes));
	DirectoryScanner scanner = new DirectoryScanner();
	scanner.setBasedir(new File(javaHome));
	scanner.setIncludes(includes);
	scanner.setExcludes(excludes);
	scanner.scan();

	StringBuilder bootClassPath = new StringBuilder();
	String[] includedFiles = scanner.getIncludedFiles();
	for (int i = 0; i < includedFiles.length; i++) {
		if (i > 0) {
			bootClassPath.append(File.pathSeparator);
		}
		bootClassPath.append(new File(javaHome, includedFiles[i]).getAbsolutePath());
	}
	return bootClassPath.toString();
}
 
Example 5
Source Project: formatter-maven-plugin   Source File: FormatterMojo.java    License: 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 6
Source Project: webstart   Source File: DefaultIOUtil.java    License: MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void copyResources( File sourceDirectory, File targetDirectory )
        throws MojoExecutionException
{
    if ( !sourceDirectory.exists() )
    {
        getLogger().info( "Directory does not exist " + sourceDirectory.getAbsolutePath() );
    }
    else
    {
        if ( !sourceDirectory.isDirectory() )
        {
            getLogger().debug( "Not a directory: " + sourceDirectory.getAbsolutePath() );
        }
        else
        {
            getLogger().debug( "Copying resources from " + sourceDirectory.getAbsolutePath() );

            // this may needs to be parametrized somehow
            String excludes = concat( DirectoryScanner.DEFAULTEXCLUDES, ", " );
            copyDirectoryStructure( sourceDirectory, targetDirectory, "**", excludes );
        }

    }
}
 
Example 7
Source Project: rice   Source File: ThemeBuilderUtils.java    License: 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 8
/**
 * 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 9
Source Project: wisdom   Source File: ProjectScanner.java    License: 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 10
Source Project: wisdom   Source File: ProjectScanner.java    License: 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 11
Source Project: spring-javaformat   Source File: FormatMojo.java    License: 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 12
Source Project: netbeans   Source File: MainClassesCoSSkipper.java    License: 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 13
Source Project: netbeans   Source File: FilteredResourcesCoSSkipper.java    License: 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 14
Source Project: netbeans   Source File: ExecutionChecker.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void executionResult(RunConfig config, ExecutionContext res, int resultCode) {

    if (NbmActionGoalProvider.NBMRELOAD.equals(config.getActionName()) && resultCode == 0) {
        DirectoryScanner scanner = new DirectoryScanner();
        NbMavenProject prj = project.getLookup().lookup(NbMavenProject.class);
        File basedir = new File(prj.getMavenProject().getBuild().getDirectory(), "nbm"); //NOI18N
        scanner.setBasedir(basedir);
        scanner.setIncludes(new String[]{
                    "**/modules/*.jar", //NOI18N
                    "**/modules/eager/*.jar", //NOI18N
                    "**/modules/autoload/*.jar" //NOI18N
                });
        scanner.scan();
        String[] incl = scanner.getIncludedFiles();
        if (incl != null && incl.length > 0) {
            if (incl[0].indexOf("eager") > -1 || incl[0].indexOf("autoload") > -1) { //NOI18N
                res.getInputOutput().getErr().println("NetBeans: Cannot reload 'autoload' or 'eager' modules.");
            }
            try {
                res.getInputOutput().getOut().println("NetBeans: Deploying NBM module in development IDE...");
                TestModuleDeployer.deployTestModule(FileUtil.normalizeFile(new File(basedir, incl[0])));
            } catch (IOException ex) {
                res.getInputOutput().getOut().println("NetBeans: Error redeploying NBM module in development IDE.");
                Logger.getLogger(ExecutionChecker.class.getName()).log(Level.INFO, "Error reloading netbeans module in development IDE.", ex); //NOI18N
            }
        } else {
            res.getInputOutput().getErr().println("NetBeans: Cannot find any built NetBeans Module artifacts for reload.");
        }

    }
}
 
Example 15
Source Project: eclipse.jdt.ls   Source File: ProjectUtils.java    License: 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 16
Source Project: nexus-public   Source File: ClassDefScannerTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private List<ClassDef> scan(final File basedir) throws Exception {
  DirectoryScanner files = new DirectoryScanner();
  files.setBasedir(basedir);
  files.setIncludes(new String[]{"**/*.js"});

  List<ClassDef> classes = scanner.scan(files);
  log("Classes:");
  for (ClassDef def : classes) {
    log("  {} [priority: {}]", def.getName(), def.getPriority());
    for (String dep : def.getDependencies()) {
      log("    + {}", dep);
    }
  }
  return classes;
}
 
Example 17
Source Project: tcases   Source File: ApiTestMojoTest.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the set of paths relative to the given base directory matching any of the given patterns.
 */
private String[] findPathsMatching( File baseDir, String... patterns)
  {
  DirectoryScanner scanner = new DirectoryScanner();
  scanner.setBasedir( baseDir);
  scanner.setIncludes( patterns);
  scanner.scan();
  return scanner.getIncludedFiles();
  }
 
Example 18
Source Project: tcases   Source File: ApiMojoTest.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the set of paths relative to the given base directory matching any of the given patterns.
 */
private String[] findPathsMatching( File baseDir, String... patterns)
  {
  DirectoryScanner scanner = new DirectoryScanner();
  scanner.setBasedir( baseDir);
  scanner.setIncludes( patterns);
  scanner.scan();
  return scanner.getIncludedFiles();
  }
 
Example 19
Source Project: tcases   Source File: TcasesMojoTest.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the set of paths relative to the given base directory matching any of the given patterns.
 */
private String[] findPathsMatching( File baseDir, String... patterns)
  {
  DirectoryScanner scanner = new DirectoryScanner();
  scanner.setBasedir( baseDir);
  scanner.setIncludes( patterns);
  scanner.scan();
  return scanner.getIncludedFiles();
  }
 
Example 20
Source Project: tcases   Source File: ReducerMojoTest.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the set of paths relative to the given base directory matching any of the given patterns.
 */
private String[] findPathsMatching( File baseDir, String... patterns)
  {
  DirectoryScanner scanner = new DirectoryScanner();
  scanner.setBasedir( baseDir);
  scanner.setIncludes( patterns);
  scanner.scan();
  return scanner.getIncludedFiles();
  }
 
Example 21
Source Project: xml-maven-plugin   Source File: AbstractXmlMojo.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Scans a directory for files and returns a set of path names.
 */
protected String[] getFileNames( File pDir, String[] pIncludes, String[] pExcludes )
    throws MojoFailureException, MojoExecutionException
{
    if ( pDir == null )
    {
        throw new MojoFailureException( "A ValidationSet or TransformationSet"
            + " requires a nonempty 'dir' child element." );
    }
    final File dir = asAbsoluteFile( pDir );
    if ( !dir.isDirectory() )
    {
        throw new MojoExecutionException("The directory " + dir.getPath()
            + ", which is a base directory of a ValidationSet or TransformationSet, does not exist.");
    }
    final DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir( dir );
    if ( pIncludes != null && pIncludes.length > 0 )
    {
        ds.setIncludes( pIncludes );
    }
    if ( pExcludes != null && pExcludes.length > 0 )
    {
        ds.setExcludes( pExcludes );
    }
    ds.scan();
    return ds.getIncludedFiles();
}
 
Example 22
Source Project: xml-maven-plugin   Source File: CheckFormatMojo.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * A {@link DirectoryScanner} boiler plate.
 *
 * @param fileSet {@link FileSet} to scan
 * @return the included paths
 */
private String[] scan( FileSet fileSet )
{
    File basedir = new File( fileSet.getDirectory() );
    if ( !basedir.exists() || !basedir.isDirectory() )
    {
        return null;
    }

    DirectoryScanner scanner = new DirectoryScanner();

    List<String> includes = fileSet.getIncludes();
    List<String> excludes = fileSet.getExcludes();

    if ( includes != null && includes.size() > 0 )
    {
        scanner.setIncludes( includes.toArray( new String[0] ) );
    }

    if ( excludes != null && excludes.size() > 0 )
    {
        scanner.setExcludes( excludes.toArray( new String[0] ) );
    }

    scanner.setBasedir( basedir );

    scanner.scan();
    return scanner.getIncludedFiles();
}
 
Example 23
Source Project: maven-jaxb2-plugin   Source File: IOUtils.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Scans given directory for files satisfying given inclusion/exclusion
 * patterns.
 * 
 * @param buildContext
 *            Build context provided by the environment, used to scan for files.
 * @param directory
 *            Directory to scan.
 * @param includes
 *            inclusion pattern.
 * @param excludes
 *            exclusion pattern.
 * @param defaultExcludes
 *            default exclusion flag.
 * @return Files from the given directory which satisfy given patterns. The
 *         files are {@link File#getCanonicalFile() canonical}.
 * @throws IOException
 *             If an I/O error occurs, which is possible because the
 *             construction of the canonical pathname may require filesystem
 *             queries.
 */
public static List<File> scanDirectoryForFiles(BuildContext buildContext, final File directory,
		final String[] includes, final String[] excludes, boolean defaultExcludes) throws IOException {
	if (!directory.exists()) {
		return Collections.emptyList();
	}
	final Scanner scanner;

	if (buildContext != null) {
		scanner = buildContext.newScanner(directory, true);
	} else {
		final DirectoryScanner directoryScanner = new DirectoryScanner();
		directoryScanner.setBasedir(directory.getAbsoluteFile());
		scanner = directoryScanner;
	}
	scanner.setIncludes(includes);
	scanner.setExcludes(excludes);
	if (defaultExcludes) {
		scanner.addDefaultExcludes();
	}

	scanner.scan();

	final List<File> files = new ArrayList<File>();
	for (final String name : scanner.getIncludedFiles()) {
		files.add(new File(directory, name).getCanonicalFile());
	}

	return files;
}
 
Example 24
Source Project: twirl-maven-plugin   Source File: CompileMojo.java    License: 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 25
Source Project: rice   Source File: ThemeBuilderUtils.java    License: 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 26
Source Project: rice   Source File: ThemeBuilderUtils.java    License: Educational Community License v2.0 5 votes vote down vote up
/**
 * Copies all the contents from the directory given by the source path to the directory given by the
 * target path
 *
 * <p>
 * If source directory does not exist nothing is performed. The target directory will be created if it
 * does not exist. Any hidden directories (directory names that start with ".") will be deleted from the
 * target directory
 * </p>
 *
 * @param sourceDirectoryPath absolute path to the source directory
 * @param targetDirectoryPath absolute path to the target directory
 * @throws IOException
 */
public static void copyDirectory(String sourceDirectoryPath, String targetDirectoryPath)
        throws IOException {
    File sourceDir = new File(sourceDirectoryPath);

    if (!sourceDir.exists()) {
        return;
    }

    File targetDir = new File(targetDirectoryPath);
    if (targetDir.exists()) {
        // force removal so the copy starts clean
        FileUtils.forceDelete(targetDir);
    }

    targetDir.mkdir();

    FileUtils.copyDirectoryStructure(sourceDir, targetDir);

    // remove hidden directories from the target
    DirectoryScanner scanner = new DirectoryScanner();
    scanner.setBasedir(targetDir);

    scanner.scan();

    for (String includedDirectory : scanner.getIncludedDirectories()) {
        File subdirectory = new File(targetDir, includedDirectory);

        if (subdirectory.exists() && subdirectory.isDirectory()) {
            if (subdirectory.getName().startsWith(".")) {
                FileUtils.forceDelete(subdirectory);
            }
        }
    }
}
 
Example 27
Source Project: opoopress   Source File: GitHub.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get matching paths found in given base directory
 *
 * @param includes
 * @param excludes
 * @param baseDir
 * @return non-null but possibly empty array of string paths relative to the
 *         base directory
 */
public static String[] getMatchingPaths(final String[] includes,
		final String[] excludes, final String baseDir) {
	DirectoryScanner scanner = new DirectoryScanner();
	scanner.setBasedir(baseDir);
	if (includes != null && includes.length > 0){
		scanner.setIncludes(includes);
	}
	if (excludes != null && excludes.length > 0){
		scanner.setExcludes(excludes);
	}
	scanner.scan();
	return scanner.getIncludedFiles();
}
 
Example 28
private ArtifactFile newDirectoryArtifact(File directory, ArtifactFile previousArtifact) {
  StringBuilder msg = new StringBuilder();
  DirectoryScanner scanner = new DirectoryScanner();
  scanner.setBasedir(directory);
  scanner.setIncludes(new String[] {"**/*"});
  scanner.scan();
  long maxLastModified = 0, fileCount = 0;
  for (String path : scanner.getIncludedFiles()) {
    File file = new File(directory, path);
    long lastModified = file.lastModified();
    maxLastModified = Math.max(maxLastModified, lastModified);
    fileCount++;
    if (previousArtifact != null && previousArtifact.lastModified < lastModified) {
      msg.append("\n   new or modfied class folder member ").append(file);
    }
  }

  if (previousArtifact != null && previousArtifact.length != fileCount) {
    msg.append("\n   classfolder member count changed (new ").append(fileCount).append(" previous ").append(previousArtifact.length).append(')');
  }

  if (msg.length() > 0) {
    log.debug("Changed dependency class folder {}: {}", directory, msg.toString());
  }

  return new ArtifactFile(directory, false, fileCount, maxLastModified);
}
 
Example 29
Source Project: netbeans   Source File: CopyResourcesOnSave.java    License: Apache License 2.0 4 votes vote down vote up
private Tuple findResource(List<Resource> resources, Project prj, NbMavenProject nbproj, FileObject child, boolean test) {
    LOG.log(Level.FINE, "findResource for {0}", child.getPath());        
    if (resources == null) {
        LOG.log(Level.FINE, "findResource for {0} : No Resources", child.getPath());
        return null;
    }
    FileObject target;
    //now figure the destination output folder
    File fil = nbproj.getOutputDirectory(test);
    File stamp = new File(fil, CosChecker.NB_COS);
    if (stamp.exists()) {
        target = FileUtil.toFileObject(fil);
    } else {
        LOG.log(Level.FINE, "findResource for {0} : No Stamp", child.getPath());
        // no compile on save stamp, means no copying, classes don't get copied/compiled either.
        return null;
    }
    
    logResources(child, resources);

    resourceLoop:
    for (Resource res : resources) {
        String dir = res.getDirectory();
        if (dir == null) {
            continue;
        }
        URI uri = FileUtilities.getDirURI(prj.getProjectDirectory(), dir);
        FileObject fo = FileUtil.toFileObject(Utilities.toFile(uri));
        if (fo != null && FileUtil.isParentOf(fo, child)) {
            String path = FileUtil.getRelativePath(fo, child);
            //now check includes and excludes
            List<String> incls = res.getIncludes();
            if (incls.isEmpty()) {
                incls = Arrays.asList(FilteredResourcesCoSSkipper.DEFAULT_INCLUDES);
            }
            boolean included = false;
            for (String incl : incls) {
                if (DirectoryScanner.match(incl, path)) {
                    included = true;
                    break;
                }
            }
            if (!included) {
                LOG.log(Level.FINE, "findResource for {0} : Not included {1}, {2} ", new Object[] {child.getPath(), included, res});
                if(res.isFiltering()) {
                    continue;
                } else {
                    break; 
                }
            }
            List<String> excls = new ArrayList<String>(res.getExcludes());
            excls.addAll(Arrays.asList(DirectoryScanner.DEFAULTEXCLUDES));
            for (String excl : excls) {
                if (DirectoryScanner.match(excl, path)) {
                    LOG.log(Level.FINER, "findResource for {0} : Excluded {1}, {2} ", new Object[] {child.getPath(), included, res});
                    continue resourceLoop;
                }
            }
            LOG.log(Level.FINE, "findResource for {0} : Returns {1}, {2}, {3} ", new Object[] {child.getPath(), res, fo.getPath(), target});
            return new Tuple(res, fo, target);
        } else {
            LOG.log(Level.FINE, "findResource {0} does not apply to file {1}", new Object[]{res, child.getPath()});
        }
    }
    LOG.log(Level.FINE, "findResource for {0} : Retuerns Null", child.getPath());
    return null;
}
 
Example 30
@Override
public void run()  throws  Exception {
    final ProgressLogger progress = startProgress("Prepare sources");

    final GolangSettings settings = getGolang();
    final BuildSettings build = getBuild();
    boolean atLeastOneCopied = false;
    if (!FALSE.equals(build.getUseTemporaryGopath())) {
        final Path gopath = build.getFirstGopath();
        progress.progress("Prepare GOPATH " + gopath + "...");
        LOGGER.info("Prepare GOPATH ({})...", gopath);
        final Path projectBasedir = settings.getProjectBasedir();
        final Path packagePath = settings.packagePathFor(gopath);
        final Path dependencyCachePath = getDependencies().getDependencyCache();
        prepareDependencyCacheIfNeeded(packagePath, dependencyCachePath);

        final DirectoryScanner scanner = new DirectoryScanner();
        scanner.setBasedir(projectBasedir.toFile());
        scanner.setIncludes(build.getIncludes());
        scanner.setExcludes(build.getExcludes());
        scanner.setCaseSensitive(true);
        scanner.scan();
        for (final String file : scanner.getIncludedFiles()) {
            final Path sourceFile = projectBasedir.resolve(file);
            final Path targetFile = packagePath.resolve(file);
            if (!sourceFile.equals(dependencyCachePath)) {
                if (!exists(targetFile)
                    || size(sourceFile) != size(targetFile)
                    || !getLastModifiedTime(sourceFile).equals(getLastModifiedTime(targetFile))) {
                    atLeastOneCopied = true;
                    progress.progress("Prepare source file: " + file + "...");
                    LOGGER.debug("* {}", file);
                    ensureParentOf(targetFile);
                    try (final InputStream is = newInputStream(sourceFile)) {
                        try (final OutputStream os = newOutputStream(targetFile)) {
                            IOUtils.copy(is, os);
                        }
                    }
                    setLastModifiedTime(targetFile, getLastModifiedTime(sourceFile));
                }
            }
        }
        if (!atLeastOneCopied) {
            getState().setOutcome(UP_TO_DATE);
        }
    } else {
        getState().setOutcome(SKIPPED);
    }

    progress.completed();
}