Example usage for java.util HashMap HashMap

List of usage examples for java.util HashMap HashMap

Introduction

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

Prototype

public HashMap() 

Source Link

Document

Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).

Usage

From source file:org.eclipse.swordfish.core.configuration.xml.SaxParsingPrototype.java

/**
 * @param args/*from  w  w  w  . j a va  2s  .  c  o m*/
 */
public static void main(String[] args) throws Exception {
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    LinkedList<String> currentElements = new LinkedList<String>();
    InputStream in = SaxParsingPrototype.class.getResource("ComplexPidXmlProperties.xml").openStream();
    XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
    Map<String, List<String>> props = new HashMap<String, List<String>>();
    // Read the XML document
    while (eventReader.hasNext()) {
        XMLEvent event = eventReader.nextEvent();
        if (event.isCharacters() && !event.asCharacters().isWhiteSpace()) {
            putElement(props, getQualifiedName(currentElements), event.asCharacters().getData());

        } else if (event.isStartElement()) {
            System.out.println(event.asStartElement().getName());
            currentElements.add(event.asStartElement().getName().getLocalPart());
            for (Iterator attrIt = event.asStartElement().getAttributes(); attrIt.hasNext();) {
                Attribute attribute = (Attribute) attrIt.next();
                putElement(props, getQualifiedName(currentElements) + "[@" + attribute.getName() + "]",
                        attribute.getValue());

            }
        } else if (event.isAttribute()) {
        } else if (event.isEndElement()) {
            String lastElem = event.asEndElement().getName().getLocalPart();
            if (!currentElements.getLast().equals(lastElem)) {
                throw new UnsupportedOperationException(lastElem + "," + currentElements.getLast());
            }
            currentElements.removeLast();
        }
    }

    eventReader.close();
}

From source file:com.joliciel.talismane.terminology.Main.java

