Example usage for java.util Hashtable put

List of usage examples for java.util Hashtable put

Introduction

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

Prototype

public synchronized V put(K key, V value) 

Source Link

Document

Maps the specified key to the specified value in this hashtable.

Usage

From source file:SerObjWithCodebase.java

public static void main(String[] args) {

    if (args.length != 1) {
        System.err.println("usage: java SerObjWithCodebase <codebase URL>");
        System.exit(-1);// w  ww.jav  a  2  s .  co m
    }

    String codebase = args[0];

    // Set up environment for creating initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

    try {
        // Create the initial context
        DirContext ctx = new InitialDirContext(env);

        // Create object to be bound
        Flower f = new Flower("rose", "pink");

        // Perform bind and specify codebase
        ctx.bind("cn=Flower", f, new BasicAttributes("javaCodebase", codebase));

        // Check that it is bound
        Flower f2 = (Flower) ctx.lookup("cn=Flower");
        System.out.println(f2);

        // Close the context when we're done
        ctx.close();
    } catch (NamingException e) {
        System.out.println("Operation failed: " + e);
    }
}

From source file:HashtableDemo.java

public static void main(String[] argv) {

    // Construct and load the hash. This simulates loading a
    // database or reading from a file, or wherever the data is.

    Hashtable h = new Hashtable();

    // The hash maps from company name to address.
    // In real life this might map to an Address object...
    h.put("Adobe", "Mountain View, CA");
    h.put("IBM", "White Plains, NY");
    h.put("Learning Tree", "Los Angeles, CA");
    h.put("Microsoft", "Redmond, WA");
    h.put("Netscape", "Mountain View, CA");
    h.put("O'Reilly", "Sebastopol, CA");
    h.put("Sun", "Mountain View, CA");

    // Two versions of the "retrieval" phase.
    // Version 1: get one pair's value given its key
    // (presumably the key would really come from user input):
    String queryString = "O'Reilly";
    System.out.println("You asked about " + queryString + ".");
    String resultString = (String) h.get(queryString);
    System.out.println("They are located in: " + resultString);
    System.out.println();/*from  w  ww .ja v  a2 s. c  o  m*/

    // Version 2: get ALL the keys and pairs
    // (maybe to print a report, or to save to disk)
    Enumeration k = h.keys();
    while (k.hasMoreElements()) {
        String key = (String) k.nextElement();
        System.out.println("Key " + key + "; Value " + (String) h.get(key));
    }
}

From source file:Rebind.java

public static void main(String[] args) {

    // Set up the environment for creating the initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

    try {/*from  w  w  w.ja  v a2 s  . c om*/
        // Create the initial context
        Context ctx = new InitialContext(env);

        // Create the object to be bound
        Fruit fruit = new Fruit("lemon");

        // Perform the bind
        ctx.rebind("cn=Favorite Fruit", fruit);

        // Check that it is bound
        Object obj = ctx.lookup("cn=Favorite Fruit");
        System.out.println(obj);

        // Close the context when we're done
        ctx.close();
    } catch (NamingException e) {
        System.out.println("Operation failed: " + e);
    }
}

From source file:Bind.java

public static void main(String[] args) {

    // Set up the environment for creating the initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

    try {//from   w w w.j  a v  a2s .  c  o  m
        // Create the initial context
        Context ctx = new InitialContext(env);

        // Create the object to be bound
        Fruit fruit = new Fruit("orange");

        // Perform the bind
        ctx.bind("cn=Favorite Fruit", fruit);

        // Check that it is bound
        Object obj = ctx.lookup("cn=Favorite Fruit");
        System.out.println(obj);

        // Close the context when we're done
        ctx.close();
    } catch (NamingException e) {
        System.out.println("Operation failed: " + e);
    }
}

From source file:gamlss.algorithm.Gamlss.java

/**
 * Main method.// ww w. j a  va 2 s  .c o  m
 * @param args -  command-line arguments
 */
