org.apache.commons.io.filefilter.WildcardFileFilter Java Examples

The following examples show how to use org.apache.commons.io.filefilter.WildcardFileFilter. 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: MockFileFinder.java    From synopsys-detect with Apache License 2.0 7 votes vote down vote up
@Override
public List<File> findFiles(final File directoryToSearch, final List<String> filenamePatterns, final int depth, boolean findInsideMatchingDirectories) {
    List<File> found = new ArrayList<>();
    for (int i = 0; i <= depth; i++) {
        if (files.containsKey(i)) {
            List<File> possibles = files.get(i);
            for (String pattern : filenamePatterns) {
                FileFilter fileFilter = new WildcardFileFilter(pattern);
                for (File possible : possibles) {
                    if (fileFilter.accept(possible)) {
                        found.add(possible);
                    }
                }

            }
        }
    }
    return found;
}
 
Example #2
Source File: FlagMaker.java    From datawave with Apache License 2.0 7 votes vote down vote up
/**
 * Determine the number of unprocessed flag files in the flag directory
 * 
 * @param fc
 * @return the flag found for this ingest pool
 */
private int countFlagFileBacklog(final FlagDataTypeConfig fc) {
    final MutableInt fileCounter = new MutableInt(0);
    final FileFilter fileFilter = new WildcardFileFilter("*_" + fc.getIngestPool() + "_" + fc.getDataName() + "_*.flag");
    final FileVisitor<java.nio.file.Path> visitor = new SimpleFileVisitor<java.nio.file.Path>() {
        
        @Override
        public FileVisitResult visitFile(java.nio.file.Path path, BasicFileAttributes attrs) throws IOException {
            if (fileFilter.accept(path.toFile())) {
                fileCounter.increment();
            }
            return super.visitFile(path, attrs);
        }
    };
    try {
        Files.walkFileTree(Paths.get(fmc.getFlagFileDirectory()), visitor);
    } catch (IOException e) {
        // unable to get a flag count....
        log.error("Unable to get flag file count", e);
        return -1;
    }
    return fileCounter.intValue();
}
 
Example #3
Source File: FileDAO.java    From MtgDesktopCompanion with GNU General Public License v3.0 6 votes vote down vote up
@Override
public List<MagicCardStock> listStocks(MagicCard mc, MagicCollection col,boolean editionStrict) throws SQLException {
	List<MagicCardStock> st = new ArrayList<>();
	File f = new File(directory, STOCKDIR);
	for (File fstock : FileUtils.listFiles(f, new WildcardFileFilter("*" + IDGenerator.generate(mc)),TrueFileFilter.INSTANCE)) {
		try {
			MagicCardStock s = read(MagicCardStock.class, fstock);
			if (s.getMagicCollection().getName().equals(col.getName()))
				st.add(s);

		} catch (Exception e) {
			throw new SQLException(e);
		}
	}

	return st;
}
 
Example #4
Source File: NodeAgent.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private void customJar(String simpleName, byte[] bytes) throws Exception {
	File jar = new File(Config.dir_custom_jars(true), simpleName + ".jar");
	FileUtils.writeByteArrayToFile(jar, bytes, false);
	List<String> contexts = new ArrayList<>();
	for (String s : Config.dir_custom().list(new WildcardFileFilter("*.war"))) {
		contexts.add("/" + FilenameUtils.getBaseName(s));
	}
	if (Servers.applicationServerIsRunning()) {
		GzipHandler gzipHandler = (GzipHandler) Servers.applicationServer.getHandler();
		HandlerList hanlderList = (HandlerList) gzipHandler.getHandler();
		for (Handler handler : hanlderList.getHandlers()) {
			if (QuickStartWebApp.class.isAssignableFrom(handler.getClass())) {
				QuickStartWebApp app = (QuickStartWebApp) handler;
				if (contexts.contains(app.getContextPath())) {
					app.stop();
					Thread.sleep(2000);
					app.start();
				}
			}
		}
	}
}
 
