Example usage for com.google.common.io PatternFilenameFilter PatternFilenameFilter

List of usage examples for com.google.common.io PatternFilenameFilter PatternFilenameFilter

Introduction

In this page you can find the example usage for com.google.common.io PatternFilenameFilter PatternFilenameFilter.

Prototype

public PatternFilenameFilter(Pattern pattern) 

Source Link

Document

Constructs a pattern file name filter object.

Usage

From source file:roycurtis.softplugin.Compiler.java

/** Generates classpath string using paths of all plugins available and the Bukkit JAR */
private String generateClasspath() {
    File pluginDir = new File("plugins/").getAbsoluteFile();
    File[] plugins = pluginDir.listFiles(new PatternFilenameFilter(".+\\.jar"));
    String classpath = BUKKIT_JAR;

    for (File plugin : plugins)
        classpath += ";" + plugin.getAbsolutePath();

    return classpath;
}

From source file:gov.nih.nci.caarray.dataStorage.fileSystem.FilesystemDataStorage.java

/**
 * {@inheritDoc}/*from   w  w  w.j  a v  a  2 s .  c om*/
 */
@Override
public Iterable<StorageMetadata> list() {
    final Set<StorageMetadata> metadatas = Sets.newHashSet();
    final File[] files = baseStorageDir().listFiles(new PatternFilenameFilter(".*\\.unc"));
    if (files != null) {
        for (final File file : files) {
            final StorageMetadata sm = new StorageMetadata();
            sm.setCreationTimestamp(new Date(file.lastModified()));
            sm.setHandle(handleFromFile(file));
            sm.setUncompressedSize(file.length());
            metadatas.add(sm);
        }
    }
    return metadatas;
}

From source file:com.android.tradefed.build.LocalDeviceBuildProvider.java

/**
 * Creates a build image zip file from the given build-dir
 *
 * @return the {@link File} referencing the zip output.
 * @throws BuildRetrievalError// w  w w.  jav  a 2s. c o m
 */
@VisibleForTesting
File createBuildImageZip() throws BuildRetrievalError {
    File zipFile = null;
    File[] imageFiles = mBuildDir.listFiles(new PatternFilenameFilter(".*\\.img"));
    File buildInfo = findFileInDir(BUILD_INFO_FILE);
    List<File> buildFiles = new ArrayList<>(Arrays.asList(imageFiles));
    buildFiles.add(buildInfo);
    try {
        zipFile = ZipUtil.createZip(buildFiles);
    } catch (IOException e) {
        throw new BuildRetrievalError("Unable to create build image zip file", e);
    }
    CLog.i("Created build image zip on: %s", zipFile.getAbsolutePath());
    return zipFile;
}

From source file:dk.dma.dmiweather.service.FTPLoader.java

/**
 * Copied the files from DMIs ftp server to the local machine
 *
 * @return a Map with a local file and the time the file was created on the FTP server
 *///  w  w  w  .ja  v  a  2 s .c om
