Example usage for java.util Map put

List of usage examples for java.util Map put

Introduction

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

Prototype

V put(K key, V value);

Source Link

Document

Associates the specified value with the specified key in this map (optional operation).

Usage

From source file:com.joliciel.jochre.search.JochreSearch.java

/**
 * @param args/*w  w w  . j av  a  2 s .  com*/
 */
public static void main(String[] args) {
    try {
        Map<String, String> argMap = new HashMap<String, String>();

        for (String arg : args) {
            int equalsPos = arg.indexOf('=');
            String argName = arg.substring(0, equalsPos);
            String argValue = arg.substring(equalsPos + 1);
            argMap.put(argName, argValue);
        }

        String command = argMap.get("command");
        argMap.remove("command");

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

        LOG.debug("##### Arguments:");
        for (Entry<String, String> arg : argMap.entrySet()) {
            LOG.debug(arg.getKey() + ": " + arg.getValue());
        }

        SearchServiceLocator locator = SearchServiceLocator.getInstance();
        SearchService searchService = locator.getSearchService();

        if (command.equals("buildIndex")) {
            String indexDirPath = argMap.get("indexDir");
            String documentDirPath = argMap.get("documentDir");
            File indexDir = new File(indexDirPath);
            indexDir.mkdirs();
            File documentDir = new File(documentDirPath);

            JochreIndexBuilder builder = searchService.getJochreIndexBuilder(indexDir);
            builder.updateDocument(documentDir);
        } else if (command.equals("updateIndex")) {
            String indexDirPath = argMap.get("indexDir");
            String documentDirPath = argMap.get("documentDir");
            boolean forceUpdate = false;
            if (argMap.containsKey("forceUpdate")) {
                forceUpdate = argMap.get("forceUpdate").equals("true");
            }
            File indexDir = new File(indexDirPath);
            indexDir.mkdirs();
            File documentDir = new File(documentDirPath);

            JochreIndexBuilder builder = searchService.getJochreIndexBuilder(indexDir);
            builder.updateIndex(documentDir, forceUpdate);
        } else if (command.equals("search")) {
            HighlightServiceLocator highlightServiceLocator = HighlightServiceLocator.getInstance(locator);
            HighlightService highlightService = highlightServiceLocator.getHighlightService();

            String indexDirPath = argMap.get("indexDir");
            File indexDir = new File(indexDirPath);
            JochreQuery query = searchService.getJochreQuery(argMap);

            JochreIndexSearcher searcher = searchService.getJochreIndexSearcher(indexDir);
            TopDocs topDocs = searcher.search(query);

            Set<Integer> docIds = new LinkedHashSet<Integer>();
            for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
                docIds.add(scoreDoc.doc);
            }
            Set<String> fields = new HashSet<String>();
            fields.add("text");

            Highlighter highlighter = highlightService.getHighlighter(query, searcher.getIndexSearcher());
            HighlightManager highlightManager = highlightService
                    .getHighlightManager(searcher.getIndexSearcher());
            highlightManager.setDecimalPlaces(query.getDecimalPlaces());
            highlightManager.setMinWeight(0.0);
            highlightManager.setIncludeText(true);
            highlightManager.setIncludeGraphics(true);

            Writer out = new PrintWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8));
            if (command.equals("highlight")) {
                highlightManager.highlight(highlighter, docIds, fields, out);
            } else {
                highlightManager.findSnippets(highlighter, docIds, fields, out);
            }
        } else {
            throw new RuntimeException("Unknown command: " + command);
        }
    } catch (RuntimeException e) {
        LogUtils.logError(LOG, e);
        throw e;
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:com.athena.dolly.web.aws.s3.S3Controller.java

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

    //String [] keys = {"directory/", "directory/browse.png", "peacock.mp4", "temp/logo.png", "temp/subdir/", "temp/subdir/index.png"};
    //String [] keys = {"directory/", "directory/browse.png"};
    String[] keys = { "temp/logo.png", "temp/subdir/", "temp/subdir/index.png" };

    Map<String, S3Dto> map = new HashMap<String, S3Dto>();
    for (String key : keys) {
        //S3Dto dto = test(null, key);
        //S3Dto dto = test("directory", key);
        S3Dto dto = test("temp", key);
        if (dto != null)
            map.put(dto.getKey(), dto);

    }/*ww w . j av  a 2  s. com*/

    System.out.println(map);
}