Example #5
Source File: SpoonMojoTest.java    From spoon-maven-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testSpoonCheckGoalWithTest() throws Exception {
	File basedir = resources.getBasedir("hello-world-with-test");
	rule.executeMojo(basedir, "check");

	final File dirOutputResults = new File(basedir, "target/spoon-maven-plugin");
	assertThat(dirOutputResults).exists();

	final File contentSource = new File(basedir, "target/generated-sources/spoon/fr/inria/gforge/spoon");
	assertThat(contentSource).doesNotExist();

	final WildcardFileFilter filter = new WildcardFileFilter("result-spoon-*.xml");
	final File[] files = dirOutputResults.listFiles((FileFilter) filter);
	assertThat(files.length).isEqualTo(1);
	assertThat(files[0].getName()).startsWith("result-spoon");
}
 
Example #6
Source File: MetaModelBuilder.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private static List<File> classpath(File o2oadir, File outputdir) {
	List<File> cp = new ArrayList<>();

	cp.add(outputdir);

	IOFileFilter filter = new WildcardFileFilter("x_base_core_project.jar");
	for (File o : FileUtils.listFiles(new File(o2oadir, "o2server/store/jars"), filter, null)) {
		cp.add(o);
	}

	ClassLoader cl = MetaModelBuilder.class.getClassLoader();

	URL[] urls = ((URLClassLoader) cl).getURLs();

	for (URL url : urls) {
		cp.add(new File(url.getFile()));
	}
	return cp;
}
 
Example #7
Source File: SpoonMojoTest.java    From spoon-maven-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testSpoonGoalWithCustomPConfiguration() throws Exception {
	File basedir = resources.getBasedir("custom-configuration");
	rule.executeMojo(basedir, "generate");

	final File dirOutputResults = new File(basedir, "target/spoon-maven-plugin");
	assertThat(dirOutputResults).exists();

	final WildcardFileFilter filter = new WildcardFileFilter("result-spoon-*.xml");
	final File[] files = dirOutputResults.listFiles((FileFilter) filter);
	assertThat(files.length).isEqualTo(1);
	assertThat(files[0].getName()).startsWith("result-spoon");

	File generateFiles = new File(basedir, "target/generate-source-with-spoon");
	assertThat(generateFiles).exists();
}
 
Example #8
Source File: ImportTestAction.java    From apimanager-swagger-promote with Apache License 2.0 6 votes vote down vote up
private void copyImagesAndCertificates(String origConfigFile, TestContext context) {
	File sourceDir = new File(origConfigFile).getParentFile();
	if(!sourceDir.exists()) {
		sourceDir = new File(ImportTestAction.class.getResource(origConfigFile).getFile()).getParentFile();
		if(!sourceDir.exists()) { 
			return;
		}
	}
	FileFilter filter = new WildcardFileFilter(new String[] {"*.crt", "*.jpg", "*.png", "*.pem"});
	try {
		LOG.info("Copy certificates and images from source: "+sourceDir+" into test-dir: '"+testDir+"'");
		FileUtils.copyDirectory(sourceDir, testDir, filter);
	} catch (IOException e) {

	}
}
 