private Map<File, Instant> transferFilesIfNeeded(FTPClient client, String directoryName, List<FTPFile> files)
        throws IOException {

    File current = new File(tempDirLocation, directoryName);
    if (newestDirectories.isEmpty()) {
        // If we just started check if there is data from an earlier run and delete it
        File temp = new File(tempDirLocation);
        if (temp.exists()) {
            File[] oldFolders = temp.listFiles(new PatternFilenameFilter(FOLDER_PATTERN));
            if (oldFolders != null) {
                List<File> foldersToDelete = Lists.newArrayList(oldFolders);
                foldersToDelete.remove(current);
                for (File oldFolder : foldersToDelete) {
                    log.info("deleting old GRIB folder {}", oldFolder);
                    deleteRecursively(oldFolder);
                }
            }
        }
    }

    if (!current.exists()) {
        if (!current.mkdirs()) {
            throw new IOException("Unable to create temp directory " + current.getAbsolutePath());
        }
    }

    Stopwatch stopwatch = Stopwatch.createStarted();
    Map<File, Instant> transferred = new HashMap<>();
    for (FTPFile file : files) {
        File tmp = new File(current, file.getName());
        if (tmp.exists()) {
            long localSize = Files.size(tmp.toPath());
            if (localSize != file.getSize()) {
                log.info("deleting {} local file has size {}, remote is {}", tmp.getName(), localSize,
                        file.getSize());
                if (!tmp.delete()) {
                    log.warn("Unable to delete " + tmp.getAbsolutePath());
                }
            } else {
                // If the file has the right size we assume it was copied correctly (otherwise we needed to hash them)
                log.info("Reusing already downloaded version of {}", tmp.getName());
                transferred.put(tmp, file.getTimestamp().toInstant());
                continue;
            }
        }
        if (tmp.createNewFile()) {
            log.info("downloading {}", tmp.getName());

            // this often fails with java.net.ConnectException: Operation timed out
            int count = 0;
            while (count++ < MAX_TRIES) {
                try (FileOutputStream fout = new FileOutputStream(tmp)) {
                    client.retrieveFile(file.getName(), fout);
                    fout.flush();
                    break;
                } catch (IOException e) {
                    log.warn(String.format("Failed to transfer file %s, try number %s", file.getName(), count),
                            e);
                }
            }
        } else {
            throw new IOException("Unable to create temp file on disk.");
        }

        transferred.put(tmp, file.getTimestamp().toInstant());
    }
    log.info("transferred weather files in {} ms", stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
    return transferred;
}

From source file:org.jclouds.cleanup.DomainObjectDocletCleaner.java

private static List<File> listFiles(File file, List<File> result) {
    if (file.isDirectory()) {
        for (File directory : file.listFiles(new FileFilter() {
            public boolean accept(File file) {
                return file.isDirectory();
            }//from  w w w  .  j ava2  s .c  o  m
        })) {
            listFiles(directory, result);
        }
        result.addAll(Arrays.asList(file.listFiles(new PatternFilenameFilter(".*\\.java"))));
    }
    return result;
}

From source file:de.keyle.dungeoncraft.editor.editors.trigger.TriggerEditor.java

@Override
public void openDungeon(File dungeonFolder) {
    resetFields();//from w ww  .  j  a va2  s.c o  m

    triggerFolder = new File(dungeonFolder, "trigger");
    if (triggerFolder.exists() && triggerFolder.isDirectory()) {
        File[] triggerFiles = triggerFolder.listFiles(
                new PatternFilenameFilter(Pattern.compile("[.-_a-z0-9]+\\.js", Pattern.CASE_INSENSITIVE)));
        if (triggerFiles != null) {
            for (File triggerFile : triggerFiles) {
                String triggerName = triggerFile.getName().substring(0, triggerFile.getName().length() - 3);
                String triggerContent = Util.readFile(triggerFile);
                Trigger trigger = new Trigger(triggerName, triggerContent);
                TriggerPanel panel = new TriggerPanel(trigger);
                triggerPanels.add(panel);
                triggerFilesTabbedPane.add(panel);
            }
            if (triggerPanels.size() > 0) {
                triggerFilesTabbedPane.setVisible(true);
                deleteTriggerButton.setEnabled(true);
                renameTriggerButton.setEnabled(true);
            }
        }
    }
}

From source file:net.myrrix.online.eval.AbstractEvaluator.java

private static DataFileContents readDataFile(File dataDir, double evaluationPercentage,
        RescorerProvider provider) throws IOException {
    // evaluationPercentage filters per user and item, not per datum, since time scales with users and
    // items. We select sqrt(evaluationPercentage) of users and items to overall select about evaluationPercentage
    // of all data.
    int perMillion = (int) (1000000 * FastMath.sqrt(evaluationPercentage));

    Multimap<Long, RecommendedItem> data = ArrayListMultimap.create();
    Multimap<String, RecommendedItem> itemTags = ArrayListMultimap.create();
    Multimap<String, RecommendedItem> userTags = ArrayListMultimap.create();

    for (File dataFile : dataDir.listFiles(new PatternFilenameFilter(".+\\.csv(\\.(zip|gz))?"))) {
        log.info("Reading {}", dataFile);
        int count = 0;
        for (CharSequence line : new FileLineIterable(dataFile)) {
            Iterator<String> parts = COMMA_TAB_SPLIT.split(line).iterator();
            String userIDString = parts.next();
            if (userIDString.hashCode() % 1000000 <= perMillion) {
                String itemIDString = parts.next();
                if (itemIDString.hashCode() % 1000000 <= perMillion) {

                    Long userID = null;
                    boolean userIsTag = userIDString.startsWith("\"");
                    if (!userIsTag) {
                        userID = Long.valueOf(userIDString);
                    }/*from w  ww  .ja v a  2s  . c om*/

                    boolean itemIsTag = itemIDString.startsWith("\"");
                    Long itemID = null;
                    if (!itemIsTag) {
                        itemID = Long.valueOf(itemIDString);
                    }

                    Preconditions.checkArgument(!(userIsTag && itemIsTag),
                            "Can't have a user tag and item tag in one line");

                    if (parts.hasNext()) {
                        String token = parts.next().trim();
                        if (!token.isEmpty()) {
                            float value = LangUtils.parseFloat(token);
                            if (userIsTag) {
                                itemTags.put(userIDString, new GenericRecommendedItem(itemID, value));
                            } else if (itemIsTag) {
                                userTags.put(itemIDString, new GenericRecommendedItem(userID, value));
                            } else {
                                if (provider != null) {
                                    IDRescorer rescorer = provider.getRecommendRescorer(new long[] { userID },
                                            null);
                                    if (rescorer != null) {
                                        value = (float) rescorer.rescore(itemID, value);
                                    }
                                }
                                data.put(userID, new GenericRecommendedItem(itemID, value));
                            }
                        }
                        // Ignore remove lines
                    } else {
                        if (userIsTag) {
                            itemTags.put(userIDString, new GenericRecommendedItem(itemID, 1.0f));
                        } else if (itemIsTag) {
                            userTags.put(itemIDString, new GenericRecommendedItem(userID, 1.0f));
                        } else {
                            float value = 1.0f;
                            if (provider != null) {
                                IDRescorer rescorer = provider.getRecommendRescorer(new long[] { userID },
                                        null);
                                if (rescorer != null) {
                                    value = (float) rescorer.rescore(itemID, value);
                                }
                            }
                            data.put(userID, new GenericRecommendedItem(itemID, value));
                        }
                    }
                }
            }
            if (++count % 1000000 == 0) {
                log.info("Finished {} lines", count);
            }
        }
    }

    return new DataFileContents(data, itemTags, userTags);
}

From source file:com.android.tradefed.build.LocalDeviceBuildProvider.java

/**
 * Find a matching file in a given directory.
 *
 * @param regex Regular expression to match a file
 * @param dir a {@link File} referencing the directory to search
 * @return A matching {@link File} or null if none is found
 * @throws BuildRetrievalError/*from  w  w w .  j a v  a 2 s. c o  m*/
 */
@VisibleForTesting
File findFileInDir(String regex, File dir) throws BuildRetrievalError {
    File[] files = dir.listFiles(new PatternFilenameFilter(regex));
    if (files.length == 0) {
        return null;
    } else if (files.length > 1) {
        throw new BuildRetrievalError(String.format("Found more than one file matching '%s' in '%s'.", regex,
                mBuildDir.getAbsolutePath()));
    }
    return files[0];
}

From source file:com.flaptor.indextank.storage.Segment.java

private static List<File> listSegmentFiles(File parent) {
    File[] files = parent.listFiles(new PatternFilenameFilter(SEGMENT_FILE));
    Arrays.sort(files);//from   w w  w. ja v a  2 s  .  c o m
    return Arrays.asList(files);
}

From source file:com.mcleodmoores.mvn.natives.PackageMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (isSkip()) {
        getLog().debug("Skipping step");
        return;/*from  ww w  . j  ava  2 s  . com*/
    }
    applyDefaults();
    final MavenProject project = (MavenProject) getPluginContext().get("project");
    final File targetDir = new File(project.getBuild().getDirectory());
    targetDir.mkdirs();
    final File targetFile = new File(targetDir, project.getArtifactId() + ".zip");
    getLog().debug("Writing to " + targetFile);
    final OutputStream output;
    try {
        output = getOutputStreams().open(targetFile);
    } catch (final IOException e) {
        throw new MojoFailureException("Can't write to " + targetFile);
    }
    final IOExceptionHandler errorLog = new MojoLoggingErrorCallback(this);
    if ((new IOCallback<OutputStream, Boolean>(output) {

        @Override
        protected Boolean apply(final OutputStream output) throws IOException {
            final byte[] buffer = new byte[4096];
            final ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(output));
            for (final Map.Entry<Source, String> sourceInfo : gatherSources().entrySet()) {
                final Source source = sourceInfo.getKey();
                getLog().info("Processing " + source.getPath() + " into " + sourceInfo.getValue() + " ("
                        + source.getPattern() + ")");
                final File folder = new File(source.getPath());
                final String[] files = folder.list(new PatternFilenameFilter(regex(source.getPattern())));
                if (files != null) {
                    for (final String file : files) {
                        getLog().debug("Adding " + file + " to archive");
                        final ZipEntry entry = new ZipEntry(sourceInfo.getValue() + file);
                        zip.putNextEntry(entry);
                        if ((new IOCallback<InputStream, Boolean>(
                                getInputStreams().open(new File(folder, file))) {

                            @Override
                            protected Boolean apply(final InputStream input) throws IOException {
                                int bytes;
                                while ((bytes = input.read(buffer, 0, buffer.length)) > 0) {
                                    zip.write(buffer, 0, bytes);
                                }
                                return Boolean.TRUE;
                            }

                        }).call(errorLog) != Boolean.TRUE) {
                            return Boolean.FALSE;
                        }
                        zip.closeEntry();
                    }
                } else {
                    getLog().debug("Source folder is empty or does not exist");
                }
            }
            zip.close();
            return Boolean.TRUE;
        }

    }).call(errorLog) != Boolean.TRUE) {
        throw new MojoFailureException("Error writing to " + targetFile);
    }
    project.getArtifact().setFile(targetFile);
}