Example usage for java.util HashSet contains

List of usage examples for java.util HashSet contains

Introduction

In this page you can find the example usage for java.util HashSet contains.

Prototype

public boolean contains(Object o) 

Source Link

Document

Returns true if this set contains the specified element.

Usage

From source file:de.biomedical_imaging.ij.steger.LineDetector.java

private Junctions fixJunctions(Lines lines, Junctions junctions) {
    /*/*from  w  ww .j a v  a2 s  .  c o  m*/
     * For some reason, the x and y coordinates are permuted
     */
    for (Junction junction : junctions) {
        float help = junction.x;
        junction.x = junction.y;
        junction.y = help;
    }

    Junctions newJunctions = new Junctions(junctions.getFrame());
    ArrayList<Point2D.Float> processedJunctions = new ArrayList<Point2D.Float>();
    for (int i = 0; i < junctions.size(); i++) {
        Junction junc = junctions.get(i);
        Line mainLine = null;
        int mainLineIndex = -1;
        int mainLinePos = -1;
        ArrayList<Line> secondaryLines = new ArrayList<Line>();
        ArrayList<Integer> secondaryLineIndex = new ArrayList<Integer>();
        ArrayList<Integer> secondaryLinePos = new ArrayList<Integer>();

        //Verarbeite jede Junction-Position nur einmal.
        if (!processedJunctions.contains(new Point2D.Float(junc.x, junc.y))) { //processed[(int)junc.x][(int)junc.y]==0

            processedJunctions.add(new Point2D.Float(junc.x, junc.y));

            /*
             * Finde die Sekundrlinien und Hauptlinien
             */
            for (int j = 0; j < lines.size(); j++) {
                Line l = lines.get(j);

                double[] mindist = minDistance(l, junc.x, junc.y);
                if (mindist[0] < 0.1) { //Wenn der Punkt auf der Linie liegt, analysiere genauer

                    if (mindist[1] == 0 || mindist[1] == (l.num - 1)) { //Wenn der Junction-Point am Ende oder am Anfang liegt, ist es sekundre Linie.
                        secondaryLines.add(l);
                        secondaryLineIndex.add(j);
                        secondaryLinePos.add((int) mindist[1]);
                    } else { // Wenn er innerhalb der Linie liegt, ist dies die Hauptlinie.

                        if (mainLine != null) {
                            if (mainLine.getID() == l.getID()) {
                                continue;
                            }
                            log("h, zwei Hauptlininen geht nich..." + mainLine.getID() + " x " + junc.x
                                    + " y " + junc.y);
                            log("h, zwei Hauptlininen geht nich..." + l.getID() + " x " + junc.x + " y "
                                    + junc.y);
                        }
                        mainLine = l;
                        mainLineIndex = j;
                        mainLinePos = (int) mindist[1];

                    }
                }
            }
            if (mainLine != null) {
                for (int j = 0; j < secondaryLines.size(); j++) {
                    Junction newJunc = new Junction();
                    newJunc.cont1 = mainLineIndex;
                    newJunc.cont2 = secondaryLineIndex.get(j);
                    newJunc.x = junc.x;
                    newJunc.y = junc.y;
                    newJunc.pos = mainLinePos;
                    //lines.get(newJunc.cont1).setContourClass(reconstructContourClass(lines.get(newJunc.cont1), mainLinePos));
                    //lines.get(newJunc.cont2).setContourClass(reconstructContourClass(lines.get(newJunc.cont2), secondaryLinePos.get(j)));
                    newJunctions.add(newJunc);
                    log("NewJunc Mainline: " + lines.get(newJunc.cont1).getID() + "-"
                            + lines.get(newJunc.cont2).getID() + " pos " + newJunc.pos + " num "
                            + lines.get(newJunc.cont1).num);

                }
            } else {
                //In manchen Fllen gibt es keine Hauptlinie... (bug im Algorithmus, ich bin aber nicht fhig ihn zu finden=.
                HashSet<Integer> uniqueIDs = new HashSet<Integer>();
                ArrayList<Line> uniqueLines = new ArrayList<Line>();
                ArrayList<Integer> uniqueLineIndex = new ArrayList<Integer>();
                ArrayList<Integer> uniqueLinePos = new ArrayList<Integer>();
                for (int j = 0; j < secondaryLines.size(); j++) {
                    if (!uniqueIDs.contains(secondaryLines.get(j).getID())) {
                        uniqueIDs.add(secondaryLines.get(j).getID());
                        uniqueLines.add(secondaryLines.get(j));
                        uniqueLineIndex.add(secondaryLineIndex.get(j));
                        uniqueLinePos.add(secondaryLinePos.get(j));

                    }

                }
                for (int j = 0; j < uniqueLines.size(); j++) {
                    for (int k = j + 1; k < uniqueLines.size(); k++) {
                        Junction newJunc = new Junction();
                        newJunc.cont1 = uniqueLineIndex.get(j);
                        newJunc.cont2 = uniqueLineIndex.get(k);
                        newJunc.x = junc.x;
                        newJunc.y = junc.y;
                        newJunc.pos = uniqueLinePos.get(j);
                        newJunctions.add(newJunc);
                        log("NewJunc Second: " + lines.get(newJunc.cont1).getID() + "-"
                                + lines.get(newJunc.cont2).getID() + " pos " + newJunc.pos + " num "
                                + lines.get(newJunc.cont1).num);

                        //lines.get(newJunc.cont1).setContourClass(reconstructContourClass(lines.get(newJunc.cont1), uniqueLinePos.get(j)));
                        //lines.get(newJunc.cont2).setContourClass(reconstructContourClass(lines.get(newJunc.cont2), uniqueLinePos.get(k)));
                        alreadyProcessedJunctionPoints.add(newJunctions.size() - 1);

                    }
                }
            }

        }
    }
    return newJunctions;

}

