Example usage for java.util Map computeIfAbsent

List of usage examples for java.util Map computeIfAbsent

Introduction

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

Prototype

default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) 

Source Link

Document

If the specified key is not already associated with a value (or is mapped to null ), attempts to compute its value using the given mapping function and enters it into this map unless null .

Usage

From source file:com.mgmtp.perfload.perfalyzer.reporting.ReportCreator.java

public void createReport(final List<PerfAlyzerFile> files) throws IOException {
    Function<PerfAlyzerFile, String> classifier = perfAlyzerFile -> {
        String marker = perfAlyzerFile.getMarker();
        return marker == null ? "Overall" : marker;
    };/*  ww  w.j av a 2  s .c  o m*/
    Supplier<Map<String, List<PerfAlyzerFile>>> mapFactory = () -> new TreeMap<>(Ordering.explicit(tabNames));

    Map<String, List<PerfAlyzerFile>> filesByMarker = files.stream()
            .collect(Collectors.groupingBy(classifier, mapFactory, toList()));

    Map<String, SortedSetMultimap<String, PerfAlyzerFile>> contentItemFiles = new LinkedHashMap<>();

    for (Entry<String, List<PerfAlyzerFile>> entry : filesByMarker.entrySet()) {
        SortedSetMultimap<String, PerfAlyzerFile> contentItemFilesByMarker = contentItemFiles.computeIfAbsent(
                entry.getKey(),
                s -> TreeMultimap.create(new ItemComparator(reportContentsConfigMap.get("priorities")),
                        Ordering.natural()));

        for (PerfAlyzerFile perfAlyzerFile : entry.getValue()) {
            File file = perfAlyzerFile.getFile();
            String groupKey = removeExtension(file.getPath());
            boolean excluded = false;
            for (Pattern pattern : reportContentsConfigMap.get("exclusions")) {
                Matcher matcher = pattern.matcher(groupKey);
                if (matcher.matches()) {
                    excluded = true;
                    log.debug("Excluded from report: {}", groupKey);
                    break;
                }
            }
            if (!excluded) {
                contentItemFilesByMarker.put(groupKey, perfAlyzerFile);
            }
        }
    }

    // explicitly copy it because it is otherwise filtered from the report in order to only show in the overview
    String loadProfilePlot = new File("console", "[loadprofile].png").getPath();
    copyFile(new File(soureDir, loadProfilePlot), new File(destDir, loadProfilePlot));

    Map<String, List<ContentItem>> tabItems = new LinkedHashMap<>();
    Map<String, QuickJump> quickJumps = new HashMap<>();
    Set<String> tabNames = contentItemFiles.keySet();

    for (Entry<String, SortedSetMultimap<String, PerfAlyzerFile>> tabEntry : contentItemFiles.entrySet()) {
        String tab = tabEntry.getKey();
        SortedSetMultimap<String, PerfAlyzerFile> filesForTab = tabEntry.getValue();

        List<ContentItem> contentItems = tabItems.computeIfAbsent(tab, list -> new ArrayList<>());
        Map<String, String> quickJumpMap = new LinkedHashMap<>();
        quickJumps.put(tab, new QuickJump(tab, quickJumpMap));

        int itemIndex = 0;
        for (Entry<String, Collection<PerfAlyzerFile>> itemEntry : filesForTab.asMap().entrySet()) {
            String title = itemEntry.getKey();
            Collection<PerfAlyzerFile> itemFiles = itemEntry.getValue();

            TableData tableData = null;
            String plotSrc = null;
            for (PerfAlyzerFile file : itemFiles) {
                if ("png".equals(getExtension(file.getFile().getName()))) {
                    plotSrc = file.getFile().getPath();
                    copyFile(new File(soureDir, plotSrc), new File(destDir, plotSrc));
                } else {
                    tableData = createTableData(file.getFile());
                }
            }

            // strip off potential marker
            title = substringBefore(title, "{");

            String[] titleParts = split(title, SystemUtils.FILE_SEPARATOR);
            StringBuilder sb = new StringBuilder(50);
            String separator = " - ";
            sb.append(resourceBundle.getString(titleParts[0]));
            sb.append(separator);
            sb.append(resourceBundle.getString(titleParts[1]));

            List<String> fileNameParts = extractFileNameParts(titleParts[1], true);
            if (titleParts[1].contains("[distribution]")) {
                String operation = fileNameParts.get(1);
                sb.append(separator);
                sb.append(operation);
            } else if ("comparison".equals(titleParts[0])) {
                String operation = fileNameParts.get(1);
                sb.append(separator);
                sb.append(operation);
            } else if (titleParts[1].contains("[gclog]")) {
                if (fileNameParts.size() > 1) {
                    sb.append(separator);
                    sb.append(fileNameParts.get(1));
                }
            }

            title = sb.toString();
            ContentItem item = new ContentItem(tab, itemIndex, title, tableData, plotSrc,
                    resourceBundle.getString("report.topLink"));
            contentItems.add(item);

            quickJumpMap.put(tab + "_" + itemIndex, title);
            itemIndex++;
        }
    }

    NavBar navBar = new NavBar(tabNames, quickJumps);
    String testName = removeExtension(testMetadata.getTestPlanFile());
    OverviewItem overviewItem = new OverviewItem(testMetadata, resourceBundle, locale);
    Content content = new Content(tabItems);

    String perfAlyzerVersion;
    try {
        perfAlyzerVersion = Resources.toString(Resources.getResource("perfAlyzer.version"), Charsets.UTF_8);
    } catch (IOException ex) {
        log.error("Could not read perfAlyzer version from classpath resource 'perfAlyzer.version'", ex);
        perfAlyzerVersion = "";
    }

    String dateTimeString = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withLocale(locale)
            .format(ZonedDateTime.now());
    String createdString = String.format(resourceBundle.getString("footer.created"), perfAlyzerVersion,
            dateTimeString);
    HtmlSkeleton html = new HtmlSkeleton(testName, createdString, navBar, overviewItem, content);
    writeReport(html);
}