public static void main(final String[] args) {

    //String fileName = "Data/dataReduced.csv";
    String fileName = "Data/oil.csv";
    // String fileName = "Data/sp.csv";
    //String fileName = "Data/dataReduced.csv";
    CSVFileReader readData = new CSVFileReader(fileName);
    readData.readFile();
    ArrayList<String> data = readData.storeValues;

    ArrayRealVector y = new ArrayRealVector(data.size());
    BlockRealMatrix muX = new BlockRealMatrix(data.size(), 1);
    BlockRealMatrix sigmaX = new BlockRealMatrix(data.size(), 1);
    BlockRealMatrix nuX = new BlockRealMatrix(data.size(), 1);
    BlockRealMatrix tauX = new BlockRealMatrix(data.size(), 1);
    ArrayRealVector w = new ArrayRealVector(data.size());

    BlockRealMatrix muS = new BlockRealMatrix(data.size(), 1);
    BlockRealMatrix sigmaS = new BlockRealMatrix(data.size(), 1);
    BlockRealMatrix nuS = new BlockRealMatrix(data.size(), 1);
    BlockRealMatrix tauS = new BlockRealMatrix(data.size(), 1);

    for (int i = 0; i < data.size(); i++) {
        String[] line = data.get(i).split(",");
        y.setEntry(i, Double.parseDouble(line[0]));
        muX.setEntry(i, 0, Double.parseDouble(line[1]));
        muS.setEntry(i, 0, Double.parseDouble(line[1]));
        sigmaX.setEntry(i, 0, Double.parseDouble(line[1]));
        sigmaS.setEntry(i, 0, Double.parseDouble(line[1]));
        nuX.setEntry(i, 0, Double.parseDouble(line[1]));
        nuS.setEntry(i, 0, Double.parseDouble(line[1]));
        tauX.setEntry(i, 0, Double.parseDouble(line[1]));
        tauS.setEntry(i, 0, Double.parseDouble(line[1]));
    }

    Hashtable<Integer, BlockRealMatrix> designMatrices = new Hashtable<Integer, BlockRealMatrix>();
    designMatrices.put(DistributionSettings.MU, muX);
    designMatrices.put(DistributionSettings.SIGMA, sigmaX);
    designMatrices.put(DistributionSettings.NU, nuX);
    designMatrices.put(DistributionSettings.TAU, tauX);

    HashMap<Integer, BlockRealMatrix> smoothMatrices = new HashMap<Integer, BlockRealMatrix>();
    smoothMatrices.put(DistributionSettings.MU, muS);
    smoothMatrices.put(DistributionSettings.SIGMA, sigmaS);
    smoothMatrices.put(DistributionSettings.NU, nuS);
    smoothMatrices.put(DistributionSettings.TAU, tauS);

    //smoothMatrices.put(DistributionSettings.MU, null);
    //smoothMatrices.put(DistributionSettings.SIGMA, null);
    //smoothMatrices.put(DistributionSettings.NU, null);
    //smoothMatrices.put(DistributionSettings.TAU, null);

    DistributionSettings.DISTR = DistributionSettings.SST;
    Controls.GLOB_DEVIANCE_TOL = 5500;
    Controls.INTER = 50;//only for the PB smoother
    Controls.SMOOTHER = Controls.PB; //or PB
    Controls.IS_SVD = true;
    Controls.BIG_DATA = true;
    Controls.JAVA_OPTIMIZATION = false;
    Controls.GAMLSS_NUM_CYCLES = 50;
    //Gamlss gamlss = new Gamlss(y, designMatrices, null);
    Gamlss gamlss = new Gamlss(y, designMatrices, null);
    //Gamlss gamlss = new Gamlss(y, null, smoothMatrices);      
    gamlss.saveFittedDistributionParameters("Data/oilresults.csv");
}

From source file:org.ala.hbase.RepoDataLoader.java

/**
 * This takes a list of infosource ids...
 * <p/>/*w  w  w. j a  v  a 2s .  c  om*/
 * Usage: -stats or -reindex or -gList and list of infosourceId
 *
 * @param args
 */
