Example usage for java.util Map containsKey

List of usage examples for java.util Map containsKey

Introduction

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

Prototype

boolean containsKey(Object key);

Source Link

Document

Returns true if this map contains a mapping for the specified key.

Usage

From source file:Main.java

public static void main(String[] a) {

    Map<String, String> map = new HashMap<String, String>();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("key3", "value3");

    System.out.println(map.get("key2"));
    System.out.println(map.containsKey("key2"));
    System.out.println(map.containsKey("key4"));
}

From source file:de.ingrid.iplug.AdminServer.java

/**
 * To start the admin web server from the commandline. 
 * @param args The server port and the web app folder. 
 * @throws Exception Something goes wrong.
 *//*from  w w  w.  ja  v  a 2s  .  c  om*/
public static void main(String[] args) throws Exception {

    String usage = "<serverPort> <webappFolder>";
    if ((args.length == 0) && (args.length != 4) && (args.length != 6)) {
        System.err.println(usage);
        return;
    }

    Map arguments = readParameters(args);
    File plugDescriptionFile = new File(PLUG_DESCRIPTION);
    if (arguments.containsKey("--plugdescription")) {
        plugDescriptionFile = new File((String) arguments.get("--plugdescription"));
    }
    File communicationProperties = new File(COMMUNICATION_PROPERTES);
    if (arguments.containsKey("--descriptor")) {
        communicationProperties = new File((String) arguments.get("--descriptor"));
    }

    int port = Integer.parseInt(args[0]);
    File webFolder = new File(args[1]);

    //push init params for all contexts (e.g. step1 and step2)
    HashMap hashMap = new HashMap();
    hashMap.put("plugdescription.xml", plugDescriptionFile.getAbsolutePath());
    hashMap.put("communication.xml", communicationProperties.getAbsolutePath());

    WebContainer container = startWebContainer(hashMap, port, webFolder, false, null);
    container.join();
}

From source file:com.joliciel.talismane.TalismaneMain.java

public static void main(String[] args) throws Exception {
    Map<String, String> argsMap = StringUtils.convertArgs(args);
    OtherCommand otherCommand = null;//from   w ww .j ava  2  s.c  o m
    if (argsMap.containsKey("command")) {
        try {
            otherCommand = OtherCommand.valueOf(argsMap.get("command"));
            argsMap.remove("command");
        } catch (IllegalArgumentException e) {
            // not anotherCommand
        }
    }

    String sessionId = "";
    TalismaneServiceLocator locator = TalismaneServiceLocator.getInstance(sessionId);
    TalismaneService talismaneService = locator.getTalismaneService();
    TalismaneSession talismaneSession = talismaneService.getTalismaneSession();

    if (otherCommand == null) {
        // regular command
        TalismaneConfig config = talismaneService.getTalismaneConfig(argsMap, sessionId);
        if (config.getCommand() == null)
            return;

        Talismane talismane = config.getTalismane();

        talismane.process();
    } else {
        // other command
        String logConfigPath = argsMap.get("logConfigFile");
        if (logConfigPath != null) {
            argsMap.remove("logConfigFile");
            Properties props = new Properties();
            props.load(new FileInputStream(logConfigPath));
            PropertyConfigurator.configure(props);
        }

        switch (otherCommand) {
        case serializeLexicon: {
            LexiconSerializer serializer = new LexiconSerializer();
            serializer.serializeLexicons(argsMap);
            break;
        }
        case testLexicon: {
            String lexiconFilePath = null;
            String[] wordList = null;
            for (String argName : argsMap.keySet()) {
                String argValue = argsMap.get(argName);
                if (argName.equals("lexicon")) {
                    lexiconFilePath = argValue;
                } else if (argName.equals("words")) {
                    wordList = argValue.split(",");
                } else {
                    throw new TalismaneException("Unknown argument: " + argName);
                }
            }
            File lexiconFile = new File(lexiconFilePath);
            LexiconDeserializer lexiconDeserializer = new LexiconDeserializer(talismaneSession);
            List<PosTaggerLexicon> lexicons = lexiconDeserializer.deserializeLexicons(lexiconFile);
            for (PosTaggerLexicon lexicon : lexicons)
                talismaneSession.addLexicon(lexicon);
            PosTaggerLexicon mergedLexicon = talismaneSession.getMergedLexicon();
            for (String word : wordList) {
                LOG.info("################");
                LOG.info("Word: " + word);
                List<LexicalEntry> entries = mergedLexicon.getEntries(word);
                for (LexicalEntry entry : entries) {
                    LOG.info(entry + ", Full morph: " + entry.getMorphologyForCoNLL());
                }
            }
            break;
        }
        }
    }
}