From source file:com.mentor.questa.vrm.jenkins.QuestaVrmHostAction.java

private CategoryDataset buildDataSet(StaplerRequest req) {
    boolean showAction = Boolean.valueOf(req.getParameter("showActions")) || getActionCookie(req);
    DataSetBuilder<String, Long> dsb = new DataSetBuilder<String, Long>();

    PriorityQueue<Pair> pq = new PriorityQueue<Pair>();
    HashMap<String, Integer> hostCount = new HashMap<String, Integer>();
    for (TestResult temp : getRegressionResult().getActions()) {
        QuestaVrmAbstractResult action = (QuestaVrmAbstractResult) temp;
        if (showAction || action instanceof QuestaVrmTestResult) {
            if (action.getStartTime() == -1 || action.getDoneTime() == -1) {
                continue;
            }//from  ww  w.j ava2 s .  c o  m
            pq.add(new Pair(action.getStartTimeDate(), action.getHost(), 1));
            pq.add(new Pair(action.getDoneTimeDate(), action.getHost(), -1));
            hostCount.put(action.getHost(), 0);
        }
    }

    if (pq.isEmpty()) {
        return dsb.build();
    }

    long offset = getRegressionResult().getRegressionBegin().getTime();
    int noOfTests;
    HashSet<String> visited = new HashSet<String>();

    while (!pq.isEmpty()) {
        long currentKey = pq.peek().date.getTime();

        while (!pq.isEmpty() && pq.peek().date.getTime() == currentKey) {
            Pair current = pq.peek();
            noOfTests = hostCount.get(current.host);
            while (!pq.isEmpty() && pq.peek().compareTo(current) == 0) {
                noOfTests += pq.poll().diff;
            }
            dsb.add(noOfTests, current.host, (current.date.getTime() - offset) / 1000);
            hostCount.put(current.host, noOfTests);
            visited.add(current.host);

        }
        for (String host : hostCount.keySet()) {
            if (!visited.contains(host)) {
                dsb.add(hostCount.get(host), host, (currentKey - offset) / 1000);
            }
        }
        visited.clear();

    }
    return dsb.build();

}

From source file:net.jsign.PESignerTest.java

/**
 * Tests that a custom Timestamper implementation can be provided.
 * @throws Exception // ww w.  j ava 2 s .com
 */
public void testWithTimestamper() throws Exception {
    File sourceFile = new File("target/test-classes/wineyes.exe");
    File targetFile = new File("target/test-classes/wineyes-timestamped-authenticode.exe");

    FileUtils.copyFile(sourceFile, targetFile);

    PEFile peFile = new PEFile(targetFile);

    final HashSet<Boolean> called = new HashSet<Boolean>();

    PESigner signer = new PESigner(getKeyStore(), ALIAS, PRIVATE_KEY_PASSWORD);
    signer.withDigestAlgorithm(DigestAlgorithm.SHA1);
    signer.withTimestamping(true);
    signer.withTimestamper(new AuthenticodeTimestamper() {

        @Override
        protected CMSSignedData timestamp(DigestAlgorithm algo, byte[] encryptedDigest)
                throws IOException, TimestampingException {
            called.add(true);
            return super.timestamp(algo, encryptedDigest);
        }

    });
    signer.sign(peFile);

    peFile = new PEFile(targetFile);
    List<CMSSignedData> signatures = peFile.getSignatures();
    assertNotNull(signatures);
    assertEquals(1, signatures.size());

    CMSSignedData signature = signatures.get(0);

    assertNotNull(signature);

    assertTrue("expecting our Timestamper to be used", called.contains(true));
}

