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:eu.annocultor.utils.OntologySubtractor.java

private static void copyRdfFiles(File sourceDir, File destinationDir) throws IOException {
    File[] allRdfFiles = sourceDir.listFiles(new FilenameFilter() {

        @Override/* w  ww.j  a v a2s  .  co  m*/
        public boolean accept(File dir, String name) {
            return name.endsWith(".rdf") && !name.endsWith(DELETED_RDF);
        }
    });

    for (File file : allRdfFiles) {
        FileUtils.copyFileToDirectory(file, destinationDir);
    }
}

From source file:jpad.MainEditor.java

public void openFile_OSX_Nix() {
    isOpen = true;/*from  ww w.ja v a 2  s . co m*/
    FilenameFilter awtFilter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            String lowercaseName = name.toLowerCase();
            if (lowercaseName.endsWith(".txt"))
                return true;
            else
                return false;
        }
    };
    FileDialog fd = new FileDialog(this, "Open Text File", FileDialog.LOAD);
    fd.setFilenameFilter(awtFilter);
    fd.setVisible(true);
    if (fd.getFile() == null)
        return;
    else
        curFile = fd.getDirectory() + fd.getFile();
    //TODO: actually open the file
    try (FileInputStream inputStream = new FileInputStream(curFile)) {
        String allText = org.apache.commons.io.IOUtils.toString(inputStream);
        mainTextArea.setText(allText);
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(this, ex.getMessage(), "Error While Reading", JOptionPane.ERROR_MESSAGE);
    }
    JRootPane root = this.getRootPane();
    root.putClientProperty("Window.documentFile", new File(curFile));
    root.putClientProperty("Window.documentModified", Boolean.FALSE);
    hasChanges = false;
    hasSavedToFile = true;
    this.setTitle(String.format("JPad - %s", curFile));
    isOpen = false;
}

From source file:edu.wisc.doit.tcrypt.dao.impl.KeysKeeper.java

private void forcedScanForKeys() {
    try {//from w ww . ja  va 2s . co m
        logger.debug("Scanning {} for updates to key files", directory);

        final File[] keyfiles = directory.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                if (KEY_NAME_PATTERN.matcher(name).matches()) {
                    return true;
                }

                logger.warn("Ignoring {} in {}", name, dir);

                return false;
            }
        });

        final Set<String> oldKeys = new HashSet<String>(this.keysCache.keySet());

        for (final File keyFile : keyfiles) {
            final String keyName = keyFile.getName();
            final Matcher keyNameMatcher = KEY_NAME_PATTERN.matcher(keyName);

            if (!keyNameMatcher.matches()) {
                throw new IllegalStateException("Some how " + keyFile
                        + " matched the FilenameFilter but does not match the key name pattern");
            }

            logger.debug("Found key: {}", keyFile);

            final String serviceName = keyNameMatcher.group(1);

            //Record that we saw the service name and if it wasn't removed it must be a new key
            if (!oldKeys.remove(serviceName)) {
                final String createdByNetId = keyNameMatcher.group(2);
                final String dayCreatedStr = keyNameMatcher.group(3);
                final DateTime dayCreated = KEY_CREATED_FORMATTER.parseDateTime(dayCreatedStr);
                final int keyLength = Integer.parseInt(keyNameMatcher.group(4));

                final ServiceKey serviceKey = new ServiceKey(serviceName, keyLength, createdByNetId, dayCreated,
                        keyFile);
                this.keysCache.put(serviceName, serviceKey);
            }
        }

        //Remove any keys that have been deleted from the file system
        if (!oldKeys.isEmpty()) {
            logger.info("Removed old service keys: {}", oldKeys);
            this.keysCache.keySet().removeAll(oldKeys);
        }

        logger.info("Scanned {}, keysCache contains {} keys", directory, this.keysCache.size());
    } catch (Exception e) {
        logger.error("Failed to scan {} for keys", this.directory, e);
    }
}

From source file:com.abiquo.am.services.filesystem.TemplateFileSystem.java

