Example usage for java.util Hashtable containsKey

List of usage examples for java.util Hashtable containsKey

Introduction

In this page you can find the example usage for java.util Hashtable containsKey.

Prototype

public synchronized boolean containsKey(Object key) 

Source Link

Document

Tests if the specified object is a key in this hashtable.

Usage

From source file:MainClass.java

public static void main(String[] s) {
    Hashtable table = new Hashtable();
    table.put("key1", "value1");
    table.put("key2", "value2");
    table.put("key3", "value3");

    System.out.println(table.containsKey("key3"));

}

From source file:Main.java

public static void main(String[] args) {
    Hashtable<String, String> ht = new Hashtable<String, String>();
    ht.put("1", "One");
    ht.put("2", "Two");
    ht.put("3", "Three");

    boolean blnExists = ht.containsKey("2");
    System.out.println("2 exists in Hashtable ? : " + blnExists);
}

From source file:Main.java

public static void main(String args[]) {
    Hashtable<Integer, String> htable = new Hashtable<Integer, String>();

    // put values into the table
    htable.put(1, "A");
    htable.put(2, "B");
    htable.put(3, "C");
    htable.put(4, "from java2s.com");

    // check if table contains key "3"
    boolean isavailable = htable.containsKey(3);

    // display search result
    System.out.println("Hash table contains key '3': " + isavailable);
}

From source file:asl.seedscan.SeedScan.java

