Example usage for java.util Map get

List of usage examples for java.util Map get

Introduction

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

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Document doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(getXMLData())));

    Map entityValues = new HashMap();
    getEntityValues(doc, entityValues);/*from ww w. j a  v  a 2  s.  c  om*/

    NamedNodeMap entities = doc.getDoctype().getEntities();
    for (int i = 0; i < entities.getLength(); i++) {
        Entity entity = (Entity) entities.item(i);
        System.out.println(entity);
        String entityName = entity.getNodeName();
        System.out.println(entityName);
        String entityPublicId = entity.getPublicId();
        System.out.println(entityPublicId);
        String entitySystemId = entity.getSystemId();
        System.out.println(entitySystemId);
        Node entityValue = (Node) entityValues.get(entityName);
        System.out.println(entityValue);
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);//ww w.  j  ava 2s  . c  o  m
    factory.setExpandEntityReferences(false);

    Document doc = factory.newDocumentBuilder().parse(new File("filename"));

    Map entityValues = new HashMap();
    getEntityValues(doc, entityValues);

    NamedNodeMap entities = doc.getDoctype().getEntities();
    for (int i = 0; i < entities.getLength(); i++) {
        Entity entity = (Entity) entities.item(i);
        System.out.println(entity);
        String entityName = entity.getNodeName();
        System.out.println(entityName);
        String entityPublicId = entity.getPublicId();
        System.out.println(entityPublicId);
        String entitySystemId = entity.getSystemId();
        System.out.println(entitySystemId);
        Node entityValue = (Node) entityValues.get(entityName);
        System.out.println(entityValue);
    }
}

From source file:org.bigtextml.drivers.BigMapTest.java

public static void main(String[] args) {
    /*// w ww .j  a va2 s . c  o  m
    ApplicationContext context = 
    new ClassPathXmlApplicationContext(new String[] {"InMemoryDataMining.xml"});
    */
    System.out.println(System.getProperty("InvokedFromSpring"));
    //Map<String,List<Integer>> bm = context.getBean("bigMapTest",BigMap.class);
    Map<String, List<Integer>> bm = ManagementServices.getBigMap("tmCache");
    System.out.println(((BigMap) bm).getCacheName());
    int max = 1000000;

    //bm.setMaxCapacity(1000);

    for (int i = 0; i < max; i++) {
        List<Integer> x = new ArrayList<Integer>();
        for (int j = 0; j < 5; j++) {
            x.add(j);
        }
        x.add(i);
        bm.put(Integer.toString(i), x);
    }
    String key = Integer.toString(max - 1);
    //bm.remove(key);
    for (int i = 0; i < 3; i++) {
        long millis = System.currentTimeMillis();
        System.out.println(bm.get(Integer.toString(500000)));
        System.out.println(System.currentTimeMillis() - millis);
    }
    bm.clear();
}

From source file:net.roboconf.iaas.openstack.IaasOpenstack.java

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

    Map<String, String> conf = new HashMap<String, String>();

    java.util.Properties p = new java.util.Properties();
    p.load(new java.io.FileReader(args[0]));

    for (Object name : p.keySet()) {
        conf.put(name.toString(), p.get(name).toString());
    }/*from w ww .j  a  va2s. co m*/
    // conf.put("openstack.computeUrl", "http://localhost:8888/v2");

    IaasOpenstack iaas = new IaasOpenstack();
    iaas.setIaasProperties(conf);

    String machineImageId = conf.get("openstack.image");
    String channelName = "test";
    String applicationName = "roboconf";
    String ipMessagingServer = "localhost";
    String serverId = iaas.createVM(machineImageId, ipMessagingServer, channelName, applicationName);
    /*Thread.sleep(25000);
    iaas.terminateVM(serverId);*/
}

From source file:TweetAttributes.java