From source file:gpl.pierrick.brihaye.aramorph.InMemoryDictionaryHandler.java

/** Loads a dictionary into a <CODE>Set</CODE> where the <PRE>key</PRE> is entry and its <PRE>value</PRE> is a
 * <CODE>List</CODE> (each entry can have multiple values)
 * @param set The set/*from w w  w .  ja  v a  2 s  .  co  m*/
 * @param name A human-readable name
 * @param is The stream
 * @throws RuntimeException If a problem occurs when reading the dictionary
 */
private void loadDictionary(Map set, String name, InputStream is) throws RuntimeException { //TODO : should be static
    HashSet lemmas = new HashSet();
    int forms = 0;
    String lemmaID = "";
    System.out.print("Loading dictionary : " + name + " ");
    try {
        LineNumberReader IN = new LineNumberReader(new InputStreamReader(is, "ISO8859_1"));
        String line = null;
        while ((line = IN.readLine()) != null) {
            if ((IN.getLineNumber() % 1000) == 1)
                System.out.print(".");
            // new lemma
            if (line.startsWith(";; ")) {
                lemmaID = line.substring(3);
                // lemmaID's must be unique
                if (lemmas.contains(lemmaID))
                    throw new RuntimeException("Lemma " + lemmaID + "in " + name + " (line "
                            + IN.getLineNumber() + ") isn't unique");
                lemmas.add(lemmaID);
            }
            // comment
            else if (line.startsWith(";")) {
            } else {
                String split[] = line.split("\t", -1); //-1 to avoid triming of trail values

                //a little error-checking won't hurt :
                if (split.length != 4) {
                    throw new RuntimeException("Entry in " + name + " (line " + IN.getLineNumber()
                            + ") doesn't have 4 fields (3 tabs)");
                }
                String entry = split[0]; // get the entry for use as key
                String vocalization = split[1];
                String morphology = split[2];
                String glossPOS = split[3];

                String gloss;
                String POS;

                Pattern p;
                Matcher m;

                // two ways to get the POS info:
                // (1) explicitly, by extracting it from the gloss field:
                p = Pattern.compile(".*" + "<pos>(.+?)</pos>" + ".*");
                m = p.matcher(glossPOS);
                if (m.matches()) {
                    POS = m.group(1); //extract POS from glossPOS
                    gloss = glossPOS; //we clean up the gloss later (see below)
                }
                // (2) by deduction: use the morphology (and sometimes the voc and gloss) to deduce the appropriate POS
                else {
                    // we need the gloss to guess proper names
                    gloss = glossPOS;
                    // null prefix or suffix
                    if (morphology.matches("^(Pref-0|Suff-0)$")) {
                        POS = "";
                    } else if (morphology.matches("^F" + ".*")) {
                        POS = vocalization + "/FUNC_WORD";
                    } else if (morphology.matches("^IV" + ".*")) {
                        POS = vocalization + "/VERB_IMPERFECT";
                    } else if (morphology.matches("^PV" + ".*")) {
                        POS = vocalization + "/VERB_PERFECT";
                    } else if (morphology.matches("^CV" + ".*")) {
                        POS = vocalization + "/VERB_IMPERATIVE";
                    } else if (morphology.matches("^N" + ".*")) {
                        // educated guess (99% correct)
                        if (gloss.matches("^[A-Z]" + ".*")) {
                            POS = vocalization + "/NOUN_PROP";
                        }
                        // (was NOUN_ADJ: some of these are really ADJ's and need to be tagged manually)
                        else if (vocalization.matches(".*" + "iy~$")) {
                            POS = vocalization + "/NOUN";
                        } else
                            POS = vocalization + "/NOUN";
                    } else {
                        throw new RuntimeException(
                                "No POS can be deduced in " + name + " (line " + IN.getLineNumber() + ")");
                    }
                }

                // clean up the gloss: remove POS info and extra space, and convert upper-ASCII  to lower (it doesn't convert well to UTF-8)
                gloss = gloss.replaceFirst("<pos>.+?</pos>", "");
                gloss = gloss.trim();
                //TODO : we definitely need a translate() method in the java packages !
                gloss = gloss.replaceAll(";", "/"); //TODO : is it necessary ?
                gloss = gloss.replaceAll("", "A");
                gloss = gloss.replaceAll("", "A");
                gloss = gloss.replaceAll("", "A");
                gloss = gloss.replaceAll("", "A");
                gloss = gloss.replaceAll("", "A");
                gloss = gloss.replaceAll("", "A");
                gloss = gloss.replaceAll("", "C");
                gloss = gloss.replaceAll("", "E");
                gloss = gloss.replaceAll("", "E");
                gloss = gloss.replaceAll("", "E");
                gloss = gloss.replaceAll("", "E");
                gloss = gloss.replaceAll("", "I");
                gloss = gloss.replaceAll("", "I");
                gloss = gloss.replaceAll("", "I");
                gloss = gloss.replaceAll("", "I");
                gloss = gloss.replaceAll("", "N");
                gloss = gloss.replaceAll("", "O");
                gloss = gloss.replaceAll("", "O");
                gloss = gloss.replaceAll("", "O");
                gloss = gloss.replaceAll("", "O");
                gloss = gloss.replaceAll("", "O");
                gloss = gloss.replaceAll("", "U");
                gloss = gloss.replaceAll("", "U");
                gloss = gloss.replaceAll("", "U");
                gloss = gloss.replaceAll("", "U");
                gloss = gloss.replaceAll("", "a");
                gloss = gloss.replaceAll("", "a");
                gloss = gloss.replaceAll("", "a");
                gloss = gloss.replaceAll("", "a");
                gloss = gloss.replaceAll("", "a");
                gloss = gloss.replaceAll("", "a");
                gloss = gloss.replaceAll("", "c");
                gloss = gloss.replaceAll("", "e");
                gloss = gloss.replaceAll("", "e");
                gloss = gloss.replaceAll("", "e");
                gloss = gloss.replaceAll("", "e");
                gloss = gloss.replaceAll("", "i");
                gloss = gloss.replaceAll("", "i");
                gloss = gloss.replaceAll("", "i");
                gloss = gloss.replaceAll("", "i");
                gloss = gloss.replaceAll("", "n");
                gloss = gloss.replaceAll("", "o");
                gloss = gloss.replaceAll("", "o");
                gloss = gloss.replaceAll("", "o");
                gloss = gloss.replaceAll("", "o");
                gloss = gloss.replaceAll("", "o");
                gloss = gloss.replaceAll("", "u");
                gloss = gloss.replaceAll("", "u");
                gloss = gloss.replaceAll("", "u");
                gloss = gloss.replaceAll("", "u");
                gloss = gloss.replaceAll("", "AE");
                gloss = gloss.replaceAll("", "Sh");
                gloss = gloss.replaceAll("", "Zh");
                gloss = gloss.replaceAll("", "ss");
                gloss = gloss.replaceAll("", "ae");
                gloss = gloss.replaceAll("", "sh");
                gloss = gloss.replaceAll("", "zh");
                // note that although we read 4 fields from the dict we now save 5 fields in the hash table
                // because the info in last field, glossPOS, was split into two: gloss and POS
                DictionaryEntry de = new DictionaryEntry(entry, lemmaID, vocalization, morphology, gloss, POS);
                if (set.containsKey(entry)) {
                    ((Collection) set.get(entry)).add(de);
                } else
                    set.put(entry, de);
                forms++;
            }
        }
        IN.close();
        System.out.println();
        if (!"".equals(lemmaID))
            System.out.print(lemmas.size() + " lemmas and ");
        System.out.println(set.size() + " entries totalizing " + forms + " forms");
    } catch (IOException e) {
        throw new RuntimeException("Can not open : " + name);
    }
}