Example #9
Source File: ResourceUtils.java    From elasticsearch-pool with Apache License 2.0 6 votes vote down vote up
private static URL[] load3(String locationPattern) throws MalformedURLException {
    if (StringUtils.contains(locationPattern, PunctuationConstants.STAR.getValue())
            || StringUtils.contains(locationPattern, PunctuationConstants.QUESTION_MARK.getValue())) {
        String directoryPath = StringUtils.substringBeforeLast(locationPattern,
                ResourceConstants.FOLDER_SEPARATOR.getValue());
        directoryPath = StringUtils.substringAfter(directoryPath, ResourceConstants.FILE_URL_PREFIX.getValue());
        File directory = new File(directoryPath);
        String filePattern = StringUtils.substringAfter(locationPattern,
                ResourceConstants.FOLDER_SEPARATOR.getValue());
        while (filePattern.contains(ResourceConstants.FOLDER_SEPARATOR.getValue())) {
            filePattern = StringUtils.substringAfter(filePattern, ResourceConstants.FOLDER_SEPARATOR.getValue());
        }

        Set<URL> result = new LinkedHashSet<URL>(16);
        Iterator<File> iterator = FileUtils.iterateFiles(directory, new WildcardFileFilter(filePattern), null);
        while (iterator.hasNext()) {
            result.add(iterator.next().toURI().toURL());
        }

        return result.toArray(new URL[result.size()]);
    } else {
        // a single resource with the given name
        URL url = new URL(locationPattern);
        return new File(url.getFile()).exists() ? new URL[] { url } : null;
    }
}
 
Example #10
Source File: SpoonMojoTest.java    From spoon-maven-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testSpoonGoalWithAProcessor() throws Exception {
	File basedir = resources.getBasedir("processor");
	rule.executeMojo(basedir, "generate");

	final File dirOutputResults = new File(basedir, "target/spoon-maven-plugin");
	assertThat(dirOutputResults).exists();

	final WildcardFileFilter filter = new WildcardFileFilter("result-spoon-*.xml");
	final File[] files = dirOutputResults.listFiles((FileFilter) filter);
	assertThat(files.length).isEqualTo(1);
	assertThat(files[0].getName()).startsWith("result-spoon");

	final File resultFileProcessor = new File(basedir, "target/spoon-maven-plugin/spoon-nb-statement.txt");
	assertThat(resultFileProcessor).exists();
}
 
Example #11
Source File: FileUtils.java    From neural-style-gui with GNU General Public License v3.0 6 votes vote down vote up
public static File[] getTempOutputImageIterations(File outputImage) {
    // Unix-like searching for image iterations
    String outputImageBase = getFileName(outputImage);
    FileFilter fileFilter = new WildcardFileFilter(String.format("%s_*.png", outputImageBase));
    File[] files = NeuralStyleWrapper.getWorkingFolder().listFiles(fileFilter);

    // sort the files by the iteration progress
    if (files != null && files.length > 1) {
        int[] fileIters = new int[files.length];
        for (int i = 0; i < files.length; i++)
            fileIters[i] = FileUtils.parseImageIteration(files[i]);
        FileUtils.quickSort(fileIters, files, 0, files.length - 1);

        // if the latest file was still being written to during the check
        // then replace it with the previous file (set will remove it)
        if (isFileBeingWritten(files[files.length - 1]))
            files[files.length - 1] = files[files.length - 2];
    }

    return files;
}
 
Example #12
Source File: TestSigmet.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Parameterized.Parameters(name = "{0}")
public static Collection<Object[]> getTestParameters() throws IOException {
  final Collection<Object[]> filenames = new ArrayList<>();

  try {
    TestDir.actOnAll(TestDir.cdmUnitTestDir + "formats/sigmet/", new WildcardFileFilter("*IRIS"), new TestDir.Act() {
      public int doAct(String filename) throws IOException {
        filenames.add(new Object[] {filename});
        return 1;
      }
    }, true);
  } catch (IOException e) {
    // JUnit *always* executes a test class's @Parameters method, even if it won't subsequently run the class's tests
    // due to an @Category exclusion. Therefore, we must not let it throw an exception, or else we'll get a build
    // failure. Instead, we return a collection containing a nonsense value (to wit, the exception message).
    //
    // Naturally, if we execute a test using that nonsense value, it'll fail. That's fine; we need to deal with the
    // root cause. However, it is more likely that the exception occurred because "!isCdmUnitTestDirAvailable", and
    // as a result, all NeedsCdmUnitTest tests will be excluded.
    filenames.add(new Object[] {e.getMessage()});
  }

  return filenames;
}
 