public static void main(String[] args) throws Exception {
    //RepoDataLoader loader = new RepoDataLoader();
    ApplicationContext context = SpringUtils.getContext();
    RepoDataLoader loader = (RepoDataLoader) context.getBean(RepoDataLoader.class);
    long start = System.currentTimeMillis();
    loader.loadInfoSources();
    String filePath = repositoryDir;
    if (args.length > 0) {
        if (args[0].equalsIgnoreCase("-stats")) {
            loader.statsOnly = true;
            args = (String[]) ArrayUtils.subarray(args, 1, args.length);
        }
        if (args[0].equalsIgnoreCase("-reindex")) {
            loader.reindex = true;
            loader.indexer = context.getBean(PartialIndex.class);
            args = (String[]) ArrayUtils.subarray(args, 1, args.length);
            logger.info("**** -reindex: " + loader.reindex);
            logger.debug("reindex url: " + loader.reindexUrl);
        }
        if (args[0].equalsIgnoreCase("-gList")) {
            loader.gList = true;
            args = (String[]) ArrayUtils.subarray(args, 1, args.length);
            logger.info("**** -gList: " + loader.gList);
        }
        if (args[0].equalsIgnoreCase("-biocache")) {
            Hashtable<String, String> hashTable = new Hashtable<String, String>();
            hashTable.put("accept", "application/json");
            ObjectMapper mapper = new ObjectMapper();
            mapper.getDeserializationConfig().set(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
                    false);
            RestfulClient restfulClient = new RestfulClient(0);
            String fq = "&fq=";
            if (args.length > 1) {
                java.util.Date date = new java.util.Date();
                if (args[1].equals("-lastWeek")) {
                    date = DateUtils.addWeeks(date, -1);
                } else if (args[1].equals("-lastMonth")) {
                    date = DateUtils.addMonths(date, -1);
                } else if (args[1].equals("-lastYear")) {
                    date = DateUtils.addYears(date, -1);
                } else
                    date = null;
                if (date != null) {
                    SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

                    fq += "last_load_date:%5B" + sfd.format(date) + "%20TO%20*%5D";
                }
            }

            Object[] resp = restfulClient
                    .restGet("http://biocache.ala.org.au/ws/occurrences/search?q=multimedia:Image" + fq
                            + "&facets=data_resource_uid&pageSize=0", hashTable);
            logger.info("The URL: " + "http://biocache.ala.org.au/ws/occurrences/search?q=multimedia:Image" + fq
                    + "&facets=data_resource_uid&pageSize=0");
            if ((Integer) resp[0] == HttpStatus.SC_OK) {
                String content = resp[1].toString();
                logger.debug(resp[1]);
                if (content != null && content.length() > "[]".length()) {
                    Map map = mapper.readValue(content, Map.class);
                    try {
                        List<java.util.LinkedHashMap<String, String>> list = ((List<java.util.LinkedHashMap<String, String>>) ((java.util.LinkedHashMap) ((java.util.ArrayList) map
                                .get("facetResults")).get(0)).get("fieldResult"));
                        Set<String> arg = new LinkedHashSet<String>();
                        for (int i = 0; i < list.size(); i++) {
                            java.util.LinkedHashMap<String, String> value = list.get(i);
                            String dataResource = getDataResource(value.get("fq"));
                            Object provider = (loader.getUidInfoSourceMap().get(dataResource));
                            if (provider != null) {
                                arg.add(provider.toString());
                            }
                        }
                        logger.info("Set of biocache infosource ids to load: " + arg);
                        args = new String[] {};
                        args = arg.toArray(args);
                        //handle the situation where biocache-service reports no data resources
                        if (args.length < 1) {
                            logger.error("No biocache data resources found. Unable to load.");
                            System.exit(0);
                        }
                    } catch (Exception e) {
                        logger.error("ERROR: exit process....." + e);
                        e.printStackTrace();
                        System.exit(0);
                    }
                }
            } else {
                logger.warn("Unable to process url: ");
            }
        }
    }
    int filesRead = loader.load(filePath, args); //FIX ME - move to config
    long finish = System.currentTimeMillis();
    logger.info(filesRead + " files scanned/loaded in: " + ((finish - start) / 60000) + " minutes "
            + ((finish - start) / 1000) + " seconds.");
    System.exit(1);
}

From source file:com.seanmadden.fast.ldap.main.Main.java