public static void main(String[] args) throws Exception {
    String termFilePath = null;//from w  w w  .ja v a  2  s . c o m
    String outFilePath = null;
    Command command = Command.extract;
    int depth = -1;
    String databasePropertiesPath = null;
    String projectCode = null;

    Map<String, String> argMap = TalismaneConfig.convertArgs(args);

    String logConfigPath = argMap.get("logConfigFile");
    if (logConfigPath != null) {
        argMap.remove("logConfigFile");
        Properties props = new Properties();
        props.load(new FileInputStream(logConfigPath));
        PropertyConfigurator.configure(props);
    }

    Map<String, String> innerArgs = new HashMap<String, String>();
    for (Entry<String, String> argEntry : argMap.entrySet()) {
        String argName = argEntry.getKey();
        String argValue = argEntry.getValue();

        if (argName.equals("command"))
            command = Command.valueOf(argValue);
        else if (argName.equals("termFile"))
            termFilePath = argValue;
        else if (argName.equals("outFile"))
            outFilePath = argValue;
        else if (argName.equals("depth"))
            depth = Integer.parseInt(argValue);
        else if (argName.equals("databaseProperties"))
            databasePropertiesPath = argValue;
        else if (argName.equals("projectCode"))
            projectCode = argValue;
        else
            innerArgs.put(argName, argValue);
    }
    if (termFilePath == null && databasePropertiesPath == null)
        throw new TalismaneException("Required argument: termFile or databasePropertiesPath");

    if (termFilePath != null) {
        String currentDirPath = System.getProperty("user.dir");
        File termFileDir = new File(currentDirPath);
        if (termFilePath.lastIndexOf("/") >= 0) {
            String termFileDirPath = termFilePath.substring(0, termFilePath.lastIndexOf("/"));
            termFileDir = new File(termFileDirPath);
            termFileDir.mkdirs();
        }
    }

    long startTime = new Date().getTime();
    try {
        TerminologyServiceLocator terminologyServiceLocator = TerminologyServiceLocator.getInstance();
        TerminologyService terminologyService = terminologyServiceLocator.getTerminologyService();
        TerminologyBase terminologyBase = null;

        if (projectCode == null)
            throw new TalismaneException("Required argument: projectCode");

        File file = new File(databasePropertiesPath);
        FileInputStream fis = new FileInputStream(file);
        Properties dataSourceProperties = new Properties();
        dataSourceProperties.load(fis);
        terminologyBase = terminologyService.getPostGresTerminologyBase(projectCode, dataSourceProperties);

        if (command.equals(Command.analyse) || command.equals(Command.extract)) {
            if (depth < 0)
                throw new TalismaneException("Required argument: depth");

            if (command.equals(Command.analyse)) {
                innerArgs.put("command", "analyse");
            } else {
                innerArgs.put("command", "process");
            }

            TalismaneFrench talismaneFrench = new TalismaneFrench();
            TalismaneConfig config = new TalismaneConfig(innerArgs, talismaneFrench);

            PosTagSet tagSet = TalismaneSession.getPosTagSet();
            Charset outputCharset = config.getOutputCharset();

            TermExtractor termExtractor = terminologyService.getTermExtractor(terminologyBase);
            termExtractor.setMaxDepth(depth);
            termExtractor.setOutFilePath(termFilePath);
            termExtractor.getIncludeChildren().add(tagSet.getPosTag("P"));
            termExtractor.getIncludeChildren().add(tagSet.getPosTag("P+D"));
            termExtractor.getIncludeChildren().add(tagSet.getPosTag("CC"));

            termExtractor.getIncludeWithParent().add(tagSet.getPosTag("DET"));

            if (outFilePath != null) {
                if (outFilePath.lastIndexOf("/") >= 0) {
                    String outFileDirPath = outFilePath.substring(0, outFilePath.lastIndexOf("/"));
                    File outFileDir = new File(outFileDirPath);
                    outFileDir.mkdirs();
                }
                File outFile = new File(outFilePath);
                outFile.delete();
                outFile.createNewFile();

                Writer writer = new BufferedWriter(
                        new OutputStreamWriter(new FileOutputStream(outFilePath), outputCharset));
                TermAnalysisWriter termAnalysisWriter = new TermAnalysisWriter(writer);
                termExtractor.addTermObserver(termAnalysisWriter);
            }

            Talismane talismane = config.getTalismane();
            talismane.setParseConfigurationProcessor(termExtractor);
            talismane.process();
        } else if (command.equals(Command.list)) {

            List<Term> terms = terminologyBase.getTermsByFrequency(2);
            for (Term term : terms) {
                LOG.debug("Term: " + term.getText());
                LOG.debug("Frequency: " + term.getFrequency());
                LOG.debug("Heads: " + term.getHeads());
                LOG.debug("Expansions: " + term.getExpansions());
                LOG.debug("Contexts: " + term.getContexts());
            }
        }
    } finally {
        long endTime = new Date().getTime();
        long totalTime = endTime - startTime;
        LOG.info("Total time: " + totalTime);
    }
}

From source file:org.eclipseplugins.impexeditor.http.ImpexHttpClient.java

public static void main(final String[] args) throws Exception {

    final ImpexHttpClient impexHttpClient = new ImpexHttpClient("http://localhost:9001/hac");
    final long startTime = System.currentTimeMillis();
    final Map<String, JsonArray> allatypes = new HashMap<String, JsonArray>();
    for (final JsonValue type : impexHttpClient.getAllTypes()) {
        allatypes.put(type.asString(),//from   w w w.j  a v  a  2  s .com
                impexHttpClient.getTypeandAttribute(type.asString()).get("attributes").asArray());
    }
    for (final String type : allatypes.keySet()) {
        System.out.println("type :" + type);
        for (final JsonValue string : allatypes.get(type)) {
            System.out.println("---- " + string.asString());
        }
    }
    final long stopTime = System.currentTimeMillis();
    final long elapsedTime = stopTime - startTime;
    System.out.println("Success elapsed time in seconde " + TimeUnit.MILLISECONDS.toSeconds(elapsedTime));
}

From source file:com.knowbout.epg.FakeUpdate.java

