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.sketchy.server.action.GetRenderedImageFiles.java

@Override
public JSONServletResult execute(HttpServletRequest request) throws Exception {
    JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS);
    try {//from ww  w .j a v a 2  s .  c o  m
        File[] files = HttpServer.IMAGE_UPLOAD_DIRECTORY.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File arg0, String filename) {
                return (StringUtils.endsWithIgnoreCase(filename, "rendered.dat"));
            }
        });

        String imageName = request.getParameter("imageName");

        List<Object> rows = new ArrayList<Object>();

        for (File file : files) {

            if (file.getName().startsWith(imageName)) {
                Map<String, Object> row = new HashMap<String, Object>();
                File dimFile = new File(file.getPath());
                if (dimFile.exists()) {
                    String json = FileUtils.readFileToString(dimFile);
                    RenderedImageAttributes renderedImageAttributes = (RenderedImageAttributes) ImageAttributes
                            .fromJson(json);
                    row.put("imageSize", Integer.toString(renderedImageAttributes.getWidth()) + " x "
                            + Integer.toString(renderedImageAttributes.getHeight()));
                    row.put("imageName", renderedImageAttributes.getImageName());
                    row.put("penWidth", renderedImageAttributes.getPenWidth());
                    row.put("filename", renderedImageAttributes.getImageFilename());
                    row.put("drawingSize", renderedImageAttributes.getDrawingSize());
                    row.put("contrast", renderedImageAttributes.getContrast());
                    row.put("brightness", renderedImageAttributes.getBrightness());
                    row.put("threshold", renderedImageAttributes.getThreshold());
                }

                rows.add(row);
            }
        }
        jsonServletResult.put("rows", rows);
    } catch (Throwable t) {
        jsonServletResult = new JSONServletResult(Status.ERROR, "Error! " + t.getMessage());
    }
    return jsonServletResult;
}

From source file:TrainLogistic.java

static void mainToOutput(String[] args, PrintWriter output) throws Exception {
    if (parseArgs(args)) {
        double logPEstimate = 0;
        int samples = 0;
        /*read files in dir of inputFile*/
        int fi = 0;//file ID
        File file = new File(inputFile);
        String[] fns = file.list(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                if (name.endsWith(".svm")) {
                    return true;
                } else {
                    return false;
                }/*  w w w. j a v  a2s .c om*/
            }
        });

        String[] ss = new String[lmp.getNumFeatures() + 1];
        String[] iv = new String[2];
        OnlineLogisticRegression lr = lmp.createRegression();
        while (fi < fns.length) {
            for (int pass = 0; pass < passes; pass++) {
                BufferedReader in = open(inputFile + fns[fi]);
                System.out.println(pass + 1);
                try {
                    // read variable names

                    String line = in.readLine();
                    int lineCount = 1;
                    while (line != null) {
                        // for each new line, get target and predictors
                        Vector input = new RandomAccessSparseVector(lmp.getNumFeatures());
                        ss = line.split(" ");
                        int targetValue;
                        if (ss[0].startsWith("+"))
                            targetValue = 1;
                        else
                            targetValue = 0;
                        int k = 1;
                        while (k < ss.length) {
                            iv = ss[k].split(":");
                            input.setQuick(Integer.valueOf(iv[0]) - 1, Double.valueOf(iv[1]));
                            //System.out.printf("%d-----%d:%.4f====%d\n", k,Integer.valueOf(iv[0])-1,Double.valueOf(iv[1]),lineCount);
                            k++;
                        }
                        input.setQuick(lmp.getNumFeatures() - 1, 1);
                        // check performance while this is still news
                        double logP = lr.logLikelihood(targetValue, input);
                        if (!Double.isInfinite(logP)) {
                            if (samples < 20) {
                                logPEstimate = (samples * logPEstimate + logP) / (samples + 1);
                            } else {
                                logPEstimate = 0.95 * logPEstimate + 0.05 * logP;
                            }
                            samples++;
                        }
                        double p = lr.classifyScalar(input);
                        if (scores) {
                            output.printf(Locale.ENGLISH, "%10d %2d %10.2f %2.4f %10.4f %10.4f\n", samples,
                                    targetValue, lr.currentLearningRate(), p, logP, logPEstimate);
                        }
                        // now update model
                        lr.train(targetValue, input);
                        if ((lineCount) % 1000 == 0)
                            System.out.printf("%d\t", lineCount);
                        line = in.readLine();
                        lineCount++;
                    }
                } finally {
                    Closeables.closeQuietly(in);
                }
                System.out.println();
            }
            fi++;
        }

        FileOutputStream modelOutput = new FileOutputStream(outputFile);
        try {
            saveTo(modelOutput, lr);
        } finally {
            Closeables.closeQuietly(modelOutput);
        }
        /*
              output.printf(Locale.ENGLISH, "%d\n", lmp.getNumFeatures());
              output.printf(Locale.ENGLISH, "%s ~ ", lmp.getTargetVariable());
              String sep = "";
              for (String v : csv.getTraceDictionary().keySet()) {
                double weight = predictorWeight(lr, 0, csv, v);
                if (weight != 0) {
                  output.printf(Locale.ENGLISH, "%s%.3f*%s", sep, weight, v);
                  sep = " + ";
                }
              }
              output.printf("\n");
              model = lr;
              for (int row = 0; row < lr.getBeta().numRows(); row++) {
                for (String key : csv.getTraceDictionary().keySet()) {
                  double weight = predictorWeight(lr, row, csv, key);
                  if (weight != 0) {
                    output.printf(Locale.ENGLISH, "%20s %.5f\n", key, weight);
                  }
                }
                for (int column = 0; column < lr.getBeta().numCols(); column++) {
                  output.printf(Locale.ENGLISH, "%15.9f ", lr.getBeta().get(row, column));
                }
                output.println();
              }*/
    }
}

