List of usage examples for java.util Map getOrDefault
default V getOrDefault(Object key, V defaultValue)
From source file:com.serphacker.serposcope.task.google.GoogleTask.java
protected void finalizeSummaries() { Map<Integer, Integer> searchCountByGroup = googleDB.search.countByGroup(); for (GoogleTargetSummary summary : summariesByTarget.values()) { summary.computeScoreBP(searchCountByGroup.getOrDefault(summary.getGroupId(), 0)); }/*www . j a v a2 s .c om*/ googleDB.targetSummary.insert(summariesByTarget.values()); }
From source file:org.apache.nifi.minifi.c2.security.authorization.GrantedAuthorityAuthorizer.java
@Override public void authorize(Authentication authentication, UriInfo uriInfo) throws AuthorizationException { if (authentication == null) { throw new AuthorizationException("null authentication object provided."); }//from w w w .ja v a2s . com if (!authentication.isAuthenticated()) { throw new AuthorizationException(authentication + " not authenticated."); } Set<String> authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority) .collect(Collectors.toSet()); String defaultAction = as(String.class, grantedAuthorityMap.getOrDefault(DEFAULT_ACTION, DENY)); String path = uriInfo.getAbsolutePath().getPath(); Map<String, Object> pathAuthorizations = as(Map.class, grantedAuthorityMap.get("Paths")); if (pathAuthorizations == null && !ALLOW.equalsIgnoreCase(defaultAction)) { throw new AuthorizationException("Didn't find authorizations for " + path + " and default policy is " + defaultAction + " instead of allow"); } Map<String, Object> pathAuthorization = as(Map.class, pathAuthorizations.get(path)); if (pathAuthorization == null && !ALLOW.equalsIgnoreCase(defaultAction)) { throw new AuthorizationException("Didn't find authorizations for " + path + " and default policy is " + defaultAction + " instead of allow"); } defaultAction = as(String.class, pathAuthorization.getOrDefault(DEFAULT_ACTION, defaultAction)); List<Map<String, Object>> actions = as(List.class, pathAuthorization.get("Actions")); MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters(); for (Map<String, Object> action : actions) { String ruleAction = as(String.class, action.get("Action")); if (ruleAction == null || !(ALLOW.equalsIgnoreCase(ruleAction) || DENY.equalsIgnoreCase(ruleAction))) { throw new AuthorizationException("Expected Action key of allow or deny for " + action); } String authorization = as(String.class, action.get("Authorization")); if (authorization != null && !authorities.contains(authorization)) { continue; } Map<String, Object> parameters = as(Map.class, action.get("Query Parameters")); if (parameters != null) { boolean foundParameterMismatch = false; for (Map.Entry<String, Object> parameter : parameters.entrySet()) { Object value = parameter.getValue(); if (value instanceof String) { value = Arrays.asList((String) value); } if (!Objects.equals(queryParameters.get(parameter.getKey()), value)) { foundParameterMismatch = true; break; } } if (foundParameterMismatch) { continue; } } if (ALLOW.equalsIgnoreCase(ruleAction)) { if (logger.isDebugEnabled()) { logger.debug("Action " + action + "matched which resulted in " + ruleAction); } return; } else { throw new AuthorizationException("Action " + action + " matched which resulted in " + ruleAction); } } if (ALLOW.equalsIgnoreCase(defaultAction)) { if (logger.isDebugEnabled()) { logger.debug("Found no matching actions so falling back to default action " + defaultAction); } } else { throw new AuthorizationException("Didn't find authorizations for " + path + " and default policy is " + defaultAction + " instead of allow"); } }
From source file:org.apache.sentry.binding.solr.authz.SentrySolrPluginImpl.java
@SuppressWarnings("unchecked") @Override/*w w w .j a v a 2 s.c o m*/ public void init(Map<String, Object> pluginConfig) { Map<String, String> params = new HashMap<>(); String sysPropPrefix = (String) pluginConfig.getOrDefault(SYSPROP_PREFIX_PROPERTY, "solr."); java.util.Collection<String> authConfigNames = (java.util.Collection<String>) pluginConfig .getOrDefault(AUTH_CONFIG_NAMES_PROPERTY, Collections.emptyList()); Map<String, String> authConfigDefaults = (Map<String, String>) pluginConfig .getOrDefault(DEFAULT_AUTH_CONFIGS_PROPERTY, Collections.emptyMap()); for (String configName : authConfigNames) { String systemProperty = sysPropPrefix + configName; String defaultConfigVal = authConfigDefaults.get(configName); String configVal = System.getProperty(systemProperty, defaultConfigVal); if (configVal != null) { params.put(configName, configVal); } } initializeSentry(params); }
From source file:org.ligoj.app.plugin.prov.azure.in.ProvAzurePriceImportResource.java
/** * Install storage prices from the JSON file provided by AWS. * * @param context/*from w w w. ja v a 2s.c o m*/ * The update context. */ private void installStoragePrices(final UpdateContext context) throws IOException { final Node node = context.getNode(); log.info("Azure managed-disk prices..."); nextStep(node, "managed-disk-initialize", 1); // The previously installed storage types cache. Key is the storage type name context.setStorageTypes(stRepository.findAllBy(BY_NODE, node.getId()).stream() .collect(Collectors.toMap(INamableBean::getName, Function.identity()))); context.setPreviousStorages(new HashMap<>()); spRepository.findAllBy("type.node.id", node.getId()).forEach(p -> context.getPreviousStorages() .computeIfAbsent(p.getType(), t -> new HashMap<>()).put(p.getLocation(), p)); // Fetch the remote prices stream nextStep(node, "managed-disk-retrieve-catalog", 1); try (CurlProcessor curl = new CurlProcessor()) { final String rawJson = StringUtils.defaultString(curl.get(getManagedDiskApi()), "{}"); final ManagedDisks prices = objectMapper.readValue(rawJson, ManagedDisks.class); // Add region as needed nextStep(node, "managed-disk-update-catalog", 1); prices.getRegions().stream().filter(this::isEnabledRegion).forEach(r -> installRegion(context, r)); // Update or install storage price final Map<String, ManagedDisk> offers = prices.getOffers(); context.setTransactions(offers.getOrDefault("transactions", new ManagedDisk()).getPrices()); offers.entrySet().stream().filter(p -> !"transactions".equals(p.getKey())) .forEach(o -> installStoragePrice(context, o)); } }
From source file:ox.softeng.burst.service.report.ReportService.java
private Map<SeverityEnum, List<Message>> getEmailContentsMessages(List<Message> messages) { Map<SeverityEnum, List<Message>> emailContents = new HashMap<>(); messages.forEach(msg -> {//from w w w. j a va 2s. c o m // We send a message with the concatenation of all the messages List<Message> msgs = emailContents.getOrDefault(msg.getSeverity(), new ArrayList<>()); msgs.add(msg); emailContents.put(msg.getSeverity(), msgs); }); return emailContents; }
From source file:com.wrmsr.wava.util.collect.MoreMultimaps.java
public static <K, V> Multimap<K, V> unmodifiableMultimapView(Map<K, Collection<V>> collectionMap) { // checkArgument(collectionMap.values().stream().allMatch(coll -> !coll.isEmpty())); return new Multimap<K, V>() { private OptionalInt size = OptionalInt.empty(); private int cachedSize() { if (!size.isPresent()) { size = OptionalInt.of(collectionMap.values().stream().mapToInt(coll -> { checkState(!coll.isEmpty()); return coll.size(); }).sum());//from ww w .j a va 2 s. c o m } return size.getAsInt(); } @Override public int size() { return cachedSize(); } @Override public boolean isEmpty() { return !collectionMap.isEmpty(); } @Override public boolean containsKey(@Nullable Object key) { return collectionMap.containsKey(key); } @Override public boolean containsValue(@Nullable Object value) { return collectionMap.values().stream().anyMatch(coll -> coll.contains(value)); } @Override public boolean containsEntry(@Nullable Object key, @Nullable Object value) { return collectionMap.getOrDefault(key, ImmutableList.of()).contains(value); } @Override public boolean put(@Nullable K key, @Nullable V value) { throw new UnsupportedOperationException(); } @Override public boolean remove(@Nullable Object key, @Nullable Object value) { throw new UnsupportedOperationException(); } @Override public boolean putAll(@Nullable K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } @Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { throw new UnsupportedOperationException(); } @Override public Collection<V> replaceValues(@Nullable K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } @Override public Collection<V> removeAll(@Nullable Object key) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Collection<V> get(@Nullable K key) { return collectionMap.getOrDefault(key, ImmutableList.of()); } @Override public Set<K> keySet() { return collectionMap.keySet(); } @Override public Multiset<K> keys() { // FIXME throw new UnsupportedOperationException(); } @Override public Collection<V> values() { return new AbstractCollection<V>() { @Override public Iterator<V> iterator() { return Iterators.concat(collectionMap.values().stream().map(Iterable::iterator).iterator()); } @Override public int size() { return cachedSize(); } }; } @Override public Collection<Map.Entry<K, V>> entries() { return new AbstractCollection<Map.Entry<K, V>>() { @Override public Iterator<Map.Entry<K, V>> iterator() { return Iterators.concat(collectionMap.entrySet().stream() .map(entry -> entry.getValue().stream() .map(value -> ImmutablePair.of(entry.getKey(), value)).iterator()) .iterator()); } @Override public int size() { return cachedSize(); } }; } @Override public Map<K, Collection<V>> asMap() { return collectionMap; } }; }
From source file:org.apache.storm.grouping.LoadAwareShuffleGroupingTest.java
private Map<Integer, Double> count(int[] choices, List<Integer>[] rets) { Map<Integer, Double> ret = new HashMap<>(); for (int i : choices) { int task = rets[i].get(0); ret.put(task, ret.getOrDefault(task, 0.0) + 1); }/*w ww .ja va 2 s . c o m*/ return ret; }
From source file:org.mitre.mpf.wfm.service.component.StartupComponentRegistrationServiceImpl.java
private List<Path> getComponentRegistrationOrder(Collection<RegisterComponentModel> allComponents, Collection<Path> uploadedComponentPackages, Map<Path, Path> packageToDescriptorMapping) { Stream<Path> registeredDescriptors = allComponents.stream() .filter(rcm -> rcm.getComponentState() == ComponentState.REGISTERED) .map(rcm -> Paths.get(rcm.getJsonDescriptorPath())); Set<Path> unregisteredPaths = uploadedComponentPackages.stream() .map(p -> packageToDescriptorMapping.getOrDefault(p, p)).collect(toSet()); Set<Path> allPaths = Stream.concat(registeredDescriptors, unregisteredPaths.stream()).collect(toSet()); try {/*from ww w .j a v a 2 s .c o m*/ return _componentDependencyFinder.getRegistrationOrder(allPaths).stream() .filter(unregisteredPaths::contains).collect(toList()); } catch (IllegalStateException e) { _log.error("An error occurred while trying to get component registration order.", e); for (Path componentPath : uploadedComponentPackages) { Path descriptorPath = packageToDescriptorMapping.get(componentPath); if (descriptorPath == null) { _componentStateSvc.addRegistrationErrorEntry(componentPath); } else { _componentStateSvc.addEntryForDeployedPackage(componentPath, descriptorPath); } } return Collections.emptyList(); } }
From source file:br.ufjf.pgcc.plscience.bean.experiments.execution.TavernaWorkflows.java
public void startRun() { TavernaWorkflowRun run = workspace.getTavernaRun(); String uuid = workspace.getTavernaRun().getUuid(); try {/*from ww w. j a v a 2 s .c o m*/ String status = client.getStatus(run.getUuid()); if (TavernaServerStatus.INITIALIZED.getStatus().equals(status)) { ExternalContext context = FacesContext.getCurrentInstance().getExternalContext(); Map<String, String> parameterMap = (Map<String, String>) context.getRequestParameterMap(); for (TavernaWorkflowInput expectedInput : run.getTavernaWorkflow().getInputs()) { TavernaWorkflowRunInputValue inputValue = new TavernaWorkflowRunInputValue(); String value = parameterMap.getOrDefault(expectedInput.getName(), ""); inputValue.setInput(expectedInput); inputValue.setInputValue(value); new TavernaWorkflowRunInputValueDAO().save(inputValue); client.setInputValue(uuid, expectedInput.getName(), value); } client.start(uuid); run.setStatus(client.getStatus(uuid)); } else { run.setStatus(status); } new TavernaWorkflowRunDAO().update(run); } catch (Exception e) { e.printStackTrace(); } try { ExternalContext context = FacesContext.getCurrentInstance().getExternalContext(); context.redirect( context.getRequestContextPath() + "/faces/experiments/execution/taverna/run.xhtml?tab=3"); } catch (Exception e) { } }
From source file:org.apache.solr.cloud.autoscaling.sim.TestLargeCluster.java
public void benchmarkNodeLost() throws Exception { List<String> results = new ArrayList<>(); for (int wait : renard5x) { for (int delay : renard5x) { SummaryStatistics totalTime = new SummaryStatistics(); SummaryStatistics ignoredOurEvents = new SummaryStatistics(); SummaryStatistics ignoredOtherEvents = new SummaryStatistics(); SummaryStatistics startedOurEvents = new SummaryStatistics(); SummaryStatistics startedOtherEvents = new SummaryStatistics(); for (int i = 0; i < 5; i++) { if (cluster != null) { cluster.close();/*from ww w. j a v a2s. c o m*/ } setupCluster(); setUp(); setupTest(); long total = doTestNodeLost(wait, delay * 1000, 0); totalTime.addValue(total); // get event counts Map<String, Map<String, AtomicInteger>> counts = cluster.simGetEventCounts(); Map<String, AtomicInteger> map = counts.remove("node_lost_trigger"); startedOurEvents.addValue(map.getOrDefault("STARTED", ZERO).get()); ignoredOurEvents.addValue(map.getOrDefault("IGNORED", ZERO).get()); int otherStarted = 0; int otherIgnored = 0; for (Map<String, AtomicInteger> m : counts.values()) { otherStarted += m.getOrDefault("STARTED", ZERO).get(); otherIgnored += m.getOrDefault("IGNORED", ZERO).get(); } startedOtherEvents.addValue(otherStarted); ignoredOtherEvents.addValue(otherIgnored); } results.add(String.format(Locale.ROOT, "%d\t%d\t%4.0f\t%4.0f\t%4.0f\t%4.0f\t%6.0f\t%6.0f\t%6.0f\t%6.0f\t%6.0f", wait, delay, startedOurEvents.getMean(), ignoredOurEvents.getMean(), startedOtherEvents.getMean(), ignoredOtherEvents.getMean(), totalTime.getMin(), totalTime.getMax(), totalTime.getMean(), totalTime.getStandardDeviation(), totalTime.getVariance())); } } log.info("===== RESULTS ======"); log.info("waitFor\tdelay\tSTRT\tIGN\toSTRT\toIGN\tmin\tmax\tmean\tstdev\tvar"); results.forEach(s -> log.info(s)); }