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.apache.nifi.processors.orc.PutORCTest.java

private void verifyORCUsers(final Path orcUsers, final int numExpectedUsers,
        BiFunction<List<Object>, Integer, Void> assertFunction) throws IOException {
    Reader reader = OrcFile.createReader(orcUsers, OrcFile.readerOptions(testConf));
    RecordReader recordReader = reader.rows();

    TypeInfo typeInfo = TypeInfoUtils.getTypeInfoFromTypeString(
            "struct<name:string,favorite_number:int,favorite_color:string,scale:double>");
    StructObjectInspector inspector = (StructObjectInspector) OrcStruct.createObjectInspector(typeInfo);

    int currUser = 0;
    Object nextRecord = null;/*from   w ww.  j a va  2s . c o m*/
    while ((nextRecord = recordReader.next(nextRecord)) != null) {
        Assert.assertNotNull(nextRecord);
        Assert.assertTrue("Not an OrcStruct", nextRecord instanceof OrcStruct);
        List<Object> x = inspector.getStructFieldsDataAsList(nextRecord);

        if (assertFunction == null) {
            assertEquals("name" + currUser, x.get(0).toString());
            assertEquals(currUser, ((IntWritable) x.get(1)).get());
            assertEquals("blue" + currUser, x.get(2).toString());
            assertEquals(10.0 * currUser, ((DoubleWritable) x.get(3)).get(), Double.MIN_VALUE);
        } else {
            assertFunction.apply(x, currUser);
        }
        currUser++;
    }

    assertEquals(numExpectedUsers, currUser);
}

From source file:org.jsweet.transpiler.extension.Java2TypeScriptAdapter.java

protected String getMappedDocType(JCTree typeTree, Type type) {
    String qualifiedName = type.toString();
    if (typeTree instanceof JCTypeApply) {
        return getMappedDocType(((JCTypeApply) typeTree).clazz, ((JCTypeApply) typeTree).clazz.type);
    }/*w w w  .  j  a v a  2 s  .  c o m*/
    if (type instanceof TypeVar) {
        TypeVar typeVar = (TypeVar) typeTree.type;
        if (typeVar.getUpperBound() == null) {
            return "*";
        } else {
            return getMappedDocType(null, typeVar.getUpperBound());
        }
    }
    boolean isMapped = false;
    if (typeTree != null) {
        for (BiFunction<ExtendedElement, String, Object> mapping : getFunctionalTypeMappings()) {
            Object mapped = mapping.apply(new ExtendedElementSupport(typeTree), qualifiedName);
            if (mapped instanceof String) {
                isMapped = true;
                qualifiedName = (String) mapped;
            } else if (mapped instanceof JCTree) {
                isMapped = true;
                qualifiedName = getMappedDocType((JCTree) mapped, ((JCTree) mapped).type);
            }
        }
    }
    if (isMappedType(qualifiedName)) {
        isMapped = true;
        qualifiedName = getTypeMappingTarget(qualifiedName);
    }
    if (!isMapped && !type.isPrimitiveOrVoid()) {
        qualifiedName = context.getRootRelativeName(null, type.tsym);
    }
    return "any".equals(qualifiedName) ? "*" : qualifiedName;
}

From source file:org.hawkular.inventory.impl.tinkerpop.test.BasicTest.java

@Test
public void testEnvironments() throws Exception {
    BiFunction<String, String, Void> test = (tenantId, id) -> {
        GremlinPipeline<Graph, Vertex> q = new GremlinPipeline<Graph, Vertex>(graph).V().has("__type", "tenant")
                .has("__eid", tenantId).out("contains").has("__type", "environment").has("__eid", id)
                .cast(Vertex.class);

        Iterator<Vertex> envs = q.iterator();
        assert envs.hasNext();
        envs.next();//from  w w  w . j a va  2s .  com
        assert !envs.hasNext();

        //query, we should get the same results
        Environment env = inventory.tenants().get(tenantId).environments().get(id).entity();
        assert env.getId().equals(id);

        return null;
    };

    test.apply("com.acme.tenant", "production");
    test.apply("com.example.tenant", "test");

    GraphQuery query = graph.query().has("__type", "environment");
    assert StreamSupport.stream(query.vertices().spliterator(), false).count() == 2;
}

From source file:org.commonjava.indy.pkg.maven.content.MavenMetadataGenerator.java