Example #13
Source File: CommandLineHelper.java    From robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Given a wildcard pattern as string, return an array of files matching that pattern.
 *
 * @param pattern wildcard pattern to match
 * @return array of files
 * @throws IllegalArgumentException on bad pattern
 */
private static File[] getFilesByPattern(String pattern) throws IllegalArgumentException {
  if (!pattern.contains("*") && !pattern.contains("?")) {
    throw new IllegalArgumentException(wildcardError);
  }
  FileFilter fileFilter = new WildcardFileFilter(pattern);
  File[] files = new File(".").listFiles(fileFilter);
  if (files == null || files.length < 1) {
    // Warn user, but continue (empty input checked later)
    logger.error("No files match pattern: {}", pattern);
  }
  return files;
}
 
Example #14
Source File: CoprocessorJarUtils.java    From eagle with Apache License 2.0 5 votes vote down vote up
public static File getCoprocessorJarFile() {
    String projectRootDir = System.getProperty("user.dir");
    String targetDirPath = projectRootDir + "/target/";
    File targetDirFile = new File(targetDirPath);
    if (!targetDirFile.exists()) {
        throw new IllegalStateException(targetDirPath + " not found, please execute 'mvn install -DskipTests' under " + projectRootDir + " to build the project firstly and retry");
    }
    String jarFileNameWildCard = "eagle-storage-hbase-*-coprocessor.jar";
    Collection<File> jarFiles = FileUtils.listFiles(targetDirFile, new WildcardFileFilter(jarFileNameWildCard), TrueFileFilter.INSTANCE);
    if (jarFiles.size() == 0) {
        throw new IllegalStateException("jar is not found, please execute 'mvn package -DskipTests' from project root firstly and retry");
    }
    return jarFiles.iterator().next();
}
 
Example #15
Source File: ViewLogFileAction.java    From oxTrust with MIT License 5 votes vote down vote up
private Map<Integer, String> prepareLogFiles() {
	Map<Integer, String> logFiles = new HashMap<Integer, String>();

	int fileIndex = 0;
	for (SimpleCustomProperty logTemplate : this.logViewerConfiguration.getLogTemplates()) {
		String logTemplatePattern = logTemplate.getValue2();
		if (StringHelper.isEmpty(logTemplatePattern)) {
			continue;
		}

		String logTemplatePath = FilenameUtils.getFullPath(logTemplatePattern);
		String logTemplateFile = FilenameUtils.getName(logTemplatePattern);

		File logTemplateBaseDir = new File(logTemplatePath);

		FileFilter fileFilter = new AndFileFilter(FileFileFilter.FILE, new WildcardFileFilter(logTemplateFile));
		File[] files = logTemplateBaseDir.listFiles(fileFilter);
		if (files == null) {
			continue;
		}

		for (int i = 0; i < files.length; i++) {
			logFiles.put(fileIndex++, files[i].getPath());
		}
	}

	return logFiles;
}
 
Example #16
Source File: AbstractHerokuDeployMojo.java    From heroku-maven-plugin with MIT License 5 votes vote down vote up
private List<Path> resolveIncludePattern(String includePattern) {
    if (includePattern.contains("*")) {
        String[] dirs = includePattern.split(File.separator);
        String pattern = dirs[dirs.length - 1];
        File basedir = new File(mavenProject.getBasedir(), includePattern.replace(pattern, ""));

        return FileUtils
                .listFiles(basedir, new WildcardFileFilter(pattern), null)
                .stream()
                .map(File::toPath)
                .collect(Collectors.toList());
    } else {
        return Collections.singletonList(mavenProject.getBasedir().toPath().resolve(includePattern));
    }
}
 
