Example usage for java.util.function BiFunction apply

List of usage examples for java.util.function BiFunction apply

Introduction

In this page you can find the example usage for java.util.function BiFunction apply.

Prototype

R apply(T t, U u);

Source Link

Document

Applies this function to the given arguments.

Usage

From source file:nu.yona.server.subscriptions.service.BuddyService.java

private void createAndInviteBuddyUser(UUID idOfRequestingUser, BuddyDto buddy,
        BiFunction<UUID, String, String> inviteUrlGetter) {
    String tempPassword = getTempPassword();
    // To ensure the data of the new user is encrypted with the temp password, the user is created in a separate transaction
    // and crypto session.
    UUID savedUserId;//from   w  w  w  .j a va2  s.  co m
    try (CryptoSession cryptoSession = CryptoSession.start(tempPassword)) {
        savedUserId = transactionHelper.executeInNewTransaction(
                () -> userService.addUserCreatedOnBuddyRequest(buddy.getUser()).getId());
    }

    String inviteUrl = inviteUrlGetter.apply(savedUserId, tempPassword);
    UserDto requestingUser = userService.getPrivateUser(idOfRequestingUser);
    sendInvitationMessage(requestingUser, buddy, inviteUrl);
}

From source file:org.ligoj.app.plugin.vm.azure.VmAzurePluginResource.java

/**
 * Build a described {@link AzureVm} completing the VM details with the instance details.
 * /*from ww  w . jav a  2 s .  c  om*/
 * @param azureVm
 *            The Azure VM object built from the raw JSON stream.
 * @param sizeProvider
 *            Optional Azure instance size provider.
 * @return The merge VM details.
 */
private AzureVm toVm(final AzureVmEntry azureVm, final BiFunction<String, String, VmSize> sizeProvider) {
    final AzureVm result = new AzureVm();
    final AzureVmDetails properties = azureVm.getProperties();
    result.setId(azureVm.getName()); // ID is the name for Azure
    result.setInternalId(properties.getVmId());
    result.setName(azureVm.getName());
    result.setLocation(azureVm.getLocation());

    // Instance type details if available
    if (sizeProvider != null) {
        final String instanceType = properties.getHardwareProfile().get("vmSize");
        final VmSize size = sizeProvider.apply(instanceType, azureVm.getLocation());
        result.setCpu(size.getNumberOfCores());
        result.setRam(size.getMemoryInMB());
    }

    // OS
    final AzureVmOs image = properties.getStorageProfile().getImageReference();
    if (image.getOffer() == null) {
        // From image
        result.setOs(properties.getStorageProfile().getOsDisk().getOsType() + " ("
                + StringUtils.substringAfterLast(image.getId(), "/") + ")");
    } else {
        // From marketplace : provider
        result.setOs(image.getOffer() + " " + image.getSku() + " " + image.getPublisher());
    }

    // Disk size
    result.setDisk(properties.getStorageProfile().getOsDisk().getDiskSizeGB());

    return result;
}

From source file:nu.yona.server.analysis.service.ActivityService.java

private <T extends IntervalActivityDto> T getMissingInactivity(UUID userId, LocalDate date, UUID goalId,
        UserAnonymizedDto userAnonymized, ChronoUnit timeUnit,
        BiFunction<Goal, ZonedDateTime, T> inactivityEntitySupplier) {
    Goal goal = goalService.getGoalEntityForUserAnonymizedId(userAnonymized.getId(), goalId);
    ZonedDateTime dateAtStartOfInterval = date.atStartOfDay(userAnonymized.getTimeZone());
    if (!goal.wasActiveAtInterval(dateAtStartOfInterval, timeUnit)) {
        throw ActivityServiceException.activityDateGoalMismatch(userId, date, goalId);
    }//  ww  w  .j  av  a  2 s  . com
    return inactivityEntitySupplier.apply(goal, dateAtStartOfInterval);
}

From source file:spimedb.SpimeDB.java

@Nullable
DObject commit(NObject previous, NObject _next) {

    NObject next = _next;/*from   w  w  w  . ja  va 2 s  .  c om*/

    //logger.debug("commit onChange={}", onChange, previous, _next);

    if (!onChange.isEmpty()) {
        for (BiFunction<NObject, NObject, NObject> c : onChange) {
            next = c.apply(previous, next);
        }
    }

    if (next == null)
        return null;

    DObject d = DObject.get(next, this);
    String id = d.id();
    out.put(id, d);
    cache.put(id, d);
    commit();

    pub(next);

    return d;
}

From source file:org.onosproject.store.primitives.impl.EventuallyConsistentMapImpl.java