private MetadataIncrementalResult mergeMissing(final Group group,
        final MetadataIncrementalResult incrementalResult, final String toMergePath, String description,
        BiFunction<ArtifactStore, String, Callable<MetadataResult>> func) throws IndyWorkflowException {
    Set<ArtifactStore> missing = incrementalResult.missing;
    Metadata master = incrementalResult.result;

    // TODO: This should be the outer wrapper for download- or generate-specific behavior.
    logger.debug("Download missing member metadata for {}, missing: {}, size: {}", group.getKey(), missing,
            missing.size());/*ww w.ja  v a 2s . c  o  m*/

    DrainingExecutorCompletionService<MetadataResult> svc = new DrainingExecutorCompletionService<>(
            mavenMDGeneratorService);

    detectOverloadVoid(() -> missing.forEach(store -> svc.submit(func.apply(store, toMergePath))));

    Set<ArtifactStore> resultingMissing = new HashSet<>(); // return stores failed download
    Set<StoreKey> included = new HashSet<>();
    try {
        svc.drain(mr -> {
            if (mr != null) {
                if (mr.missing) {
                    resultingMissing.add(mr.store);
                } else {
                    included.add(mr.store.getKey());
                    merger.merge(master, mr.metadata, group, toMergePath);
                    putToMetadataCache(mr.store.getKey(), toMergePath, new MetadataInfo(mr.metadata));
                }
            }
        });
    } catch (InterruptedException e) {
        logger.debug("Interrupted while merging " + description + " member metadata.");
    } catch (ExecutionException e) {
        throw new IndyWorkflowException("Failed to merge downloaded " + description + " member metadata.", e);
    }

    return new MetadataIncrementalResult(resultingMissing, included, master);
}

From source file:org.jsweet.transpiler.typescript.Java2TypeScriptAdapter.java