/**
 * The Main Event./*from  www  .  java2s .c o m*/
 * 
 * @param args
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    BasicConfigurator.configure();
    log.debug("System initializing");
    try {
        Logger.getRootLogger().addAppender(
                new FileAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN), "log.log"));
    } catch (IOException e1) {
        log.error("Unable to open the log file..?");
    }

    /*
     * Initialize the configuration engine.
     */
    XMLConfiguration config = new XMLConfiguration();
    config.setListDelimiter('|');

    /*
     * Initialize the Command-Line parsing engine.
     */
    CommandLineParser parser = new PosixParser();
    Options opts = new Options();
    opts.addOption(OptionBuilder.withLongOpt("config-file").hasArg()
            .withDescription("The configuration file to load").withArgName("config.xml").create("c"));

    opts.addOption(OptionBuilder.withLongOpt("profile").hasArg().withDescription("The profile to use")
            .withArgName("Default").create("p"));

    opts.addOption(OptionBuilder.withLongOpt("password").hasArg().withDescription("Password to connect with")
            .withArgName("password").create("P"));

    opts.addOption(OptionBuilder.withLongOpt("debug").hasArg(false).create('d'));

    opts.addOption(OptionBuilder.withLongOpt("verbose").hasArg(false).create('v'));

    File configurationFile = new File("config.xml");

    try {
        // Parse the command-line options
        CommandLine cmds = parser.parse(opts, args);

        if (!cmds.hasOption('p')) {
            Logger.getRootLogger().addAppender(new GuiErrorAlerter(Level.ERROR));
        }

        Logger.getRootLogger().setLevel(Level.ERROR);
        if (cmds.hasOption('v')) {
            Logger.getRootLogger().setLevel(Level.INFO);
        }
        if (cmds.hasOption('d')) {
            Logger.getRootLogger().setLevel(Level.DEBUG);
        }

        log.debug("Enabling configuration file parsing");
        // The user has given us a file to parse.
        if (cmds.hasOption("c")) {
            configurationFile = new File(cmds.getOptionValue("c"));
        }
        log.debug("Config file: " + configurationFile);

        // Load the configuration file
        if (configurationFile.exists()) {
            config.load(configurationFile);
        } else {
            log.error("Cannot find config file");
        }

        /*
         * Convert the profiles into memory
         */
        Vector<ConnectionProfile> profs = new Vector<ConnectionProfile>();
        List<?> profList = config.configurationAt("Profiles").configurationsAt("Profile");
        for (Object p : profList) {
            SubnodeConfiguration profile = (SubnodeConfiguration) p;
            String name = profile.getString("[@name]");
            String auth = profile.getString("LdapAuthString");
            String server = profile.getString("LdapServerString");
            String group = profile.getString("LdapGroupsLocation");
            ConnectionProfile prof = new ConnectionProfile(name, server, auth, group);
            profs.add(prof);
        }
        ConnectionProfile prof = null;
        if (!cmds.hasOption('p')) {
            /*
             * Deploy the profile selector, to select a profile
             */
            ProfileSelector profSel = new ProfileSelector(profs);
            prof = profSel.getSelection();
            if (prof == null) {
                return;
            }
            /*
             * Empty the profiles and load a clean copy - then save it back
             * to the file
             */
            config.clearTree("Profiles");
            for (ConnectionProfile p : profSel.getProfiles()) {
                config.addProperty("Profiles.Profile(-1)[@name]", p.getName());
                config.addProperty("Profiles.Profile.LdapAuthString", p.getLdapAuthString());
                config.addProperty("Profiles.Profile.LdapServerString", p.getLdapServerString());
                config.addProperty("Profiles.Profile.LdapGroupsLocation", p.getLdapGroupsString());
            }
            config.save(configurationFile);
        } else {
            for (ConnectionProfile p : profs) {
                if (p.getName().equals(cmds.getOptionValue('p'))) {
                    prof = p;
                    break;
                }
            }
        }

        log.info("User selected " + prof);

        String password = "";
        if (cmds.hasOption('P')) {
            password = cmds.getOptionValue('P');
        } else {
            password = PasswordPrompter.promptForPassword("Password?");
        }

        if (password.equals("")) {
            return;
        }

        LdapInterface ldap = new LdapInterface(prof.getLdapServerString(), prof.getLdapAuthString(),
                prof.getLdapGroupsString(), password);

        /*
         * Gather options information from the configuration engine for the
         * specified report.
         */
        Hashtable<String, Hashtable<String, ReportOption>> reportDataStructure = new Hashtable<String, Hashtable<String, ReportOption>>();
        List<?> repConfig = config.configurationAt("Reports").configurationsAt("Report");
        for (Object p : repConfig) {
            SubnodeConfiguration repNode = (SubnodeConfiguration) p;

            // TODO Do something with the report profile.
            // Allowing the user to deploy "profiles" is a nice feature
            // String profile = repNode.getString("[@profile]");

            String reportName = repNode.getString("[@report]");
            Hashtable<String, ReportOption> reportOptions = new Hashtable<String, ReportOption>();
            reportDataStructure.put(reportName, reportOptions);
            // Loop through the options and add each to the table.
            for (Object o : repNode.configurationsAt("option")) {
                SubnodeConfiguration option = (SubnodeConfiguration) o;
                String name = option.getString("[@name]");
                String type = option.getString("[@type]");
                String value = option.getString("[@value]");

                ReportOption ro = new ReportOption();
                ro.setName(name);

                if (type.toLowerCase().equals("boolean")) {
                    ro.setBoolValue(Boolean.parseBoolean(value));
                } else if (type.toLowerCase().equals("integer")) {
                    ro.setIntValue(Integer.valueOf(value));
                } else {
                    // Assume a string type here then.
                    ro.setStrValue(value);
                }
                reportOptions.put(name, ro);
                log.debug(ro);
            }
        }
        System.out.println(reportDataStructure);

        /*
         * At this point, we now need to deploy the reports window to have
         * the user pick a report and select some happy options to allow
         * that report to work. Let's go.
         */
        /*
         * Deploy the Reports selector, to select a report
         */
        Reports.getInstance().setLdapConnection(ldap);
        ReportsWindow reports = new ReportsWindow(Reports.getInstance().getAllReports(), reportDataStructure);
        Report report = reports.getSelection();
        if (report == null) {
            return;
        }
        /*
         * Empty the profiles and load a clean copy - then save it back to
         * the file
         */
        config.clearTree("Reports");
        for (Report r : Reports.getInstance().getAllReports()) {
            config.addProperty("Reports.Report(-1)[@report]", r.getClass().getCanonicalName());
            config.addProperty("Reports.Report[@name]", "Standard");
            for (ReportOption ro : r.getOptions().values()) {
                config.addProperty("Reports.Report.option(-1)[@name]", ro.getName());
                config.addProperty("Reports.Report.option[@type]", ro.getType());
                config.addProperty("Reports.Report.option[@value]", ro.getStrValue());
            }
        }
        config.save(configurationFile);
        ProgressBar bar = new ProgressBar();
        bar.start();
        report.execute();
        ASCIIFormatter format = new ASCIIFormatter();
        ReportResult res = report.getResult();
        format.format(res, new File(res.getForName() + "_" + res.getReportName() + ".txt"));
        bar.stop();

        JOptionPane.showMessageDialog(null,
                "The report is at " + res.getForName() + "_" + res.getReportName() + ".txt", "Success",
                JOptionPane.INFORMATION_MESSAGE);

    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("FAST Ldap Searcher", opts);
    } catch (ConfigurationException e) {
        e.printStackTrace();
        log.fatal("OH EM GEES!  Configuration errors.");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

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);//from  ww  w  . j a v  a 2 s .  c o  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

