Java Code Examples for java.util.function.BiFunction

The following examples show how to use java.util.function.BiFunction. 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: uyuni   Source File:    License: GNU General Public License v2.0 6 votes vote down vote up
public void testGetStatusWithSelfMonitoringRestartNeeded() {
    BiFunction<String, Optional<String>, Optional<InputStream>> execCtl =
            (String cmd, Optional<String> pillar) -> {
                return Optional.of(this.getClass()

    MonitoringService.setTomcatJmxStatusSupplier(() -> true);
    MonitoringService.setTaskomaticJmxStatusSupplier(() -> true);
    MonitoringService.setSelfMonitoringStatusSupplier(() -> false);

    Optional<MonitoringService.MonitoringStatus> res = MonitoringService.getStatus();
    assertEquals(null, res.get().getMessages().get("tomcat"));
    assertEquals("enable", res.get().getMessages().get("taskomatic"));
    assertEquals("restart", res.get().getMessages().get("self_monitoring"));
Example 2
private void createFullPackageMetadataImpl(final BiFunction<String, String, String> function, String packageJsonFilename) throws URISyntaxException, IOException {
  try {
    assertThat(BaseUrlHolder.isSet(), is(false));

    File packageJsonFile = new File(NpmPackageRootMetadataUtilsTest.class.getResource(packageJsonFilename).toURI());
    File archive = tempFolderRule.newFile();
    Map<String, Object> packageJson = new NpmPackageParser()
        .parsePackageJson(() -> ArchiveUtils.pack(archive, packageJsonFile, "package/package.json"));

    NestedAttributesMap packageMetadata = NpmPackageRootMetadataUtils
        .createFullPackageMetadata(new NestedAttributesMap("metadata", packageJson),

  finally {
Example 3
 * Common function to resolve references from key.
 * @param draftBuilder                 {@link ProductDraftBuilder} to update
 * @param resourceIdentifier           resourceIdentifier instance from which key is read
 * @param keyToIdMapper                function which calls respective service to fetch the reference by key
 * @param idToResourceIdentifierMapper function which creates {@link ResourceIdentifier} instance from fetched id
 * @param resourceIdentifierSetter     function which will set the resolved reference to the {@code productDraft}
 * @param <T>                          type of reference (e.g. {@link State}, {@link TaxCategory}
 * @return {@link CompletionStage} containing {@link ProductDraftBuilder} with resolved &lt;T&gt; reference.
private <T, S extends ResourceIdentifier<T>> CompletionStage<ProductDraftBuilder> resolveResourceIdentifier(
    @Nonnull final ProductDraftBuilder draftBuilder,
    @Nullable final S resourceIdentifier,
    @Nonnull final Function<String, CompletionStage<Optional<String>>> keyToIdMapper,
    @Nonnull final Function<String, S> idToResourceIdentifierMapper,
    @Nonnull final BiFunction<ProductDraftBuilder, S, ProductDraftBuilder> resourceIdentifierSetter)
    throws ReferenceResolutionException {

    if (resourceIdentifier == null) {
        return completedFuture(draftBuilder);

    final String resourceKey = getKeyFromResourceIdentifier(resourceIdentifier);

    return keyToIdMapper
        .thenApply(optId -> optId
            .map(resourceIdentifierToSet -> resourceIdentifierSetter.apply(draftBuilder, resourceIdentifierToSet))
Example 4
Source Project: buck   Source File:    License: Apache License 2.0 6 votes vote down vote up
/** Format a single config change */
public static String formatConfigChange(Entry<String, ConfigChange> change, boolean truncate) {
  String prevVal = change.getValue().getPrevValue();
  String newVal = change.getValue().getNewValue();
  BiFunction<String, Integer, String> abbrev =
      (value, width) -> truncate ? MoreStrings.abbreviate(value, width) : value;
  if (prevVal == null) {
    return String.format("New value %s='%s'", change.getKey(), abbrev.apply(newVal, 80));
  if (newVal == null) {
    return String.format("Removed value %s='%s'", change.getKey(), abbrev.apply(prevVal, 80));

  return String.format(
      "Changed value %s='%s' (was '%s')",
      change.getKey(), abbrev.apply(newVal, 40), abbrev.apply(prevVal, 40));
Example 5
 * Given a draft of {@code D} (e.g. {@link CategoryDraft}) this method attempts to resolve it's custom type
 * reference to return {@link CompletionStage} which contains a new instance of the draft with the resolved
 * custom type reference. The key of the custom type is taken from the from the id field of the reference.
 * <p>The method then tries to fetch the key of the custom type, optimistically from a
 * cache. If the key is is not found, the resultant draft would remain exactly the same as the passed
 * draft (without a custom type reference resolution).
 * @param draftBuilder the draft builder to resolve it's references.
 * @param customGetter a function to return the CustomFieldsDraft instance of the draft builder.
 * @param customSetter a function to set the CustomFieldsDraft instance of the builder and return this builder.
 * @param errorMessage the error message to inject in the {@link ReferenceResolutionException} if it occurs.
 * @return a {@link CompletionStage} that contains as a result a new draft instance with resolved custom
 *         type references or, in case an error occurs during reference resolution,
 *         a {@link ReferenceResolutionException}.
protected CompletionStage<B> resolveCustomTypeReference(
    @Nonnull final B draftBuilder,
    @Nonnull final Function<B, CustomFieldsDraft> customGetter,
    @Nonnull final BiFunction<B, CustomFieldsDraft, B> customSetter,
    @Nonnull final String errorMessage) {

    final CustomFieldsDraft custom = customGetter.apply(draftBuilder);
    if (custom != null) {
        return getCustomTypeId(custom, errorMessage)
            .thenApply(resolvedTypeIdOptional ->
                    customSetter.apply(draftBuilder, ofTypeIdAndJson(resolvedTypeId, custom.getFields())))
    return CompletableFuture.completedFuture(draftBuilder);
Example 6
public static void main(String[] args) {
    Map<Integer,Double> unwrapped = new HashMap<>();
    unwrapped.put(1, 1.0);
    unwrapped.put(2, 2.0);
    unwrapped.put(3, 3.0);

    Map<Integer,Double> wrapped = Collections.checkedMap(unwrapped, Integer.class, Double.class);

    BiFunction evil = (k, v) -> (((int)k) % 2 != 0) ? v : "evil";

    try {
        System.out.printf("Bwahaha! I have defeated you! %s\n", wrapped);
        throw new RuntimeException("String added to checked Map<Integer,Double>");
    } catch (ClassCastException thwarted) {
        System.out.println("Curses! Foiled again!");
Example 7
	Flux<Integer> transformFlux(Flux<Integer> f) {
		Flux<String> otherStream = Flux.just("test", "test2", "test3");
//		System.out.println("Providing new downstream");

		Scheduler asyncGroup = Schedulers.newParallel("flux-p-tck", 2);

		BiFunction<Integer, String, Integer> combinator = (t1, t2) -> t1;

		return f.publishOn(sharedGroup)
		        .flatMap(stream -> stream.publishOn(asyncGroup)
				                          .scan((prev, next) -> next)
				                          .map(integer -> -integer)
				                          .filter(integer -> integer <= 0)
				                          .map(integer -> -integer)
				                          .bufferTimeout(batch, Duration.ofMillis(50))
				                          .flatMap(i ->, otherStream, combinator))
Example 8
Source Project: openjdk-8-source   Source File:    License: GNU General Public License v2.0 6 votes vote down vote up
public synchronized void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
    Objects.requireNonNull(function);     // explicit check required in case
                                          // table is empty.
    final int expectedModCount = modCount;

    Entry<K, V>[] tab = (Entry<K, V>[])table;
    for (Entry<K, V> entry : tab) {
        while (entry != null) {
            entry.value = Objects.requireNonNull(
                function.apply(entry.key, entry.value));
            entry =;

            if (expectedModCount != modCount) {
                throw new ConcurrentModificationException();
Example 9
Source Project: pravega   Source File:    License: Apache License 2.0 6 votes vote down vote up
private <T> CompletableFuture<T> applyToSegment(String segmentName, BiFunction<TableEntry, Duration, CompletableFuture<T>> ifExists,
                                                Supplier<CompletableFuture<T>> ifNotExists, Duration timeout) {
    ArrayView key = getTableKey(segmentName);
    TimeoutTimer timer = new TimeoutTimer(timeout);
    return this.tableStore
            .get(this.metadataSegmentName, Collections.singletonList(key), timer.getRemaining())
            .thenComposeAsync(existingData -> {
                assert existingData.size() == 1 : "Expecting only one result";
                if (existingData.get(0) == null) {
                    // We don't know anything about this Segment.
                    return ifNotExists.get();

                // We have an entry.
                return ifExists.apply(existingData.get(0), timer.getRemaining());
            }, this.executor);
Example 10
Source Project: selenium   Source File:    License: Apache License 2.0 6 votes vote down vote up
public BiFunction<JsonInput, PropertySetting, UUID> apply(Type type) {
  return (jsonInput, propertySetting) -> {
    String toCoerce;

    switch (jsonInput.peek()) {
      case NAME:
        toCoerce = jsonInput.nextName();

      case STRING:
        toCoerce = jsonInput.nextString();

        throw new JsonException("Unable to coerce type to URL: " + jsonInput.peek());

    return UUID.fromString(toCoerce);
Example 11
Source Project: atomix   Source File:    License: Apache License 2.0 5 votes vote down vote up
 * Resends a request due to a request failure, resetting the connection if necessary.
protected <T extends RaftRequest> void retryRequest(Throwable cause, T request, BiFunction sender, int count, int selectionId, CompletableFuture future) {
  // If the connection has not changed, reset it and connect to the next server.
  if (this.selectionId == selectionId) {
    log.trace("Resetting connection. Reason: {}", cause.getMessage());
    this.currentNode = null;

  // Attempt to send the request again.
  sendRequest(request, sender, count, future);
Example 12
Source Project: keycloak   Source File:    License: Apache License 2.0 5 votes vote down vote up
protected BiFunction<WebElement, String, Boolean> deselect() {
    return (webElement, name) -> {
        List<WebElement> tds = webElement.findElements(tagName("td"));

        if (!UIUtils.getTextFromElement(tds.get(0)).isEmpty()) {
            if (UIUtils.getTextFromElement(tds.get(0)).equals(name)) {
                return true;

        return false;
Example 13
Source Project: hono   Source File:    License: Eclipse Public License 2.0 5 votes vote down vote up
 * Closes the command consumer and removes the subscription entry for the given topic.
 * @param topic The topic string to unsubscribe.
 * @param onConsumerRemovedFunction The function to be invoked if not {@code null} during removal of a subscription.
 *                                  The first parameter is the tenant id, the second parameter the device id.
 *                                  To be returned is a future indicating the outcome of the function.
 * @param spanContext The span context (may be {@code null}).
 * @throws NullPointerException if topic is {@code null}.
 * @return A future indicating the outcome of the operation.
public Future<Void> removeSubscription(final String topic,
        final BiFunction<String, String, Future<Void>> onConsumerRemovedFunction, final SpanContext spanContext) {

    final TriTuple<CommandSubscription, ProtocolAdapterCommandConsumer, Object> removed = subscriptions.remove(topic);
    if (removed != null) {
        final CommandSubscription subscription =;
        final Future<Void> functionFuture = onConsumerRemovedFunction != null
                ? onConsumerRemovedFunction.apply(subscription.getTenant(), subscription.getDeviceId())
                : Future.succeededFuture();
        final ProtocolAdapterCommandConsumer commandConsumer = removed.two();
        return CompositeFuture
                .join(functionFuture, closeCommandConsumer(subscription, commandConsumer, spanContext)).mapEmpty();
    } else {
        LOG.debug("Cannot remove subscription; none registered for topic [{}]", topic);
        return Future.failedFuture(String.format("Cannot remove subscription; none registered for topic [%s]", topic));
Example 14
 * Returns a {@link Rectangle2D} representing an {@link Operator}. First tries to look up the
 * data from the model, if that fails it determines a position automatically. Uses the given
 * {@link ProcessRendererModel} to determine layout properties. May use a supplied {@link BiFunction}
 * to check some dependencies
 * @param op
 * 		the operator for which a rectangle should be created
 * @param model
 * 		the reference process model
 * @param checkDependencies
 * 		an optional dependency check
 * @return the rectangle representing the operator, never {@code null}
 * @since 8.2
public static Rectangle2D createOperatorPosition(Operator op, ProcessRendererModel model, BiFunction<Operator, ProcessRendererModel, Boolean> checkDependencies) {
	Rectangle2D rect = model.getOperatorRect(op);
	if (rect != null) {
		return rect;

	// if connected (e.g. because inserted by quick fix), place in the middle
	if (op.getInputPorts().getNumberOfPorts() > 0 && op.getOutputPorts().getNumberOfPorts() > 0
			&& op.getInputPorts().getPortByIndex(0).isConnected()
			&& op.getOutputPorts().getPortByIndex(0).isConnected()
			// see ProcessRendererController#isDependenciesOk
			&& (checkDependencies == null || checkDependencies.apply(op, model))) {
		Point2D sourcePos = ProcessDrawUtils.createPortLocation(op.getInputPorts().getPortByIndex(0).getSource(), model);
		Point2D destPos = ProcessDrawUtils.createPortLocation(op.getOutputPorts().getPortByIndex(0).getDestination(),
		if (sourcePos != null && destPos != null) {
			double x = Math.floor((sourcePos.getX() + destPos.getX()) / 2d - ProcessDrawer.OPERATOR_WIDTH / 2d);
			double y = Math.floor((sourcePos.getY() + destPos.getY()) / 2d - ProcessDrawer.PORT_OFFSET);
			return new Rectangle2D.Double(x, y, ProcessDrawer.OPERATOR_WIDTH, calcHeighForOperator(op));
	// otherwise, or, if positions were not known in previous approach, position according to index
	int index = 0;
	ExecutionUnit unit = op.getExecutionUnit();
	if (unit != null) {
		index = unit.getOperators().indexOf(op);
	return autoPosition(op, index, model);
Example 15
Source Project: zipkin-storage-kafka   Source File:    License: Apache License 2.0 5 votes vote down vote up
GetRemoteServiceNamesCall(KafkaStreams traceStoreStream, String serviceName,
    BiFunction<String, Integer, String> httpBaseUrl) {
  super(traceStoreStream, REMOTE_SERVICE_NAMES_STORE_NAME, httpBaseUrl,
      "/serviceNames/" + serviceName + "/remoteServiceNames", serviceName);
  this.traceStoreStream = traceStoreStream;
  this.serviceName = serviceName;
  this.httpBaseUrl = httpBaseUrl;
Example 16
Source Project: armeria   Source File:    License: Apache License 2.0 5 votes vote down vote up
private RetryRule build(RetryDecision decision) {
    if (decision != RetryDecision.noRetry() &&
        exceptionFilter() == null && responseHeadersFilter() == null && responseTrailersFilter() == null) {
        throw new IllegalStateException("Should set at least one retry rule if a backoff was set.");
    final BiFunction<? super ClientRequestContext, ? super Throwable, Boolean> ruleFilter =
            AbstractRuleBuilderUtil.buildFilter(requestHeadersFilter(), responseHeadersFilter(),
                                                responseTrailersFilter(), exceptionFilter(), false);
    return build(ruleFilter, decision, responseTrailersFilter() != null);
Example 17
Source Project: cyclops   Source File:    License: Apache License 2.0 5 votes vote down vote up
public <T2, R1, R2, R> ListT<W,R> forEach3M(Function<? super T, ? extends ListT<W,R1>> value1,
                                            BiFunction<? super T, ? super R1, ? extends ListT<W,R2>> value2,
                                            Function3<? super T, ? super R1, ? super R2, ? extends R> yieldingFunction) {

    return this.flatMapT(in->value1.apply(in).flatMapT(in2-> value2.apply(in,in2)

Example 18
Source Project: armeria   Source File:    License: Apache License 2.0 5 votes vote down vote up
 * Creates a new {@link ThrottlingStrategy} that determines whether a request should be accepted or not
 * using a given {@link BiFunction} instance.
public static <T extends Request> ThrottlingStrategy<T> of(
        BiFunction<ServiceRequestContext, T, CompletionStage<Boolean>> function) {
    return new ThrottlingStrategy<T>(null) {
        public CompletionStage<Boolean> accept(ServiceRequestContext ctx, T request) {
            return function.apply(ctx, request);
Example 19
Source Project: flink   Source File:    License: Apache License 2.0 5 votes vote down vote up
public CompletableFuture<Acknowledge> freeSlot(AllocationID allocationId, Throwable cause, Time timeout) {
	final BiFunction<AllocationID, Throwable, CompletableFuture<Acknowledge>> currentFreeSlotFunction = freeSlotFunction;

	if (currentFreeSlotFunction != null) {
		return currentFreeSlotFunction.apply(allocationId, cause);
	} else {
		return CompletableFuture.completedFuture(Acknowledge.get());
Example 20
Source Project: doma   Source File:    License: Apache License 2.0 5 votes vote down vote up
public String getTableName(BiFunction<NamingType, String, String> namingFunction) {
  if (__tableName.isEmpty()) {
    return namingFunction.apply(getNamingType(), getName());
  return __tableName;
Example 21
Source Project: sailfish-core   Source File:    License: Apache License 2.0 5 votes vote down vote up
public void manageTagToRows(List<AggregatedReportRow> rows, BiFunction<TestCaseRun, List<Tag>, Boolean> targetAction,
                            List<Tag> tags) {
    List<Object> testCaseRuns = new ArrayList<>();
    manageTagToRows(rows, targetAction, tags, testCaseRuns);
    if (!testCaseRuns.isEmpty()) {
Example 22
public void assertRequest(
    BiFunction<String, String, HttpStatus> request,
    String username,
    String credential,
    HttpStatus expected) {

  HttpStatus responseStatus = request.apply(username, credential);
          "Authentication failed with unexpected return code for user '%s:%s' ",
          username, credential),
Example 23
Source Project: jdk8u-jdk   Source File:    License: GNU General Public License v2.0 5 votes vote down vote up
private <U,V> CompletableFuture<V> biApplyStage(
    Executor e, CompletionStage<U> o,
    BiFunction<? super T,? super U,? extends V> f) {
    CompletableFuture<U> b;
    if (f == null || (b = o.toCompletableFuture()) == null)
        throw new NullPointerException();
    CompletableFuture<V> d = new CompletableFuture<V>();
    if (e != null || !d.biApply(this, b, f, null)) {
        BiApply<T,U,V> c = new BiApply<T,U,V>(e, d, this, b, f);
        bipush(b, c);
    return d;
Example 24
Source Project: openjdk-jdk9   Source File:    License: GNU General Public License v2.0 5 votes vote down vote up
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
    int expectedModCount = modCount;

    for (Entry<K, V> e = getFirstEntry(); e != null; e = successor(e)) {
        e.value = function.apply(e.key, e.value);

        if (expectedModCount != modCount) {
            throw new ConcurrentModificationException();
Example 25
public DriverFactory getDriverFactory() {
    String gridUrl = getProperty(SELENIUM_GRID_URL);
    Map<String, Object> capabilities = getCapabilities();
    DesiredCapabilities desiredCapabilities = new DesiredCapabilities(capabilities);
    BiFunction<URL, Capabilities, RemoteWebDriver> constr = getRemoteWebDriverConstructor();
    return new RemoteDriverFactory(constr, gridUrl, desiredCapabilities);
Example 26
Source Project: es6draft   Source File:    License: MIT License 5 votes vote down vote up
RuntimeContext(Supplier<? extends RuntimeContext.Data> runtimeData, Function<Realm, ? extends RealmData> realmData,
        BiFunction<RuntimeContext, ScriptLoader, ? extends ModuleLoader> moduleLoader, Locale locale,
        TimeZone timeZone, Path baseDirectory, Console console, ScriptCache scriptCache, ExecutorService executor,
        BiConsumer<ExecutionContext, Throwable> errorReporter, ExecutorService workerExecutor,
        BiConsumer<ExecutionContext, Throwable> workerErrorReporter, Futex futex,
        Consumer<ExecutionContext> debugger, BiFunction<String, MethodType, MethodHandle> nativeCallResolver,
        BiConsumer<ScriptObject, ModuleRecord> importMeta, EnumSet<CompatibilityOption> options,
        EnumSet<Parser.Option> parserOptions, EnumSet<Compiler.Option> compilerOptions) {
    this.runtimeData = runtimeData;
    this.contextData = runtimeData.get();
    this.realmData = realmData;
    this.moduleLoader = moduleLoader;
    this.locale = locale;
    this.timeZone = timeZone;
    this.baseDirectory = baseDirectory;
    this.console = console;
    this.scriptCache = scriptCache;
    this.executor = executor != null ? executor : createThreadPoolExecutor();
    this.shutdownExecutorOnFinalization = executor == null;
    this.workerExecutor = workerExecutor != null ? workerExecutor : createWorkerThreadPoolExecutor();
    this.shutdownWorkerExecutorOnFinalization = workerExecutor == null;
    this.errorReporter = errorReporter;
    this.workerErrorReporter = workerErrorReporter;
    this.futex = futex;
    this.debugger = debugger;
    this.nativeCallResolver = nativeCallResolver;
    this.importMeta = importMeta;
    this.options = EnumSet.copyOf(options);
    this.parserOptions = EnumSet.copyOf(parserOptions);
    this.compilerOptions = EnumSet.copyOf(compilerOptions);
Example 27
Source Project: Bytecoder   Source File:    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked") // Function must actually operate over strings
private Object implComputeIfPresent(Object key, BiFunction<? super Object,
        ? super Object, ? extends Object> remappingFunction) {
    if (key instanceof String) {
        if (isProviderInfo(key)) {
            return null;
        legacyChanged = true;
    return super.computeIfPresent(key, remappingFunction);
Example 28
Source Project: caffeine   Source File:    License: Apache License 2.0 5 votes vote down vote up
@CheckNoWriter @CheckNoStats
@Test(dataProvider = "caches", expectedExceptions = NullPointerException.class)
@CacheSpec(removalListener = { Listener.DEFAULT, Listener.REJECTING })
public void getAllBifunction_nullBifunction(
    AsyncCache<Integer, Integer> cache, CacheContext context) {
  BiFunction<Iterable<? extends Integer>, Executor, CompletableFuture<Map<Integer, Integer>>> f;
  cache.getAll(context.original().keySet(), (f = null));
Example 29
private <T> CallOptions patchOption(CallOptions baseOptions, Function<CallOptions, T> getter, BiFunction<CallOptions, T, CallOptions> setter) {
    T baseValue = getter.apply(baseOptions);
    if (baseValue == null || overwrite) {
        T patchValue = getter.apply(defaultOptions);
        if (patchValue != null) {
            return setter.apply(baseOptions, patchValue);

    return baseOptions;
Example 30
public <U> DependentPromise<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn) {
    return handleAsync(fn, defaultEnlistOrigin());