List of usage examples for java.util Map getOrDefault
default V getOrDefault(Object key, V defaultValue)
From source file:org.apache.fluo.recipes.core.export.it.ExportTestBase.java
protected void diff(Map<String, Set<String>> fr, Map<String, Set<String>> er) { HashSet<String> allKeys = new HashSet<>(fr.keySet()); allKeys.addAll(er.keySet());// www . j a va 2 s. c o m for (String k : allKeys) { Set<String> s1 = fr.getOrDefault(k, Collections.emptySet()); Set<String> s2 = er.getOrDefault(k, Collections.emptySet()); HashSet<String> sub1 = new HashSet<>(s1); sub1.removeAll(s2); HashSet<String> sub2 = new HashSet<>(s2); sub2.removeAll(s1); if (sub1.size() > 0 || sub2.size() > 0) { System.out.println(k + " " + sub1 + " " + sub2); } } }
From source file:info.plichta.maven.plugins.changelog.RepositoryProcessor.java
public List<TagWrapper> process(Repository repository) throws IOException { final List<TagWrapper> tags = new ArrayList<>(); log.info("Processing git repository " + repository.getDirectory()); final ObjectId head = repository.resolve(toRef); if (head == null) { return tags; }/* ww w .j av a 2 s. c o m*/ try (RevWalk walk = new RevWalk(repository)) { walk.sort(RevSort.TOPO); final Map<ObjectId, TagWrapper> tagMapping = extractTags(repository, walk); TagWrapper currentTag = new TagWrapper(nextRelease); tags.add(currentTag); RevCommit commit = walk.parseCommit(head); while (commit != null) { currentTag = tagMapping.getOrDefault(commit.getId(), currentTag); if (tagMapping.containsKey(commit.getId())) { tags.add(currentTag); } final CommitWrapper commitWrapper = processCommit(commit); if (commitFilter.test(commit) && isInPath(repository, walk, commit)) { currentTag.getCommits().add(commitWrapper); } final RevCommit[] parents = commit.getParents(); if (parents != null && parents.length > 0) { final RevCommit parent = walk.parseCommit(parents[0]); try (RevWalk childWalk = new RevWalk(repository)) { childWalk.markStart(childWalk.parseCommit(commit)); childWalk.markUninteresting(childWalk.parseCommit(parent)); childWalk.next(); for (RevCommit childCommit : childWalk) { final CommitWrapper childWrapper = processCommit(childCommit); if (commitFilter.test(childCommit) && isInPath(repository, walk, commit) && !(deduplicateChildCommits && Objects.equals(commitWrapper.getTitle(), childWrapper.getTitle()))) { commitWrapper.getChildren().add(childWrapper); } } } commit = parent; } else { commit = null; } } } return tags; }
From source file:com.uimirror.location.Country.java
/** * converts a map that comes from DB into Country object object. * @param raw/*from w w w. j a v a 2 s . c o m*/ * @return {@link Country} */ private Country init(Map<String, Object> raw) { //First validate the source for invalid MAP validateSource(raw); String _id = (String) raw.get(CountryDBFields.ID); String sh_name = (String) raw.get(CountryDBFields.SHORT_NAME); String name = (String) raw.get(CountryDBFields.NAME); int code = (int) raw.getOrDefault(CountryDBFields.CODE, 0); return new CountryBuilder(_id).updateName(name).updateShortName(sh_name).updateCode(code).build(); }
From source file:com.yahoo.validatar.execution.rest.JSON.java
@Override public void execute(Query query) { Map<String, String> metadata = query.getMetadata(); Objects.requireNonNull(metadata); String data = makeRequest(createClient(metadata), createRequest(metadata), query); String function = metadata.getOrDefault(METADATA_FUNCTION_NAME_KEY, String.valueOf(defaultFunction)); String columnarData = convertToColumnarJSON(data, function, query); Map<String, List<TypedObject>> typedData = convertToMap(columnarData, query); query.createResults().addColumns(typedData); }
From source file:org.ligoj.app.plugin.vm.azure.AbstractAzureToolPluginResource.java
/** * Build a fully qualified management URL from the target resource and the subscription parameters. Replace * resourceGroup, apiVersion, subscription, and VM name when available within the resource URL. * //from w w w.j a v a2s.c o m * @param parameters * The subscription parameters. * @param resource * Resource URL with parameters to replace. * @return The target URL with interpolated variables. */ protected String buildUrl(final Map<String, String> parameters, final String resource) { return getManagementUrl() + resource.replace("{apiVersion}", getApiVersion()) .replace("{resourceGroup}", parameters.getOrDefault(PARAMETER_RESOURCE_GROUP, "-")) .replace("{subscriptionId}", parameters.getOrDefault(PARAMETER_SUBSCRIPTION, "-")); }
From source file:com.frederikam.gensokyobot.Config.java
@SuppressWarnings("unchecked") public Config(File credentialsFile, File configFile) { try {/* ww w . j ava 2 s . co m*/ Yaml yaml = new Yaml(); String credsFileStr = FileUtils.readFileToString(credentialsFile, "UTF-8"); String configFileStr = FileUtils.readFileToString(configFile, "UTF-8"); //remove those pesky tab characters so a potential json file is YAML conform credsFileStr = credsFileStr.replaceAll("\t", ""); configFileStr = configFileStr.replaceAll("\t", ""); Map<String, Object> creds = (Map<String, Object>) yaml.load(credsFileStr); Map<String, Object> config = (Map<String, Object>) yaml.load(configFileStr); //avoid null values, rather change them to empty strings creds.keySet().forEach((String key) -> creds.putIfAbsent(key, "")); config.keySet().forEach((String key) -> config.putIfAbsent(key, "")); // Determine distribution if ((boolean) config.getOrDefault("development", false)) {//Determine distribution distribution = DistributionEnum.DEVELOPMENT; } else { distribution = DistributionEnum.MUSIC; } log.info("Determined distribution: " + distribution); token = (String) creds.get("token"); numShards = DiscordUtil.getRecommendedShardCount(token); prefix = (String) config.getOrDefault("prefix", DEFAULT_PREFIX); streamUrl = (String) config.getOrDefault("streamUrl", GENSOKYO_RADIO_STREAM_URL); } catch (IOException | UnirestException e) { throw new RuntimeException(e); } }
From source file:com.ikanow.aleph2.graph.titan.utils.TitanGraphBuildingUtils.java
/** (2/3) Creates a stream of user-generated assets together (grouped by vertex key) with associated data * @param tx/*ww w. j a v a 2s.co m*/ * @param config * @param security_service * @param logger * @param vertices_and_edges * @return */ public static Stream<Tuple4<ObjectNode, List<ObjectNode>, List<ObjectNode>, List<Vertex>>> buildGraph_collectUserGeneratedAssets( final TitanTransaction tx, final GraphSchemaBean config, final Tuple2<String, ISecurityService> security_service, final Optional<IBucketLogger> logger, final DataBucketBean bucket, final MutableStatsBean mutable_stats, final Stream<ObjectNode> vertices_and_edges) { // Convert the list of vertexes into a mega query - will have a false positive rate to keep the query simple final Map<ObjectNode, Tuple2<List<ObjectNode>, List<ObjectNode>>> nodes_to_get = groupNewEdgesAndVertices( config, mutable_stats, vertices_and_edges); final Map<JsonNode, List<Vertex>> grouped_vertices = getGroupedVertices(nodes_to_get.keySet(), tx, config.deduplication_fields(), vertex -> isAllowed(bucket.full_name(), security_service, vertex)); //TRACE: //System.err.println(new Date().toString() + ": DUPS=" + grouped_vertices); // Match up the user vertices with the ones obtained from the system return nodes_to_get.entrySet().stream().map(kv -> Tuples._4T(kv.getKey(), kv.getValue()._1(), kv.getValue()._2(), grouped_vertices.getOrDefault(kv.getKey(), Collections.emptyList()))); }
From source file:com.netflix.spinnaker.halyard.deploy.provider.v1.ProviderInterface.java
public void reapOrcaServerGroups(AccountDeploymentDetails<T> details, OrcaService orcaService) { Orca orca = connectTo(details, orcaService); Map<String, Orca.ActiveExecutions> executions = orca.getActiveExecutions(); Map<String, Integer> executionsByServerGroup = new HashMap<>(); // Record the total number of executions in each pool of orcas. executions.forEach((s, e) -> {//w ww . ja v a 2s. co m String instanceName = s.split("@")[1]; String serverGroupName = getServerGroupFromInstanceId(details, orcaService, instanceName); int count = executionsByServerGroup.getOrDefault(serverGroupName, 0); count += e.getCount(); executionsByServerGroup.put(serverGroupName, count); }); // Omit the last deployed orcas from being deleted, since they are kept around for rollbacks. List<String> allOrcas = new ArrayList<>(executionsByServerGroup.keySet()); allOrcas.sort(String::compareTo); int orcaCount = allOrcas.size(); if (orcaCount <= MAX_REMAINING_SERVER_GROUPS) { return; } allOrcas = allOrcas.subList(0, orcaCount - MAX_REMAINING_SERVER_GROUPS); for (String orcaName : allOrcas) { // TODO(lwander) consult clouddriver to ensure this orca isn't enabled if (executionsByServerGroup.get(orcaName) == 0) { DaemonTaskHandler.log("Reaping old orca instance " + orcaName); deleteServerGroup(details, orcaService, orcaName); } } }
From source file:com.khartec.waltz.service.authoritative_source.AuthoritativeSourceCalculator.java
/** (ouNode, ouId -> [authSource]) -> dataType -> appId -> rating */ private Map<String, Map<Long, AuthoritativeSource>> calculateCumulativeRules( Node<OrganisationalUnit, Long> node, Map<Long, Collection<AuthoritativeSource>> authSourcesByOrgId) { // get orgIds in order from root (reverse of our parents + us) List<Long> ids = append(reverse(map(parents(node), x -> x.getId())), node.getId()); Map<String, Map<Long, AuthoritativeSource>> cumulativeRules = newHashMap(); for (Long unitId : ids) { Collection<AuthoritativeSource> authSources = authSourcesByOrgId.getOrDefault(unitId, newArrayList()); Map<String, Collection<AuthoritativeSource>> byType = groupBy(as -> as.dataType(), authSources); for (String type : byType.keySet()) { Map<Long, AuthoritativeSource> appRatingMap = cumulativeRules.getOrDefault(type, newHashMap()); byType.get(type).forEach(as -> appRatingMap.put(as.applicationReference().id(), as)); cumulativeRules.put(type, appRatingMap); }//from www .j av a 2 s. c om } return cumulativeRules; }
From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.view.provider.KubernetesV2LoadBalancerProvider.java
private Set<KubernetesV2LoadBalancer> fromLoadBalancerCacheData(List<CacheData> loadBalancerData) { List<CacheData> serverGroupData = kindMap.translateSpinnakerKind(SERVER_GROUPS).stream() .map(kind -> cacheUtils.loadRelationshipsFromCache(loadBalancerData, kind.toString())) .flatMap(Collection::stream).collect(Collectors.toList()); List<CacheData> instanceData = kindMap.translateSpinnakerKind(INSTANCES).stream() .map(kind -> cacheUtils.loadRelationshipsFromCache(serverGroupData, kind.toString())) .flatMap(Collection::stream).collect(Collectors.toList()); Map<String, List<CacheData>> loadBalancerToServerGroups = cacheUtils.mapByRelationship(serverGroupData, LOAD_BALANCERS);/*from www. j a v a 2 s . com*/ Map<String, List<CacheData>> serverGroupToInstances = cacheUtils.mapByRelationship(instanceData, SERVER_GROUPS); return loadBalancerData.stream() .map(cd -> KubernetesV2LoadBalancer.fromCacheData(cd, loadBalancerToServerGroups.getOrDefault(cd.getId(), new ArrayList<>()), serverGroupToInstances)) .filter(Objects::nonNull).collect(Collectors.toSet()); }