@Override
public AbstractTreePrinter<C> substituteAndPrintType(JCTree typeTree, boolean arrayComponent,
        boolean inTypeParameters, boolean completeRawTypes, boolean disableSubstitution) {
    if (typeTree.type.tsym instanceof TypeVariableSymbol) {
        if (typeVariablesToErase.contains(typeTree.type.tsym)) {
            return print("any");
        }//from www.j ava  2 s  . com
    }
    if (!disableSubstitution) {
        if (context.hasAnnotationType(typeTree.type.tsym, ANNOTATION_ERASED)) {
            return print("any");
        }
        if (context.hasAnnotationType(typeTree.type.tsym, ANNOTATION_OBJECT_TYPE)) {
            // TODO: in case of object types, we should replace with the org
            // object type...
            return print("any");
        }
        String typeFullName = typeTree.type.getModelType().toString(); // typeTree.type.tsym.getQualifiedName().toString();
        if (Runnable.class.getName().equals(typeFullName)) {
            if (arrayComponent) {
                print("(");
            }
            print("() => void");
            if (arrayComponent) {
                print(")");
            }
            return getPrinter();
        }
        if (typeTree instanceof JCTypeApply) {
            JCTypeApply typeApply = ((JCTypeApply) typeTree);
            String typeName = typeApply.clazz.toString();
            if (typeFullName.startsWith(TUPLE_CLASSES_PACKAGE + ".")) {
                print("[");
                for (JCExpression argument : typeApply.arguments) {
                    substituteAndPrintType(argument, arrayComponent, inTypeParameters, completeRawTypes, false)
                            .print(",");
                }
                if (typeApply.arguments.length() > 0) {
                    getPrinter().removeLastChar();
                }
                print("]");
                return getPrinter();
            }
            if (typeFullName.startsWith(UNION_CLASS_NAME)) {
                print("(");
                for (JCExpression argument : typeApply.arguments) {
                    print("(");
                    substituteAndPrintType(argument, arrayComponent, inTypeParameters, completeRawTypes, false);
                    print(")");
                    print("|");
                }
                if (typeApply.arguments.length() > 0) {
                    getPrinter().removeLastChar();
                }
                print(")");
                return getPrinter();
            }
            if (typeFullName.startsWith(UTIL_PACKAGE + ".") || typeFullName.startsWith("java.util.function.")) {
                if (typeName.endsWith("Consumer") || typeName.startsWith("Consumer")) {
                    if (arrayComponent) {
                        print("(");
                    }
                    print("(");
                    if (typeName.startsWith("Int") || typeName.startsWith("Long")
                            || typeName.startsWith("Double")) {
                        print("p0 : number");
                    } else {
                        printArguments(typeApply.arguments);
                    }
                    print(") => void");
                    if (arrayComponent) {
                        print(")");
                    }
                    return getPrinter();
                } else if (typeName.endsWith("Function") || typeName.startsWith("Function")) {
                    if (arrayComponent) {
                        print("(");
                    }
                    print("(");
                    if (typeName.startsWith("Int") || typeName.startsWith("Long")
                            || typeName.startsWith("Double")) {
                        print("p0 : number");
                    } else {
                        printArguments(typeApply.arguments.subList(0, typeApply.arguments.length() - 1));
                    }
                    print(") => ");
                    substituteAndPrintType(typeApply.arguments.get(typeApply.arguments.length() - 1),
                            arrayComponent, inTypeParameters, completeRawTypes, false);
                    if (arrayComponent) {
                        print(")");
                    }
                    return getPrinter();
                } else if (typeName.endsWith("Supplier") || typeName.startsWith("Supplier")) {
                    if (arrayComponent) {
                        print("(");
                    }
                    print("(");
                    print(") => ");
                    if (typeName.startsWith("Int") || typeName.startsWith("Long")
                            || typeName.startsWith("Double")) {
                        print("number");
                    } else {
                        substituteAndPrintType(typeApply.arguments.get(0), arrayComponent, inTypeParameters,
                                completeRawTypes, false);
                    }
                    if (arrayComponent) {
                        print(")");
                    }
                    return getPrinter();
                } else if (typeName.endsWith("Predicate")) {
                    if (arrayComponent) {
                        print("(");
                    }
                    print("(");
                    if (typeName.startsWith("Int") || typeName.startsWith("Long")
                            || typeName.startsWith("Double")) {
                        print("p0 : number");
                    } else {
                        printArguments(typeApply.arguments);
                    }
                    print(") => boolean");
                    if (arrayComponent) {
                        print(")");
                    }
                    return getPrinter();
                } else if (typeName.endsWith("Operator")) {
                    if (arrayComponent) {
                        print("(");
                    }
                    print("(");
                    printArgument(typeApply.arguments.head, 1);
                    if (typeName.startsWith("Binary")) {
                        print(", ");
                        printArgument(typeApply.arguments.head, 2);
                    }
                    print(") => ");
                    substituteAndPrintType(typeApply.arguments.head, arrayComponent, inTypeParameters,
                            completeRawTypes, false);
                    if (arrayComponent) {
                        print(")");
                    }
                    return getPrinter();
                }
            }
            if (typeFullName.startsWith(Class.class.getName() + "<")) {
                return print("any");
            }
        } else {
            if (!(typeTree instanceof JCArrayTypeTree) && typeFullName.startsWith("java.util.function.")) {
                // case of a raw functional type (programmer's mistake)
                return print("any");
            }
            if (typesMapping.containsKey(typeFullName)) {
                print(typesMapping.get(typeFullName));
                if (completeRawTypes && !typeTree.type.tsym.getTypeParameters().isEmpty()
                        && !typesMapping.get(typeFullName).equals("any")) {
                    getPrinter().printAnyTypeArguments(typeTree.type.tsym.getTypeParameters().size());
                }
                return getPrinter();
            }
        }
        for (BiFunction<JCTree, String, Object> mapping : complexTypesMapping) {
            Object mapped = mapping.apply(typeTree, typeFullName);
            if (mapped instanceof String) {
                getPrinter().print((String) mapped);
                return getPrinter();
            } else if (mapped instanceof JCTree) {
                substituteAndPrintType((JCTree) mapped);
                return getPrinter();
            }
        }
    }
    return super.substituteAndPrintType(typeTree, arrayComponent, inTypeParameters, completeRawTypes,
            disableSubstitution);
}

From source file:org.apache.nifi.processors.hive.TestPutHive3Streaming.java

private void configure(final PutHive3Streaming processor, final int numUsers, final int failAfter,
        final BiFunction<Integer, MockRecordParser, Void> recordGenerator) throws InitializationException {
    runner = TestRunners.newTestRunner(processor);
    runner.setProperty(PutHive3Streaming.HIVE_CONFIGURATION_RESOURCES, TEST_CONF_PATH);
    MockRecordParser readerFactory = new MockRecordParser();
    final RecordSchema recordSchema = AvroTypeUtil.createSchema(schema);
    for (final RecordField recordField : recordSchema.getFields()) {
        readerFactory.addSchemaField(recordField.getFieldName(), recordField.getDataType().getFieldType(),
                recordField.isNullable());
    }/*from  w  ww  .j a  v a2  s.  c o m*/

    if (recordGenerator == null) {
        for (int i = 0; i < numUsers; i++) {
            readerFactory.addRecord("name" + i, i, "blue" + i, i * 10.0);
        }
    } else {
        recordGenerator.apply(numUsers, readerFactory);
    }

    readerFactory.failAfter(failAfter);

    runner.addControllerService("mock-reader-factory", readerFactory);
    runner.enableControllerService(readerFactory);

    runner.setProperty(PutHive3Streaming.RECORD_READER, "mock-reader-factory");
}