public static void main(String[] args) throws IOException, ParseException, JSONException {

    int k = Integer.parseInt(args[0]);
    String inputFile = args[1];/*from  w w w.ja  v  a2  s.  c  om*/
    String initialSeedsFile = args[2];
    String outputFile = args[3];

    KMeansJaccard kmj = new KMeansJaccard(k);
    kmj.makeTweetObjects(inputFile);
    List<TweetAttributes> centroidPoints = kmj.getInitialCentroids(initialSeedsFile);

    Map<Long, List<Double>> distanceMap = new LinkedHashMap<>();
    List<TweetAttributes> tweets = kmj.getTweetList();

    buildDistanceMap(centroidPoints, tweets, kmj, distanceMap);

    for (Long i : distanceMap.keySet()) {
        kmj.assignClusterToTweet(i, distanceMap.get(i));
    }

    List<TweetAttributes> tweetCopy = tweets;
    List<TweetAttributes> centroidCopy = centroidPoints;

    double cost = calculateCost(tweets, centroidPoints, kmj);

    Map<Integer, List<TweetAttributes>> tweetClusterMapping = getTweetCLusterMapping(tweets);

    for (Integer i : tweetClusterMapping.keySet()) {
        List<TweetAttributes> ta = tweetClusterMapping.get(i);
        for (TweetAttributes tweet : ta) {
            centroidPoints.remove(i - 1);
            centroidPoints.add(i - 1, tweet);

            distanceMap.clear();
            buildDistanceMap(centroidPoints, tweets, kmj, distanceMap);

            for (Long id : distanceMap.keySet()) {
                kmj.assignClusterToTweet(id, distanceMap.get(id));
            }

            double newCost = calculateCost(tweets, centroidPoints, kmj);

            if (newCost < cost) {
                cost = newCost;
                tweetCopy = kmj.getTweetList();
                centroidCopy = kmj.getCentroidList();
            }

        }
    }
    double sse = calculateSSE(tweetCopy, centroidCopy, kmj);
    System.out.println("COST: " + cost + " " + "SSE:" + sse);
    writeOutputToFile(tweetCopy, outputFile);

}

From source file:com.yahoo.storm.yarn.MasterServer.java

@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
    LOG.info("Starting the AM!!!!");

    Options opts = new Options();
    opts.addOption("app_attempt_id", true, "App Attempt ID. Not to be used " + "unless for testing purposes");

    CommandLine cl = new GnuParser().parse(opts, args);

    ApplicationAttemptId appAttemptID;//w  w w .  j a  v a  2 s.  c  o m
    Map<String, String> envs = System.getenv();
    if (cl.hasOption("app_attempt_id")) {
        String appIdStr = cl.getOptionValue("app_attempt_id", "");
        appAttemptID = ConverterUtils.toApplicationAttemptId(appIdStr);
    } else if (envs.containsKey(ApplicationConstants.Environment.CONTAINER_ID.name())) {
        ContainerId containerId = ConverterUtils
                .toContainerId(envs.get(ApplicationConstants.Environment.CONTAINER_ID.name()));
        appAttemptID = containerId.getApplicationAttemptId();
        LOG.info("appAttemptID from env:" + appAttemptID.toString());
    } else {
        LOG.error("appAttemptID is not specified for storm master");
        throw new Exception("appAttemptID is not specified for storm master");
    }

    @SuppressWarnings("rawtypes")
    Map storm_conf = Config.readStormConfig(null);
    Util.rmNulls(storm_conf);

    YarnConfiguration hadoopConf = new YarnConfiguration();

    final String host = InetAddress.getLocalHost().getHostName();
    storm_conf.put("nimbus.host", host);

    StormAMRMClient rmClient = new StormAMRMClient(appAttemptID, storm_conf, hadoopConf);
    rmClient.init(hadoopConf);
    rmClient.start();

    BlockingQueue<Container> launcherQueue = new LinkedBlockingQueue<Container>();

    MasterServer server = new MasterServer(storm_conf, rmClient);
    try {
        final int port = Utils.getInt(storm_conf.get(Config.MASTER_THRIFT_PORT));
        final String target = host + ":" + port;
        InetSocketAddress addr = NetUtils.createSocketAddr(target);
        RegisterApplicationMasterResponse resp = rmClient.registerApplicationMaster(addr.getHostName(), port,
                null);
        LOG.info("Got a registration response " + resp);
        LOG.info("Max Capability " + resp.getMaximumResourceCapability());
        rmClient.setMaxResource(resp.getMaximumResourceCapability());
        LOG.info("Starting HB thread");
        server.initAndStartHeartbeat(rmClient, launcherQueue,
                (Integer) storm_conf.get(Config.MASTER_HEARTBEAT_INTERVAL_MILLIS));
        LOG.info("Starting launcher");
        initAndStartLauncher(rmClient, launcherQueue);
        rmClient.startAllSupervisors();
        LOG.info("Starting Master Thrift Server");
        server.serve();
        LOG.info("StormAMRMClient::unregisterApplicationMaster");
        rmClient.unregisterApplicationMaster(FinalApplicationStatus.SUCCEEDED, "AllDone", null);
    } finally {
        if (server.isServing()) {
            LOG.info("Stop Master Thrift Server");
            server.stop();
        }
        LOG.info("Stop RM client");
        rmClient.stop();
    }
    System.exit(0);
}