From source file:net.sf.jabref.model.database.BibtexDatabase.java

/**
 * If the label represents a string contained in this database, returns
 * that string's content. Resolves references to other strings, taking
 * care not to follow a circular reference pattern.
 * If the string is undefined, returns null.
 *//*from   w w  w. jav a2 s. co m*/
private String resolveString(String label, HashSet<String> usedIds) {
    for (BibtexString string : bibtexStrings.values()) {

        //Util.pr(label+" : "+string.getName());
        if (string.getName().toLowerCase().equals(label.toLowerCase())) {

            // First check if this string label has been resolved
            // earlier in this recursion. If so, we have a
            // circular reference, and have to stop to avoid
            // infinite recursion.
            if (usedIds.contains(string.getId())) {
                LOGGER.info("Stopped due to circular reference in strings: " + label);
                return label;
            }
            // If not, log this string's ID now.
            usedIds.add(string.getId());

            // Ok, we found the string. Now we must make sure we
            // resolve any references to other strings in this one.
            String result = string.getContent();
            result = resolveContent(result, usedIds);

            // Finished with recursing this branch, so we remove our
            // ID again:
            usedIds.remove(string.getId());

            return result;
        }
    }

    // If we get to this point, the string has obviously not been defined locally.
    // Check if one of the standard BibTeX month strings has been used:
    MonthUtil.Month month = MonthUtil.getMonthByShortName(label);
    if (month.isValid()) {
        return month.fullName;
    } else {
        return null;
    }
}