From source file:org.apache.nifi.web.api.ApplicationResource.java

/**
 * Executes an action through the service facade using the specified revision.
 *
 * @param serviceFacade service facade//  w  w  w .  j  av  a  2 s .  c om
 * @param revision      revision
 * @param authorizer    authorizer
 * @param verifier      verifier
 * @param action        executor
 * @return the response
 */
protected <T extends Entity> Response withWriteLock(final NiFiServiceFacade serviceFacade, final T entity,
        final Revision revision, final AuthorizeAccess authorizer, final Runnable verifier,
        final BiFunction<Revision, T, Response> action) {

    final NiFiUser user = NiFiUserUtils.getNiFiUser();

    if (isTwoPhaseRequest(httpServletRequest)) {
        if (isValidationPhase(httpServletRequest)) {
            // authorize access
            serviceFacade.authorizeAccess(authorizer);
            serviceFacade.verifyRevision(revision, user);

            // verify if necessary
            if (verifier != null) {
                verifier.run();
            }

            // store the request
            phaseOneStoreTransaction(entity, revision, null);

            return generateContinueResponse().build();
        } else if (isExecutionPhase(httpServletRequest)) {
            // get the original request and run the action
            final Request<T> phaseOneRequest = phaseTwoVerifyTransaction();
            return action.apply(phaseOneRequest.getRevision(), phaseOneRequest.getRequest());
        } else if (isCancellationPhase(httpServletRequest)) {
            cancelTransaction();
            return generateOkResponse().build();
        } else {
            throw new IllegalStateException("This request does not appear to be part of the two phase commit.");
        }
    } else {
        // authorize access and run the action
        serviceFacade.authorizeAccess(authorizer);
        serviceFacade.verifyRevision(revision, user);

        return action.apply(revision, entity);
    }
}

From source file:org.apache.nifi.web.api.ApplicationResource.java

/**
 * Executes an action through the service facade using the specified revision.
 *
 * @param serviceFacade service facade//from  ww w  .  j a  va2s  . com
 * @param revisions     revisions
 * @param authorizer    authorizer
 * @param verifier      verifier
 * @param action        executor
 * @return the response
 */
protected <T extends Entity> Response withWriteLock(final NiFiServiceFacade serviceFacade, final T entity,
        final Set<Revision> revisions, final AuthorizeAccess authorizer, final Runnable verifier,
        final BiFunction<Set<Revision>, T, Response> action) {

    final NiFiUser user = NiFiUserUtils.getNiFiUser();

    if (isTwoPhaseRequest(httpServletRequest)) {
        if (isValidationPhase(httpServletRequest)) {
            // authorize access
            serviceFacade.authorizeAccess(authorizer);
            serviceFacade.verifyRevisions(revisions, user);

            // verify if necessary
            if (verifier != null) {
                verifier.run();
            }

            // store the request
            phaseOneStoreTransaction(entity, null, revisions);

            return generateContinueResponse().build();
        } else if (isExecutionPhase(httpServletRequest)) {
            // get the original request and run the action
            final Request<T> phaseOneRequest = phaseTwoVerifyTransaction();
            return action.apply(phaseOneRequest.getRevisions(), phaseOneRequest.getRequest());
        } else if (isCancellationPhase(httpServletRequest)) {
            cancelTransaction();
            return generateOkResponse().build();
        } else {
            throw new IllegalStateException("This request does not appear to be part of the two phase commit.");
        }
    } else {
        // authorize access and run the action
        serviceFacade.authorizeAccess(authorizer);
        serviceFacade.verifyRevisions(revisions, user);

        return action.apply(revisions, entity);
    }
}

From source file:com.samsung.sjs.ABackendTest.java