From source file:edu.cuhk.hccl.evaluation.EvaluationApp.java

public static void main(String[] args) throws IOException, TasteException {
    File realFile = new File(args[0]);
    File estimateFile = new File(args[1]);

    // Build real-rating map
    Map<String, long[]> realMap = buildRatingMap(realFile);

    // Build estimate-rating map
    Map<String, long[]> estimateMap = buildRatingMap(estimateFile);

    // Compare realMap with estimateMap
    Map<Integer, List<Double>> realList = new HashMap<Integer, List<Double>>();
    Map<Integer, List<Double>> estimateList = new HashMap<Integer, List<Double>>();

    // Use set to store non-duplicate pairs only
    Set<String> noRatingList = new HashSet<String>();

    for (String pair : realMap.keySet()) {
        long[] realRatings = realMap.get(pair);
        long[] estimateRatings = estimateMap.get(pair);

        if (realRatings == null || estimateRatings == null)
            continue;

        for (int i = 0; i < realRatings.length; i++) {
            long real = realRatings[i];
            long estimate = estimateRatings[i];

            // continue if the aspect rating can not be estimated due to incomplete reviews
            if (estimate <= 0) {
                noRatingList.add(pair.replace("@", "\t"));
                continue;
            }/*  www.  j  a  v a  2s .  com*/

            if (real > 0 && estimate > 0) {
                if (!realList.containsKey(i))
                    realList.put(i, new ArrayList<Double>());

                realList.get(i).add((double) real);

                if (!estimateList.containsKey(i))
                    estimateList.put(i, new ArrayList<Double>());

                estimateList.get(i).add((double) estimate);
            }
        }
    }

    System.out.println("[INFO] RMSE, MAE for estimate ratings: ");
    System.out.println("------------------------------");
    System.out.println("Index \t RMSE \t MAE");
    for (int i = 1; i < 6; i++) {
        double rmse = Metric.computeRMSE(realList.get(i), estimateList.get(i));
        double mae = Metric.computeMAE(realList.get(i), estimateList.get(i));

        System.out.printf("%d \t %.3f \t %.3f \n", i, rmse, mae);
    }

    System.out.println("------------------------------");

    if (noRatingList.size() > 0) {
        String noRatingFileName = "evaluation-no-ratings.txt";
        FileUtils.writeLines(new File(noRatingFileName), noRatingList, false);

        System.out.println("[INFO] User-item pairs with no ratings are saved in file: " + noRatingFileName);
    } else {
        System.out.println("[INFO] All user-item pairs have ratings.");
    }
}

From source file:edu.cmu.lti.oaqa.knn4qa.apps.LuceneIndexer.java