public static void main(String[] args) {
    String configFile = "/etc/knowbout.tv/epg.xml";
    int nextarg = 0;
    if (args.length > 1) {
        if (args.length == 3 && args[0].equals("-config")) {
            configFile = args[1];/*  w w  w  .  java2  s.c  om*/
            nextarg = 2;
        } else {
            System.err.println(
                    "Usage: java " + FakeUpdate.class.getName() + " [-config <xmlfile>] <program title>");
            System.exit(1);
        }
    }
    if (args.length <= nextarg) {
        System.err
                .println("Usage: java " + FakeUpdate.class.getName() + " [-config <xmlfile>] <program title>");
        System.exit(1);
    }
    String title = args[nextarg];

    try {
        XMLConfiguration config = new XMLConfiguration(configFile);

        HashMap<String, String> hibernateProperties = new HashMap<String, String>();
        Configuration database = config.subset("database");
        hibernateProperties.put(Environment.DRIVER, database.getString("driver"));
        hibernateProperties.put(Environment.URL, database.getString("url"));
        hibernateProperties.put(Environment.USER, database.getString("user"));
        hibernateProperties.put(Environment.PASS, database.getString("password"));
        hibernateProperties.put(Environment.DATASOURCE, null);

        HibernateUtil.setProperties(hibernateProperties);

        Session session = HibernateUtil.openSession();
        Transaction tx = session.beginTransaction();

        String hqlUpdate = "update Program set lastModified = :now where title = :title";
        int updatedEntities = session.createQuery(hqlUpdate).setTimestamp("now", new Date())
                .setString("title", title).executeUpdate();
        tx.commit();
        session.close();

        String alertUrl = config.getString("alertUrl");
        HessianProxyFactory factory = new HessianProxyFactory();
        AlertQueue alerts = (AlertQueue) factory.create(AlertQueue.class, alertUrl);
        alerts.checkAlerts();
    } catch (ConfigurationException e) {
        log.fatal("Configuration error in file " + configFile, e);
    } catch (IOException e) {
        log.fatal("Error downloading or processing EPG information", e);
    }

}

From source file:com.impetus.kundera.ycsb.utils.MailUtils.java

public static void main(String[] args) {
    MailUtils mailUtils = new MailUtils();
    mailUtils.sendMail(new HashMap<String, Double>(), "load", "Cassandra");
}

From source file:com.sm.replica.grizzly.DefaultReplicaServer.java

public static void main(String[] args) {
    String[] opts = new String[] { "-store", "-path", "-port", "-mode", "index" };
    String[] defaults = new String[] { "replica", "./data", "7120", "0", "0" };
    String[] paras = getOpts(args, opts, defaults);
    String store = paras[0];/*from   ww  w . ja v a  2  s. c  o m*/
    int port = Integer.valueOf(paras[2]);
    String path = paras[1];
    int mode = Integer.valueOf(paras[3]);
    int index = Integer.valueOf(paras[4]);
    CacheStore cacheStore = new CacheStore(path, null, mode);
    LogChannel logChannel = new LogChannel(store, index, path);
    DefaultReplicaServer defaultReplicaServer = new DefaultReplicaServer(logChannel, index, store, path);
    HashMap<String, CacheStore> storesMap = new HashMap<String, CacheStore>();
    storesMap.put(store, cacheStore);
    UnisonFilter unisonServerFilter = new UnisonFilter(defaultReplicaServer);
    unisonServerFilter.setFreq(1);
    logger.info("start server at " + port);
    ReplicaServer server = new ReplicaServer(port, storesMap, unisonServerFilter);
    defaultReplicaServer.hookShutdown();
    logger.info("set main thread to wait()");
    try {
        //System.in.read();
        Object obj = new Object();
        synchronized (obj) {
            obj.wait();
        }
    } catch (Exception io) {
        logger.error(io.getMessage(), io);
    }
}

From source file:com.mycompany.javaapplicaton3.ExcelWorkSheetHandlerTest.java