From source file:com.glaf.core.xml.XmlBuilder.java

public static void main(String[] args) throws Exception {
    long start = System.currentTimeMillis();
    String systemName = "default";

    XmlBuilder builder = new XmlBuilder();
    InputStream in = new FileInputStream("./template/user.template.xml");
    String filename = "user.xml";
    byte[] bytes = FileUtils.getBytes(in);
    Map<String, Object> dataMap = new HashMap<String, Object>();
    dataMap.put("now", new Date());
    Document doc = builder.process(systemName, new ByteArrayInputStream(bytes), dataMap);
    FileUtils.save(filename, com.glaf.core.util.Dom4jUtils.getBytesFromPrettyDocument(doc, "GBK"));
    // net.sf.json.xml.XMLSerializer xmlSerializer = new
    // net.sf.json.xml.XMLSerializer();
    // net.sf.json.JSON json = xmlSerializer.read(doc.asXML());
    // System.out.println(json.toString(1));

    long time = (System.currentTimeMillis() - start) / 1000;
    System.out.println("times:" + time + " seconds");
}

From source file:com.act.biointerpretation.ProductExtractor.java

public static void main(String[] args) throws Exception {
    CLIUtil cliUtil = new CLIUtil(ProductExtractor.class, HELP_MESSAGE, OPTION_BUILDERS);
    CommandLine cl = cliUtil.parseCommandLine(args);

    String orgPrefix = cl.getOptionValue(OPTION_ORGANISM_PREFIX);
    LOGGER.info("Using organism prefix %s", orgPrefix);

    MongoDB db = new MongoDB(DEFAULT_DB_HOST, DEFAULT_DB_PORT, cl.getOptionValue(OPTION_DB_NAME));

    Map<Long, String> validOrganisms = new TreeMap<>();
    DBIterator orgIter = db.getDbIteratorOverOrgs();
    Organism o = null;/* w w  w.  j  a v  a  2  s  . com*/
    while ((o = db.getNextOrganism(orgIter)) != null) {
        if (!o.getName().isEmpty() && o.getName().startsWith(orgPrefix)) {
            validOrganisms.put(o.getUUID(), o.getName());
        }
    }

    LOGGER.info("Found %d valid organisms", validOrganisms.size());

    Set<Long> productIds = new TreeSet<>(); // Use something with implicit ordering we can traverse in order.
    DBIterator reactionIterator = db.getIteratorOverReactions();
    Reaction r;
    while ((r = db.getNextReaction(reactionIterator)) != null) {
        Set<JSONObject> proteins = r.getProteinData();
        boolean valid = false;
        for (JSONObject j : proteins) {
            if (j.has("organism") && validOrganisms.containsKey(j.getLong("organism"))) {
                valid = true;
                break;
            } else if (j.has("organisms")) {
                JSONArray organisms = j.getJSONArray("organisms");
                for (int i = 0; i < organisms.length(); i++) {
                    if (validOrganisms.containsKey(organisms.getLong(i))) {
                        valid = true;
                        break;
                    }
                }
            }
        }

        if (valid) {
            for (Long id : r.getProducts()) {
                productIds.add(id);
            }
            for (Long id : r.getProductCofactors()) {
                productIds.add(id);
            }
        }
    }

    LOGGER.info("Found %d valid product ids for '%s'", productIds.size(), orgPrefix);
    PrintWriter writer = cl.hasOption(OPTION_OUTPUT_FILE)
            ? new PrintWriter(new FileWriter(cl.getOptionValue(OPTION_OUTPUT_FILE)))
            : new PrintWriter(System.out);

    for (Long id : productIds) {
        Chemical c = db.getChemicalFromChemicalUUID(id);
        String inchi = c.getInChI();
        if (inchi.startsWith("InChI=") && !inchi.startsWith("InChI=/FAKE")) {
            writer.println(inchi);
        }
    }

    if (cl.hasOption(OPTION_OUTPUT_FILE)) {
        writer.close();
    }
    LOGGER.info("Done.");
}