From source file:com.apifest.doclet.integration.tests.DocletModeTest.java

private void findFile(String directory, String name, final String extension) {
    File dir = new File(directory);

    File[] files = dir.listFiles(new FilenameFilter() {
        public boolean accept(File directory, String fileName) {
            if (fileName.startsWith("all") && fileName.endsWith(extension)) {
                return true;
            }//  w w  w.j av a  2s.  co m
            return false;
        }
    });
    for (File f : files) {
        Assert.assertEquals(name, f.getName());
        f.deleteOnExit();
    }
}

From source file:com.devbury.mkremote.server.QuickLaunchServiceImpl.java

public ArrayList<LaunchItem> list(String dir) {
    Base64 base64 = new Base64();
    JFileChooser chooser = new JFileChooser();
    File new_dir = newFileDir(dir);
    logger.debug("Looking for files in {}", new_dir.getAbsolutePath());
    ArrayList<LaunchItem> items = new ArrayList<LaunchItem>();
    if (isSupported()) {
        if (new_dir.isDirectory()) {
            FilenameFilter filter = new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return !name.startsWith(".");
                }//w  w w.ja v a2s.  c om
            };
            for (File f : new_dir.listFiles(filter)) {
                if (!f.isHidden()) {
                    LaunchItem item = new LaunchItem();
                    item.setName(f.getName());
                    item.setPath(dir);
                    if (f.isDirectory()) {
                        if (isMac() && f.getName().endsWith(".app")) {
                            item.setType(LaunchItem.FILE_TYPE);
                            item.setName(f.getName().substring(0, f.getName().length() - 4));
                        } else {
                            item.setType(LaunchItem.DIR_TYPE);
                        }
                    } else {
                        item.setType(LaunchItem.FILE_TYPE);
                    }
                    Icon icon = chooser.getIcon(f);
                    BufferedImage bi = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(),
                            BufferedImage.TYPE_INT_RGB);
                    icon.paintIcon(null, bi.createGraphics(), 0, 0);
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    try {
                        ImageIO.write(bi, "png", os);
                        item.setIcon(base64.encodeToString(os.toByteArray()));
                    } catch (IOException e) {
                        logger.debug("could not write image {}", e);
                        item.setIcon(null);
                    }
                    logger.debug("Adding LaunchItem : {}", item);
                    items.add(item);
                } else {
                    logger.debug("Skipping hidden file {}", f.getName());
                }
            }
        }
    } else {
        new Thread() {
            @Override
            public void run() {
                JOptionPane.showMessageDialog(null,
                        "We are sorry but quick launch is not supported on your platform",
                        "Quick Launch Not Supported", JOptionPane.ERROR_MESSAGE);
            }
        }.start();
    }
    return items;
}

From source file:gov.nih.nci.cacis.cdw.CDWPendingLoader.java