@Override
public V compute(K key, BiFunction<K, V, V> recomputeFunction) {
    checkState(!destroyed, destroyedMessage);
    checkNotNull(key, ERROR_NULL_KEY);/*from   w w w . jav  a  2 s . co  m*/
    checkNotNull(recomputeFunction, "Recompute function cannot be null");

    AtomicBoolean updated = new AtomicBoolean(false);
    AtomicReference<MapValue<V>> previousValue = new AtomicReference<>();
    MapValue<V> computedValue = items.compute(serializer.copy(key), (k, mv) -> {
        previousValue.set(mv);
        V newRawValue = recomputeFunction.apply(key, mv == null ? null : mv.get());
        if (mv != null && Objects.equals(newRawValue, mv.get())) {
            // value was not updated
            return mv;
        }
        MapValue<V> newValue = new MapValue<>(newRawValue, timestampProvider.apply(key, newRawValue));
        if (mv == null || newValue.isNewerThan(mv)) {
            updated.set(true);
            // We return a copy to ensure updates to peers can be serialized.
            // This prevents replica divergence due to serialization failures.
            return serializer.copy(newValue);
        } else {
            return mv;
        }
    });
    if (updated.get()) {
        notifyPeers(new UpdateEntry<>(key, computedValue), peerUpdateFunction.apply(key, computedValue.get()));
        EventuallyConsistentMapEvent.Type updateType = computedValue.isTombstone() ? REMOVE : PUT;
        V value = computedValue.isTombstone() ? previousValue.get() == null ? null : previousValue.get().get()
                : computedValue.get();
        if (value != null) {
            notifyListeners(new EventuallyConsistentMapEvent<>(mapName, updateType, key, value));
        }
    }
    return computedValue.get();
}

From source file:com.netflix.spinnaker.orca.libdiffs.LibraryDiffTool.java

public LibraryDiffs calculateLibraryDiffs(List<Library> sourceLibs, List<Library> targetLibs) {
    LibraryDiffs libraryDiffs = new LibraryDiffs();
    libraryDiffs.setTotalLibraries(targetLibs != null ? targetLibs.size() : 0);

    BiFunction<Library, String, Diff> buildDiff = (Library library, String display) -> {
        Diff diff = new Diff();
        diff.setLibrary(includeLibraryDetails ? library : null);
        diff.setDisplayDiff(display);/*  ww w . j  a v  a 2  s  . c o m*/
        return diff;
    };

    try {
        if (!targetLibs.isEmpty() && !sourceLibs.isEmpty()) {
            Set<Library> uniqueCurrentList = new HashSet<>(targetLibs);
            Map<String, List<Library>> duplicatesMap = filterValues(
                    targetLibs.stream().collect(groupingBy(Library::getName)), it -> it.size() > 1);
            sourceLibs.forEach((Library oldLib) -> {
                if (!duplicatesMap.keySet().contains(oldLib.getName())) {
                    Library currentLib = uniqueCurrentList.stream()
                            .filter(it -> it.getName().equals(oldLib.getName())).findFirst().orElse(null);
                    if (currentLib != null) {
                        if (isEmpty(currentLib.getVersion()) || isEmpty(oldLib.getVersion())) {
                            libraryDiffs.getUnknown().add(buildDiff.apply(oldLib, oldLib.getName()));
                        } else if (currentLib.getVersion() != null && oldLib.getVersion() != null) {
                            int comparison = comparableLooseVersion.compare(currentLib.getVersion(),
                                    oldLib.getVersion());
                            if (comparison == 1) {
                                libraryDiffs.getUpgraded().add(buildDiff.apply(oldLib, format("%s: %s -> %s",
                                        oldLib.getName(), oldLib.getVersion(), currentLib.getVersion())));
                            }
                            if (comparison == -1) {
                                libraryDiffs.getDowngraded().add(buildDiff.apply(oldLib, format("%s: %s -> %s",
                                        oldLib.getName(), oldLib.getVersion(), currentLib.getVersion())));
                            }
                        }
                    } else {
                        libraryDiffs.getRemoved().add(buildDiff.apply(oldLib,
                                format("%s: %s", oldLib.getName(), oldLib.getVersion())));
                    }
                }
            });

            uniqueCurrentList.stream().filter(it -> !sourceLibs.contains(it))
                    .forEach(newLib -> libraryDiffs.getAdded().add(
                            buildDiff.apply(newLib, format("%s: %s", newLib.getName(), newLib.getVersion()))));

            duplicatesMap.forEach((key, value) -> {
                Library currentLib = targetLibs.stream().filter(it -> it.getName().equals(key)).findFirst()
                        .orElse(null);
                if (currentLib != null) {
                    boolean valid = value.stream().map(Library::getVersion).filter(Objects::nonNull)
                            .collect(groupingBy(Function.identity())).keySet().size() > 1;
                    if (valid) {
                        String displayDiff = format("%s: %s", currentLib.getName(),
                                value.stream().map(Library::getVersion).collect(joining(", ")));
                        libraryDiffs.getDuplicates().add(buildDiff.apply(currentLib, displayDiff));
                    }
                }
            });

            libraryDiffs
                    .setHasDiff(!libraryDiffs.getDowngraded().isEmpty() || !libraryDiffs.getUpgraded().isEmpty()
                            || !libraryDiffs.getAdded().isEmpty() || !libraryDiffs.getRemoved().isEmpty());
        }

        return libraryDiffs;
    } catch (Exception e) {
        throw new RuntimeException("Exception occurred while calculating library diffs", e);
    }
}