public static void main(String args[]) {
    // Default locations of config and schema files
    File configFile = new File("config.xml");
    File schemaFile = new File("schemas/SeedScanConfig.xsd");
    boolean parseConfig = true;

    ArrayList<File> schemaFiles = new ArrayList<File>();
    schemaFiles.add(schemaFile);// w w w  .  j a  va 2 s .co m

    // ==== Command Line Parsing ====
    Options options = new Options();
    Option opConfigFile = new Option("c", "config-file", true,
            "The config file to use for seedscan. XML format according to SeedScanConfig.xsd.");
    Option opSchemaFile = new Option("s", "schema-file", true,
            "The xsd schema file which should be used to verify the config file format. ");

    OptionGroup ogConfig = new OptionGroup();
    ogConfig.addOption(opConfigFile);

    OptionGroup ogSchema = new OptionGroup();
    ogConfig.addOption(opSchemaFile);

    options.addOptionGroup(ogConfig);
    options.addOptionGroup(ogSchema);

    PosixParser optParser = new PosixParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = optParser.parse(options, args, true);
    } catch (org.apache.commons.cli.ParseException e) {
        logger.error("Error while parsing command-line arguments.");
        System.exit(1);
    }

    Option opt;
    Iterator<?> iter = cmdLine.iterator();
    while (iter.hasNext()) {
        opt = (Option) iter.next();
        if (opt.getOpt().equals("c")) {
            configFile = new File(opt.getValue());
        } else if (opt.getOpt().equals("s")) {
            schemaFile = new File(opt.getValue());
        }
    }

    // ==== Configuration Read and Parse Actions ====
    ConfigParser parser = new ConfigParser(schemaFiles);
    ConfigT config = parser.parseConfig(configFile);

    // Print out configuration file contents
    Formatter formatter = new Formatter(new StringBuilder(), Locale.US);

    // ===== CONFIG: LOCK FILE =====
    File lockFile = new File(config.getLockfile());
    logger.info("SeedScan lock file is '" + lockFile + "'");
    LockFile lock = new LockFile(lockFile);
    if (!lock.acquire()) {
        logger.error("Could not acquire lock.");
        System.exit(1);
    }

    // ===== CONFIG: LOGGING =====
    // MTH: This is now done in log4j.properties file

    // ===== CONFIG: DATABASE =====
    MetricDatabase readDB = new MetricDatabase(config.getDatabase());
    MetricDatabase writeDB = new MetricDatabase(config.getDatabase());
    MetricReader reader = new MetricReader(readDB);
    MetricInjector injector = new MetricInjector(writeDB);

    // ===== CONFIG: SCANS =====
    Hashtable<String, Scan> scans = new Hashtable<String, Scan>();
    if (config.getScans().getScan() == null) {
        logger.error("No scans in configuration.");
        System.exit(1);
    } else {
        for (ScanT scanCfg : config.getScans().getScan()) {
            String name = scanCfg.getName();
            if (scans.containsKey(name)) {
                logger.error("Duplicate scan name '" + name + "' encountered.");
                System.exit(1);
            }

            // This should really be handled by jaxb by setting it up in schemas/SeedScanConfig.xsd
            if (scanCfg.getStartDay() == null && scanCfg.getStartDate() == null) {
                logger.error(
                        "== SeedScan Error: Must set EITHER cfg:start_day -OR- cfg:start_date in config.xml to start Scan!");
                System.exit(1);
            }

            // Configure this Scan
            Scan scan = new Scan(scanCfg.getName());
            scan.setPathPattern(scanCfg.getPath());
            scan.setDatalessDir(scanCfg.getDatalessDir());
            scan.setEventsDir(scanCfg.getEventsDir());
            scan.setPlotsDir(scanCfg.getPlotsDir());
            scan.setDaysToScan(scanCfg.getDaysToScan().intValue());
            if (scanCfg.getStartDay() != null) {
                scan.setStartDay(scanCfg.getStartDay().intValue());
            }
            if (scanCfg.getStartDate() != null) {
                scan.setStartDate(scanCfg.getStartDate().intValue());
            }

            if (scanCfg.getNetworkSubset() != null) {
                logger.debug("Filter on Network Subset=[{}]", scanCfg.getNetworkSubset());
                Filter filter = new Filter(false);
                for (String network : scanCfg.getNetworkSubset().split(",")) {
                    logger.debug("Network =[{}]", network);
                    filter.addFilter(network);
                }
                scan.setNetworks(filter);
            }
            if (scanCfg.getStationSubset() != null) {
                logger.debug("Filter on Station Subset=[{}]", scanCfg.getStationSubset());
                Filter filter = new Filter(false);
                for (String station : scanCfg.getStationSubset().split(",")) {
                    logger.debug("Station =[{}]", station);
                    filter.addFilter(station);
                }
                scan.setStations(filter);
            }
            if (scanCfg.getLocationSubset() != null) {
                logger.debug("Filter on Location Subset=[{}]", scanCfg.getLocationSubset());
                Filter filter = new Filter(false);
                for (String location : scanCfg.getLocationSubset().split(",")) {
                    logger.debug("Location =[{}]", location);
                    filter.addFilter(location);
                }
                scan.setLocations(filter);
            }
            if (scanCfg.getChannelSubset() != null) {
                logger.debug("Filter on Channel Subset=[{}]", scanCfg.getChannelSubset());
                Filter filter = new Filter(false);
                for (String channel : scanCfg.getChannelSubset().split(",")) {
                    logger.debug("Channel =[{}]", channel);
                    filter.addFilter(channel);
                }
                scan.setChannels(filter);
            }

            for (MetricT met : scanCfg.getMetrics().getMetric()) {
                try {
                    Class<?> metricClass = Class.forName(met.getClassName());
                    MetricWrapper wrapper = new MetricWrapper(metricClass);
                    for (ArgumentT arg : met.getArgument()) {
                        wrapper.add(arg.getName(), arg.getValue());
                    }
                    scan.addMetric(wrapper);
                } catch (ClassNotFoundException ex) {
                    logger.error("No such metric class '" + met.getClassName() + "'");
                    System.exit(1);
                } catch (InstantiationException ex) {
                    logger.error("Could not dynamically instantiate class '" + met.getClassName() + "'");
                    System.exit(1);
                } catch (IllegalAccessException ex) {
                    logger.error("Illegal access while loading class '" + met.getClassName() + "'");
                    System.exit(1);
                } catch (NoSuchFieldException ex) {
                    logger.error("Invalid dynamic argument to Metric subclass '" + met.getClassName() + "'");
                    System.exit(1);
                }

            }
            scans.put(name, scan);
        }
    }

    // ==== Establish Database Connection ====
    // TODO: State Tracking in the Database
    // - Record scan started in database.
    // - Track our progress as we go so a new process can pick up where
    //   we left off if our process dies.
    // - Mark when each date-station-channel-operation is complete
    //LogDatabaseHandler logDB = new LogDatabaseHandler(configuration.get

    // For each day ((yesterday - scanDepth) to yesterday)
    // scan for these channel files, only process them if
    // they have not yet been scanned, or if changes have
    // occurred to the file since its last scan. Do this for
    // each scan type. Do not re-scan data for each type,
    // launch processes for each scan and use the same data set
    // for each. If we can pipe the data as it is read, do so.
    // If we need to push all of it at once, do these in sequence
    // in order to preserve overall system memory resources.

    Scan scan = null;

    // ==== Perform Scans ====

    scan = scans.get("daily");

    //MTH: This part could/should be moved up higher except that we need to know datalessDir, which,
    //     at this point, is configured on a per scan basis ... so we need to know what scan we're doing
    MetaServer metaServer = null;
    if (config.getMetaserver() != null) {
        if (config.getMetaserver().getUseRemote().equals("yes")
                || config.getMetaserver().getUseRemote().equals("true")) {
            String remoteServer = config.getMetaserver().getRemoteUri();
            try {
                metaServer = new MetaServer(new URI(remoteServer));
            } catch (Exception e) {
                logger.error("caught URI exception:" + e.getMessage());
            }
        } else {
            metaServer = new MetaServer(scan.getDatalessDir());
        }
    } else { // Use local MetaServer
        metaServer = new MetaServer(scan.getDatalessDir());
    }

    List<Station> stations = null;

    if (config.getStationList() == null) { // get StationList from MetaServer
        logger.info("Get StationList from MetaServer");
        stations = metaServer.getStationList();
    } else { // read StationList from config.xml
        logger.info("Read StationList from config.xml");
        List<String> stationList = config.getStationList().getStation();
        if (stationList.size() > 0) {
            stations = new ArrayList<Station>();
            for (String station : stationList) {
                String[] words = station.split("_");
                if (words.length != 2) {
                    logger.warn(String.format("stationList: station=[%s] is NOT a valid station --> Skip",
                            station));
                } else {
                    stations.add(new Station(words[0], words[1]));
                    logger.info("config.xml: Read station:" + station);
                }
            }
        } else {
            logger.error("Error: No valid stations read from config.xml");
        }
    }

    if (stations == null) {
        logger.error("Found NO stations to scan --> EXITTING SeedScan");
        System.exit(1);
    }

    Thread readerThread = new Thread(reader);
    readerThread.start();
    logger.info("Reader thread started.");

    Thread injectorThread = new Thread(injector);
    injectorThread.start();
    logger.info("Injector thread started.");

    // Loop over scans and hand each one to a ScanManager
    logger.info("Hand scan to ScanManager");
    for (String key : scans.keySet()) {
        scan = scans.get(key);
        logger.info(String.format("Scan=[%s] startDay=%d startDate=%d daysToScan=%d\n", key, scan.getStartDay(),
                scan.getStartDate(), scan.getDaysToScan()));
        ScanManager scanManager = new ScanManager(reader, injector, stations, scan, metaServer);
    }

    logger.info("ScanManager is [ FINISHED ] --> stop the injector and reader threads");

    try {
        injector.halt();
        logger.info("All stations processed. Waiting for injector thread to finish...");
        synchronized (injectorThread) {
            //injectorThread.wait();
            injectorThread.interrupt();
        }
        logger.info("Injector thread halted.");
    } catch (InterruptedException ex) {
        logger.warn("The injector thread was interrupted while attempting to complete requests.");
    }

    try {
        reader.halt();
        logger.info("All stations processed. Waiting for reader thread to finish...");
        synchronized (readerThread) {
            //readerThread.wait();
            readerThread.interrupt();
        }
        logger.info("Reader thread halted.");
    } catch (InterruptedException ex) {
        logger.warn("The reader thread was interrupted while attempting to complete requests.");
    }

    try {
        lock.release();
    } catch (IOException e) {
        ;
    } finally {
        logger.info("Release seedscan lock and quit metaServer");
        lock = null;
        metaServer.quit();
    }
}