Example #17
Source File: MavenRepositoryDeployer.java    From maven-repository-tools with Eclipse Public License 1.0 5 votes vote down vote up
public static Collection<File> getPomFiles( File repoPath )
{
    Collection<File> pomFiles = new ArrayList<File>();
    Collection<File> leafDirectories = getLeafDirectories( repoPath );
    for ( File leafDirectory : leafDirectories )
    {
        IOFileFilter fileFilter = new AndFileFilter( new WildcardFileFilter( "*.pom" ),
                                           new NotFileFilter( new SuffixFileFilter( "sha1" ) ) );
        pomFiles.addAll( FileUtils.listFiles( leafDirectory, fileFilter, null ) );
    }
    return pomFiles;
}
 
Example #18
Source File: GatewayBasicFuncTest.java    From knox with Apache License 2.0 5 votes vote down vote up
private File findFile( File dir, String pattern ) {
  File file = null;
  FileFilter filter = new WildcardFileFilter( pattern );
  File[] files = dir.listFiles(filter);
  if( files != null && files.length > 0 ) {
    file = files[0];
  }
  return file;
}
 
Example #19
Source File: CacheRefreshSnapshotFileService.java    From oxTrust with MIT License 5 votes vote down vote up
private String[] getSnapshotsList(CacheRefreshConfiguration cacheRefreshConfiguration) {
	File file = new File(cacheRefreshConfiguration.getSnapshotFolder());
	String[] files = file.list(new WildcardFileFilter(String.format(SNAPSHOT_FILE_NAME_PATTERN, "*")));
	Arrays.sort(files);

	return files;
}
 
Example #20
Source File: WorkflowExecutionDemo.java    From flux with Apache License 2.0 5 votes vote down vote up
/**
 * Does necessary actions to run an example/user's workflow.
 * @param moduleName name of user module in which workflow code is present
 * @param workflowClassFQN fully qualified name of main class which triggers user workflow execution at client side.
 *                         @see com.flipkart.flux.examples.concurrent.RunEmailMarketingWorkflow for example.
 * @param configFileName "flux_config.yml" which contains workflow related configuration.
 *                       @see flux/examples/src/main/resources/flux_config.yml for example.
 * @throws Exception
 */
private static void runExample(String moduleName, String workflowClassFQN, String configFileName, String mavenPath) throws Exception {

    //copy dependencies to module's target directory
    executeCommand(mavenPath+" -pl " + moduleName + " -q package dependency:copy-dependencies -DincludeScope=runtime -DskipTests");

    //get deployment path from configuration.yml
    FileReader reader = new FileReader(WorkflowExecutionDemo.class.getResource("/packaged/configuration.yml").getFile());
    String deploymentUnitsPath = (String) ((Map)new Yaml().load(reader)).get("deploymentUnitsPath");
    if(!deploymentUnitsPath.endsWith("/")) {
        deploymentUnitsPath = deploymentUnitsPath + "/";
    }
    reader.close();

    //create deployment structure
    String deploymentUnitName = "DU1/1";
    String mainDirPath = deploymentUnitsPath + deploymentUnitName + "/main";
    String libDirPath = deploymentUnitsPath + deploymentUnitName + "/lib";
    executeCommand("mkdir -p " + mainDirPath);
    executeCommand("mkdir -p " + libDirPath);

    //copy dependencies to deployment unit
    FileUtils.copyFile(new File(moduleName + "/target/").listFiles((FilenameFilter) new WildcardFileFilter(moduleName + "*.jar"))[0], new File(mainDirPath + "/" + moduleName + ".jar"));
    FileUtils.copyDirectory(new File(moduleName + "/target/dependency"), new File(libDirPath));
    FileUtils.copyFile(new File(moduleName + "/src/main/resources/" + configFileName), new File(deploymentUnitsPath + deploymentUnitName + "/flux_config.yml"));

    //start flux runtime
    FluxInitializer.main(new String[]{});

    //Invoke workflow in separate process, the below system out prints this process's output in blue color
    System.out.println((char)27 + "[34m"+executeCommand("java -cp " + moduleName +"/target/*:" + moduleName + "/target/dependency/* " + workflowClassFQN) + (char)27 + "[0m");
}
 