public static void main(String[] args) {
    Options options = new Options();

    options.addOption(CommonParams.ROOT_DIR_PARAM, null, true, CommonParams.ROOT_DIR_DESC);
    options.addOption(CommonParams.SUB_DIR_TYPE_PARAM, null, true, CommonParams.SUB_DIR_TYPE_DESC);
    options.addOption(CommonParams.MAX_NUM_REC_PARAM, null, true, CommonParams.MAX_NUM_REC_DESC);
    options.addOption(CommonParams.SOLR_FILE_NAME_PARAM, null, true, CommonParams.SOLR_FILE_NAME_DESC);
    options.addOption(CommonParams.OUT_INDEX_PARAM, null, true, CommonParams.OUT_MINDEX_DESC);

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    try {/* ww w . j  a  v a  2s .  c  o m*/
        CommandLine cmd = parser.parse(options, args);

        String rootDir = null;

        rootDir = cmd.getOptionValue(CommonParams.ROOT_DIR_PARAM);

        if (null == rootDir)
            Usage("Specify: " + CommonParams.ROOT_DIR_DESC, options);

        String outputDirName = cmd.getOptionValue(CommonParams.OUT_INDEX_PARAM);

        if (null == outputDirName)
            Usage("Specify: " + CommonParams.OUT_MINDEX_DESC, options);

        String subDirTypeList = cmd.getOptionValue(CommonParams.SUB_DIR_TYPE_PARAM);

        if (null == subDirTypeList || subDirTypeList.isEmpty())
            Usage("Specify: " + CommonParams.SUB_DIR_TYPE_DESC, options);

        String solrFileName = cmd.getOptionValue(CommonParams.SOLR_FILE_NAME_PARAM);
        if (null == solrFileName)
            Usage("Specify: " + CommonParams.SOLR_FILE_NAME_DESC, options);

        int maxNumRec = Integer.MAX_VALUE;

        String tmp = cmd.getOptionValue(CommonParams.MAX_NUM_REC_PARAM);

        if (tmp != null) {
            try {
                maxNumRec = Integer.parseInt(tmp);
                if (maxNumRec <= 0) {
                    Usage("The maximum number of records should be a positive integer", options);
                }
            } catch (NumberFormatException e) {
                Usage("The maximum number of records should be a positive integer", options);
            }
        }

        File outputDir = new File(outputDirName);
        if (!outputDir.exists()) {
            if (!outputDir.mkdirs()) {
                System.out.println("couldn't create " + outputDir.getAbsolutePath());
                System.exit(1);
            }
        }
        if (!outputDir.isDirectory()) {
            System.out.println(outputDir.getAbsolutePath() + " is not a directory!");
            System.exit(1);
        }
        if (!outputDir.canWrite()) {
            System.out.println("Can't write to " + outputDir.getAbsolutePath());
            System.exit(1);
        }

        String subDirs[] = subDirTypeList.split(",");

        int docNum = 0;

        // No English analyzer here, all language-related processing is done already,
        // here we simply white-space tokenize and index tokens verbatim.
        Analyzer analyzer = new WhitespaceAnalyzer();
        FSDirectory indexDir = FSDirectory.open(outputDir);
        IndexWriterConfig indexConf = new IndexWriterConfig(analyzer.getVersion(), analyzer);

        System.out.println("Creating a new Lucene index, maximum # of docs to process: " + maxNumRec);
        indexConf.setOpenMode(OpenMode.CREATE);
        IndexWriter indexWriter = new IndexWriter(indexDir, indexConf);

        for (int subDirId = 0; subDirId < subDirs.length && docNum < maxNumRec; ++subDirId) {
            String inputFileName = rootDir + "/" + subDirs[subDirId] + "/" + solrFileName;

            System.out.println("Input file name: " + inputFileName);

            BufferedReader inpText = new BufferedReader(
                    new InputStreamReader(CompressUtils.createInputStream(inputFileName)));
            String docText = XmlHelper.readNextXMLIndexEntry(inpText);

            for (; docText != null && docNum < maxNumRec; docText = XmlHelper.readNextXMLIndexEntry(inpText)) {
                ++docNum;
                Map<String, String> docFields = null;

                Document luceneDoc = new Document();

                try {
                    docFields = XmlHelper.parseXMLIndexEntry(docText);
                } catch (Exception e) {
                    System.err.println(String.format("Parsing error, offending DOC #%d:\n%s", docNum, docText));
                    System.exit(1);
                }

                String id = docFields.get(UtilConst.TAG_DOCNO);

                if (id == null) {
                    System.err.println(String.format("No ID tag '%s', offending DOC #%d:\n%s",
                            UtilConst.TAG_DOCNO, docNum, docText));
                }

                luceneDoc.add(new StringField(UtilConst.TAG_DOCNO, id, Field.Store.YES));

                for (Map.Entry<String, String> e : docFields.entrySet())
                    if (!e.getKey().equals(UtilConst.TAG_DOCNO)) {
                        luceneDoc.add(new TextField(e.getKey(), e.getValue(), Field.Store.YES));
                    }
                indexWriter.addDocument(luceneDoc);
                if (docNum % 1000 == 0)
                    System.out.println("Indexed " + docNum + " docs");
            }
            System.out.println("Indexed " + docNum + " docs");
        }

        indexWriter.commit();
        indexWriter.close();

    } catch (ParseException e) {
        Usage("Cannot parse arguments", options);
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }

}