public static TemplateStateDto getTemplateStatus(final String enterpriseRepositoryPath, final String ovfId) {
    final TemplateStateDto state = new TemplateStateDto();
    state.setOvfId(ovfId);/*from w ww .j av  a2s  .com*/

    if (!TemplateConventions.isValidOVFLocation(ovfId)) {
        state.setStatus(TemplateStatusEnumType.ERROR);
        state.setErrorCause(AMError.TEMPLATE_INVALID_LOCATION.toString());
        return state;
    }

    final boolean isInstance = TemplateConventions.isBundleOvfId(ovfId);
    final String packagePath = getTemplatePath(enterpriseRepositoryPath, ovfId);

    if (isInstance) {

        final String snapshot = ovfId.substring(ovfId.lastIndexOf('/') + 1, ovfId.indexOf("-snapshot-"));
        final String masterPath = TemplateConventions.getTemplatePath(enterpriseRepositoryPath,
                TemplateConventions.getBundleMasterOvfId(ovfId));

        final File folder = new File(masterPath);
        if (folder.list(new FilenameFilter() {
            @Override
            public boolean accept(final File file, final String name) {
                return name.startsWith(snapshot);
            }

        }).length == 0) {
            state.setStatus(TemplateStatusEnumType.NOT_DOWNLOAD);
        } else {
            state.setStatus(TemplateStatusEnumType.DOWNLOAD);
        }

        return state;
    }

    final String ovfEnvelopePath = FilenameUtils.concat(enterpriseRepositoryPath,
            getRelativeTemplatePath(ovfId));

    File errorMarkFile = new File(packagePath + TEMPLATE_STATUS_ERROR_MARK);
    if (errorMarkFile.exists()) {
        state.setStatus(TemplateStatusEnumType.ERROR);
        state.setErrorCause(readErrorMarkFile(errorMarkFile));
    } else if (new File(packagePath + TEMPLATE_STATUS_DOWNLOADING_MARK).exists()) {
        state.setStatus(TemplateStatusEnumType.DOWNLOADING);

    } else if (!new File(ovfEnvelopePath).exists()) {
        state.setStatus(TemplateStatusEnumType.NOT_DOWNLOAD);
    } else {
        state.setStatus(TemplateStatusEnumType.DOWNLOAD);
    }

    return state;
}

From source file:com.meltmedia.cadmium.core.FileSystemManager.java

public static String[] getDirectoriesInDirectory(String directory, final String baseName) {
    File dir = new File(directory);
    if (dir.isDirectory()) {
        String files[] = null;/*from w  ww . ja  v  a 2 s  .  c  om*/
        files = dir.list(new FilenameFilter() {

            @Override
            public boolean accept(File file, String name) {
                if (baseName != null && baseName.length() > 0) {
                    return file.isDirectory() && file.isAbsolute() && name.startsWith(baseName);
                }
                return file.isDirectory();
            }

        });
        if (files != null) {
            return files;
        }
    }
    return new String[] {};
}

From source file:com.jhash.oimadmin.ui.UIJavaCompile.java

@Override
public void initializeComponent() {
    logger.debug("Initializing {}", this);
    this.outputDirectory = configuration.getWorkArea() + Config.VAL_WORK_AREA_CLASSES + File.separator
            + System.currentTimeMillis();
    logger.debug("Compile output directory {}", outputDirectory);
    File templateDirectory = new File(configuration.getWorkArea() + File.separator + Config.VAL_WORK_AREA_CONF
            + File.separator + "templates");
    logger.debug("Trying to validate template directory {} exists and is directory", templateDirectory);
    if (templateDirectory.exists() && templateDirectory.isDirectory()) {
        logger.debug("Trying to list files in directory");
        String[] listOfFile = templateDirectory.list(new FilenameFilter() {
            @Override/*from w w  w.j av  a 2  s  .com*/
            public boolean accept(File dir, String name) {
                logger.trace("Validating file {}", name);
                if (name.startsWith(templatePrefix)) {
                    logger.trace("File {} begins with prefix", name);
                    return true;
                }
                return false;
            }
        });
        java.util.List<String> fixedListOfFile = new ArrayList<>();
        logger.debug("Extract class name and display name from file names {}", listOfFile);
        for (String fileName : listOfFile) {
            String fileSuffix = fileName.replaceAll(templatePrefix, "");
            logger.trace("Adding class {} to list", fileSuffix);
            fixedListOfFile.add(fileSuffix);
        }
        if (fixedListOfFile != null && fixedListOfFile.size() > 0) {
            logger.debug("Creating combo-box with values {}", fixedListOfFile);
            sourceCodeSelector = new JComboBox<String>(fixedListOfFile.toArray(new String[0]));
            sourceCodeSelector.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    logger.debug("Event {} triggered on combo box {}", e, sourceCodeSelector);
                    String sourceCodeSelected = (String) sourceCodeSelector.getSelectedItem();
                    if (sourceCodeSelector != null) {
                        logger.debug("Trying to read file for selected source code {}", sourceCodeSelected);
                        String readData = Utils.readFile(templatePrefix + sourceCodeSelected,
                                templateDirectory.getAbsolutePath());
                        sourceCode.setText(readData);
                        classNameText.setText(sourceCodeSelected);
                    }
                }
            });
            sourceCodeSelector.setSelectedIndex(0);
        }
    }
    compileButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                logger.debug("Triggered action {} on {}", e, compileButton);
                compile();
                logger.debug("Completed action {} on {}", e, compileButton);
            } catch (Exception exception) {
                displayMessage("Compilation failed", "Failed to compile", exception);
            }
        }
    });
    javaCompileUI = buildCodePanel();
}

