List of usage examples for java.util Map getOrDefault
default V getOrDefault(Object key, V defaultValue)
From source file:Main.java
public static void main(String[] args) { Map<Integer, String> map = new HashMap<>(); for (int i = 0; i < 10; i++) { map.putIfAbsent(i, "val" + i); }/*ww w . j a va2 s . co m*/ map.forEach((id, val) -> System.out.println(val)); System.out.println(map.getOrDefault(42, "not found")); // not found }
From source file:org.eclipse.che.util.GwtXmlGenerator.java
/** * Generated consolidated gwt.xml based on exists XX.gwt.xml in class path * * @param args/*from w ww . j ava 2 s .c om*/ * possible arguments * --rootDir - directory where gwt.xml file will be generated, default "." * --gwtFileName - Name of the generated file in rootDir, default "org/eclipse/che/ide/IDE.gwt.xml" * --entryPoint - gwt xml entry point, default "org.eclipse.che.ide.client.IDE" * --styleSheet - gwt xml stylesheet, default "IDE.css" * --loggingEnabled - Enable or disable gwt logging, default "false" * --includePackages - Include only specific packages where *.gwt.xml can be found, default "No value. Means all packages" * --excludePackages - Exclude packages from *.gwt.xml scanning , default "com.google", "elemental","java.util","java.lang" */ public static void main(String[] args) { try { System.out.println(" ------------------------------------------------------------------------ "); System.out.println("Searching for GWT"); System.out.println(" ------------------------------------------------------------------------ "); Map<String, Set<String>> parsedArgs = GeneratorUtils.parseArgs(args); GwtXmlModuleSearcher searcher = new GwtXmlModuleSearcher( parsedArgs.getOrDefault("excludePackages", ImmutableSet.of("com.google", "elemental", "java.util", "java.lang")), parsedArgs.getOrDefault("includePackages", Collections.emptySet()), Collections.emptySet()); Set<String> gwtModules = searcher.getGwtModulesFromClassPath(); gwtModules.forEach(System.out::println); System.out.println("Found " + gwtModules.size() + " gwt modules"); GwtXmlGeneratorConfig gwtXmlGeneratorConfig = new GwtXmlGeneratorConfig(gwtModules, new File(getSingleValueOrDefault(parsedArgs, "rootDir", ".")), getSingleValueOrDefault(parsedArgs, "gwtFileName", DEFAULT_GWT_XML_PATH), getSingleValueOrDefault(parsedArgs, "entryPoint", DEFAULT_GWT_ETNRY_POINT), getSingleValueOrDefault(parsedArgs, "styleSheet", DEFAULT_STYLE_SHEET), parseBoolean( getSingleValueOrDefault(parsedArgs, "loggingEnabled", DEFAULT_LOGGING.toString()))); GwtXmlGenerator gwtXmlGenerator = new GwtXmlGenerator(gwtXmlGeneratorConfig); gwtXmlGenerator.generateGwtXml(); } catch (IOException e) { System.err.println(e.getMessage()); // error System.exit(1);//NOSONAR } }
From source file:org.apache.tinkerpop.gremlin.driver.util.ProfilingApplication.java
public static void main(final String[] args) { final Map<String, Object> options = ElementHelper.asMap(args); final boolean noExit = Boolean.parseBoolean(options.getOrDefault("noExit", "false").toString()); final int parallelism = Integer.parseInt(options.getOrDefault("parallelism", "16").toString()); final BasicThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern("profiler-%d") .build();/*from w ww . ja v a2 s . c o m*/ final ExecutorService executor = Executors.newFixedThreadPool(parallelism, threadFactory); final String host = options.getOrDefault("host", "localhost").toString(); final int minExpectedRps = Integer.parseInt(options.getOrDefault("minExpectedRps", "1000").toString()); final int timeout = Integer.parseInt(options.getOrDefault("timeout", "1200000").toString()); final int warmups = Integer.parseInt(options.getOrDefault("warmups", "5").toString()); final int executions = Integer.parseInt(options.getOrDefault("executions", "10").toString()); final int nioPoolSize = Integer.parseInt(options.getOrDefault("nioPoolSize", "1").toString()); final int requests = Integer.parseInt(options.getOrDefault("requests", "10000").toString()); final int minConnectionPoolSize = Integer .parseInt(options.getOrDefault("minConnectionPoolSize", "256").toString()); final int maxConnectionPoolSize = Integer .parseInt(options.getOrDefault("maxConnectionPoolSize", "256").toString()); final int minSimultaneousUsagePerConnection = Integer .parseInt(options.getOrDefault("minSimultaneousUsagePerConnection", "8").toString()); final int maxSimultaneousUsagePerConnection = Integer .parseInt(options.getOrDefault("maxSimultaneousUsagePerConnection", "32").toString()); final int maxInProcessPerConnection = Integer .parseInt(options.getOrDefault("maxInProcessPerConnection", "64").toString()); final int minInProcessPerConnection = Integer .parseInt(options.getOrDefault("minInProcessPerConnection", "16").toString()); final int maxWaitForConnection = Integer .parseInt(options.getOrDefault("maxWaitForConnection", "3000").toString()); final int workerPoolSize = Integer.parseInt(options.getOrDefault("workerPoolSize", "2").toString()); final int tooSlowThreshold = Integer.parseInt(options.getOrDefault("tooSlowThreshold", "125").toString()); final String channelizer = options .getOrDefault("channelizer", Channelizer.WebSocketChannelizer.class.getName()).toString(); final String serializer = options.getOrDefault("serializer", Serializers.GRYO_V1D0.name()).toString(); final String script = options.getOrDefault("script", "1+1").toString(); final Cluster cluster = Cluster.build(host).minConnectionPoolSize(minConnectionPoolSize) .maxConnectionPoolSize(maxConnectionPoolSize) .minSimultaneousUsagePerConnection(minSimultaneousUsagePerConnection) .maxSimultaneousUsagePerConnection(maxSimultaneousUsagePerConnection) .minInProcessPerConnection(minInProcessPerConnection) .maxInProcessPerConnection(maxInProcessPerConnection).nioPoolSize(nioPoolSize) .channelizer(channelizer).maxWaitForConnection(maxWaitForConnection) .serializer(Serializers.valueOf(serializer)).workerPoolSize(workerPoolSize).create(); try { final Object fileName = options.get("store"); final File f = null == fileName ? null : new File(fileName.toString()); if (f != null && f.length() == 0) { try (final PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(f, true)))) { writer.println( "parallelism\tnioPoolSize\tminConnectionPoolSize\tmaxConnectionPoolSize\tminSimultaneousUsagePerConnection\tmaxSimultaneousUsagePerConnection\tminInProcessPerConnection\tmaxInProcessPerConnection\tworkerPoolSize\trequestPerSecond"); } } // not much point to continuing with a line of tests if we can't get at least minExpectedRps. final AtomicBoolean meetsRpsExpectation = new AtomicBoolean(true); System.out.println("---------------------------WARMUP CYCLE---------------------------"); for (int ix = 0; ix < warmups && meetsRpsExpectation.get(); ix++) { final long averageRequestsPerSecond = new ProfilingApplication("warmup-" + (ix + 1), cluster, 1000, executor, script, tooSlowThreshold).execute(); meetsRpsExpectation.set(averageRequestsPerSecond > minExpectedRps); TimeUnit.SECONDS.sleep(1); // pause between executions } final AtomicBoolean exceededTimeout = new AtomicBoolean(false); long totalRequestsPerSecond = 0; // no need to execute this if we didn't pass the basic expectation in the warmups if (meetsRpsExpectation.get()) { final long start = System.nanoTime(); System.out.println("----------------------------TEST CYCLE----------------------------"); for (int ix = 0; ix < executions && !exceededTimeout.get(); ix++) { totalRequestsPerSecond += new ProfilingApplication("test-" + (ix + 1), cluster, requests, executor, script, tooSlowThreshold).execute(); exceededTimeout.set((System.nanoTime() - start) > TimeUnit.NANOSECONDS.convert(timeout, TimeUnit.MILLISECONDS)); TimeUnit.SECONDS.sleep(1); // pause between executions } } final int averageRequestPerSecond = !meetsRpsExpectation.get() || exceededTimeout.get() ? 0 : Math.round(totalRequestsPerSecond / executions); System.out.println(String.format("avg req/sec: %s", averageRequestPerSecond)); if (f != null) { try (final PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(f, true)))) { writer.println(String.join("\t", String.valueOf(parallelism), String.valueOf(nioPoolSize), String.valueOf(minConnectionPoolSize), String.valueOf(maxConnectionPoolSize), String.valueOf(minSimultaneousUsagePerConnection), String.valueOf(maxSimultaneousUsagePerConnection), String.valueOf(minInProcessPerConnection), String.valueOf(maxInProcessPerConnection), String.valueOf(workerPoolSize), String.valueOf(averageRequestPerSecond))); } } if (!noExit) System.exit(0); } catch (Exception ex) { ex.printStackTrace(); if (!noExit) System.exit(1); } finally { executor.shutdown(); cluster.close(); } }
From source file:com.mycompany.sparkrentals.Main.java
public static void main(String[] args) { initializeSolrCqlHostsFromArgs(args); // Configure Solr connection RentalSolrClient solrClient = new RentalSolrClient(); solrClient.connect(solrUrl);// w w w .jav a 2s .co m // Configure Cassandra connection CqlClient cqlClient = new CqlClient(); cqlClient.connect(cqlHost); cqlClient.setCqlKeyspace(cqlKeyspace); // Configure the view directory Configuration viewConfig = new Configuration(); viewConfig.setClassForTemplateLoading(Main.class, "/views"); FreeMarkerEngine freeMarkerEngine = new FreeMarkerEngine(viewConfig); // Configure the static files directory staticFileLocation("/public"); //exception handling exception(DriverException.class, (exception, request, response) -> { //handle exception for cassandra serve exception response.body("Something wrong for cassandra server " + exception.getMessage()); }); exception(Exception.class, (exception, request, response) -> { //handle exception response.body("Sorry something went wrong. Please try again later."); }); //start setting up routes here get("/add", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); attributes.put("data", new HashMap<>()); fillFormSelectionOption(attributes); return new ModelAndView(attributes, "add.ftl"); }, freeMarkerEngine); post("/add", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); AddRentalForm form = new AddRentalForm(); form.setQueryMap(request.queryMap()); if (form.validate()) { //valid rental data, so will insert into database and solr // or it'll update if one recrod already exists with the same key Rental rental = new Rental(); rental.SetValuesFromMap(form.getCleanedData()); //Assuming for now there's only one currency $ //so we don't need to ask the user to select, we preset it here rental.setCurrency("$"); rental.setUpdated(new Date()); //insert into cql db cqlClient.insertOrUpdateRental(rental); //add index to solr at the same time try { solrClient.addRental(rental); } catch (IOException e) { attributes.put("message", "exception connecting to solr server"); return new ModelAndView(attributes, "exception.ftl"); } catch (SolrServerException e) { attributes.put("message", "solr server exception"); return new ModelAndView(attributes, "exception.ftl"); } return new ModelAndView(attributes, "add_done.ftl"); } // form contains errors attributes.put("errorMessages", form.getErrorMessages()); attributes.put("data", form.getDataToDisplay()); fillFormSelectionOption(attributes); return new ModelAndView(attributes, "add.ftl"); }, freeMarkerEngine); //index is the search page get("/", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); SearchRentalForm form = new SearchRentalForm(); form.setQueryMap(request.queryMap()); int perPage = 20; //number of results per page if (form.validate()) { Map<String, Object> cleanedData = form.getCleanedData(); //get the search results from SOLR try { QueryResponse queryResponse = solrClient.searchRentals(cleanedData, perPage); List<Rental> rentalList = queryResponse.getBeans(Rental.class); //these are for pagination purpose long resultsTotal = queryResponse.getResults().getNumFound(); attributes.put("resultsTotal", resultsTotal); int currentPage = (int) cleanedData.getOrDefault("page", 1); attributes.put("currentPage", currentPage); long maxPage = (resultsTotal % perPage > 0 ? 1 : 0) + resultsTotal / perPage; attributes.put("maxPage", maxPage); attributes.put("rentalList", rentalList); attributes.put("errorMessages", new ArrayList<>()); } catch (IOException e) { attributes.put("errorMessages", Arrays.asList("Exception when connecting to Solr!" + e.getMessage())); } catch (SolrException e) { //there is an error for querying attributes.put("errorMessages", Arrays.asList("Solr query error!")); } } else { //search form not valid attributes.put("rentalList", new ArrayList<>()); attributes.put("errorMessages", form.getErrorMessages()); } if (!attributes.containsKey("rentalList")) { attributes.put("rentalList", new ArrayList<>()); } //for disply back to user entered data attributes.put("data", form.getDataToDisplay()); fillFormSelectionOption(attributes); return new ModelAndView(attributes, "index.ftl"); }, freeMarkerEngine); }
From source file:com.dgtlrepublic.model.test.DataTest.java
@SuppressWarnings("unchecked") private static void verify(Map entry) throws Exception { String fileName = (String) entry.getOrDefault("file_name", ""); boolean ignore = (Boolean) entry.getOrDefault("ignore", false); int id = (Integer) entry.getOrDefault("id", -1); HashMap<String, Object> testCases = (HashMap<String, Object>) entry.getOrDefault("results", new HashMap<String, Object>()); if (ignore || StringUtils.isBlank(fileName) || testCases.size() == 0) { System.out.println(String.format("Ignoring [%s] : { id: %s | results: %s | explicit: %s }", fileName, id, testCases.size(), ignore)); return;//from w w w .j av a 2 s . c om } System.out.println("Parsing: " + fileName); HashMap<String, Object> parseResults = (HashMap<String, Object>) DataJsonConverter.toTestCaseMap(fileName) .getOrDefault("results", null); for (Entry<String, Object> testCase : testCases.entrySet()) { Object elValue = parseResults.get(testCase.getKey()); if (elValue == null) { throw new Exception(String.format("%n[%s] Missing Element: %s [%s]", fileName, testCase.getKey(), testCase.getValue())); } else if (elValue instanceof String && !elValue.equals(testCase.getValue())) { throw new Exception(String.format("%n[%s] Incorrect Value:(%s) [%s] { required: [%s] } ", fileName, testCase.getKey(), elValue, testCase.getValue())); } else if (elValue instanceof List && !((List) elValue).containsAll((Collection<?>) testCase.getValue())) { throw new Exception(String.format("%n[%s] Incorrect List Values:(%s) [%s] { required: [%s] } ", fileName, testCase.getKey(), elValue, testCase.getValue())); } } }
From source file:com.github.lburgazzoli.hazelcast.discovery.etcd.EtcdDiscovery.java
@SuppressWarnings("unchecked") public static <T extends Comparable> T getProperty(Map<String, Comparable> properties, PropertyDefinition property, T defaultValue) { return (T) properties.getOrDefault(property.key(), defaultValue); }
From source file:org.springframework.core.codec.Hints.java
/** * Obtain the hint {@link #LOG_PREFIX_HINT}, if present, or an empty String. * @param hints the hints passed to the encode method * @return the log prefix/*from ww w .j a va 2s . c om*/ */ public static String getLogPrefix(@Nullable Map<String, Object> hints) { return (hints != null ? (String) hints.getOrDefault(LOG_PREFIX_HINT, "") : ""); }
From source file:org.springframework.core.codec.Hints.java
/** * Whether to suppress logging based on the hint {@link #SUPPRESS_LOGGING_HINT}. * @param hints the hints map//from ww w . j a v a2s . c om * @return whether logging of data is allowed */ public static boolean isLoggingSuppressed(@Nullable Map<String, Object> hints) { return (hints != null && (boolean) hints.getOrDefault(SUPPRESS_LOGGING_HINT, false)); }
From source file:Main.java
public static <K, V> Map<K, Collection<V>> toMap(final Collection<? extends V> items, final Function<V, K> mapper) { Map<K, Collection<V>> buffer = new HashMap<K, Collection<V>>(); // TODO this isn't probably thread-safe items.stream().forEach(item -> {/*from w w w. j av a2s .co m*/ K key = mapper.apply(item); Collection<V> c = buffer.getOrDefault(key, new ArrayList<V>()); c.add(item); buffer.put(key, c); }); return buffer; }
From source file:org.apache.metron.elasticsearch.client.ElasticsearchClientFactory.java
private static Map<String, Object> getEsSettings(Map<String, Object> globalConfig) { return (Map<String, Object>) globalConfig.getOrDefault(ES_SETTINGS_KEY, new HashMap<>()); }