From source file:net.itransformers.idiscover.core.DiscoveryManager.java

public static void main(String[] args) throws Exception, IllegalAccessException, JAXBException {
    Map<String, String> params = CmdLineParser.parseCmdLine(args);
    if (params == null) {
        printUsage("mibDir");
        return;//from  ww w .j a v a  2  s  . c o  m
    }
    final String fileName = params.get("-f");
    if (fileName == null) {
        printUsage("fileName");
        return;
    }
    File file = new File(fileName);

    DiscoveryManager manager = createDiscoveryManager(file.getParentFile(), file.getName(), "network", true);

    String mode = params.get("-d");
    if (mode == null) {
        //Set default snmpDiscovery mode to discover network!!!
        mode = "network";
    }

    Map<String, String> resourceSelectionParams = new HashMap<String, String>();
    resourceSelectionParams.put("protocol", "SNMP");
    ResourceType snmp = manager.discoveryResource.returnResourceByParam(resourceSelectionParams);

    Map<String, String> snmpConnParams = new HashMap<String, String>();
    snmpConnParams = manager.discoveryResource.getParamMap(snmp, "snmp");

    String host = params.get("-h");
    IPv4Address initialIPaddress = new IPv4Address(host, null);
    snmpConnParams.put("status", "initial");
    String mibDir = params.get("-m");
    snmpConnParams.put("mibDir", mibDir);

    snmpConnParams.get("port");
    Resource resource = new Resource(initialIPaddress, null, Integer.parseInt(snmpConnParams.get("port")),
            snmpConnParams);

    if (resource == null)
        ;

    String[] discoveryTypes = new String[] { "PHYSICAL", "NEXT_HOP", "OSPF", "ISIS", "BGP", "RIP", "ADDITIONAL",
            "IPV6" };

    //        DiscovererFactory.init(new SimulSnmpWalker(resource, new File("logs.log")));
    //        DiscovererFactory.init();
    //        Discoverer discoverer = new SnmpWalker(resource);
    NetworkType network = manager.discoverNetwork(resource, mode, discoveryTypes);

    for (DiscoveredDeviceData data : network.getDiscoveredDevice()) {
        System.out.println(data.getName() + "\n");
        for (ObjectType object : data.getObject()) {
            for (ObjectType innterObject : object.getObject()) {
                System.out.println(innterObject.getObjectType());
            }
        }

    }
    //        List<DiscoveredDeviceData> discoveredDeviceDatas = network.getDiscoveredDevice();
    //        for (DiscoveredDeviceData discoveredDeviceData : discoveredDeviceDatas) {
    //            discoveredDeviceData.getName();
    //            ParametersType parameters = discoveredDeviceData.getParameters();
    //            List<ParameterType> paras =   parameters.getParameter();
    //            for (ParameterType para : paras) {
    //
    //            }
    //
    //        }

}

