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:org.lambdamatic.mongodb.apt.template.MetadataTemplateContext.java

/**
 * Full constructor/*  w w w.j a v a  2  s.  c  om*/
 * 
 * @param domainElement the {@link TypeElement} to work on.
 * @param templateFieldBuildFunction the {@link Function} used to generate a single
 *        {@link TemplateField} from a given relevant {@link VariableElement} in the given
 *        {@link TypeElement}.
 * @param templateMethodsBuildFunction the {@link Function} used to generate zero or more
 *        {@link TemplateMethods} from a given relevant {@link VariableElement} in the given
 *        {@link TypeElement}.
 * 
 */
private MetadataTemplateContext(final TypeElement domainElement,
        final BaseAnnotationProcessor annotationProcessor,
        final BiFunction<VariableElement, ProcessingEnvironment, TemplateField> templateFieldBuildFunction,
        final Function<DeclaredType, String> simpleClassNameBuilder, final String templateFileName) {
    super((DeclaredType) domainElement.asType(), annotationProcessor);
    this.domainTypeFields = domainElement.getEnclosedElements().stream()
            .filter(e -> e.getKind() == ElementKind.FIELD)
            .filter(e -> e.getAnnotation(TransientField.class) == null).map(e -> (VariableElement) e)
            .collect(Collectors.toList());
    this.templateFields = this.domainTypeFields.stream().map(f -> {
        return templateFieldBuildFunction.apply(f, annotationProcessor.getProcessingEnvironment());
    }).collect(Collectors.toList());
    this.simpleClassName = simpleClassNameBuilder.apply(this.domainType);
    this.fullyQualifiedClassName = getPackageName() + '.' + this.simpleClassName;
    this.templateFileName = templateFileName;
    this.annotations = Stream.of(domainElement.getAnnotationsByType(EmbeddedDocument.class))
            .map(a -> TemplateAnnotation.Builder.type(EmbeddedDocument.class).build())
            .collect(Collectors.toList());
}

From source file:org.onosproject.store.cluster.messaging.impl.NettyMessagingManager.java

@Override
public void registerHandler(String type, BiFunction<Endpoint, byte[], byte[]> handler, Executor executor) {
    checkPermission(CLUSTER_WRITE);//  w ww  .  ja v  a  2 s  .  c  om
    handlers.put(type, message -> executor.execute(() -> {
        byte[] responsePayload = null;
        Status status = Status.OK;
        try {
            responsePayload = handler.apply(message.sender(), message.payload());
        } catch (Exception e) {
            status = Status.ERROR_HANDLER_EXCEPTION;
        }
        sendReply(message, status, Optional.ofNullable(responsePayload));
    }));
}

From source file:ddf.catalog.definition.impl.DefinitionParser.java

private <T> void handleSection(Changeset changeset, String sectionName, T sectionData,
        BiFunction<Changeset, T, List<Callable<Boolean>>> parser) throws Exception {
    if (sectionData != null) {
        List<Callable<Boolean>> stagedAdds;
        try {//from  ww  w.j  a v a2s  . com
            stagedAdds = parser.apply(changeset, sectionData);
        } catch (Exception e) {
            throw new IllegalArgumentException(String.format("Could not parse %s section.", sectionName), e);
        }

        LOGGER.debug("Committing {}", sectionName);
        commitStaged(stagedAdds);
    }
}

From source file:com.dgtlrepublic.anitomyj.Tokenizer.java

/** Tokenize by bracket. */
private void tokenizeByBrackets() {
    /** a ref to the closing brace of a found opening brace. (e.g "}" if we found an "}") */
    AtomicReference<String> matchingBracket = new AtomicReference<>();

    /** function to find an opening brace */
    BiFunction<Integer, Integer, Integer> findFirstBracket = (start, end) -> {
        for (int i = start; i < end; i++) {
            for (Pair<String, String> bracket : brackets) {
                if (String.valueOf(filename.charAt(i)).equals(bracket.getLeft())) {
                    matchingBracket.set(bracket.getRight());
                    return i;
                }// w  ww . j a  va2 s.com
            }
        }

        return -1;
    };

    boolean isBracketOpen = false;
    for (int i = 0; i < filename.length();) {
        int foundIdx;
        if (!isBracketOpen) {
            /** look for opening brace */
            foundIdx = findFirstBracket.apply(i, filename.length());
        } else {
            /** look for closing brace */
            foundIdx = filename.indexOf(matchingBracket.get(), i);
        }

        TokenRange range = new TokenRange(i, foundIdx == -1 ? filename.length() : foundIdx - i);
        if (range.getSize() > 0) {
            /** check if our range contains any known anime identifies */
            tokenizeByPreidentified(isBracketOpen, range);
        }

        if (foundIdx != -1) {
            /** mark as bracket */
            addToken(TokenCategory.kBracket, true, new TokenRange(range.getOffset() + range.getSize(), 1));
            isBracketOpen = !isBracketOpen;
            i = foundIdx + 1;
        } else {
            break;
        }
    }
}

From source file:de.ks.idnadrev.information.chart.ChartDataEditor.java

private EventHandler<KeyEvent> getInputKeyHandler(int rowNum, int column,
        BiFunction<Integer, Integer, TextField> nextTextField, BiConsumer<Integer, Integer> clipBoardHandler) {
    return e -> {
        KeyCode code = e.getCode();/*from   w w w .j  a  v  a  2  s  .  c  om*/
        if (e.isControlDown() && code == KeyCode.V) {
            clipBoardHandler.accept(rowNum, column);
            e.consume();
        }
        boolean selectNext = false;
        if (e.getCode() == KeyCode.ENTER && !e.isControlDown()) {
            selectNext = true;
        }
        if (selectNext) {
            int next = rowNum + 1;
            TextField textField = nextTextField.apply(next, column);
            if (textField != null) {
                textField.requestFocus();
            }
            e.consume();
        }
    };
}