public void loadPendingCDWDocuments(CDWLoader loader) {
    LOG.debug("Pending folder: " + cdwLoadPendingDirectory);
    LOG.info("SSSSSSS STARTED CDW LOAD SSSSSSSS");
    File pendingFolder = new File(cdwLoadPendingDirectory);
    FilenameFilter loadFileFilter = new FilenameFilter() {

        public boolean accept(File dir, String name) {
            return true;
        }/*ww  w.  j av a2 s.  c o  m*/
    };
    String[] loadFileNames = pendingFolder.list(loadFileFilter);
    LOG.info("Total Files to Load: " + loadFileNames.length);
    int filesLoaded = 0;
    int fileNumber = 0;
    for (String fileName : loadFileNames) {
        fileNumber++;
        LOG.info("Processing File [" + fileNumber + "] " + fileName);
        File loadFile = new File(cdwLoadPendingDirectory + "/" + fileName);
        try {
            final String[] params = StringUtils.split(fileName, "@@");
            String siteId = params[0];
            String studyId = params[1];
            String patientId = params[2];
            LOG.debug("SiteId: " + siteId);

            // the below code is not working, so parsing the file name for attributes.
            // DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            // DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            // Document document = documentBuilder.parse(loadFile);
            // XPathFactory factory = XPathFactory.newInstance();
            // XPath xPath = factory.newXPath();
            // String siteID = xPath.evaluate("/caCISRequest/clinicalMetaData/@siteIdRoot", document);

            loader.load(FileUtils.getStringFromFile(loadFile), loader.generateContext(), studyId, siteId,
                    patientId);
            LOG.info(String.format("Successfully processed file [%s] [%s] and moving into [%s]", fileNumber,
                    loadFile.getAbsolutePath(), cdwLoadProcessedDirectory));
            org.apache.commons.io.FileUtils.moveFileToDirectory(loadFile, new File(cdwLoadProcessedDirectory),
                    true);
            filesLoaded++;
        } catch (Exception e) {
            LOG.error(e.getMessage());
            e.printStackTrace();
            try {
                Properties props = new Properties();
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.host", cdwLoadSenderHost);
                props.put("mail.smtp.port", cdwLoadSenderPort);

                Session session = Session.getInstance(props, new javax.mail.Authenticator() {

                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(cdwLoadSenderUser, cdwLoadSenderPassword);
                    }
                });
                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress(cdwLoadSenderAddress));
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(cdwLoadRecipientAddress));
                message.setSubject(cdwLoadNotificationSubject);
                message.setText(cdwLoadNotificationMessage + " [" + e.getMessage() + "]");

                Transport.send(message);
                org.apache.commons.io.FileUtils.moveFileToDirectory(loadFile, new File(cdwLoadErrorDirectory),
                        true);
                // TODO add logic to send email
            } catch (Exception e1) {
                LOG.error(e1.getMessage());
                e1.printStackTrace();
            }
        }
    }
    LOG.info("Files Successfully Loaded: " + filesLoaded);
    LOG.info("EEEEEEE ENDED CDW LOAD EEEEEEE");
}

From source file:de.sub.goobi.persistence.apache.FolderInformation.java

/**
 * Get images tif directory.//w  ww.  j av a2 s  .co m
 *
 * @param useFallBack
 *            boolean
 * @return String
 */
public String getImagesTifDirectory(boolean useFallBack) {
    SafeFile dir = new SafeFile(getImagesDirectory());
    DIRECTORY_SUFFIX = ConfigCore.getParameter("DIRECTORY_SUFFIX", "tif");
    DIRECTORY_PREFIX = ConfigCore.getParameter("DIRECTORY_PREFIX", "orig");
    /* nur die _tif-Ordner anzeigen, die nicht mir orig_ anfangen */
    FilenameFilter filterVerz = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return (name.endsWith("_" + DIRECTORY_SUFFIX) && !name.startsWith(DIRECTORY_PREFIX + "_"));
        }
    };

    String tifOrdner = "";
    String[] verzeichnisse = dir.list(filterVerz);

    if (verzeichnisse != null) {
        for (int i = 0; i < verzeichnisse.length; i++) {
            tifOrdner = verzeichnisse[i];
        }
    }

    if (tifOrdner.equals("") && useFallBack) {
        String suffix = ConfigCore.getParameter("MetsEditorDefaultSuffix", "");
        if (!suffix.equals("")) {
            String[] folderList = dir.list();
            for (String folder : folderList) {
                if (folder.endsWith(suffix)) {
                    tifOrdner = folder;
                    break;
                }
            }
        }
    }
    if (!tifOrdner.equals("") && useFallBack) {
        String suffix = ConfigCore.getParameter("MetsEditorDefaultSuffix", "");
        if (!suffix.equals("")) {
            SafeFile tif = new SafeFile(tifOrdner);
            String[] files = tif.list();
            if (files == null || files.length == 0) {
                String[] folderList = dir.list();
                for (String folder : folderList) {
                    if (folder.endsWith(suffix)) {
                        tifOrdner = folder;
                        break;
                    }
                }
            }
        }
    }

    if (tifOrdner.equals("")) {
        tifOrdner = this.title + "_" + DIRECTORY_SUFFIX;
    }

    String rueckgabe = getImagesDirectory() + tifOrdner;

    if (!rueckgabe.endsWith(File.separator)) {
        rueckgabe += File.separator;
    }

    return rueckgabe;
}

