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.talend.dataprep.conversions.BeanConversionService.java

/**
 * Similar {@link #convert(Object, Class)} but allow user to specify a constant conversion that overrides previously defined
 * conversions.// www  .j a  v a2s . c  o  m
 *
 * @param source The bean to convert.
 * @param aClass The target class for conversion.
 * @param onTheFlyConvert The function to apply on the transformed bean.
 * @param <U> The source type.
 * @param <T> The target type.
 * @return The converted bean (typed as <code>T</code>).
 */
public <U, T> T convert(U source, Class<T> aClass, BiFunction<U, T, T> onTheFlyConvert) {
    try {
        T converted = aClass.newInstance();
        BeanUtils.copyProperties(source, converted);
        return onTheFlyConvert.apply(source, converted);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.op.handler.KubernetesStatefulSetHandler.java

@Override
public void addRelationships(Map<KubernetesKind, List<KubernetesManifest>> allResources,
        Map<KubernetesManifest, List<KubernetesManifest>> relationshipMap) {
    BiFunction<String, String, String> manifestName = (namespace, name) -> namespace + ":" + name;

    Map<String, KubernetesManifest> services = allResources.getOrDefault(SERVICE, new ArrayList<>()).stream()
            .collect(Collectors.toMap((m) -> manifestName.apply(m.getNamespace(), m.getName()), (m) -> m));

    for (KubernetesManifest manifest : allResources.getOrDefault(STATEFUL_SET, new ArrayList<>())) {
        String serviceName = KubernetesStatefulSetHandler.serviceName(manifest);
        if (StringUtils.isEmpty(serviceName)) {
            continue;
        }/*from   w  w w .  j a v a2  s.  c om*/

        String key = manifestName.apply(manifest.getNamespace(), serviceName);

        if (!services.containsKey(key)) {
            continue;
        }

        KubernetesManifest service = services.get(key);
        relationshipMap.put(manifest, Collections.singletonList(service));
    }
}

From source file:io.dfox.junit.http.JUnitHttpApplication.java

/**
 * Run the specified function using the context created by the specified path.
 *
 * @param path The path to the function//from ww  w  .j a va2s  .  c  o m
 * @param func The function to execute using the runner and parsed path
 * @return The runner Summary
 * @throws InvalidPathException If the path is invalid
 */
public Summary run(final String path, final BiFunction<JUnitHttpRunner, Path, Summary> func)
        throws InvalidPathException {

    final Optional<Path> maybePath = Path.parse(path);

    if (maybePath.isPresent()) {
        Path testPath = maybePath.get();
        final JUnitHttpRunner runner = getRunner(testPath);
        return func.apply(runner, testPath);
    } else {
        throw new InvalidPathException(path);
    }
}

From source file:org.xsystem.sql2.http.impl.HttpHelper.java

public static FileTransfer getFileTransfer(FileFormat fileFormat, Object value,
        BiFunction<String, Object, byte[]> bi) {
    Map row = null;/*w w  w. jav a  2  s  .  c  o m*/
    if (value instanceof List) {
        List lst = (List) value;
        if (!lst.isEmpty()) {
            Object test = lst.get(0);
            if (test instanceof Map) {
                row = (Map) test;
            }
        }
    } else if (value instanceof Map) {
        row = (Map) value;
    }
    if (row == null) {
        return null;
    }
    String evalContenttype = fileFormat.getContenttype();
    String evalFilename = fileFormat.getFilename();
    String evalContent = fileFormat.getContent();
    String evalFormat = fileFormat.getFormat();
    JXPathContext context = JXPathContext.newContext(row);
    context.setLenient(true);
    String contenttype = (String) context.getValue(evalContenttype);
    String filename = (String) context.getValue(evalFilename);
    //byte[] content = (byte[]) context.getValue(evalContent);
    String format = (String) context.getValue(evalFormat);
    Object data = context.getValue(evalContent);

    byte[] content = bi.apply(fileFormat.getStorage(), data);

    if (content == null) {
        return null;
    }
    FileTransfer ret = new FileTransfer();
    ret.setContentType(contenttype);
    ret.setData(content);
    ret.setFileName(filename);
    ret.setFileType(format);
    return ret;
}

From source file:org.apache.metron.common.stellar.evaluators.ArithmeticEvaluator.java

public Token<? extends Number> evaluate(BiFunction<Number, Number, Token<? extends Number>> function,
        Pair<Token<? extends Number>, Token<? extends Number>> p) {
    if (p == null || p.getKey() == null || p.getValue() == null) {
        throw new IllegalArgumentException();
    }//w  w  w  .j a  va2 s .  co  m

    final Number l = p.getKey().getValue();
    final Number r = p.getValue().getValue();

    return function.apply(l == null ? 0 : l, r == null ? 0 : r);
}

From source file:me.Wundero.Ray.variables.Variables.java

/**
 * Register a new variable wrapper/*ww  w  .ja v  a 2 s .c om*/
 */
public boolean registerWrapper(String key, BiFunction<Variable, Text, Text> funct) {
    return registerWrapper(new VariableWrapper(key) {

        @Override
        public Text parse(Variable v, Text returned) {
            return funct.apply(v, returned);
        }
    });
}

From source file:org.talend.dataprep.command.GenericCommand.java

/**
 * Runs a data prep command with the following steps:
 * <ul>/*  ww  w  .j  a va 2  s  .  co  m*/
 * <li>Gets the HTTP command to execute (see {@link #execute(Supplier)}.</li>
 * <li>Gets the behavior to adopt based on returned HTTP code (see {@link #on(HttpStatus...)}).</li>
 * <li>If no behavior was defined for returned code, returns an error as defined in {@link #onError(Function)}</li>
 * <li>If a behavior was defined, invokes defined behavior.</li>
 * </ul>
 *
 * @return A instance of <code>T</code>.
 * @throws Exception If command execution fails.
 */
@Override
protected T run() throws Exception {
    final HttpRequestBase request = httpCall.get();

    // update request header with security token
    if (StringUtils.isNotBlank(authenticationToken)) {
        request.addHeader(AUTHORIZATION, authenticationToken);
    }

    final HttpResponse response;
    try {
        LOGGER.trace("Requesting {} {}", request.getMethod(), request.getURI());
        response = client.execute(request);
    } catch (Exception e) {
        throw onError.apply(e);
    }
    commandResponseHeaders = response.getAllHeaders();

    status = HttpStatus.valueOf(response.getStatusLine().getStatusCode());

    // do we have a behavior for this status code (even an error) ?
    // if yes use it
    BiFunction<HttpRequestBase, HttpResponse, T> function = behavior.get(status);
    if (function != null) {
        try {
            return function.apply(request, response);
        } catch (Exception e) {
            throw onError.apply(e);
        }
    }

    // handle response's HTTP status
    if (status.is4xxClientError() || status.is5xxServerError()) {
        // Http status >= 400 so apply onError behavior
        return callOnError(onError).apply(request, response);
    } else {
        // Http status is not error so apply onError behavior
        return behavior.getOrDefault(status, missingBehavior()).apply(request, response);
    }
}

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

private <T> T createInactivity(UUID userAnonymizedId, UUID goalId, Supplier<T> existingActivityFinder,
        BiFunction<UserAnonymized, Goal, T> creator, Consumer<T> storer) {
    T existingActivity = existingActivityFinder.get();
    if (existingActivity != null) {
        return existingActivity;
    }//from w  w w.  ja va 2s  .com
    UserAnonymized userAnonymized = userAnonymizedService.getUserAnonymizedEntity(userAnonymizedId);
    Goal goal = goalService.getGoalEntityForUserAnonymizedId(userAnonymizedId, goalId);
    T inactivityEntity = creator.apply(userAnonymized, goal);

    storer.accept(inactivityEntity);

    return inactivityEntity;
}

From source file:org.onosproject.d.config.sync.impl.netconf.NetconfDeviceConfigSynchronizerProviderTest.java

/**
 * Creates mock YangRuntimeService./*from  w w  w . j a v a  2s  .  com*/
 *
 * @param body to execute when {@link YangRuntimeService#encode(CompositeData, RuntimeContext)} was called.
 * @return YangRuntimeService instance
 */
TestYangRuntimeService onEncode(BiFunction<CompositeData, RuntimeContext, CompositeStream> body) {
    return new TestYangRuntimeService() {
        @Override
        public CompositeStream encode(CompositeData internal, RuntimeContext context) {
            return body.apply(internal, context);
        }
    };
}

From source file:com.act.lcms.v2.fullindex.Searcher.java

/**
 * Extracts the value bytes from the index corresponding to a list of keys of fixed primitive type.
 * @param cf The column family from which to read.
 * @param keys A list of keys whose values to extract.
 * @param keyBytes The exact number of bytes required by a key; should be uniform for primitive-typed keys
 * @param put A function that writes a key to a ByteBuffer.
 * @param <K> The type of the key.
 * @return An array of arrays of bytes, one per key, containing the values of the key at that position.
 * @throws RocksDBException//  w ww  . j  av a2 s. c  o m
 */
private <K> byte[][] extractValueBytes(ColumnFamilies cf, List<K> keys, int keyBytes,
        BiFunction<ByteBuffer, K, ByteBuffer> put) throws RocksDBException {
    byte[][] valBytes = new byte[keys.size()][];
    ByteBuffer keyBuffer = ByteBuffer.allocate(keyBytes);
    for (int i = 0; i < keys.size(); i++) {
        K k = keys.get(i);
        keyBuffer.clear();
        put.apply(keyBuffer, k).flip();
        // TODO: try compacting the keyBuffer array to be safe?
        valBytes[i] = dbAndHandles.get(cf, keyBuffer.array());
        assert (valBytes[i] != null);
    }
    return valBytes;
}