Example #21
Source File: FileUtils.java    From thym with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Resolves a filename including wildcard characters to files in the 
 * given directory tree. This method recurses in the the subdirectories.
 * @param parent a directory
 * @param filename name for file 
 * @return array of files found matching filename or an empty array 
 */
public static File[] resolveFile(File parent, String filename){
	if(parent == null){
		return new File[0];
	}
	if( !parent.isDirectory() || filename == null || filename.isEmpty() || filename.equals(".")){
		return new File[]{parent};
	}
	File f = new File(parent,filename);
	if(f.exists()){
		return new File[]{f};
	}
	Collection<File> theFiles= org.apache.commons.io.FileUtils.listFiles(parent, new WildcardFileFilter(filename), TrueFileFilter.INSTANCE);
	return theFiles.toArray(new File[theFiles.size()]);
}
 
Example #22
Source File: ImportWorker.java    From magarena with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a filter that returns everything in the "mods" folder except
 * the specified cubes which are distributed with each new release and
 * any existing themes which are now found in the "themes" folder.
 */
private FileFilter getModsFileFilter() {
    final String[] excludedCubes = new String[]{
        "legacy_cube.txt", "modern_cube.txt", "standard_cube.txt", "extended_cube.txt", "ubeefx_cube.txt"
    };
    final IOFileFilter cubesFilter = new NameFileFilter(excludedCubes, IOCase.INSENSITIVE);
    final IOFileFilter excludeCubes = FileFilterUtils.notFileFilter(cubesFilter);
    final IOFileFilter excludeThemes = FileFilterUtils.notFileFilter(new WildcardFileFilter("*_theme*"));
    return FileFilterUtils.and(excludeCubes, excludeThemes);
}
 
Example #23
Source File: InstallerService.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onHandleWork(@NonNull Intent intent) {
    final Apk apk = intent.getParcelableExtra(Installer.EXTRA_APK);
    if (apk == null) {
        return;
    }
    Installer installer = InstallerFactory.create(this, apk);

    if (ACTION_INSTALL.equals(intent.getAction())) {
        Uri uri = intent.getData();
        Uri canonicalUri = intent.getParcelableExtra(org.fdroid.fdroid.net.Downloader.EXTRA_CANONICAL_URL);
        installer.installPackage(uri, canonicalUri);
    } else if (ACTION_UNINSTALL.equals(intent.getAction())) {
        installer.uninstallPackage();
        new Thread() {
            @Override
            public void run() {
                setPriority(MIN_PRIORITY);
                File mainObbFile = apk.getMainObbFile();
                if (mainObbFile == null) {
                    return;
                }
                File obbDir = mainObbFile.getParentFile();
                if (obbDir == null) {
                    return;
                }
                FileFilter filter = new WildcardFileFilter("*.obb");
                File[] obbFiles = obbDir.listFiles(filter);
                if (obbFiles == null) {
                    return;
                }
                for (File f : obbFiles) {
                    Utils.debugLog(TAG, "Uninstalling OBB " + f);
                    FileUtils.deleteQuietly(f);
                }
            }
        }.start();
    }
}
 
Example #24
Source File: CommonsIOUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenGetFilewith_ANDFileFilter_thenFindsampletxt() throws IOException {

    String path = getClass().getClassLoader().getResource("fileTest.txt").getPath();
    File dir = FileUtils.getFile(FilenameUtils.getFullPath(path));

    Assert.assertEquals("sample.txt", dir.list(new AndFileFilter(new WildcardFileFilter("*ple*", IOCase.INSENSITIVE), new SuffixFileFilter("txt")))[0]);
}
 
Example #25
Source File: LockFile.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
public static boolean checkFileExistByPattern(String path, String pattern) {
    if (path == null) {
        path = ".";
    }
    File dir = new File(path);
    FileFilter ff = new WildcardFileFilter(pattern);
    File[] found = dir.listFiles(ff);
    return found != null && found.length > 0;
}
 