From source file:com.github.besherman.fingerprint.Main.java

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

    options.addOption(OptionBuilder.withDescription("creates a fingerprint file for the directory").hasArg()
            .withArgName("dir").create('c'));

    options.addOption(OptionBuilder.withDescription("shows a diff between two fingerprint files")
            .withArgName("left-file> <right-file").hasArgs(2).create('d'));

    options.addOption(OptionBuilder.withDescription("shows a diff between a fingerprint and a directory")
            .withArgName("fingerprint> <dir").hasArgs(2).create('t'));

    options.addOption(OptionBuilder.withDescription("shows duplicates in a directory").withArgName("dir")
            .hasArgs(1).create('u'));

    options.addOption(/*from ww  w  . j a  v a2s  . co m*/
            OptionBuilder.withDescription("output to file").withArgName("output-file").hasArg().create('o'));

    PosixParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException ex) {
        System.out.println(ex.getMessage());
        System.out.println("");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fingerprint-dir", options, true);
        System.exit(7);
    }

    if (cmd.hasOption('c')) {
        Path root = Paths.get(cmd.getOptionValue('c'));

        if (!Files.isDirectory(root)) {
            System.err.println("root is not a directory");
            System.exit(7);
        }

        OutputStream out = System.out;

        if (cmd.hasOption('o')) {
            Path p = Paths.get(cmd.getOptionValue('o'));
            out = Files.newOutputStream(p);
        }

        Fingerprint fp = new Fingerprint(root, "");
        fp.write(out);

    } else if (cmd.hasOption('d')) {
        String[] ar = cmd.getOptionValues('d');
        Path leftFingerprintFile = Paths.get(ar[0]), rightFingerprintFile = Paths.get(ar[1]);
        if (!Files.isRegularFile(leftFingerprintFile)) {
            System.out.printf("%s is not a file%n", leftFingerprintFile);
            System.exit(7);
        }
        if (!Files.isRegularFile(rightFingerprintFile)) {
            System.out.printf("%s is not a file%n", rightFingerprintFile);
            System.exit(7);
        }

        Fingerprint left, right;
        try (InputStream input = Files.newInputStream(leftFingerprintFile)) {
            left = new Fingerprint(input);
        }

        try (InputStream input = Files.newInputStream(rightFingerprintFile)) {
            right = new Fingerprint(input);
        }

        Diff diff = new Diff(left, right);

        // TODO: if we have redirected output
        diff.print(System.out);
    } else if (cmd.hasOption('t')) {
        throw new RuntimeException("Not yet implemented");
    } else if (cmd.hasOption('u')) {
        Path root = Paths.get(cmd.getOptionValue('u'));
        Fingerprint fp = new Fingerprint(root, "");
        Map<String, FilePrint> map = new HashMap<>();
        fp.stream().forEach(f -> {
            if (map.containsKey(f.getHash())) {
                System.out.println("  " + map.get(f.getHash()).getPath());
                System.out.println("= " + f.getPath());
                System.out.println("");
            } else {
                map.put(f.getHash(), f);
            }
        });
    } else {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fingd", options, true);
    }
}

From source file:Main.java

public static void main(String[] args) {
    Map<Employee, String> map2 = new HashMap<Employee, String>();
    Employee e2 = new Employee("J", 26);
    map2.put(e2, "MGMT");
    System.out.println(map2);//from w  ww  .  j av a2 s . c om
    e2.setAge(27);
    System.out.println(map2);
    System.out.println(map2.containsKey(e2));//false

    IdentityHashMap<Employee, String> map1 = new IdentityHashMap<Employee, String>(map2);

    System.out.println(map1);
}

From source file:com.datatorrent.stram.StreamingAppMaster.java

/**
 * @param args/*from   w w  w .  ja va2  s.c om*/
 *          Command line args
 * @throws Throwable
 */