From source file:org.ligoj.app.plugin.prov.azure.in.ProvAzurePriceImportResource.java

private ProvInstancePrice installInstancePrice(final UpdateContext context, final ProvInstancePriceTerm term,
        final VmOs os, final String globalCode, final ProvInstanceType type, final String region) {
    final Map<String, ProvInstancePrice> previous = term.getName().equals(TERM_LOW)
            ? context.getPreviousLowPriority()
            : context.getPrevious();// w w w .  j  av  a 2 s  . c  om
    return previous.computeIfAbsent(region + "-" + globalCode, code -> {
        // New instance price (not update mode)
        final ProvInstancePrice newPrice = new ProvInstancePrice();
        newPrice.setCode(code);
        newPrice.setLocation(context.getRegions().get(region));
        newPrice.setOs(os);
        newPrice.setTerm(term);
        newPrice.setTenancy(
                dedicatedTypes.contains(type.getName()) ? ProvTenancy.DEDICATED : ProvTenancy.SHARED);
        newPrice.setType(type);
        return newPrice;
    });
}

From source file:org.ligoj.app.plugin.prov.azure.in.ProvAzurePriceImportResource.java

/**
 * Install or update a storage price.//from w w w . ja  v a2 s .c  om
 *
 * @param context
 *            The update context.
 * @see <a href="https://azure.microsoft.com/en-us/pricing/details/managed-disks/"></a>
 */
private ProvStoragePrice installStoragePrice(final UpdateContext context,
        final Map<ProvLocation, ProvStoragePrice> regionPrices, final ProvLocation region,
        final ProvStorageType type, final double value) {
    final ProvStoragePrice price = regionPrices.computeIfAbsent(region, r -> {
        final ProvStoragePrice newPrice = new ProvStoragePrice();
        newPrice.setType(type);
        newPrice.setLocation(region);
        newPrice.setCode(region.getName() + "-" + type.getName());
        return newPrice;
    });
    // Fixed cost
    price.setCost(value);

    if (!type.getName().startsWith("premium")) {
        // Additional transaction based cost : $/10,000 transaction -> $/1,000,000 transaction
        price.setCostTransaction(Optional.ofNullable(context.getTransactions().get(region.getName()))
                .map(v -> round3Decimals(v.getValue() * 100)).orElse(0d));
    }
    spRepository.saveAndFlush(price);
    return price;
}

From source file:guru.qas.martini.gherkin.DefaultMixology.java

protected List<Recipe> getRecipes(FeatureWrapper feature, Collection<Pickle> pickles) {
    Map<Integer, Recipe> recipeIndex = new LinkedHashMap<>();

    RangeMap<Integer, ScenarioDefinition> rangeMap = getRangeMap(feature);
    for (Pickle pickle : pickles) {
        List<PickleLocation> locations = pickle.getLocations();
        Map<Integer, PickleLocation> locationIndex = new HashMap<>();
        locations.forEach(l -> {/*from  w  w w .j a  v a  2s .  c o  m*/
            int line = l.getLine();
            locationIndex.put(line, l);
        });

        Integer line = Ordering.natural().max(locationIndex.keySet());
        recipeIndex.computeIfAbsent(line, l -> {
            PickleLocation location = locationIndex.get(l);
            Range<Integer> range = Range.singleton(line);
            RangeMap<Integer, ScenarioDefinition> subRangeMap = rangeMap.subRangeMap(range);
            Map<Range<Integer>, ScenarioDefinition> asMap = subRangeMap.asMapOfRanges();
            checkState(1 == asMap.size(), "no single range found encompassing PickleLocation %s", location);
            ScenarioDefinition definition = Iterables.getOnlyElement(asMap.values());
            return new DefaultRecipe(feature, pickle, location, definition);
        });
    }
    return ImmutableList.copyOf(recipeIndex.values());
}