From source file:org.ala.harvester.MaHarvester.java

/**
 * Main method for testing this particular Harvester
 *
 * @param args/*from  w w w  .jav  a  2s  . co  m*/
 */
public static void main(String[] args) throws Exception {
    String[] locations = { "classpath*:spring.xml" };
    ApplicationContext context = new ClassPathXmlApplicationContext(locations);
    MaHarvester h = new MaHarvester();
    Repository r = (Repository) context.getBean("repository");
    h.setRepository(r);

    //set the connection params   
    Map<String, String> connectParams = new HashMap<String, String>();
    connectParams.put("endpoint", "http://medent.usyd.edu.au/photos/mosquitoesofaustralia.htm");

    h.setConnectionParams(connectParams);
    h.start(MA_INFOSOURCE_ID);
}

From source file:kindleclippings.quizlet.QuizletSync.java

public static void main(String[] args)
        throws IOException, JSONException, URISyntaxException, InterruptedException, BackingStoreException {

    ProgressMonitor progress = new ProgressMonitor(null, "QuizletSync", "loading Kindle clippings file", 0,
            100);// w  ww . java2 s . c om
    progress.setMillisToPopup(0);
    progress.setMillisToDecideToPopup(0);
    progress.setProgress(0);
    try {

        Map<String, List<Clipping>> books = readClippingsFile();

        if (books == null)
            return;

        if (books.isEmpty()) {
            JOptionPane.showMessageDialog(null, "no clippings to be uploaded", "QuizletSync",
                    JOptionPane.OK_OPTION);
            return;
        }
        progress.setNote("checking Quizlet account");
        progress.setProgress(5);

        Preferences prefs = getPrefs();

        QuizletAPI api = new QuizletAPI(prefs.get("access_token", null));

        Collection<TermSet> sets = null;
        try {
            progress.setNote("checking Quizlet library");
            progress.setProgress(10);
            sets = api.getSets(prefs.get("user_id", null));
        } catch (IOException e) {
            if (e.toString().contains("401")) {
                // Not Authorized => Token has been revoked
                clearPrefs();
                prefs = getPrefs();
                api = new QuizletAPI(prefs.get("access_token", null));
                sets = api.getSets(prefs.get("user_id", null));
            } else {
                throw e;
            }
        }

        progress.setProgress(15);
        progress.setMaximum(15 + books.size());
        progress.setNote("uploading new notes");

        Map<String, TermSet> indexedSets = new HashMap<String, TermSet>(sets.size());

        for (TermSet t : sets) {
            indexedSets.put(t.getTitle(), t);
        }

        int pro = 15;
        int createdSets = 0;
        int createdTerms = 0;
        int updatedTerms = 0;
        for (List<Clipping> c : books.values()) {

            String book = c.get(0).getBook();
            progress.setNote(book);
            progress.setProgress(pro++);

            TermSet termSet = indexedSets.get(book);
            if (termSet == null) {
                if (c.size() < 2) {
                    System.err.println("ignored [" + book + "] (need at least two notes)");
                    continue;
                }

                addSet(api, book, c);
                createdSets++;
                createdTerms += c.size();
                continue;
            }
            // compare against existing terms
            for (Clipping cl : c) {
                if (!checkExistingTerm(cl, termSet)) {
                    addTerm(api, termSet, cl);
                    updatedTerms++;
                }
            }
        }
        progress.setProgress(pro++);

        if (createdSets == 0 && updatedTerms == 0) {
            JOptionPane.showMessageDialog(null, "Done.\nNo new data was uploaded", "QuizletSync",
                    JOptionPane.OK_OPTION);
        } else if (createdSets > 0) {
            JOptionPane.showMessageDialog(null,
                    String.format(
                            "Done.\nCreated %d new sets with %d cards, and added %d cards to existing sets",
                            createdSets, createdTerms, updatedTerms),
                    "QuizletSync", JOptionPane.OK_OPTION);
        } else {
            JOptionPane.showMessageDialog(null,
                    String.format("Done.\nAdded %d cards to existing sets", updatedTerms), "QuizletSync",
                    JOptionPane.OK_OPTION);
        }
    } finally {
        progress.close();
    }

    System.exit(0);
}