From source file:any.servable.LsServable.java

public void process(String cmd, String content, BlockingQueue<Message> outQueue) {
    logger.info("start LS SERVABLE");
    String filename = content.substring(0, content.length());

    File file = new File(filename);

    try {/*from  w w  w .  j  a va2  s .  c  o  m*/

        File[] list = file.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File arg0, String name) {
                return !(name.startsWith(".") && !(name.endsWith("~")));
            }
        });

        StringBuilder sb = new StringBuilder();

        // parent
        File fp = file.getParentFile();

        logger.debug("do file: " + file + " - list: " + list + " fp:" + fp);

        if (fp != null) {
            TblUtil tbl = new TblUtil();

            // DISPLAYTEXT
            tbl.set(TblUtil.DISPLAYTEXT, "[..] " + fp.getName());

            // DETAILTEXT
            tbl.set(TblUtil.DETAILTEXT, "UP");

            //            // ICONRES
            //            try { 
            //               JFileChooser ch = new JFileChooser();
            //               Icon icon = ch.getIcon(fp);
            //
            //               BufferedImage offscreen = new BufferedImage(
            //                     icon.getIconHeight(), icon.getIconWidth(),
            //                     BufferedImage.TYPE_4BYTE_ABGR);
            //               icon.paintIcon(null, offscreen.getGraphics(), 0, 0);
            //
            //               ByteArrayOutputStream baos = new ByteArrayOutputStream();
            //               ImageIO.write(offscreen, "png", baos);
            //               baos.flush();
            //               byte[] imageInByte = baos.toByteArray();
            //               baos.close();
            //
            //               String strrep = new String(imageInByte);
            //               if (!resSet.containsKey(strrep)) {
            //
            //                  System.out.println(fp.getName() + ": "
            //                        + icon.toString() + " " + icon.hashCode());
            //
            //                  outQueue.put(new Message("res", icon.toString(),
            //                        "image/png", "NO", imageInByte));
            //                  resSet.put(strrep, icon.toString());
            //                  tbl.set(TblUtil.ICONRES, icon.toString());
            //               } else {
            //                  tbl.set(TblUtil.ICONRES, resSet.get(strrep));
            //               }
            //            } catch (Error e) {
            //               // TODO
            //               System.err.println("Exception due to icon caught");
            //               // e.printStackTrace();
            //            }

            // TABCMD
            String tcmd = ((fp.isDirectory() ? "ls://host" : "get://host") + fp.getAbsolutePath());
            tbl.set(TblUtil.TABCMD, tcmd);

            // DETAILCMD
            tbl.set(TblUtil.DETAILCMD, "tmpl:" + tcmd);

            // DELETECMD

            sb.append(tbl.makeCell());

        }

        logger.debug("do list: " + list);

        if (list != null) {
            for (File f : list) {

                logger.debug("do file: " + f);

                TblUtil tbl = new TblUtil();

                // DISPLAYTEXT
                tbl.set(TblUtil.DISPLAYTEXT, f.getName());

                // DETAILTEXT
                tbl.set(TblUtil.DETAILTEXT,
                        (f.isDirectory() ? " --      " : humanReadableByteCount(f.length(), true)) + " - "
                                + df.format(f.lastModified()));

                //               // ICONRES
                //               try {
                //                  JFileChooser ch = new JFileChooser();
                //                  Icon icon = ch.getIcon(f);
                //
                //                  BufferedImage offscreen = new BufferedImage(
                //                        icon.getIconHeight(), icon.getIconWidth(),
                //                        BufferedImage.TYPE_4BYTE_ABGR);
                //                  icon.paintIcon(null, offscreen.getGraphics(), 0, 0);
                //
                //                  ByteArrayOutputStream baos = new ByteArrayOutputStream();
                //                  ImageIO.write(offscreen, "png", baos);
                //                  baos.flush();
                //                  byte[] imageInByte = baos.toByteArray();
                //                  baos.close();
                //
                //                  String strrep = new String(imageInByte);
                //                  if (!resSet.containsKey(strrep)) {
                //
                //                     System.out.println(f.getName() + ": "
                //                           + icon.toString() + " " + icon.hashCode());
                //
                //                     outQueue.put(new Message("res", icon.toString(),
                //                           "image/png", "NO", imageInByte));
                //                     resSet.put(strrep, icon.toString());
                //                     tbl.set(TblUtil.ICONRES, icon.toString());
                //                  } else {
                //                     tbl.set(TblUtil.ICONRES, resSet.get(strrep));
                //                  }
                //
                //               } catch (Error e) {
                //                  // TODO
                //                  System.err.println("Exception due to icon caught");
                //                  // e.printStackTrace();
                //               }

                String fullpath = f.getAbsolutePath();
                if (!fullpath.startsWith("/")) {
                    fullpath = "/" + fullpath;
                }

                // TABCMD
                String tcmd = ((f.isDirectory() ? "ls://host" : "get://host") + fullpath);
                tbl.set(TblUtil.TABCMD, tcmd);

                // DETAILCMD
                tbl.set(TblUtil.DETAILCMD, "tmpl:" + tcmd);

                // DELETECMD

                sb.append(tbl.makeCell());
            }

            outQueue.put(
                    new Message("vset", file.getName(), TblUtil.TYPE, "YES", "1", sb.toString().getBytes()));

        }
    } catch (InterruptedException e) {
        e.printStackTrace();
        final Writer result = new StringWriter();
        final PrintWriter printWriter = new PrintWriter(result);
        e.printStackTrace(printWriter);
        outQueue.add(new Message("vset", "_error", "text/plain", "YES", result.toString().getBytes()));
        //      } catch (IOException e) {
        //         e.printStackTrace();
        //         final Writer result = new StringWriter();
        //         final PrintWriter printWriter = new PrintWriter(result);
        //         e.printStackTrace(printWriter);
        //         outQueue.add(new Message("vset", "_error", "text/plain", "YES",
        //               result.toString().getBytes()));
    } catch (NullPointerException e) {
        e.printStackTrace();
        final Writer result = new StringWriter();
        final PrintWriter printWriter = new PrintWriter(result);
        e.printStackTrace(printWriter);
        outQueue.add(new Message("vset", "_error", "text/plain", "YES", result.toString().getBytes()));
    }

    logger.info("finished LS SERVABLE");
}

