Example usage for java.io FilenameFilter FilenameFilter

List of usage examples for java.io FilenameFilter FilenameFilter

Introduction

In this page you can find the example usage for java.io FilenameFilter FilenameFilter.

Prototype

FilenameFilter

Source Link

Usage

From source file:com.zotoh.maedr.etc.CmdAppOps.java

private void scanJars(File dir, StringBuilder out) throws Exception {
    File[] fs = dir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.endsWith(".jar");
        }//from ww w. ja  va  2 s .  c  o m
    });
    String p;
    if (fs != null)
        for (int i = 0; i < fs.length; ++i) {
            p = niceFPath(fs[i]);
            p = "<classpathentry kind=\"lib\" path=\"" + p + "\"/>\n";
            out.append(p);
        }
}

From source file:eu.optimis.ip.gui.server.IPManagerWebServiceImpl.java

@Override
public ArrayList<String> getComponentConfigurationList() {

    ArrayList<String> ret = new ArrayList<String>();
    String path = null;//from  w  w w . j av  a 2s.c o m

    File configDir = new File(ConfigManager.getFilePath(ConfigManager.COMPONENT_CONFIGURATION_FOLDER));
    File[] folders = configDir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            logger.debug(dir.getAbsolutePath().concat("/").concat(name));
            return (new File(dir.getAbsolutePath().concat("/").concat(name))).isDirectory();
        }
    });
    for (File file : folders) {
        ret.add(file.getName());
    }
    ret.add("OPTIMIS Global");

    return ret;
}

From source file:de.mprengemann.intellij.plugin.androidicons.dialogs.AndroidMultiDrawableImporter.java

private void importZipArchive(VirtualFile virtualFile) {
    final String filePath = virtualFile.getCanonicalPath();
    if (filePath == null) {
        return;// w  w  w  .ja  v  a  2 s  . com
    }
    final File tempDir = new File(ImageInformation.getTempDir(), virtualFile.getNameWithoutExtension());
    final String archiveName = virtualFile.getName();
    new Task.Modal(project, "Importing Archive...", true) {
        @Override
        public void run(@NotNull final ProgressIndicator progressIndicator) {
            progressIndicator.setIndeterminate(true);
            try {
                FileUtils.forceMkdir(tempDir);
                ZipUtil.extract(new File(filePath), tempDir, new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String name) {
                        final String mimeType = new MimetypesFileTypeMap().getContentType(name);
                        final String type = mimeType.split("/")[0];
                        return type.equals("image");
                    }
                }, true);
                progressIndicator.checkCanceled();

                final Iterator<File> fileIterator = FileUtils.iterateFiles(tempDir, TrueFileFilter.INSTANCE,
                        TrueFileFilter.INSTANCE);
                while (fileIterator.hasNext()) {
                    File file = fileIterator.next();
                    if (file.isDirectory() || file.isHidden()) {
                        continue;
                    }
                    final String fileRoot = file.getParent().toUpperCase();
                    final String name = FilenameUtils.getBaseName(file.toString());
                    if (name.startsWith(".") || fileRoot.contains("__MACOSX")) {
                        continue;
                    }
                    for (Resolution resolution : RESOLUTIONS) {
                        if (name.toUpperCase().contains("-" + resolution)
                                || name.toUpperCase().contains("_" + resolution)
                                || fileRoot.contains(resolution.toString())) {
                            controller.addZipImage(file, resolution);
                            break;
                        }
                    }
                }
                progressIndicator.checkCanceled();

                final Map<Resolution, List<ImageInformation>> zipImages = controller.getZipImages();
                final List<Resolution> foundResolutions = new ArrayList<Resolution>();
                int foundAssets = 0;
                for (Resolution resolution : zipImages.keySet()) {
                    final List<ImageInformation> assetInformation = zipImages.get(resolution);
                    if (assetInformation != null && assetInformation.size() > 0) {
                        foundAssets += assetInformation.size();
                        foundResolutions.add(resolution);
                    }
                }
                progressIndicator.checkCanceled();

                final int finalFoundAssets = foundAssets;
                UIUtil.invokeLaterIfNeeded(new DumbAwareRunnable() {
                    public void run() {
                        final String title = String.format("Import '%s'", archiveName);
                        if (foundResolutions.size() == 0 || finalFoundAssets == 0) {
                            Messages.showErrorDialog("No assets found.", title);
                            FileUtils.deleteQuietly(tempDir);
                            return;
                        }
                        final String[] options = new String[] { "Import", "Cancel" };
                        final String description = String.format("Import %d assets for %s to %s.",
                                finalFoundAssets, StringUtils.join(foundResolutions, ", "),
                                controller.getTargetRoot());
                        final int selection = Messages.showDialog(description, title, options, 0,
                                Messages.getQuestionIcon());
                        if (selection == 0) {
                            controller.getZipTask(project, tempDir).queue();
                            close(0);
                        } else {
                            FileUtils.deleteQuietly(tempDir);
                        }
                    }
                });
            } catch (ProcessCanceledException e) {
                FileUtils.deleteQuietly(tempDir);
            } catch (IOException e) {
                LOGGER.error(e);
            }
        }
    }.queue();
}