From source file:org.apache.hive.ptest.execution.JIRAService.java

public static void main(String[] args) throws Exception {
    CommandLine cmd = null;/*from www. j  a  v a2s.  com*/

    try {
        cmd = parseCommandLine(args);
    } catch (ParseException e) {
        System.out.println("Error parsing command arguments: " + e.getMessage());
        System.exit(1);
    }

    // If null is returned, then help message was displayed in parseCommandLine method
    if (cmd == null) {
        System.exit(0);
    }

    Map<String, Object> jsonValues = parseJsonFile(cmd.getOptionValue(OPT_FILE_LONG));

    Map<String, String> context = Maps.newHashMap();
    context.put(FIELD_JIRA_URL, (String) jsonValues.get(FIELD_JIRA_URL));
    context.put(FIELD_JIRA_USER, cmd.getOptionValue(OPT_USER_LONG));
    context.put(FIELD_JIRA_PASS, cmd.getOptionValue(OPT_PASS_LONG));
    context.put(FIELD_LOGS_URL, (String) jsonValues.get(FIELD_LOGS_URL));
    context.put(FIELD_REPO, (String) jsonValues.get(FIELD_REPO));
    context.put(FIELD_REPO_NAME, (String) jsonValues.get(FIELD_REPO_NAME));
    context.put(FIELD_REPO_TYPE, (String) jsonValues.get(FIELD_REPO_TYPE));
    context.put(FIELD_REPO_BRANCH, (String) jsonValues.get(FIELD_REPO_BRANCH));
    context.put(FIELD_JENKINS_URL, (String) jsonValues.get(FIELD_JENKINS_URL));

    TestLogger logger = new TestLogger(System.err, TestLogger.LEVEL.TRACE);
    TestConfiguration configuration = new TestConfiguration(new Context(context), logger);
    configuration.setJiraName((String) jsonValues.get(FIELD_JIRA_NAME));
    configuration.setPatch((String) jsonValues.get(FIELD_PATCH_URL));

    JIRAService service = new JIRAService(logger, configuration, (String) jsonValues.get(FIELD_BUILD_TAG));
    List<String> messages = (List) jsonValues.get(FIELD_MESSAGES);
    SortedSet<String> failedTests = (SortedSet) jsonValues.get(FIELD_FAILED_TESTS);
    boolean error = (Integer) jsonValues.get(FIELD_BUILD_STATUS) == 0 ? false : true;
    service.postComment(error, (Integer) jsonValues.get(FIELD_NUM_TESTS_EXECUTED), failedTests, messages);
}

From source file:com.recomdata.datasetexplorer.proxy.XmlHttpProxy.java