From source file:com.thinkbiganalytics.alerts.rest.AlertsModel.java

public Collection<AlertSummaryGrouped> groupAlertSummaries(List<AlertSummary> alertSummaries) {
    Map<String, AlertSummaryGrouped> group = new HashMap<>();
    alertSummaries.forEach(alertSummary -> {

        String key = alertSummary.getType() + ":" + alertSummary.getSubtype();

        String displayName = alertTypeDisplayName(alertSummary);
        if (alertSummary instanceof EntityAwareAlertSummary) {
            EntityAwareAlertSummary entityAwareAlertSummary = (EntityAwareAlertSummary) alertSummary;
            key = entityAwareAlertSummary.getGroupByKey();
            group.computeIfAbsent(key,
                    key1 -> new AlertSummaryGrouped.Builder().typeString(alertSummary.getType())
                            .typeDisplayName(displayName).subType(entityAwareAlertSummary.getSubtype())
                            .feedId(entityAwareAlertSummary.getFeedId() != null
                                    ? entityAwareAlertSummary.getFeedId().toString()
                                    : null)
                            .feedName(entityAwareAlertSummary.getFeedName())
                            .slaId(entityAwareAlertSummary.getSlaId() != null
                                    ? entityAwareAlertSummary.getSlaId().toString()
                                    : null)
                            .slaName(entityAwareAlertSummary.getSlaName()).build())
                    .add(toModel(alertSummary.getLevel()), alertSummary.getCount(),
                            alertSummary.getLastAlertTimestamp());
        } else {/*  ww w. j  a v a2 s. c o m*/
            group.computeIfAbsent(key,
                    key1 -> new AlertSummaryGrouped.Builder().typeString(alertSummary.getType())
                            .typeDisplayName(displayName).subType(alertSummary.getSubtype()).build())
                    .add(toModel(alertSummary.getLevel()), alertSummary.getCount(),
                            alertSummary.getLastAlertTimestamp());
        }
    });
    return group.values();
}

From source file:com.netflix.spinnaker.clouddriver.cloudfoundry.client.Applications.java

public List<CloudFoundryApplication> all() {
    List<CloudFoundryServerGroup> serverGroups = collectPages("applications", page -> api.all(page, null, null))
            .stream().map(this::map).collect(toList());
    serverGroupCache.invalidateAll();/* w w w. j a  v a2  s . c o  m*/
    serverGroups.forEach(sg -> serverGroupCache.put(sg.getId(), sg));

    Map<String, Set<CloudFoundryServerGroup>> serverGroupsByClusters = new HashMap<>();
    Map<String, Set<String>> clustersByApps = new HashMap<>();

    for (CloudFoundryServerGroup serverGroup : serverGroups) {
        Names names = Names.parseName(serverGroup.getName());
        serverGroupsByClusters.computeIfAbsent(names.getCluster(), clusterName -> new HashSet<>())
                .add(serverGroup);
        clustersByApps.computeIfAbsent(names.getApp(), appName -> new HashSet<>()).add(names.getCluster());
    }

    return clustersByApps.entrySet().stream().map(clustersByApp -> CloudFoundryApplication.builder()
            .name(clustersByApp.getKey())
            .clusters(clustersByApp.getValue().stream()
                    .map(clusterName -> CloudFoundryCluster.builder().accountName(account).name(clusterName)
                            .serverGroups(serverGroupsByClusters.get(clusterName)).build())
                    .collect(toSet()))
            .build()).collect(toList());
}

From source file:com.netflix.spinnaker.orca.clouddriver.utils.TrafficGuard.java