/**
 * @param args/* w  ww .  j  av  a2 s.  c om*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    String SAMPLE_PERSON_DATA_FILE_PATH = "C:/Users/lprates/Documents/Sample-Person-Data.xlsx";

    // Input File initialize
    File file = new File(SAMPLE_PERSON_DATA_FILE_PATH);
    InputStream inputStream = new FileInputStream(file);

    // Excel Cell Mapping
    Map<String, String> cellMapping = new HashMap<String, String>();
    cellMapping.put("HEADER", "Person Id,Name,Height,Email Address,DOB,Salary");
    cellMapping.put("A", "personId");
    cellMapping.put("B", "name");
    cellMapping.put("C", "height");
    cellMapping.put("D", "emailId");
    cellMapping.put("E", "dob");
    cellMapping.put("F", "salary");

    // The package open is instantaneous, as it should be.
    OPCPackage pkg = null;
    try {

        ExcelWorkSheetHandler<PersonVO> workSheetHandler = new ExcelWorkSheetHandler<PersonVO>(PersonVO.class,
                cellMapping);

        pkg = OPCPackage.open(inputStream);

        ExcelSheetCallback sheetCallback = new ExcelSheetCallback() {
            private int sheetNumber = 0;

            public void startSheet(int sheetNum, String sheetName) {
                this.sheetNumber = sheetNum;
                System.out.println("Started processing sheet number=" + sheetNumber + " and Sheet Name is '"
                        + sheetName + "'");
            }

            @Override
            public void endSheet() {
                System.out.println("Processing completed for sheet number=" + sheetNumber);
            }

            public void startSheet(int sheetNum) {
                System.out.println("Started processing sheet number=" + sheetNum);
            }

        };

        System.out.println("Constructor: pkg, workSheetHandler, sheetCallback");
        ExcelReader example1 = new ExcelReader(pkg, workSheetHandler, sheetCallback);
        example1.process("Lot 1 Data");

        if (workSheetHandler.getValueList().isEmpty()) {
            // No data present
            LOG.error("sHandler.getValueList() is empty");
        } else {

            LOG.info(workSheetHandler.getValueList().size()
                    + " no. of records read from given excel worksheet successfully.");

            // Displaying data ead from Excel file
            displayPersonList(workSheetHandler.getValueList());
        }
        /*
              System.out.println("\nConstructor: filePath, workSheetHandler, sheetCallback");
              ExcelReader example2 =
                  new ExcelReader(SAMPLE_PERSON_DATA_FILE_PATH, workSheetHandler, sheetCallback);
              example2.process();
                
              System.out.println("\nConstructor: file, workSheetHandler, sheetCallback");
              ExcelReader example3 = new ExcelReader(file, workSheetHandler, null);
              example3.process();
        */
    } catch (RuntimeException are) {
        LOG.error(are.getMessage(), are.getCause());
    } catch (InvalidFormatException ife) {
        LOG.error(ife.getMessage(), ife.getCause());
    } catch (IOException ioe) {
        LOG.error(ioe.getMessage(), ioe.getCause());
    } finally {
        IOUtils.closeQuietly(inputStream);
        try {
            if (null != pkg) {
                pkg.close();
            }
        } catch (IOException e) {
            // just ignore IO exception
        }
    }
}

From source file:at.tlphotography.jAbuseReport.Reporter.java

/**
 * The main method.//from w  w  w  . j a  v a2 s . c  o  m
 *
 * @param args
 *          the arguments
 */
public static void main(String[] args) {
    parseArguments(args);

    File[] directory = new File(logDir).listFiles(); // get the files in the dir

    for (File file : directory) // iterate over the file
    {
        if (!file.isDirectory() && file.getName().contains(logNames)) // if the file is not a dir and the name contains the logName string
        {
            if (file.getName().endsWith(".gz")) // is it zipped?
            {
                content.putAll(readGZFile(file));
            } else {
                content.putAll(readLogFile(file));
            }
        }
    }

    // save the mails to the log lines
    HashMap<String, ArrayList<LogObject>> finalContent = new HashMap<>();

    Iterator<Entry<String, String>> it = content.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, String> pair = it.next();
        String mail = whoIsLookUp(pair.getKey());

        if (finalContent.containsKey(mail)) {
            finalContent.get(mail).add(new LogObject(pair.getValue()));
        } else {
            ArrayList<LogObject> temp = new ArrayList<LogObject>();
            temp.add(new LogObject(pair.getValue()));
            finalContent.put(mail, temp);
        }

        it.remove();
    }

    // sort them
    Iterator<Entry<String, ArrayList<LogObject>>> it2 = finalContent.entrySet().iterator();
    while (it2.hasNext()) {
        Entry<String, ArrayList<LogObject>> pair = it2.next();
        Collections.sort(pair.getValue());
        println(pair.getKey() + " =");
        for (LogObject obj : pair.getValue()) {
            println(obj.logContent);
        }

        println("\n");
        it2.remove();
    }

}