From source file:Main.java

protected static void expandTree(JTree tree, TreePath path, Hashtable lookedAt) {
    Object node = path.getLastPathComponent();
    if (lookedAt.containsKey(node))
        return;//from   w  w  w . j a v  a 2  s  .  co m
    lookedAt.put(node, node);

    Vector paths = new Vector();
    tree.makeVisible(path);
    int childCount = tree.getModel().getChildCount(node);
    for (int i = 0; i < childCount; i++) {
        Object child = tree.getModel().getChild(node, i);
        TreePath p = path.pathByAddingChild(child);
        expandTree(tree, p, lookedAt);
    }
}

From source file:Main.java

public static Hashtable contarElementos(Vector list) {
    Hashtable hash = new Hashtable();

    for (int i = 0; i < list.size(); i++) {
        Object key = list.elementAt(i);
        if (hash.containsKey(key)) {
            Integer qtde = new Integer(((Integer) hash.get(key)).intValue() + 1);
            hash.put(key, qtde);//  ww  w. j a va  2 s  .  c om
        } else {
            hash.put(key, new Integer(1));
        }
    }

    return hash;
}

From source file:Main.java

public static Hashtable<Integer, Set<Integer>> getNodeMembership(Hashtable<Integer, Set<Integer>> nIDComVH,
        final Vector<Set<Integer>> cmtyVV) {
    for (int i = 0; i < cmtyVV.size(); i++) {
        int CID = i;
        for (Integer NID : cmtyVV.get(i)) {
            if (nIDComVH.containsKey(NID)) {
                Set<Integer> x = nIDComVH.get(NID);
                x.add(CID);/*ww  w  .  j  a  v  a2s . co m*/
            } else {
                Set<Integer> x = new HashSet<Integer>();
                x.add(CID);
                nIDComVH.put(NID, x);
            }

        }
    }
    return nIDComVH;
}