public void verifyInstanceTermination(String serverGroupNameFromStage, List<String> instanceIds, String account,
        Location location, String cloudProvider, String operationDescriptor) {
    Map<String, List<String>> instancesPerServerGroup = new HashMap<>();
    for (String instanceId : instanceIds) {
        String serverGroupName = serverGroupNameFromStage;
        if (serverGroupName == null) {
            Optional<String> resolvedServerGroupName = resolveServerGroupNameForInstance(instanceId, account,
                    location.getValue(), cloudProvider);
            serverGroupName = resolvedServerGroupName.orElse(null);
        }//from  w ww .  ja v  a 2s  .co m

        if (serverGroupName != null) {
            instancesPerServerGroup.computeIfAbsent(serverGroupName, serverGroup -> new ArrayList<>())
                    .add(instanceId);
        }
    }

    instancesPerServerGroup.entrySet().forEach(entry -> {
        String serverGroupName = entry.getKey();
        Names names = Names.parseName(serverGroupName);
        if (hasDisableLock(names.getCluster(), account, location)) {
            Optional<TargetServerGroup> targetServerGroup = oortHelper.getTargetServerGroup(account,
                    serverGroupName, location.getValue(), cloudProvider);

            targetServerGroup.ifPresent(serverGroup -> {
                Optional<Map> thisInstance = serverGroup.getInstances().stream()
                        .filter(i -> "Up".equals(i.get("healthState"))).findFirst();
                if (thisInstance.isPresent() && "Up".equals(thisInstance.get().get("healthState"))) {
                    long otherActiveInstances = serverGroup.getInstances().stream().filter(
                            i -> "Up".equals(i.get("healthState")) && !entry.getValue().contains(i.get("name")))
                            .count();
                    if (otherActiveInstances == 0) {
                        verifyOtherServerGroupsAreTakingTraffic(serverGroupName, location, account,
                                cloudProvider, operationDescriptor);
                    }
                }
            });
        }
    });
}

From source file:com.streamsets.datacollector.classpath.ClasspathValidator.java

public ClasspathValidatorResult validate(Properties explicitWhitelist) {
    LOG.trace("Validating classpath for {}", name);
    ClasspathValidatorResult.Builder resultBuilder = new ClasspathValidatorResult.Builder(name);
    // Name of dependency -> Version(s) of the dependency -> Individual dependencies
    Map<String, Map<String, List<Dependency>>> dependecies = new HashMap<>();

    // (Re-)Parse all URLs (all dependencies)
    for (URL url : urls) {
        Optional<Dependency> parsed = DependencyParser.parseURL(url);

        if (!parsed.isPresent()) {
            resultBuilder.addUnparseablePath(url.toString());
            continue;
        }//from w ww  .j  a v a2  s . c om

        Dependency dependency = parsed.get();
        LOG.trace("Parsed {} to dependency {} on version {}", dependency.getSourceName(), dependency.getName(),
                dependency.getVersion());

        dependecies.computeIfAbsent(dependency.getName(), (i) -> new HashMap<>())
                .computeIfAbsent(dependency.getVersion(), (i) -> new LinkedList<>()).add(dependency);
    }

    // And finally validate each dependency have allowed list of versions
    for (Map.Entry<String, Map<String, List<Dependency>>> entry : dependecies.entrySet()) {
        // Ideal the inner map with versions should have only one item, otherwise that is most likely a problem
        if (entry.getValue().size() > 1) {
            if (CollisionWhitelist.isWhitelisted(entry.getKey(), explicitWhitelist, entry.getValue())) {
                LOG.trace("Whitelisted dependency {} on versions {}", entry.getKey(),
                        StringUtils.join(entry.getValue().keySet(), ","));
                continue;
            }

            // No exceptions were applied, hence this is truly a collision
            resultBuilder.addVersionCollision(entry.getKey(), entry.getValue());
        }
    }

    return resultBuilder.build();
}

From source file:at.gridtec.lambda4j.function.bi.to.ToByteBiFunction.java

/**
 * Returns a memoized (caching) version of this {@link ToByteBiFunction}. Whenever it is called, the mapping between
 * the input parameters and the return value is preserved in a cache, making subsequent calls returning the memoized
 * value instead of computing the return value again.
 * <p>/*from  w ww  . j  a  v a2 s.c o m*/
 * Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values
 * forever.
 *
 * @return A memoized (caching) version of this {@code ToByteBiFunction}.
 * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
 * resulting memoized function, as the cache used internally does not permit {@code null} keys or values.
 * @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it
 * thread-safe.
 */
@Nonnull
default ToByteBiFunction<T, U> memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Pair<T, U>, Byte> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (ToByteBiFunction<T, U> & Memoized) (t, u) -> {
            final byte returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Pair.of(t, u),
                        key -> applyAsByte(key.getLeft(), key.getRight()));
            }
            return returnValue;
        };
    }
}

From source file:com.thinkbiganalytics.feedmgr.rest.model.RegisteredTemplate.java

@JsonIgnore
public void initializeInputProcessors() {
    Map<String, Processor> processorMap = new HashMap<>();

    properties.stream().filter(isValidInput()).forEach(property -> {
        processorMap.computeIfAbsent(property.getProcessorId(),
                processorId -> new Processor(property.getProcessorId())).addProperty(property);
    });//w  ww  . j a v  a 2  s.  c o m
    inputProcessors = Lists.newArrayList(processorMap.values());
}