Java Code Examples for java.util.SortedMap#computeIfAbsent()

The following examples show how to use java.util.SortedMap#computeIfAbsent() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: batfish   File: VendorConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
private void addStructureReference(
    SortedMap<String, SortedMap<String, SortedMap<String, SortedMap<String, SortedSet<Integer>>>>>
        referenceMap,
    StructureType structureType,
    String name,
    StructureUsage usage,
    int line) {
  String filename = getFilename();
  SortedMap<String, SortedMap<String, SortedMap<String, SortedSet<Integer>>>> byType =
      referenceMap.computeIfAbsent(filename, k -> new TreeMap<>());
  String type = structureType.getDescription();
  SortedMap<String, SortedMap<String, SortedSet<Integer>>> byName =
      byType.computeIfAbsent(type, k -> new TreeMap<>());
  SortedMap<String, SortedSet<Integer>> byUsage =
      byName.computeIfAbsent(name, k -> new TreeMap<>());
  String usageStr = usage.getDescription();
  SortedSet<Integer> lines = byUsage.computeIfAbsent(usageStr, k -> new TreeSet<>());
  lines.add(line);
}
 
Example 2
Map<ReleaseNotesSection, List<Issue>> collate(List<Issue> issues) {
	SortedMap<ReleaseNotesSection, List<Issue>> collated = new TreeMap<>(
			Comparator.comparing(this.sections::indexOf));
	for (Issue issue : issues) {
		ReleaseNotesSection section = getSection(issue);
		if (section != null) {
			collated.computeIfAbsent(section, (key) -> new ArrayList<>());
			collated.get(section).add(issue);
		}
	}
	return collated;
}
 
Example 3
Source Project: batfish   File: NodeRoleDimension.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a map from each role name to the set of nodes that play that role
 *
 * @param nodeNames The universe of nodes that we need to classify
 * @return The created map
 */
public SortedMap<String, SortedSet<String>> createRoleNodesMap(Set<String> nodeNames) {
  SortedMap<String, SortedSet<String>> roleNodesMap = new TreeMap<>();
  SortedMap<String, String> nodeRolesMap = createNodeRolesMap(nodeNames);
  for (Map.Entry<String, String> entry : nodeRolesMap.entrySet()) {
    String nodeName = entry.getKey();
    String roleName = entry.getValue();
    SortedSet<String> roleNodes = roleNodesMap.computeIfAbsent(roleName, k -> new TreeSet<>());
    roleNodes.add(nodeName);
  }
  return roleNodesMap;
}
 
Example 4
Source Project: batfish   File: VendorConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
public void referenceStructure(StructureType type, String name, StructureUsage usage, int line) {
  SortedMap<String, SortedMap<StructureUsage, SortedMultiset<Integer>>> byName =
      _structureReferences.computeIfAbsent(type, k -> new TreeMap<>());
  SortedMap<StructureUsage, SortedMultiset<Integer>> byUsage =
      byName.computeIfAbsent(name, k -> new TreeMap<>());
  SortedMultiset<Integer> lines = byUsage.computeIfAbsent(usage, k -> TreeMultiset.create());
  lines.add(line);
}
 
Example 5
Source Project: batfish   File: VendorConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Updates structure definitions to include the specified structure {@code name} and {@code
 * structureType} and initializes the number of referrers.
 */
public void defineSingleLineStructure(StructureType structureType, String name, int line) {
  String type = structureType.getDescription();
  SortedMap<String, DefinedStructureInfo> byName =
      _structureDefinitions.computeIfAbsent(type, k -> new TreeMap<>());
  DefinedStructureInfo info =
      byName.computeIfAbsent(name, k -> new DefinedStructureInfo(new TreeSet<>(), 0));
  info.getDefinitionLines().add(line);
}
 
Example 6
Source Project: batfish   File: InitIssuesAnswerer.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static SortedMap<ParseStatus, Set<String>> aggregateParseStatuses(
    SortedMap<String, ParseStatus> fileStatuses) {
  SortedMap<ParseStatus, Set<String>> aggregatedStatuses = new TreeMap<>();
  for (Entry<String, ParseStatus> entry : fileStatuses.entrySet()) {
    Set<String> files =
        aggregatedStatuses.computeIfAbsent(entry.getValue(), s -> new HashSet<>());
    files.add(entry.getKey());
  }
  return aggregatedStatuses;
}
 
Example 7
Source Project: robozonky   File: Util.java    License: Apache License 2.0 4 votes vote down vote up
/**
 *
 * @param strategy
 * @param portfolio
 * @return More demanded ratings come first.
 */
static Set<Rating> rankRatingsByDemand(final ParsedStrategy strategy, final PortfolioOverview portfolio) {
    final SortedMap<Ratio, SortedMap<Ratio, EnumSet<Rating>>> mostWantedRatings = new TreeMap<>();
    // put the ratings into buckets based on how much we're missing them
    for (Rating r : Rating.values()) {
        final Ratio permittedShare = strategy.getPermittedShare(r);
        if (permittedShare.compareTo(Ratio.ZERO) <= 0) { // prevent division by zero later
            LOGGER.debug("Rating {} permitted share is {} %, skipping.", r, permittedShare.asPercentage());
            continue;
        }
        // under 0 = underinvested, over 0 = overinvested
        final Ratio currentRatingShare = portfolio.getShareOnInvestment(r);
        final Ratio ratio = Ratio.fromRaw(divide(currentRatingShare.bigDecimalValue(),
                permittedShare.bigDecimalValue()));
        final boolean overinvested = ratio.compareTo(Ratio.ONE) >= 0;
        if (overinvested) { // we over-invested into this rating; do not include
            final BigDecimal percentOver = ratio.asPercentage()
                .subtract(HUNDRED);
            LOGGER.debug("Rating {} over-invested by {} %, skipping. (Expected {}, got {}.)", r, percentOver,
                    permittedShare, currentRatingShare);
            continue;
        }
        LOGGER.debug("Rating {} under-invested by {} %. (Expected {}, got {}.)", r,
                HUNDRED.subtract(ratio.asPercentage()), permittedShare, currentRatingShare);
        // rank the rating
        mostWantedRatings.computeIfAbsent(ratio, k -> new TreeMap<>(Comparator.reverseOrder()));
        mostWantedRatings.get(ratio)
            .compute(permittedShare, (k, v) -> {
                if (v == null) {
                    return EnumSet.of(r);
                } else {
                    v.add(r);
                    return v;
                }
            });
    }
    return mostWantedRatings.values()
        .stream()
        .flatMap(s -> s.values()
            .stream())
        .flatMap(Collection::stream)
        .collect(Collectors.toCollection(LinkedHashSet::new));
}
 