From source file:org.sejda.impl.sambox.component.AcroFormsMerger.java

private void updateForm(PDAcroForm originalForm, LookupTable<PDAnnotation> widgets,
        BiFunction<PDTerminalField, LookupTable<PDField>, PDTerminalField> getTerminalField,
        BiConsumer<PDField, LookupTable<PDField>> createNonTerminalField) {
    mergeFormDictionary(originalForm);/*ww  w .  j  a va2 s.  c o m*/
    LookupTable<PDField> fieldsLookup = new LookupTable<>();
    for (PDField field : originalForm.getFieldTree()) {
        if (!field.isTerminal()) {
            createNonTerminalField.accept(field, fieldsLookup);
        } else {
            List<PDAnnotationWidget> relevantWidgets = findMappedWidgetsFor((PDTerminalField) field, widgets);
            if (!relevantWidgets.isEmpty()) {
                PDTerminalField terminalField = getTerminalField.apply((PDTerminalField) field, fieldsLookup);
                if (nonNull(terminalField)) {
                    for (PDAnnotationWidget widget : relevantWidgets) {
                        terminalField.addWidgetIfMissing(widget);
                    }
                    terminalField.getCOSObject().removeItems(WIDGET_KEYS);
                }
            } else {
                LOG.info("Discarded not relevant field {}", field.getPartialName());
            }
        }
    }
    this.form.addFields(originalForm.getFields().stream().map(fieldsLookup::lookup).filter(Objects::nonNull)
            .collect(Collectors.toList()));
}

From source file:com.github.jsonj.JsonObject.java

public Stream<JsonElement> map(BiFunction<String, JsonElement, JsonElement> f) {
    return entrySet().stream().map(e -> f.apply(e.getKey(), e.getValue()));
}

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

private <T extends AbstractCreateServiceInstance, S extends AbstractServiceInstance> ServiceInstanceResponse createServiceInstance(
        T command, Function<T, Resource<S>> create, BiFunction<String, T, Resource<S>> update,
        BiFunction<Integer, List<String>, Page<S>> getAllServices,
        Function<T, CloudFoundryServiceInstance> getServiceInstance,
        BiConsumer<T, CloudFoundryServiceInstance> updateValidation, boolean updatable,
        CloudFoundrySpace space) {//from  w ww.j  av  a2s .c o  m
    LastOperation.Type operationType;
    List<String> serviceInstanceQuery = getServiceQueryParams(Collections.singletonList(command.getName()),
            space);
    List<Resource<? extends AbstractServiceInstance>> serviceInstances = new ArrayList<>();
    serviceInstances.addAll(
            collectPageResources("service instances", pg -> getAllServices.apply(pg, serviceInstanceQuery)));

    operationType = CREATE;
    if (serviceInstances.size() == 0) {
        safelyCall(() -> create.apply(command)).map(res -> res.getMetadata().getGuid())
                .orElseThrow(() -> new CloudFoundryApiException(
                        "service instance '" + command.getName() + "' could not be created"));
    } else if (updatable) {
        operationType = UPDATE;
        serviceInstances.stream().findFirst().map(r -> r.getMetadata().getGuid()).orElseThrow(
                () -> new CloudFoundryApiException("Service instance '" + command.getName() + "' not found"));
        CloudFoundryServiceInstance serviceInstance = getServiceInstance.apply(command);
        if (serviceInstance == null) {
            throw new CloudFoundryApiException("No service instances with name '" + command.getName()
                    + "' found in space " + space.getName());
        }
        updateValidation.accept(command, serviceInstance);
        safelyCall(() -> update.apply(serviceInstance.getId(), command));
    }

    return new ServiceInstanceResponse().setServiceInstanceName(command.getName()).setType(operationType);
}

From source file:org.onosproject.store.ecmap.EventuallyConsistentMapImpl.java

@Override
public V compute(K key, BiFunction<K, V, V> recomputeFunction) {
    checkState(!destroyed, destroyedMessage);
    checkNotNull(key, ERROR_NULL_KEY);/*  w w  w. j  a va 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(key, (k, mv) -> {
        previousValue.set(mv);
        V newRawValue = recomputeFunction.apply(key, mv == null ? null : mv.get());
        MapValue<V> newValue = new MapValue<>(newRawValue, timestampProvider.apply(key, newRawValue));
        if (mv == null || newValue.isNewerThan(mv)) {
            updated.set(true);
            return 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:alfio.manager.AdminReservationManager.java

private <T> Result<T> reduceResults(Result<T> r1, Result<T> r2, BiFunction<T, T, T> processData) {
    boolean successful = r1.isSuccess() && r2.isSuccess();
    ResultStatus global = r1.isSuccess() ? r2.getStatus() : r1.getStatus();
    List<ErrorCode> errors = new ArrayList<>();
    if (!successful) {
        errors.addAll(r1.getErrors());/*from   w  w w  .j a v  a2  s.c o m*/
        errors.addAll(r2.getErrors());
        return new Result<>(global, null, errors);
    } else {
        return new Result<>(global, processData.apply(r1.getData(), r2.getData()), errors);
    }
}