public static void main(final String[] args) throws Throwable {
    StdOutErrLog.tieSystemOutAndErrToLog();
    LOG.info("Master starting with classpath: {}", System.getProperty("java.class.path"));

    LOG.info("version: {}", VersionInfo.APEX_VERSION.getBuildVersion());
    StringWriter sw = new StringWriter();
    for (Map.Entry<String, String> e : System.getenv().entrySet()) {
        sw.append("\n").append(e.getKey()).append("=").append(e.getValue());
    }
    LOG.info("appmaster env:" + sw.toString());

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

    opts.addOption("help", false, "Print usage");
    CommandLine cliParser = new GnuParser().parse(opts, args);

    // option "help" overrides and cancels any run
    if (cliParser.hasOption("help")) {
        new HelpFormatter().printHelp("ApplicationMaster", opts);
        return;
    }

    Map<String, String> envs = System.getenv();
    ApplicationAttemptId appAttemptID = Records.newRecord(ApplicationAttemptId.class);
    if (!envs.containsKey(Environment.CONTAINER_ID.name())) {
        if (cliParser.hasOption("app_attempt_id")) {
            String appIdStr = cliParser.getOptionValue("app_attempt_id", "");
            appAttemptID = ConverterUtils.toApplicationAttemptId(appIdStr);
        } else {
            throw new IllegalArgumentException("Application Attempt Id not set in the environment");
        }
    } else {
        ContainerId containerId = ConverterUtils.toContainerId(envs.get(Environment.CONTAINER_ID.name()));
        appAttemptID = containerId.getApplicationAttemptId();
    }

    boolean result = false;
    StreamingAppMasterService appMaster = null;
    try {
        appMaster = new StreamingAppMasterService(appAttemptID);
        LOG.info("Initializing Application Master.");

        Configuration conf = new YarnConfiguration();
        appMaster.init(conf);
        appMaster.start();
        result = appMaster.run();
    } catch (Throwable t) {
        LOG.error("Exiting Application Master", t);
        System.exit(1);
    } finally {
        if (appMaster != null) {
            appMaster.stop();
        }
    }

    if (result) {
        LOG.info("Application Master completed.");
        System.exit(0);
    } else {
        LOG.info("Application Master failed.");
        System.exit(2);
    }
}

From source file:com.music.tools.InstrumentExtractor.java

public static void main(String[] args) {
    Map<Integer, String> instrumentNames = new HashMap<>();
    Field[] fields = ProgramChanges.class.getDeclaredFields();
    try {/*from  w  w  w.j  av  a 2s . c  om*/
        for (Field field : fields) {
            Integer value = (Integer) field.get(null);
            if (!instrumentNames.containsKey(value)) {
                instrumentNames.put(value,
                        StringUtils.capitalize(field.getName().toLowerCase()).replace('_', ' '));
            }
        }
    } catch (IllegalArgumentException | IllegalAccessException e) {
        throw new IllegalStateException(e);
    }

    Score score = new Score();
    Read.midi(score, "C:\\Users\\bozho\\Downloads\\7938.midi");
    for (Part part : score.getPartArray()) {
        System.out.println(part.getChannel() + " : " + part.getInstrument() + ": "
                + instrumentNames.get(part.getInstrument()));
    }
}

From source file:EVT.java

/**
 * @param args/*from   w  w w. ja v  a  2s. c om*/
 */
public static void main(final String[] args) throws MalformedURLException {
    try {
        URL url = new EVT().getClass().getClassLoader().getResource("general.properties");
        config = new PropertiesConfiguration(url);

    } catch (ConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.exit(1);
    }
    final Map parameters = parseParameters(args);

    if (parameters.containsKey("-v"))
        verboseMode = 1;
    if (parameters.containsKey("-V") || parameters.containsKey("-vv"))
        verboseMode = 2;
    //the from version and the to version must be put in property file
    String supportedVersions = PropertiesUtil.concatenatePropsValues(config, ALFRESCO_VERSION, ",");
    List<String> supportedVersionsList = Arrays.asList(supportedVersions.split(","));
    String alfrescoVersion = (String) parameters.get(ALFRESCO_VERSION);
    boolean supportedVersion = (alfrescoVersion != null) && supportedVersionsList.contains(alfrescoVersion);

    System.out.println(
            "\nAlfresco Environment Validation Tool (for Alfresco Enterprise " + supportedVersions + ")");
    System.out.println("------------------------------------------------------------------");

    if (parameters.isEmpty() || parameters.containsKey("-?") || parameters.containsKey("--help")
            || parameters.containsKey("/?") || !parameters.containsKey(DBValidator.PARAMETER_DATABASE_TYPE)
            || !parameters.containsKey(DBValidator.PARAMETER_DATABASE_HOSTNAME)
            || !parameters.containsKey(DBValidator.PARAMETER_DATABASE_LOGIN)
            || !parameters.containsKey(ALFRESCO_VERSION)
            || !parameters.containsKey(IndexDiskSpeedValidator.PARAMETER_DISK_LOCATION)) {
        System.out.println("");
        System.out.println("usage: evt[.sh|.cmd] [-?|--help] [-v] [-V|-vv]");
        System.out.println("            -a alfrescoversion -t databaseType -h databaseHost [-r databasePort]");
        System.out.println(
                "            [-d databaseName] -l databaseLogin [-p databasePassword] -i indexlocation");
        System.out.println("");
        System.out.println("where:      -?|--help        - display this help");
        System.out.println("            -v               - produce verbose output");
        System.out.println("            -V|-vv           - produce super-verbose output (stack traces)");
        System.out.println(
                "            alfrescoversion  - Version for which the verification is made .  May be one of:");
        System.out.println(
                "                               4.0.0,4.0.1,4.0.2,4.1.1,4.1.2,4.1.3,4.1.4,4.1.5,4.1.6,4.2");
        System.out.println("            databaseType     - the type of database.  May be one of:");
        System.out.println("                               mysql, postgresql, oracle, mssqlserver, db2");
        System.out.println("            databaseHost     - the hostname of the database server");
        System.out.println("            databasePort     - the port the database is listening on (optional -");
        System.out.println("                               defaults to default for the database type)");
        System.out.println("            databaseName     - the name of the Alfresco database (optional -");
        System.out.println("                               defaults to 'alfresco')");
        System.out.println("            databaseLogin    - the login Alfresco will use to connect to the");
        System.out.println("                               database");
        System.out.println("            databasePassword - the password for that user (optional)");
        System.out.println(
                "            indexlocation    - a path to a folder that will contain Alfresco indexes");
        System.out.println("");
        System.out.println("The tool must be run as the OS user that Alfreso will run as.  In particular");
        System.out.println("it will report erroneous results if run as \"root\" (or equivalent on other");
        System.out.println("OSes) if Alfresco is not intended to be run as that user.");
        System.out.println("");
    } else if (!supportedVersion) {
        System.out.println("");
        System.out.println("Version " + alfrescoVersion
                + " is not in the list of the Alfresco versions supported by this tool.");
        System.out.println("Please specify one of the following versions: " + supportedVersions);
    } else {
        final StdoutValidatorCallback callback = new StdoutValidatorCallback();

        (new AllValidators()).validate(parameters, callback);

        System.out.println("\n\n                         **** FINAL GRADE: "
                + TestResult.typeToString(callback.worstResult) + " ****\n");
    }
}