/**
*
* CLI to the XmlHttpProxy/*from   w  w w .  j  a v  a  2s  .  c o  m*/
*/
public static void main(String[] args) throws IOException, MalformedURLException {

    getLogger().info("XmlHttpProxy 1.1");
    XmlHttpProxy xhp = new XmlHttpProxy();

    if (args.length == 0) {
        System.out.println(USAGE);
    }

    InputStream xslInputStream = null;
    String serviceKey = null;
    String urlString = null;
    String xslURLString = null;
    String format = "xml";
    String callback = null;
    String urlParams = null;
    String configURLString = "xhp.json";
    String resourceBase = "file:src/conf/META-INF/resources/xsl/";

    // read in the arguments
    int index = 0;
    while (index < args.length) {
        if (args[index].toLowerCase().equals("-url") && index + 1 < args.length) {
            urlString = args[++index];
        } else if (args[index].toLowerCase().equals("-key") && index + 1 < args.length) {
            serviceKey = args[++index];
        } else if (args[index].toLowerCase().equals("-id") && index + 1 < args.length) {
            serviceKey = args[++index];
        } else if (args[index].toLowerCase().equals("-callback") && index + 1 < args.length) {
            callback = args[++index];
        } else if (args[index].toLowerCase().equals("-xslurl") && index + 1 < args.length) {
            xslURLString = args[++index];
        } else if (args[index].toLowerCase().equals("-urlparams") && index + 1 < args.length) {
            urlParams = args[++index];
        } else if (args[index].toLowerCase().equals("-config") && index + 1 < args.length) {
            configURLString = args[++index];
        } else if (args[index].toLowerCase().equals("-resources") && index + 1 < args.length) {
            resourceBase = args[++index];
        }
        index++;
    }

    if (serviceKey != null) {
        try {
            InputStream is = (new URL(configURLString)).openStream();
            JSONObject services = loadServices(is);
            JSONObject service = services.getJSONObject(serviceKey);
            // default to the service default if no url parameters are specified
            if (urlParams == null && service.has("defaultURLParams")) {
                urlParams = service.getString("defaultURLParams");
            }
            String serviceURL = service.getString("url");
            // build the URL properly
            if (urlParams != null && serviceURL.indexOf("?") == -1) {
                serviceURL += "?";
            } else if (urlParams != null) {
                serviceURL += "&";
            }
            urlString = serviceURL + service.getString("apikey") + "&" + urlParams;
            if (service.has("xslStyleSheet")) {
                xslURLString = service.getString("xslStyleSheet");
                // check if the url is correct of if to load from the classpath

            }
        } catch (Exception ex) {
            getLogger().severe("XmlHttpProxy Error loading service: " + ex);
            System.exit(1);
        }
    } else if (urlString == null) {
        System.out.println(USAGE);
        System.exit(1);
    }
    // The parameters are feed to the XSL Stylsheet during transformation.
    // These parameters can provided data or conditional information.
    Map paramsMap = new HashMap();
    if (format != null) {
        paramsMap.put("format", format);
    }
    if (callback != null) {
        paramsMap.put("callback", callback);
    }

    if (xslURLString != null) {
        URL xslURL = new URL(xslURLString);
        if (xslURL != null) {
            xslInputStream = xslURL.openStream();
        } else {
            getLogger().severe("Error: Unable to locate XSL at URL " + xslURLString);
        }
    }
    xhp.doGet(urlString, System.out, xslInputStream, paramsMap);
}

From source file:com.example.geomesa.transformations.QueryTutorial.java

/**
 * Main entry point. Executes queries against an existing GDELT dataset.
 *
 * @param args//from  ww w.  j  a  v  a  2s .c o m
 *
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    // read command line options - this contains the connection to accumulo and the table to query
    CommandLineParser parser = new BasicParser();
    Options options = SetupUtil.getCommonRequiredOptions();
    options.addOption(OptionBuilder.withArgName(FEATURE_NAME_ARG).hasArg().isRequired()
            .withDescription("the FeatureTypeName used to store the GDELT data, e.g.:  gdelt")
            .create(FEATURE_NAME_ARG));
    CommandLine cmd = parser.parse(options, args);

    // verify that we can see this Accumulo destination in a GeoTools manner
    Map<String, String> dsConf = SetupUtil.getAccumuloDataStoreConf(cmd);
    //Disable states collection
    dsConf.put("collectStats", "false");
    DataStore dataStore = DataStoreFinder.getDataStore(dsConf);
    assert dataStore != null;

    // create the simple feature type for our test
    String simpleFeatureTypeName = cmd.getOptionValue(FEATURE_NAME_ARG);
    SimpleFeatureType simpleFeatureType = GdeltFeature.buildGdeltFeatureType(simpleFeatureTypeName);

    // get the feature store used to query the GeoMesa data
    FeatureStore featureStore = (FeatureStore) dataStore.getFeatureSource(simpleFeatureTypeName);

    // execute some queries
    basicQuery(simpleFeatureTypeName, featureStore);
    basicProjectionQuery(simpleFeatureTypeName, featureStore);
    basicTransformationQuery(simpleFeatureTypeName, featureStore);
    renamedTransformationQuery(simpleFeatureTypeName, featureStore);
    mutliFieldTransformationQuery(simpleFeatureTypeName, featureStore);
    geometricTransformationQuery(simpleFeatureTypeName, featureStore);

    // the list of available transform functions is available here:
    // http://docs.geotools.org/latest/userguide/library/main/filter.html - scroll to 'Function List'
}

From source file:MiniCluster.java

/**
 * Runs the {@link MiniAccumuloCluster} given a -p argument with a property file. Establishes a shutdown port for asynchronous operation.
 * /*from  w  w w  .  j av a2  s  .c  o  m*/
 * @param args
 *          An optional -p argument can be specified with the path to a valid properties file.
 */