Example #26
Source File: TenantProcessorTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testPreLoad() {
    File landingZone = Files.createTempDir();
    try {
        assertTrue(tenantProcessor.preLoad(landingZone.getAbsolutePath(), Arrays.asList("small")));
        assertTrue(landingZone.list(new WildcardFileFilter("preload-*.zip")).length == 1);
    } finally {
        landingZone.delete();
    }
}
 
Example #27
Source File: FilterFilesByExtension.java    From levelup-java-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void filter_files_by_extension () {

	File dir = new File(sourceFileURI);
	FileFilter fileFilter = new WildcardFileFilter("*.txt");
	File[] files = dir.listFiles(fileFilter);

	logger.info(Arrays.toString(files));

	assertTrue(files.length >= 4);
}
 
Example #28
Source File: ModpackDownloaderCLITest.java    From ModPackDownloader with MIT License 5 votes vote down vote up
@Ignore
@Test
public void testAppUpdate() throws InterruptedException {
	String[] args = {"-updateApp"};
	ModpackDownloaderCLI.main(args);
	FileFilter fileFilter = new WildcardFileFilter("ModpackDownloader*jar");
	File directory = new File(".");
	List<File> files = Arrays.asList(directory.listFiles(fileFilter));
	Assert.assertTrue(!CollectionUtils.isEmpty(files));
	files.forEach(File::deleteOnExit);
}
 
Example #29
Source File: ResourceUtils.java    From elasticsearch-pool with Apache License 2.0 5 votes vote down vote up
private static URL[] load2(String locationPattern) throws URISyntaxException, IOException {
    String location = locationPattern.substring(ResourceConstants.CLASSPATH_URL_PREFIX.getValue().length());
    if (location.startsWith(ResourceConstants.FOLDER_SEPARATOR.getValue())) {
        location = location.substring(1);
    }

    String cleanPath = PathUtils.cleanPath(location);
    // 只支持文件的通配符匹配,不支持文件夹的通配符匹配
    // 如需实现文件夹的通配符匹配,请参照spring.utils包,较复杂
    if (StringUtils.contains(cleanPath, PunctuationConstants.STAR.getValue())
            || StringUtils.contains(cleanPath, PunctuationConstants.QUESTION_MARK.getValue())) {
        String directoryPath = StringUtils.substringBeforeLast(locationPattern,
                ResourceConstants.FOLDER_SEPARATOR.getValue());
        File directory = new File(ResourceUtils.loadResource(directoryPath).toURI().getPath());

        String filePattern = StringUtils.substringAfter(cleanPath, ResourceConstants.FOLDER_SEPARATOR.getValue());
        while (filePattern.contains(ResourceConstants.FOLDER_SEPARATOR.getValue())) {
            filePattern = StringUtils.substringAfter(filePattern, ResourceConstants.FOLDER_SEPARATOR.getValue());
        }

        Set<URL> result = new LinkedHashSet<URL>(16);
        Iterator<File> iterator = FileUtils.iterateFiles(directory, new WildcardFileFilter(filePattern), null);
        while (iterator.hasNext()) {
            result.add(iterator.next().toURI().toURL());
        }

        return result.toArray(new URL[result.size()]);
    } else {
        // a single resource with the given name
        URL url = getDefaultClassLoader().getResource(cleanPath);
        // if (url == null) {
        // throw new UnsupportedOperationException(cleanPath);
        // }
        return url == null ? null : new URL[] { PathUtils.cleanPath(url) };
    }
}
 
Example #30
Source File: FileListParsingUtils.java    From Drop-seq with MIT License 5 votes vote down vote up
public static Collection<File> expandWildcardFile(final File wildcardFile) {
    final String fileName = wildcardFile.getName();
    if (fileName.contains("*") || fileName.contains("?"))
        return FileUtils.listFiles(wildcardFile.getParentFile(), new WildcardFileFilter(wildcardFile.getName()), null);
    else
        return Collections.singleton(wildcardFile);
}