From source file:com.sketchy.server.action.GetImageFiles.java

@Override
public JSONServletResult execute(HttpServletRequest request) throws Exception {
    JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS);
    try {/*ww w  .  j  av  a 2s.co  m*/
        File[] files = HttpServer.IMAGE_UPLOAD_DIRECTORY.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File arg0, String filename) {
                return (StringUtils.endsWithIgnoreCase(filename, ".dat")
                        && (!StringUtils.endsWithIgnoreCase(filename, "rendered.dat")));
            }
        });

        Arrays.sort(files, new Comparator<File>() {
            @Override
            public int compare(File f1, File f2) {
                if ((f1 == null) || (f2 == null))
                    return 0; // Shouldn't ever be null, but if so if either is null, then just return 0; 
                return f1.getName().compareToIgnoreCase(f2.getName());
            }
        });

        List<Object> rows = new ArrayList<Object>();
        for (File file : files) {

            Map<String, Object> row = new HashMap<String, Object>();
            File dimFile = new File(file.getPath());
            if (dimFile.exists()) {
                String json = FileUtils.readFileToString(dimFile);
                SourceImageAttributes sourceImageAttributes = (SourceImageAttributes) ImageAttributes
                        .fromJson(json);
                row.put("imageSize", Integer.toString(sourceImageAttributes.getWidth()) + " x "
                        + Integer.toString(sourceImageAttributes.getHeight()));
                row.put("imageName", sourceImageAttributes.getImageName());
                row.put("filename", sourceImageAttributes.getImageFilename());
            }

            rows.add(row);
        }

        jsonServletResult.put("rows", rows);
    } catch (Throwable t) {
        jsonServletResult = new JSONServletResult(Status.ERROR, "Error! " + t.getMessage());
    }

    return jsonServletResult;
}

From source file:it.digitalhumanities.dhcpublisher.DHCPublisher.java

private void convertFile(final File subDir) throws DocumentException, IOException {

    File[] htmlFiles = subDir.listFiles(new FilenameFilter() {

        @Override//from  w w  w. j  ava 2  s  .c  om
        public boolean accept(File dir, String name) {
            return name.endsWith(".html");
        }
    });

    if (htmlFiles.length > 0) {
        File htmlFile = htmlFiles[0];
        String targetName = htmlFile.getName().substring(0, htmlFile.getName().length() - 4) + "pdf";

        Document document = new Document();
        File targetFile = new File(subDir, targetName);
        if (targetFile.exists()) {
            targetFile.delete();
        }

        try (FileOutputStream fos = new FileOutputStream(targetFile)) {
            PdfWriter writer = PdfWriter.getInstance(document, fos);
            writer.getAcroForm().setNeedAppearances(true);
            document.open();

            HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
            htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
            htmlContext.setImageProvider(new AbstractImageProvider() {
                public String getImageRootPath() {
                    return subDir.getAbsolutePath();
                }
            });

            CSSResolver cssResolver = XMLWorkerHelper.getInstance().getDefaultCssResolver(true);

            Pipeline<?> pipeline = new CssResolverPipeline(cssResolver,
                    new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));

            XMLWorker worker = new XMLWorker(pipeline, true);
            XMLParser p = new XMLParser(worker);

            try (FileInputStream fis = new FileInputStream(htmlFile)) {
                p.parse(fis);
            } finally {
                document.close();
            }
        }
    } else {
        throw new IllegalArgumentException(subDir + " does not contain HTML files!");
    }
}

From source file:com.googlecode.deadalus.server.internal.LocalObjectFactoryRegistry.java

public final void init() {
    // for now we make a single pass over the scandirectory
    File scanDirectory = new File(deployDirectory);
    if (scanDirectory.exists() && scanDirectory.isDirectory()) {
        File[] jarFiles = scanDirectory.listFiles(new FilenameFilter() {
            @Override//from www.  j  a va 2s .co  m
            public boolean accept(File dir, String name) {
                return name.endsWith(".jar");
            }
        });
        for (File jarFile : jarFiles) {
            try {
                addJarFile(jarFile);
            } catch (IOException e) {
                //@todo: add log statement
            }
        }
    }
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.comments.pipeline.FullDebateContentReader.java

@Override
public void initialize(UimaContext context) throws ResourceInitializationException {
    super.initialize(context);

    File[] fileArray = sourceLocation.listFiles(new FilenameFilter() {
        @Override/*from w  w w  .  j  a v  a  2 s. c  om*/
        public boolean accept(File dir, String name) {
            return name.endsWith(".xml");
        }
    });

    if (fileArray != null) {
        this.files.addAll(Arrays.asList(fileArray));
    }

}