Example 8
/**
 * Returns a mapping of pods to be decommissioned with affected tasks within those pods. The returned mapping will
 * be in the order that the pods should be decommissioned.
 */
@VisibleForTesting
static SortedMap<PodKey, Collection<Protos.TaskInfo>> getPodsToDecommission(
    Logger logger,
    ServiceSpec serviceSpec,
    Collection<Protos.TaskInfo> tasks)
{
  // If multiple pod types are being decommissioned, they should be decommissioned in the reverse of the order
  // that they're declared in the ServiceSpec (opposite direction of default deployment)
  List<String> orderedPodTypes =
      serviceSpec.getPods().stream().map(PodSpec::getType).collect(Collectors.toList());
  Collections.reverse(orderedPodTypes);

  Map<String, Integer> expectedPodCounts =
      serviceSpec
          .getPods()
          .stream()
          .collect(Collectors.toMap(PodSpec::getType, PodSpec::getCount));
  logger.info("Expected pod counts: {}", expectedPodCounts);
  SortedMap<PodKey, Collection<Protos.TaskInfo>> podsToDecommission = new TreeMap<>();
  for (Protos.TaskInfo task : tasks) {
    final PodKey podKey;
    try {
      TaskLabelReader labelReader = new TaskLabelReader(task);
      podKey = new PodKey(labelReader.getType(), labelReader.getIndex(), orderedPodTypes);
    } catch (TaskException e) {
      logger.error(
          String.format(
              "Failed to retrieve task metadata. Omitting task from decommission: %s",
              task.getName()
          ),
          e
      );
      continue;
    }

    Integer expectedPodCount = expectedPodCounts.get(podKey.podType);
    if (expectedPodCount == null) {
      logger.info("Scheduling '{}' for decommission: '{}' is not present in service spec: {}",
          task.getName(), podKey.podType, expectedPodCounts.keySet());
    } else if (podKey.podIndex >= expectedPodCount) {
      logger.info("Scheduling '{}' for decommission: '{}' exceeds desired pod count {}",
          task.getName(), podKey.getPodName(), expectedPodCount);
    } else {
      // Do nothing
      continue;
    }
    Collection<Protos.TaskInfo> podTasks =
        podsToDecommission.computeIfAbsent(podKey, k -> new ArrayList<>());
    podTasks.add(task);
  }
  logger.info("Pods scheduled for decommission: {}", podsToDecommission.keySet());
  return podsToDecommission;
}
 
Example 9
Source Project: batfish   File: Vsys.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Returns a syslog server with the specified name in the specified server group. If a matching
 * server does not exist, one is created.
 */
public SyslogServer getSyslogServer(String serverGroupName, String serverName) {
  SortedMap<String, SyslogServer> serverGroup =
      _syslogServerGroups.computeIfAbsent(serverGroupName, g -> new TreeMap<>());
  return serverGroup.computeIfAbsent(serverName, SyslogServer::new);
}
 
Example 10
public Filter parseAppenderFilters(Properties props, String filterPrefix, String appenderName) {
    // extract filters and filter options from props into a hashtable mapping
    // the property name defining the filter class to a list of pre-parsed
    // name-value pairs associated to that filter
    int fIdx = filterPrefix.length();
    SortedMap<String, List<NameValue>> filters = new TreeMap<>();
    Enumeration e = props.keys();
    String name = "";
    while (e.hasMoreElements()) {
        String key = (String) e.nextElement();
        if (key.startsWith(filterPrefix)) {
            int dotIdx = key.indexOf('.', fIdx);
            String filterKey = key;
            if (dotIdx != -1) {
                filterKey = key.substring(0, dotIdx);
                name = key.substring(dotIdx + 1);
            }
            List<NameValue> filterOpts = filters.computeIfAbsent(filterKey, k -> new ArrayList<>());
            if (dotIdx != -1) {
                String value = OptionConverter.findAndSubst(key, props);
                filterOpts.add(new NameValue(name, value));
            }
        }
    }

    Filter head = null;
    Filter next = null;
    for (Map.Entry<String, List<NameValue>> entry : filters.entrySet()) {
        String clazz = props.getProperty(entry.getKey());
        Filter filter = null;
        if (clazz != null) {
            filter = manager.parseFilter(clazz, filterPrefix, props, this);
            if (filter == null) {
                LOGGER.debug("Filter key: [{}] class: [{}] props: {}", entry.getKey(), clazz, entry.getValue());
                filter = buildFilter(clazz, appenderName, entry.getValue());
            }
        }
        if (filter != null) {
            if (head != null) {
                head = filter;
                next = filter;
            } else {
                next.setNext(filter);
                next = filter;
            }
        }
    }
    return head;
}