/**
 * Convert to hashtable.//  w w  w  .  j a v  a  2s  . c  o m
 * 
 * @param data the data
 * 
 * @return the hashtable
 */
private static Hashtable convertToHashtable(Object[] data) {
    Hashtable h = new Hashtable();
    for (int i = 0; i < data.length; i++) {
        h.put(i + "", data[i]);
    }
    return h;
}

From source file:Main.java

public static Hashtable<String, String> errorCodes() {
    Hashtable<String, String> errors = new Hashtable<String, String>(13);
    errors.put("ERR1", "Invalid data and/or request syntax!");
    errors.put("ERR2", "Invalid data, possible missing data separator.");
    errors.put("ERR3", "Invalid data/syntax, could not parse data.");
    errors.put("ERR4", "Missing/Empty Command Argument(s) Recvd.");
    errors.put("ERR5", "Invalid command syntax!");
    errors.put("ERR6", "Invalid Auth Syntax!");
    errors.put("ERR7", "Access Denied!");
    errors.put("ERR8", "Server Timeout, Too Busy to Handle Request!");
    errors.put("ERR9", "Incorrect Password.");
    errors.put("ERR14", "Invalid Login Command Syntax.");
    errors.put("ERR19", "Unknown Auth Error");
    errors.put("ERR99", "Unknown exception occured.");
    errors.put("ERR100", "Invalid Host/IP.");
    errors.put("ERR101", "Cannont connect to server.");
    return errors;
}