From source file:org.yamj.core.service.file.FileStorageService.java

public List<String> getDirectoryList(StorageType type, final String dir) {
    File path = new File(getStorageDir(type, StringUtils.trimToEmpty(dir)));
    String[] directories = path.list(new FilenameFilter() {
        @Override/*w ww.j a v  a2  s .com*/
        public boolean accept(File dir, String name) {
            return new File(dir, name).isDirectory();
        }
    });

    return Arrays.asList(directories);
}

From source file:com.jayway.maven.plugins.android.phase09package.AarMojo.java

/**
 * Adds all shared libraries (.so) to a {@link JarArchiver} under 'jni'.
 *
 * @param zipArchiver The jarArchiver to add files to
 * @param directory   The directory to scan for .so files
 * @param architecture      The prefix for where in the jar the .so files will go.
 *///  w  w  w .  j a  v  a2  s .  co  m
protected void addSharedLibraries(ZipArchiver zipArchiver, File directory, String architecture) {
    getLog().debug("Searching for shared libraries in " + directory);
    File[] libFiles = directory.listFiles(new FilenameFilter() {
        public boolean accept(final File dir, final String name) {
            return name.startsWith("lib") && name.endsWith(".so");
        }
    });

    if (libFiles != null) {
        for (File libFile : libFiles) {
            String dest = NATIVE_LIBRARIES_FOLDER + "/" + architecture + "/" + libFile.getName();
            getLog().debug("Adding " + libFile + " as " + dest);
            zipArchiver.addFile(libFile, dest);
        }
    }
}

From source file:io.cloudslang.dependency.impl.services.DependencyServiceImpl.java

private void appendSelfToPathFile(String[] gav, File pathFile) {
    File resourceFolder = new File(getResourceFolderPath(gav));
    if (!resourceFolder.exists() || !resourceFolder.isDirectory()) {
        throw new IllegalStateException("Directory " + resourceFolder.getPath() + " not found");
    }/*from   w  w w . jav a 2s . c o  m*/
    File[] files = resourceFolder.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".jar") || name.toLowerCase().endsWith(".zip");
        }
    });
    //we suppose that there should be either 1 jar or 1 zip
    if (files.length == 0) {
        throw new IllegalStateException("No resource is found in " + resourceFolder.getPath());
    }
    File resourceFile = files[0];
    try (FileWriter fw = new FileWriter(pathFile, true);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter out = new PrintWriter(bw)) {
        out.print(PATH_FILE_DELIMITER);
        out.print(resourceFile.getCanonicalPath());
    } catch (IOException e) {
        throw new IllegalStateException("Failed to append to file " + pathFile.getParent(), e);
    }
}

From source file:fi.iki.elonen.SimpleWebServer.java

protected String listDirectory(String uri, File f) {
    String heading = "Directory " + uri;
    StringBuilder msg = new StringBuilder("<html><head><title>" + heading + "</title><style><!--\n"
            + "span.dirname { font-weight: bold; }\n" + "span.filesize { font-size: 75%; }\n" + "// -->\n"
            + "</style>" + "</head><body><h1>" + heading + "</h1>");

    String up = null;/*from   ww w  .  j  a  v a  2 s .  c  om*/
    if (uri.length() > 1) {
        String u = uri.substring(0, uri.length() - 1);
        int slash = u.lastIndexOf('/');
        if (slash >= 0 && slash < u.length()) {
            up = uri.substring(0, slash + 1);
        }
    }

    List<String> files = Arrays.asList(f.list(new FilenameFilter() {

        @Override
        public boolean accept(File dir, String name) {
            return new File(dir, name).isFile();
        }
    }));
    Collections.sort(files);
    List<String> directories = Arrays.asList(f.list(new FilenameFilter() {

        @Override
        public boolean accept(File dir, String name) {
            return new File(dir, name).isDirectory();
        }
    }));
    Collections.sort(directories);
    if (up != null || directories.size() + files.size() > 0) {
        msg.append("<ul>");
        if (up != null || directories.size() > 0) {
            msg.append("<section class=\"directories\">");
            if (up != null) {
                msg.append("<li><a rel=\"directory\" href=\"").append(up)
                        .append("\"><span class=\"dirname\">..</span></a></b></li>");
            }
            for (String directory : directories) {
                String dir = directory + "/";
                msg.append("<li><a rel=\"directory\" href=\"").append(encodeUri(uri + dir))
                        .append("\"><span class=\"dirname\">").append(dir).append("</span></a></b></li>");
            }
            msg.append("</section>");
        }
        if (files.size() > 0) {
            msg.append("<section class=\"files\">");
            for (String file : files) {
                msg.append("<li><a href=\"").append(encodeUri(uri + file))
                        .append("\"><span class=\"filename\">").append(file).append("</span></a>");
                File curFile = new File(f, file);
                long len = curFile.length();
                msg.append("&nbsp;<span class=\"filesize\">(");
                if (len < 1024) {
                    msg.append(len).append(" bytes");
                } else if (len < 1024 * 1024) {
                    msg.append(len / 1024).append(".").append(len % 1024 / 10 % 100).append(" KB");
                } else {
                    msg.append(len / (1024 * 1024)).append(".").append(len % (1024 * 1024) / 10000 % 100)
                            .append(" MB");
                }
                msg.append(")</span></li>");
            }
            msg.append("</section>");
        }
        msg.append("</ul>");
    }
    msg.append("</body></html>");
    return msg.toString();
}