From source file:com.fiveclouds.jasper.JasperRunner.java

public static void main(String[] args) {

    // Set-up the options for the utility
    Options options = new Options();
    Option report = new Option("report", true, "jasper report to run (i.e. /path/to/report.jrxml)");
    options.addOption(report);/*from   w w  w.  jav  a 2 s.  c  o m*/

    Option driver = new Option("driver", true, "the jdbc driver class (i.e. com.mysql.jdbc.Driver)");
    driver.setRequired(true);
    options.addOption(driver);

    options.addOption("jdbcurl", true, "database jdbc url (i.e. jdbc:mysql://localhost:3306/database)");
    options.addOption("excel", true, "Will override the PDF default and export to Microsoft Excel");
    options.addOption("username", true, "database username");
    options.addOption("password", true, "database password");
    options.addOption("output", true, "the output filename (i.e. path/to/report.pdf");
    options.addOption("help", false, "print this message");

    Option propertyOption = OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator()
            .withDescription("use value as report property").create("D");

    options.addOption(propertyOption);

    // Parse the options and build the report
    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("jasper-runner", options);
        } else {

            System.out.println("Building report " + cmd.getOptionValue("report"));
            try {
                Class.forName(cmd.getOptionValue("driver"));
                Connection connection = DriverManager.getConnection(cmd.getOptionValue("jdbcurl"),
                        cmd.getOptionValue("username"), cmd.getOptionValue("password"));
                System.out.println("Connected to " + cmd.getOptionValue("jdbcurl"));
                JasperReport jasperReport = JasperCompileManager.compileReport(cmd.getOptionValue("report"));

                JRPdfExporter pdfExporter = new JRPdfExporter();

                Properties properties = cmd.getOptionProperties("D");
                Map<String, Object> parameters = new HashMap<String, Object>();

                Map<String, JRParameter> reportParameters = new HashMap<String, JRParameter>();

                for (JRParameter param : jasperReport.getParameters()) {
                    reportParameters.put(param.getName(), param);
                }

                for (Object propertyKey : properties.keySet()) {
                    String parameterName = String.valueOf(propertyKey);
                    String parameterValue = String.valueOf(properties.get(propertyKey));
                    JRParameter reportParam = reportParameters.get(parameterName);

                    if (reportParam != null) {
                        if (reportParam.getValueClass().equals(String.class)) {
                            System.out.println(
                                    "Property " + parameterName + " set to String = " + parameterValue);
                            parameters.put(parameterName, parameterValue);
                        } else if (reportParam.getValueClass().equals(Integer.class)) {
                            System.out.println(
                                    "Property " + parameterName + " set to Integer = " + parameterValue);
                            parameters.put(parameterName, Integer.parseInt(parameterValue));
                        } else {
                            System.err.print("Unsupported type for property " + parameterName);
                            System.exit(1);

                        }
                    } else {
                        System.out.println("Property " + parameterName + " not found in the report! IGNORING");

                    }
                }

                JasperPrint print = JasperFillManager.fillReport(jasperReport, parameters, connection);

                pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
                pdfExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, cmd.getOptionValue("output"));
                System.out.println("Exporting report to " + cmd.getOptionValue("output"));
                pdfExporter.exportReport();
            } catch (JRException e) {
                System.err.print("Unable to parse report file (" + cmd.getOptionValue("r") + ")");
                e.printStackTrace();
                System.exit(1);
            } catch (ClassNotFoundException e) {
                System.err.print("Unable to find the database driver,  is it on the classpath?");
                e.printStackTrace();
                System.exit(1);
            } catch (SQLException e) {
                System.err.print("An SQL exception has occurred (" + e.getMessage() + ")");
                e.printStackTrace();
                System.exit(1);
            }
        }
    } catch (ParseException e) {
        System.err.print("Unable to parse command line options (" + e.getMessage() + ")");
        System.exit(1);
    }
}