From source file:com.linkedin.helix.tools.ZKDumper.java

public ZKDumper(String zkAddress) {
    client = new ZkClient(zkAddress, ZkClient.DEFAULT_CONNECTION_TIMEOUT);
    ZkSerializer zkSerializer = new ZkSerializer() {

        @Override//ww w  .j  a v a 2  s  .c  o m
        public byte[] serialize(Object arg0) throws ZkMarshallingError {
            return arg0.toString().getBytes();
        }

        @Override
        public Object deserialize(byte[] arg0) throws ZkMarshallingError {
            return new String(arg0);
        }
    };
    client.setZkSerializer(zkSerializer);
    filter = new FilenameFilter() {

        @Override
        public boolean accept(File dir, String name) {
            return !name.startsWith(".");
        }
    };
}

From source file:org.pentaho.telemetry.TelemetryEventSender.java

@Override
public void run() {
    //Delete everything in lastSubmission folder
    File[] submittedFiles = this.getLastSubmissionDir().listFiles();
    for (File f : submittedFiles) {
        f.delete();/* ww w  . j  ava  2  s.c o m*/
    }

    //Get all requests in telemetryPath
    File[] unsubmittedRequests = this.getTelemetryDir().listFiles(new FilenameFilter() {

        @Override
        public boolean accept(File file, String name) {
            return name.endsWith(FILE_EXT);
        }
    });

    File[] block = new File[BLOCK_SIZE];
    int blockIndex = 0;
    Calendar cld = Calendar.getInstance();
    cld.add(Calendar.DAY_OF_YEAR, -DAYS_TO_KEEP_FILES);
    for (File f : unsubmittedRequests) {

        //Check if file was created more than 5 days ago. If so, dismiss it
        if (f.lastModified() < cld.getTime().getTime()) {
            f.delete();
            continue;
        }

        //Create blocks of BLOCK_SIZE
        if (blockIndex > 0 && blockIndex % BLOCK_SIZE == 0) {
            sendRequest(block);
            block = new File[BLOCK_SIZE];
            blockIndex = 0;
        } else {
            block[blockIndex] = f;
            blockIndex++;
        }
    }

    if (blockIndex > 0) {
        sendRequest(block);
    }
}

From source file:android.databinding.annotationprocessor.ProcessExpressions.java

private IntermediateV1 createIntermediateFromLayouts(String layoutInfoFolderPath) {
    final File layoutInfoFolder = new File(layoutInfoFolderPath);
    if (!layoutInfoFolder.isDirectory()) {
        L.d("layout info folder does not exist, skipping for %s", layoutInfoFolderPath);
        return null;
    }// w  w  w.  j av  a 2 s  . c  o  m
    IntermediateV1 result = new IntermediateV1();
    for (File layoutFile : layoutInfoFolder.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".xml");
        }
    })) {
        try {
            result.addEntry(layoutFile.getName(), FileUtils.readFileToString(layoutFile));
        } catch (IOException e) {
            L.e(e, "cannot load layout file information. Try a clean build");
        }
    }
    return result;
}