From source file:com.couchbase.client.ViewConnection.java

/**
 * Reconfigures the connected ViewNodes.
 *
 * When a reconfiguration event happens, new ViewNodes may need to be added
 * or old ones need to be removed from the current configuration. This method
 * takes care that those operations are performed in the correct order and
 * are executed in a thread-safe manner.
 *
 * @param bucket the bucket which has been rebalanced.
 *//*from  w  w  w  .  j  a v a  2s. c  o  m*/
public void reconfigure(Bucket bucket) {
    reconfiguring = true;

    try {
        // get a new collection of addresses from the received config
        HashSet<SocketAddress> newServerAddresses = new HashSet<SocketAddress>();
        List<InetSocketAddress> newServers = AddrUtil.getAddressesFromURL(bucket.getConfig().getCouchServers());
        for (InetSocketAddress server : newServers) {
            // add parsed address to our collections
            newServerAddresses.add(server);
        }

        // split current nodes to "odd nodes" and "stay nodes"
        ArrayList<ViewNode> shutdownNodes = new ArrayList<ViewNode>();
        ArrayList<ViewNode> stayNodes = new ArrayList<ViewNode>();
        ArrayList<InetSocketAddress> stayServers = new ArrayList<InetSocketAddress>();

        wlock.lock();
        try {
            for (ViewNode current : couchNodes) {
                if (newServerAddresses.contains(current.getSocketAddress())) {
                    stayNodes.add(current);
                    stayServers.add((InetSocketAddress) current.getSocketAddress());
                } else {
                    shutdownNodes.add(current);
                }
            }

            // prepare a collection of addresses for new nodes
            newServers.removeAll(stayServers);

            // create a collection of new nodes
            List<ViewNode> newNodes = createConnections(newServers);

            // merge stay nodes with new nodes
            List<ViewNode> mergedNodes = new ArrayList<ViewNode>();
            mergedNodes.addAll(stayNodes);
            mergedNodes.addAll(newNodes);

            couchNodes = mergedNodes;
        } finally {
            wlock.unlock();
        }

        // shutdown for the oddNodes
        for (ViewNode qa : shutdownNodes) {
            try {
                qa.shutdown();
            } catch (IOException e) {
                getLogger().error("Error shutting down connection to " + qa.getSocketAddress());
            }
        }

    } catch (IOException e) {
        getLogger().error("Connection reconfiguration failed", e);
    } finally {
        reconfiguring = false;
    }
}

From source file:com.antsdb.saltedfish.server.mysql.replication.MysqlSlave.java