public static void main(String[] args) throws Exception {
    Opts opts = new Opts();
    opts.parseArgs(MiniCluster.class.getName(), args);

    if (opts.printProps) {
        printProperties();
        System.exit(0);
    }

    int shutdownPort = 4445;

    final File miniDir;

    if (opts.prop.containsKey(DIRECTORY_PROP))
        miniDir = new File(opts.prop.getProperty(DIRECTORY_PROP));
    else
        miniDir = Files.createTempDir();

    String rootPass = opts.prop.containsKey(ROOT_PASSWORD_PROP) ? opts.prop.getProperty(ROOT_PASSWORD_PROP)
            : "secret";
    String instanceName = opts.prop.containsKey(INSTANCE_NAME_PROP) ? opts.prop.getProperty(INSTANCE_NAME_PROP)
            : "accumulo";
    MiniAccumuloConfig config = new MiniAccumuloConfig(miniDir, instanceName, rootPass);

    if (opts.prop.containsKey(NUM_T_SERVERS_PROP))
        config.setNumTservers(Integer.parseInt(opts.prop.getProperty(NUM_T_SERVERS_PROP)));
    if (opts.prop.containsKey(ZOO_KEEPER_PORT_PROP))
        config.setZooKeeperPort(Integer.parseInt(opts.prop.getProperty(ZOO_KEEPER_PORT_PROP)));
    //    if (opts.prop.containsKey(JDWP_ENABLED_PROP))
    //      config.setJDWPEnabled(Boolean.parseBoolean(opts.prop.getProperty(JDWP_ENABLED_PROP)));
    //    if (opts.prop.containsKey(ZOO_KEEPER_MEMORY_PROP))
    //      setMemoryOnConfig(config, opts.prop.getProperty(ZOO_KEEPER_MEMORY_PROP), ServerType.ZOOKEEPER);
    //    if (opts.prop.containsKey(TSERVER_MEMORY_PROP))
    //      setMemoryOnConfig(config, opts.prop.getProperty(TSERVER_MEMORY_PROP), ServerType.TABLET_SERVER);
    //    if (opts.prop.containsKey(MASTER_MEMORY_PROP))
    //      setMemoryOnConfig(config, opts.prop.getProperty(MASTER_MEMORY_PROP), ServerType.MASTER);
    //    if (opts.prop.containsKey(DEFAULT_MEMORY_PROP))
    //      setMemoryOnConfig(config, opts.prop.getProperty(DEFAULT_MEMORY_PROP));
    //    if (opts.prop.containsKey(SHUTDOWN_PORT_PROP))
    //      shutdownPort = Integer.parseInt(opts.prop.getProperty(SHUTDOWN_PORT_PROP));

    Map<String, String> siteConfig = new HashMap<String, String>();
    for (Map.Entry<Object, Object> entry : opts.prop.entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith("site."))
            siteConfig.put(key.replaceFirst("site.", ""), (String) entry.getValue());
    }

    config.setSiteConfig(siteConfig);

    final MiniAccumuloCluster accumulo = new MiniAccumuloCluster(config);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                accumulo.stop();
                FileUtils.deleteDirectory(miniDir);
                System.out.println("\nShut down gracefully on " + new Date());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });

    accumulo.start();

    printInfo(accumulo, shutdownPort);

    // start a socket on the shutdown port and block- anything connected to this port will activate the shutdown
    ServerSocket shutdownServer = new ServerSocket(shutdownPort);
    shutdownServer.accept();

    System.exit(0);
}