From source file:Main.java

/**
 * dump bipartite community affiliation into a text file with node names
 * //from  w  ww .j  a  va 2s .  co m
 * @param OutFNm
 * @param CmtyVV
 * @param NIDNmH
 */
static void dumpCmtyVV(final String OutFNm, Vector<Vector<Integer>> CmtyVV, Hashtable<Integer, String> NIDNmH) {
    PrintWriter f;
    try {
        f = new PrintWriter(OutFNm);

        for (int c = 0; c < CmtyVV.size(); c++) {
            for (int u = 0; u < CmtyVV.get(c).size(); u++) {
                if (NIDNmH.containsKey(CmtyVV.get(c).get(u))) {
                    f.printf("%s\t", NIDNmH.get(CmtyVV.get(c).get(u)));
                } else {
                    f.printf("%d\t", (int) CmtyVV.get(c).get(u));
                }
            }
            f.printf("\n");
        }
        f.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:com.kevinquan.google.activityrecoginition.model.MotionHelper.java

public static List<MotionSnapshot> parseMotionSnapshots(Cursor result, final boolean sortDescending) {
    if (!CursorUtils.hasResults(result)) {
        Log.d(TAG, "No results were provided to parse motion snapshots from");
        return new ArrayList<MotionSnapshot>();
    }/*from   w  ww  .  j a va2 s .c  o m*/
    Hashtable<Long, MotionSnapshot> snapshots = new Hashtable<Long, MotionSnapshot>();

    do {
        Motion thisMotion = new Motion(result);
        if (thisMotion.getTimestamp() == 0) {
            Log.w(TAG, "Current motion seems corrupt: " + thisMotion);
            continue;
        }
        if (!snapshots.containsKey(thisMotion.getTimestamp())) {
            MotionSnapshot snapshot = new MotionSnapshot(thisMotion);
            snapshots.put(snapshot.getTimestamp(), snapshot);
        } else {
            if (!snapshots.get(thisMotion.getTimestamp()).addMotion(thisMotion)) {
                Log.w(TAG, "Could not add motion to snapshot: " + thisMotion.toString());
            }
        }
    } while (result.moveToNext());

    List<MotionSnapshot> results = new ArrayList<MotionSnapshot>();
    results.addAll(snapshots.values());
    Collections.sort(results, new Comparator<MotionSnapshot>() {
        @Override
        public int compare(MotionSnapshot lhs, MotionSnapshot rhs) {
            int result = ((Long) lhs.getTimestamp()).compareTo((Long) rhs.getTimestamp());
            return sortDescending ? -1 * result : result;
        }
    });
    return results;
}

From source file:org.squale.welcom.struts.lazyLoading.WLazyUtil.java

/**
 * converti un select en champ input classique
 * /*from   ww w  .java  2s .  co m*/
 * @param s chaine contenant le flux  modifier
 * @return le flux mis  jour
 */
public static String convertSelectToLightInput(final String s) {
    final StringBuffer smallInput = new StringBuffer();
    smallInput.append("<input ");

    // try {
    // Search name
    // RE reSelect=new RE("<\\s*select([^>]*)>",RE.MATCH_CASEINDEPENDENT);
    final Pattern reSelect = Pattern.compile("<\\s*select([^>]*)>",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    // RE reOptionSelected = new RE ("<\\s*option[^>]+selected[^>]*>",RE.MATCH_CASEINDEPENDENT);
    final Pattern reOptionSelected = Pattern.compile("<\\s*option[^>]+selected[^>]*>",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    // RE reOption = new RE ("<\\s*option[^>]*>",RE.MATCH_CASEINDEPENDENT);
    final Pattern reOption = Pattern.compile("<\\s*option[^>]*>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    final Matcher maSelect = reSelect.matcher(s);

    if (maSelect.find()) {
        Hashtable parameters = searchParameter(s);

        if (parameters.containsKey("name")) {
            smallInput.append("name=");
            smallInput.append(parameters.get("name"));
            smallInput.append(" ");
        } else {
            return s;
        }

        final Matcher maOptionSelected = reOptionSelected.matcher(s);

        if (maOptionSelected.find()) {
            parameters = searchParameter(maOptionSelected.group(0));

            if (parameters.containsKey("value")) {
                smallInput.append("value=");
                smallInput.append(parameters.get("value"));
            } else {
                final int posStart = maOptionSelected.end(0);
                final Pattern reOptionEnd = Pattern.compile("([^<]*)<\\s*\\/option\\s*>",
                        Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
                final Matcher maOptionEnd = reOptionEnd.matcher(s);

                // RE reOptionEnd= new RE ("([^<]*)<\\s*\\/option\\s*>");
                if (maOptionEnd.find(posStart)) {
                    final String value = maOptionEnd.group(1);
                    smallInput.append("value=");
                    smallInput.append(parameters.get("value"));
                } else {
                    return s;
                }
            }
        } else {
            final Matcher maOption = reOption.matcher(s);

            if (maOption.find()) {
                parameters = searchParameter(maOption.group(0));

                if (parameters.containsKey("value")) {
                    smallInput.append("value=");
                    smallInput.append(parameters.get("value"));
                } else {
                    final int posStart = maOption.end(0);
                    final Pattern reOptionEnd = Pattern.compile("([^<]*)<\\s*\\/option\\s*>",
                            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
                    final Matcher maOptionEnd = reOptionEnd.matcher(s);

                    // RE reOptionEnd= new RE ("([^<]*)<\\s*\\/option\\s*>");
                    if (maOptionEnd.find(posStart)) {
                        final String value = maOptionEnd.group(1);
                        smallInput.append("value=");
                        smallInput.append(parameters.get("value"));
                    } else {
                        return s;
                    }
                }
            } else {
                return s;
            }
        }
    }

    smallInput.append(">");

    return smallInput.toString();
}