From source file:com.joliciel.talismane.en.TalismaneEnglish.java

/**
 * @param args//from w ww . ja v a2s .c om
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {
    Map<String, String> argsMap = StringUtils.convertArgs(args);
    CorpusFormat corpusReaderType = null;

    if (argsMap.containsKey("corpusReader")) {
        corpusReaderType = CorpusFormat.valueOf(argsMap.get("corpusReader"));
        argsMap.remove("corpusReader");
    }

    Extensions extensions = new Extensions();
    extensions.pluckParameters(argsMap);

    String sessionId = "";
    TalismaneServiceLocator locator = TalismaneServiceLocator.getInstance(sessionId);
    TalismaneService talismaneService = locator.getTalismaneService();
    TalismaneEnglish talismaneEnglish = new TalismaneEnglish(sessionId);

    TalismaneConfig config = talismaneService.getTalismaneConfig(argsMap, talismaneEnglish);
    if (config.getCommand() == null)
        return;

    if (corpusReaderType != null) {
        if (corpusReaderType == CorpusFormat.pennDep) {
            PennDepReader corpusReader = new PennDepReader(config.getReader());
            corpusReader.setParserService(config.getParserService());
            corpusReader.setPosTaggerService(config.getPosTaggerService());
            corpusReader.setTokeniserService(config.getTokeniserService());
            corpusReader.setTokenFilterService(config.getTokenFilterService());
            corpusReader.setTalismaneService(config.getTalismaneService());

            corpusReader.setPredictTransitions(config.isPredictTransitions());

            config.setParserCorpusReader(corpusReader);
            config.setPosTagCorpusReader(corpusReader);
            config.setTokenCorpusReader(corpusReader);
            config.setSentenceCorpusReader(corpusReader);

            corpusReader.setRegex(DEFAULT_CONLL_REGEX);

            if (config.getInputRegex() != null) {
                corpusReader.setRegex(config.getInputRegex());
            }

            if (config.getCommand().equals(Command.compare)) {
                File evaluationFile = new File(config.getEvaluationFilePath());
                ParserRegexBasedCorpusReader evaluationReader = config.getParserService()
                        .getRegexBasedCorpusReader(evaluationFile, config.getInputCharset());
                config.setParserEvaluationCorpusReader(evaluationReader);
                config.setPosTagEvaluationCorpusReader(evaluationReader);

                evaluationReader.setRegex(DEFAULT_CONLL_REGEX);

                if (config.getInputRegex() != null) {
                    evaluationReader.setRegex(config.getInputRegex());
                }
            }
        } else {
            throw new TalismaneException("Unknown corpusReader: " + corpusReaderType);
        }
    }
    Talismane talismane = config.getTalismane();

    extensions.prepareCommand(config, talismane);

    talismane.process();
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    final int MAX_ENTRIES = 100;
    Map cache = new LinkedHashMap(MAX_ENTRIES + 1, .75F, true) {
        public boolean removeEldestEntry(Map.Entry eldest) {
            return size() > MAX_ENTRIES;
        }//from   w w w.ja  v  a 2  s  . com
    };

    Object key = "key";
    Object value = "value";
    cache.put(key, value);
    Object o = cache.get(key);
    if (o == null && !cache.containsKey(key)) {
    }
    cache = (Map) Collections.synchronizedMap(cache);
}