private Parameters toParameters(TableMeta meta, Pair<Row> pair) {
    List<Column> colsAft = pair.getAfter().getColumns();
    List<Column> colsBef = pair.getBefore().getColumns();

    Object[] pureValues;/* w  ww. j a  v  a2 s .c  o m*/

    PrimaryKeyMeta keyMeta = meta.getPrimaryKey();
    if (keyMeta != null) {
        List<ColumnMeta> primaryKeys = keyMeta.getColumns(meta);
        // generate set for pk column id 
        HashSet<Integer> pkNum = new HashSet<>();
        for (ColumnMeta key : primaryKeys) {
            pkNum.add(key.getColumnId());
        }

        pureValues = new Object[colsAft.size() + pkNum.size()];

        for (int i = 0; i < colsAft.size(); i++) {
            pureValues[i] = toParameter(colsAft.get(i));
        }
        // appending parameters for where clause
        for (int i = 0; i < colsBef.size(); i++) {
            // col id starts with 1
            if (pkNum.contains(i + 1)) {
                pureValues[i + colsAft.size()] = toParameter(colsBef.get(i));
            }
        }
    } else {
        pureValues = new Object[colsAft.size() + colsBef.size()];

        for (int i = 0; i < colsAft.size(); i++) {
            pureValues[i] = toParameter(colsAft.get(i));
        }
        // appending parameters for where clause
        for (int i = 0; i < colsBef.size(); i++) {
            pureValues[i + colsAft.size()] = toParameter(colsBef.get(i));
        }

    }
    return new Parameters(pureValues);
}

From source file:eu.tango.energymodeller.datastore.DataGatherer.java

/**
 * This gets a list of the VMs that are currently on a host machine.
 *
 * @param host The host machine to get the VM list for
 * @param activeVMs The list of VMs known to be active on the host.
 * @return The list of VMs on the specified host
 *//*w ww .  j a v a  2  s. co  m*/
public ArrayList<VmDeployed> getVMsOnHost(Host host, List<VmDeployed> activeVMs) {
    HashSet<VmDeployed> currentVMs = new HashSet<>();
    currentVMs.addAll(activeVMs);
    ArrayList<VmDeployed> answer = new ArrayList<>();
    for (VmDeployed vm : knownVms.values()) {
        validateVMInformation(vm);
        if (host.equals(vm.getAllocatedTo()) && currentVMs.contains(vm)) {
            answer.add(vm);
        }
    }
    return answer;
}

From source file:it.unibas.spicy.persistence.sql.DAOSql.java

public void loadInstanceSample(IDataSourceProxy dataSource, String catalog, String filePath)
        throws DAOException {
    INode root = null;/*from w  ww . j a  v  a2 s  .  c  om*/
    try {
        root = new TupleNode(getNode(catalog).getLabel(), getOID());
        root.setRoot(true);
        String sqlScript = readFile(filePath, StandardCharsets.UTF_8).trim();
        //table
        Statements stmts = CCJSqlParserUtil.parseStatements(sqlScript);
        List<net.sf.jsqlparser.statement.Statement> stmtss = stmts.getStatements();
        HashSet<String> tableNames = new HashSet<>();
        for (net.sf.jsqlparser.statement.Statement stmt : stmtss) {
            if (stmt instanceof Insert) {
                Insert insertStmt = (Insert) stmt;
                //only "INSERT into ... VALUES" support
                //not INSERT with "SELECT" or "RETURNING" yet
                if (insertStmt.isUseValues()) {
                    String tableName = insertStmt.getTable().getName();
                    SetNode setTable = null;
                    if (!tableNames.contains(tableName)) {
                        tableNames.add(tableName);
                        setTable = new SetNode(getNode(tableName).getLabel(), getOID());
                        getInstanceByTable(tableName, setTable, insertStmt, setTable.getFullSize());
                        root.addChild(setTable);
                    } else {
                        setTable = (SetNode) root.getChild(tableName);
                        getInstanceByTable(tableName, setTable, insertStmt, setTable.getFullSize());
                    }
                }
            }
        }
        dataSource.addInstanceWithCheck(root);
    } catch (IOException | JSQLParserException | DAOException ex) {
        logger.error(ex);
        throw new DAOException(ex.getMessage());
    }
}

From source file:edu.fullerton.ldvplugin.ExternalPlotManager.java

public ArrayList<File> getAllImgFiles(File dir) throws WebUtilException {
    HashSet<String> extensions;
    extensions = new HashSet<>();
    extensions.add("png");
    extensions.add("jpg");
    extensions.add("gif");

    ArrayList<File> ret = new ArrayList<>();
    if (!dir.isDirectory() || !dir.canRead()) {
        throw new WebUtilException("Can't access output directory: " + dir.getAbsolutePath());
    }// w w w .j  av  a2s.  c o m
    File[] listFiles = dir.listFiles();
    for (File file : listFiles) {
        String ext = FilenameUtils.getExtension(file.getAbsolutePath()).toLowerCase();
        if (extensions.contains(ext)) {
            // acceptable type
            ret.add(file);
        } else {
            file.delete();
        }
    }
    return ret;
}