From source file:io.compgen.cgpipe.CGPipe.java

public static void main(String[] args) {
    String fname = null;/*from w w w. j av  a 2s.c  om*/
    String logFilename = null;
    String outputFilename = null;
    PrintStream outputStream = null;

    int verbosity = 0;
    boolean silent = false;
    boolean dryrun = false;
    boolean silenceStdErr = false;
    boolean showHelp = false;

    List<String> targets = new ArrayList<String>();
    Map<String, VarValue> confVals = new HashMap<String, VarValue>();

    String k = null;

    for (int i = 0; i < args.length; i++) {
        String arg = args[i];
        if (i == 0) {
            if (new File(arg).exists()) {
                fname = arg;
                silenceStdErr = true;
                continue;
            }
        } else if (args[i - 1].equals("-f")) {
            fname = arg;
            continue;
        } else if (args[i - 1].equals("-l")) {
            logFilename = arg;
            continue;
        } else if (args[i - 1].equals("-o")) {
            outputFilename = arg;
            continue;
        }

        if (arg.equals("-h") || arg.equals("-help") || arg.equals("--help")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            showHelp = true;
        } else if (arg.equals("-license")) {
            license();
            System.exit(1);
        } else if (arg.equals("-s")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            silent = true;
        } else if (arg.equals("-nolog")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            silenceStdErr = true;
        } else if (arg.equals("-v")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            verbosity++;
        } else if (arg.equals("-vv")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            verbosity += 2;
        } else if (arg.equals("-vvv")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            verbosity += 3;
        } else if (arg.equals("-dr")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            dryrun = true;
        } else if (arg.startsWith("--")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            k = arg.substring(2);
        } else if (k != null) {
            if (k.contains("-")) {
                k = k.replaceAll("-", "_");
            }
            if (confVals.containsKey(k)) {
                try {
                    VarValue val = confVals.get(k);
                    if (val.getClass().equals(VarList.class)) {
                        ((VarList) val).add(VarValue.parseStringRaw(arg));
                    } else {
                        VarList list = new VarList();
                        list.add(val);
                        list.add(VarValue.parseStringRaw(arg));
                        confVals.put(k, list);
                    }
                } catch (VarTypeException e) {
                    System.err.println("Error setting variable: " + k + " => " + arg);
                    System.exit(1);
                    ;
                }
            } else {
                confVals.put(k, VarValue.parseStringRaw(arg));
            }
            k = null;
        } else if (arg.charAt(0) != '-') {
            targets.add(arg);
        }
    }
    if (k != null) {
        if (k.contains("-")) {
            k = k.replaceAll("-", "_");
        }
        confVals.put(k, VarBool.TRUE);
    }

    confVals.put("cgpipe.loglevel", new VarInt(verbosity));

    if (fname == null) {
        usage();
        System.exit(1);
    }

    if (!showHelp) {
        switch (verbosity) {
        case 0:
            SimpleFileLoggerImpl.setLevel(Level.INFO);
            break;
        case 1:
            SimpleFileLoggerImpl.setLevel(Level.DEBUG);
            break;
        case 2:
            SimpleFileLoggerImpl.setLevel(Level.TRACE);
            break;
        case 3:
        default:
            SimpleFileLoggerImpl.setLevel(Level.ALL);
            break;
        }
    } else {
        SimpleFileLoggerImpl.setLevel(Level.FATAL);
    }

    SimpleFileLoggerImpl.setSilent(silenceStdErr || showHelp);

    Log log = LogFactory.getLog(CGPipe.class);
    log.info("Starting new run: " + fname);

    if (logFilename != null) {
        confVals.put("cgpipe.log", new VarString(logFilename));
    }

    if (System.getenv("CGPIPE_DRYRUN") != null && !System.getenv("CGPIPE_DRYRUN").equals("")) {
        dryrun = true;
    }

    JobRunner runner = null;
    try {
        // Load config values from global config. 
        RootContext root = new RootContext();
        loadInitFiles(root);

        // Load settings from environment variables.
        root.loadEnvironment();

        // Set cmd-line arguments
        if (silent) {
            root.setOutputStream(null);
        }

        if (outputFilename != null) {
            outputStream = new PrintStream(new FileOutputStream(outputFilename));
            root.setOutputStream(outputStream);
        }

        for (String k1 : confVals.keySet()) {
            log.info("config: " + k1 + " => " + confVals.get(k1).toString());
        }

        root.update(confVals);
        root.set("cgpipe.procs", new VarInt(Runtime.getRuntime().availableProcessors()));

        // update the URL Source loader configs
        SourceLoader.updateRemoteHandlers(root.cloneString("cgpipe.remote"));

        // Now check for help, only after we've setup the remote handlers...
        if (showHelp) {
            try {
                Parser.showHelp(fname);
                System.exit(0);
            } catch (IOException e) {
                System.err.println("Unable to find pipeline: " + fname);
                System.exit(1);
            }
        }

        // Set the global config values
        //         globalConfig.putAll(root.cloneValues());

        // Parse the AST and run it
        Parser.exec(fname, root);

        // Load the job runner *after* we execute the script to capture any config changes
        runner = JobRunner.load(root, dryrun);

        // find a build-target, and submit the job(s) to a runner
        if (targets.size() > 0) {
            for (String target : targets) {
                log.debug("building: " + target);

                BuildTarget initTarget = root.build(target);
                if (initTarget != null) {
                    runner.submitAll(initTarget, root);
                } else {
                    System.out.println("CGPIPE ERROR: Unable to find target: " + target);
                }
            }
        } else {
            BuildTarget initTarget = root.build();
            if (initTarget != null) {
                runner.submitAll(initTarget, root);
                // Leave this commented out - it should be allowed to run cgpipe scripts w/o a target defined (testing)
                //            } else {
                //               System.out.println("CGPIPE ERROR: Unable to find default target");
            }
        }
        runner.done();

        if (outputStream != null) {
            outputStream.close();
        }

    } catch (ASTParseException | ASTExecException | RunnerException | FileNotFoundException e) {
        if (outputStream != null) {
            outputStream.close();
        }
        if (runner != null) {
            runner.abort();
        }

        if (e.getClass().equals(ExitException.class)) {
            System.exit(((ExitException) e).getReturnCode());
        }

        System.out.println("CGPIPE ERROR " + e.getMessage());
        if (verbosity > 0) {
            e.printStackTrace();
        }
        System.exit(1);
    }
}