public void compilerTest(BiFunction<CompilerOptions, String[], Process> compiler,
        Function<String, Process> evaluator, boolean execute_code, boolean verbose, String... extra) {
    try {//from   ww w  .j  a  v a  2s .com
        String script = getInputScriptPath();
        System.out.println("Looking for test script: " + script);
        System.err.println("COMPILING: " + script);
        File scriptfile = new File(script);
        Path tmpdir = Files.createTempDirectory("__fawefwea8ew");
        tmpdir.toFile().deleteOnExit();
        String ccode = scriptfile.getName().replaceFirst(".js$", ".c");
        File cfile = File.createTempFile("___", ccode, tmpdir.toFile());
        String exec = ccode.replaceFirst(".c$", "");
        File execfile = File.createTempFile("___", exec, tmpdir.toFile());
        CompilerOptions opts = new CompilerOptions(CompilerOptions.Platform.Native,
                scriptfile.getAbsolutePath(), verbose, // -debugcompiler
                cfile.getAbsolutePath(), true /* use GC */, "clang", "emcc", execfile.getAbsolutePath(),
                baseDirectory(), false /* don't dump C compiler spew into JUnit console */,
                true /* apply field optimizations */, verbose /* emit type inference constraints to console */,
                verbose /* dump constraint solution to console */,
                null /* find runtime src for linking locally (not running from jar) */, shouldEncodeValues(),
                false /* TODO: x86Test passes explicit -m32 flag, rather than setting this */,
                false /* we don't care about error explanations */,
                null /* we don't care about error explanations */, false /* generate efl environment code */,
                3 /* pass C compiler -O3 */);
        if (doInterop()) {
            opts.enableInteropMode();
        }
        if (bootInterop()) {
            opts.startInInteropMode();
        }
        Compiler.compile(opts);
        Process clang = compiler.apply(opts, extra);
        clang.waitFor();
        if (clang.exitValue() != 0) {
            StringWriter w_stdout = new StringWriter(), w_stderr = new StringWriter();
            IOUtils.copy(clang.getInputStream(), w_stdout, Charset.defaultCharset());
            IOUtils.copy(clang.getErrorStream(), w_stderr, Charset.defaultCharset());
            String compstdout = w_stdout.toString();
            String compstderr = w_stderr.toString();
            System.err.println("!!!!!!!!!!!!! Compiler exited with value " + clang.exitValue());
            System.err.println("Compiler stdout: " + compstdout);
            System.err.println("Compiler stderr: " + compstderr);
        }
        assertTrue(clang.exitValue() == 0);
        if (execute_code) {
            File prefixedscript = prefixJS(tmpdir, scriptfile);
            assertSameProcessOutput(runNode(prefixedscript), evaluator.apply(execfile.getAbsolutePath()));
        }
    } catch (Exception e) {
        e.printStackTrace();
        assertTrue(false);
    }
}

From source file:org.ligoj.app.plugin.prov.aws.in.ProvAwsPriceImportResource.java

/**
 * Install AWS prices from the JSON file.
 *
 * @param context//from  www  . j a  va 2 s.  co m
 *            The update context.
 * @param api
 *            The API name, only for log.
 * @param endpoint
 *            The prices end-point JSON URL.
 * @param apiClass
 *            The mapping model from JSON at region level.
 * @param mapper
 *            The mapping function from JSON at region level to JPA entity.
 */
private <R extends AwsRegionPrices, T extends AwsPrices<R>> void installPrices(final UpdateContext context,
        final String api, final String endpoint, final Class<T> apiClass,
        final BiFunction<R, ProvLocation, Integer> mapper) throws IOException {
    log.info("AWS {} prices...", api);

    // Track the created instance to cache instance and price type
    int priceCounter = 0;
    importCatalogResource.nextStep(context.getNode().getId(), t -> t.setPhase(api));

    try (CurlProcessor curl = new CurlProcessor()) {
        // Get the remote prices stream
        final String rawJson = StringUtils.defaultString(curl.get(endpoint),
                "callback({\"config\":{\"regions\":[]}});");

        // All regions are considered
        final int configIndex = rawJson.indexOf('{');
        final int configCloseIndex = rawJson.lastIndexOf('}');
        final T prices = objectMapper.readValue(rawJson.substring(configIndex, configCloseIndex + 1), apiClass);

        // Install the enabled region as needed
        final List<R> eRegions = prices.getConfig().getRegions().stream()
                .peek(r -> r.setRegion(mapSpotToNewRegion.getOrDefault(r.getRegion(), r.getRegion())))
                .filter(this::isEnabledRegion).collect(Collectors.toList());
        eRegions.forEach(r -> installRegion(context, r.getRegion()));
        nextStep(context, null, 0);

        // Install the (EC2 + Spot) prices for each region
        priceCounter = eRegions.stream().mapToInt(r -> mapper.apply(r, context.getRegions().get(r.getRegion())))
                .sum();
    } finally {
        // Report
        log.info("AWS {} import finished : {} prices", api, priceCounter);
        nextStep(context, null, 1);
    }
}