From source file:com.ebixio.virtmus.stats.StatsLogger.java

/** Should only be called from uploadLogs(). Compresses all files that belong
 to the given log set, and uploads all compressed files to the server. */
private boolean uploadLogs(final String logSet) {
    if (logSet == null)
        return false;

    File logsDir = getLogsDir();//w w w .  ja v  a  2s .  c  om
    if (logsDir == null)
        return false;
    gzipLogs(logsDir, logSet);

    // Uploading only gz'd files
    FilenameFilter gzFilter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".gz");
        }
    };
    File[] toUpload = logsDir.listFiles(gzFilter);

    String url = getUploadUrl();
    if (url == null) {
        /* This means the server is unable to accept the logs. */
        keepRecents(toUpload, 100);
        return false;
    }

    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    addHttpHeaders(post);

    MultipartEntityBuilder entity = MultipartEntityBuilder.create();
    entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("InstallId", new StringBody(String.valueOf(MainApp.getInstallId()), ContentType.TEXT_PLAIN));

    ContentType ct = ContentType.create("x-application/gzip");
    for (File f : toUpload) {
        entity.addPart("VirtMusStats", new FileBody(f, ct, f.getName()));
    }
    post.setEntity(entity.build());

    boolean success = false;
    try (CloseableHttpResponse response = client.execute(post)) {
        int status = response.getStatusLine().getStatusCode();
        Log.log(Level.INFO, "Log upload result: {0}", status);
        if (status == HttpStatus.SC_OK) { // 200
            for (File f : toUpload) {
                try {
                    f.delete();
                } catch (SecurityException ex) {
                }
            }
            success = true;
        } else {
            LogRecord rec = new LogRecord(Level.INFO, "Server Err");
            rec.setParameters(new Object[] { url, "Status: " + status });
            getLogger().log(rec);
        }

        HttpEntity rspEntity = response.getEntity();
        EntityUtils.consume(rspEntity);
        client.close();
    } catch (IOException ex) {
        Log.log(ex);
    }

    keepRecents(toUpload, 100); // In case of exceptions or errors
    return success;
}

From source file:org.sonatype.nexus.integrationtests.AbstractNexusIntegrationTest.java

protected static void cleanWorkDir() throws Exception {
    final File workDir = new File(AbstractNexusIntegrationTest.nexusWorkDir);

    // to make sure I don't delete all my MP3's and pictures, or totally screw anyone.
    // check for 'target' and not allow any '..'
    if (workDir.getAbsolutePath().lastIndexOf("target") != -1
            && workDir.getAbsolutePath().lastIndexOf("..") == -1) {
        // we cannot delete the plugin-repository or the tests will fail

        File[] filesToDelete = workDir.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                // anything but the plugin-repository directory
                return (!name.contains("plugin-repository"));
            }//  ww  w  .j ava  2s  . co m
        });

        if (filesToDelete != null) {
            for (File fileToDelete : filesToDelete) {
                // delete work dir
                if (fileToDelete != null) {
                    FileUtils.deleteDirectory(fileToDelete);
                }
            }
        }

    }
}

From source file:fr.gael.dhus.service.SystemService.java

public void cleanDumpDatabase(int keepno) {
    File[] dumps = new File(cfgManager.getDatabaseConfiguration().getDumpPath())
            .listFiles(new FilenameFilter() {
                @Override/*from  w  w w.  ja  va  2 s  .  co  m*/
                public boolean accept(File path, String name) {
                    if (name.startsWith("dump-"))
                        return true;
                    return false;
                }
            });
    if ((dumps != null) && (dumps.length > keepno)) {
        Arrays.sort(dumps, NameFileComparator.NAME_COMPARATOR);
        int last = dumps.length - keepno;
        for (int index = 0; index < last; index++) {
            File dir = dumps[index];
            try {
                Date date = new Date(Long.parseLong(dir.getName().replaceAll("dump-(.*)", "$1")));
                logger.info("Cleaned dump of " + date);
                FileUtils.deleteDirectory(dir);
            } catch (IOException e) {
                logger.warn("Cannot delete directory " + dir.getPath() + " (" + e.getMessage() + ")");
            }
        }
    }
}