From source file:com.ibm.crail.storage.StorageServer.java

public static void main(String[] args) throws Exception {
    Logger LOG = CrailUtils.getLogger();
    CrailConfiguration conf = new CrailConfiguration();
    CrailConstants.updateConstants(conf);
    CrailConstants.printConf();//from w  w w.  ja  v a2  s .c o m
    CrailConstants.verify();

    int splitIndex = 0;
    for (String param : args) {
        if (param.equalsIgnoreCase("--")) {
            break;
        }
        splitIndex++;
    }

    //default values
    StringTokenizer tokenizer = new StringTokenizer(CrailConstants.STORAGE_TYPES, ",");
    if (!tokenizer.hasMoreTokens()) {
        throw new Exception("No storage types defined!");
    }
    String storageName = tokenizer.nextToken();
    int storageType = 0;
    HashMap<String, Integer> storageTypes = new HashMap<String, Integer>();
    storageTypes.put(storageName, storageType);
    for (int type = 1; tokenizer.hasMoreElements(); type++) {
        String name = tokenizer.nextToken();
        storageTypes.put(name, type);
    }
    int storageClass = -1;

    //custom values
    if (args != null) {
        Option typeOption = Option.builder("t").desc("storage type to start").hasArg().build();
        Option classOption = Option.builder("c").desc("storage class the server will attach to").hasArg()
                .build();
        Options options = new Options();
        options.addOption(typeOption);
        options.addOption(classOption);
        CommandLineParser parser = new DefaultParser();

        try {
            CommandLine line = parser.parse(options, Arrays.copyOfRange(args, 0, splitIndex));
            if (line.hasOption(typeOption.getOpt())) {
                storageName = line.getOptionValue(typeOption.getOpt());
                storageType = storageTypes.get(storageName).intValue();
            }
            if (line.hasOption(classOption.getOpt())) {
                storageClass = Integer.parseInt(line.getOptionValue(classOption.getOpt()));
            }
        } catch (ParseException e) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Storage tier", options);
            System.exit(-1);
        }
    }
    if (storageClass < 0) {
        storageClass = storageType;
    }

    StorageTier storageTier = StorageTier.createInstance(storageName);
    if (storageTier == null) {
        throw new Exception("Cannot instantiate datanode of type " + storageName);
    }

    String extraParams[] = null;
    splitIndex++;
    if (args.length > splitIndex) {
        extraParams = new String[args.length - splitIndex];
        for (int i = splitIndex; i < args.length; i++) {
            extraParams[i - splitIndex] = args[i];
        }
    }
    storageTier.init(conf, extraParams);
    storageTier.printConf(LOG);

    RpcClient rpcClient = RpcClient.createInstance(CrailConstants.NAMENODE_RPC_TYPE);
    rpcClient.init(conf, args);
    rpcClient.printConf(LOG);

    ConcurrentLinkedQueue<InetSocketAddress> namenodeList = CrailUtils.getNameNodeList();
    ConcurrentLinkedQueue<RpcConnection> connectionList = new ConcurrentLinkedQueue<RpcConnection>();
    while (!namenodeList.isEmpty()) {
        InetSocketAddress address = namenodeList.poll();
        RpcConnection connection = rpcClient.connect(address);
        connectionList.add(connection);
    }
    RpcConnection rpcConnection = connectionList.peek();
    if (connectionList.size() > 1) {
        rpcConnection = new RpcDispatcher(connectionList);
    }
    LOG.info("connected to namenode(s) " + rpcConnection.toString());

    StorageServer server = storageTier.launchServer();
    StorageRpcClient storageRpc = new StorageRpcClient(storageType, CrailStorageClass.get(storageClass),
            server.getAddress(), rpcConnection);

    HashMap<Long, Long> blockCount = new HashMap<Long, Long>();
    long sumCount = 0;
    while (server.isAlive()) {
        StorageResource resource = server.allocateResource();
        if (resource == null) {
            break;
        } else {
            storageRpc.setBlock(resource.getAddress(), resource.getLength(), resource.getKey());
            DataNodeStatistics stats = storageRpc.getDataNode();
            long newCount = stats.getFreeBlockCount();
            long serviceId = stats.getServiceId();

            long oldCount = 0;
            if (blockCount.containsKey(serviceId)) {
                oldCount = blockCount.get(serviceId);
            }
            long diffCount = newCount - oldCount;
            blockCount.put(serviceId, newCount);
            sumCount += diffCount;
            LOG.info("datanode statistics, freeBlocks " + sumCount);
        }
    }

    while (server.isAlive()) {
        DataNodeStatistics stats = storageRpc.getDataNode();
        long newCount = stats.getFreeBlockCount();
        long serviceId = stats.getServiceId();

        long oldCount = 0;
        if (blockCount.containsKey(serviceId)) {
            oldCount = blockCount.get(serviceId);
        }
        long diffCount = newCount - oldCount;
        blockCount.put(serviceId, newCount);
        sumCount += diffCount;

        LOG.info("datanode statistics, freeBlocks " + sumCount);
        Thread.sleep(2000);
    }
}