From source file:org.moe.gradle.MoeSDK.java

private static <T> T createSDKArtifact(@NotNull Project project, String version,
        BiFunction<Configuration, ExternalDependency, T> consumer) {
    Require.nonNull(project);// ww w.  ja v a  2  s.c  om
    Require.nonNull(version);
    final String desc = MOE_GROUP_ID + ":" + MOE_SDK_ARTIFACT_ID + ":" + version + "@zip";

    // Get or create configuration
    Configuration configuration;
    ExternalDependency dependency;
    try {
        configuration = project.getConfigurations().getByName(MOE_SDK_CONFIGURATION_NAME);
        Require.EQ(configuration.getDependencies().size(), 1,
                "Unexpected number of dependencies in moeSDK configuration.");
        dependency = (ExternalDependency) configuration.getDependencies().iterator().next();
    } catch (UnknownConfigurationException ex) {
        configuration = project.getConfigurations().create(MOE_SDK_CONFIGURATION_NAME);
        // Create an external dependency
        dependency = (ExternalDependency) project.getDependencies().create(desc);
        configuration.getDependencies().add(dependency);
    }

    // Add repositories from the buildscript to be able to download the SDK
    Set<ArtifactRepository> addedRepositories = new HashSet<>();
    project.getBuildscript().getRepositories().forEach(repository -> {
        if (!project.getRepositories().contains(repository)) {
            project.getRepositories().add(repository);
            addedRepositories.add(repository);
        }
    });
    project.getRepositories().maven(repo -> {
        repo.setUrl("https://dl.bintray.com/multi-os-engine/maven/");
    });

    try {
        return consumer.apply(configuration, dependency);
    } finally {
        // Remove added repositories
        project.getRepositories().removeAll(addedRepositories);
    }
}

From source file:org.briljantframework.data.vector.AbstractVector.java

@Override
public <T> Vector mapWithIndex(Class<T> cls, BiFunction<Object, ? super T, ?> operator) {
    Vector.Builder builder = new TypeInferenceVectorBuilder();
    for (Object key : this.getIndex()) {
        builder.set(key, operator.apply(key, get(cls, key)));
    }/*from  ww  w  .j  a  v a 2 s.  co m*/
    return builder.build();
}

From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java

@Override
public void registerHandler(String type, BiFunction<Address, byte[], CompletableFuture<byte[]>> handler) {
    handlers.put(type, (message, connection) -> {
        handler.apply(message.sender(), message.payload()).whenComplete((result, error) -> {
            InternalReply.Status status;
            if (error == null) {
                status = InternalReply.Status.OK;
            } else {
                log.warn("An error occurred in a message handler: {}", error);
                status = InternalReply.Status.ERROR_HANDLER_EXCEPTION;
            }//from  w  w w  . j av a  2 s.c o  m
            connection.reply(message, status, Optional.ofNullable(result));
        });
    });
}

From source file:nu.yona.server.analysis.service.ActivityService.java

private <T extends IntervalActivityDto> void addMissingInactivity(Goal activeGoal,
        ZonedDateTime dateAtStartOfInterval, Set<T> activityEntitiesAtDate,
        BiFunction<Goal, ZonedDateTime, T> inactivityEntitySupplier,
        BiConsumer<Goal, T> existingEntityInactivityCompletor) {
    Optional<T> activityForGoal = getActivityForGoal(activityEntitiesAtDate, activeGoal);
    if (activityForGoal.isPresent()) {
        // even if activity was already recorded, it might be that this is
        // not for the complete period
        // so make the interval activity complete with a consumer
        existingEntityInactivityCompletor.accept(activeGoal, activityForGoal.get());
    } else {/*from w w w  .  j a v  a2s  . co  m*/
        activityEntitiesAtDate.add(inactivityEntitySupplier.apply(activeGoal, dateAtStartOfInterval));
    }
}