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 configure(final PutORC putORC, final int numUsers,
        final BiFunction<Integer, MockRecordParser, Void> recordGenerator) throws InitializationException {
    testRunner = TestRunners.newTestRunner(putORC);
    testRunner.setProperty(PutORC.HADOOP_CONFIGURATION_RESOURCES, TEST_CONF_PATH);
    testRunner.setProperty(PutORC.DIRECTORY, DIRECTORY);

    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  ww w  .  j  a va 2  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);
    }

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

    testRunner.setProperty(PutORC.RECORD_READER, "mock-reader-factory");
}

From source file:io.atomix.protocols.gossip.map.AntiEntropyMapDelegate.java

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

    String encodedKey = encodeKey(key);
    AtomicReference<MapDelegateEvent.Type> update = new AtomicReference<>();
    AtomicReference<MapValue> previousValue = new AtomicReference<>();
    MapValue computedValue = items.compute(encodedKey, (k, mv) -> {
        previousValue.set(mv);
        V newRawValue = recomputeFunction.apply(key, mv == null ? null : mv.get(this::decodeValue));
        byte[] newEncodedValue = encodeValue(newRawValue);
        if (mv != null && Arrays.equals(newEncodedValue, mv.get())) {
            // value was not updated
            return mv;
        }
        MapValue newValue = new MapValue(newEncodedValue,
                timestampProvider.get(Maps.immutableEntry(key, newRawValue)));
        if (mv == null) {
            update.set(INSERT);
            return newValue;
        } else if (newValue.isNewerThan(mv)) {
            update.set(UPDATE);
            return newValue;
        } else {
            return mv;
        }
    });
    if (update.get() != null) {
        notifyPeers(new UpdateEntry(encodedKey, computedValue), peerUpdateFunction
                .select(Maps.immutableEntry(key, computedValue.get(this::decodeValue)), membershipService));
        MapDelegateEvent.Type updateType = computedValue.isTombstone() ? REMOVE : update.get();
        V value = computedValue.isTombstone()
                ? previousValue.get() == null ? null : previousValue.get().get(this::decodeValue)
                : computedValue.get(this::decodeValue);
        if (value != null) {
            notifyListeners(new MapDelegateEvent<>(updateType, key, value));
        }
        return value;
    }
    return computedValue.get(this::decodeValue);
}

From source file:org.openmhealth.data.generator.service.AbstractDataPointGeneratorImpl.java

/**
 * @param measure a measure//  w w w . j  ava2s  .c  o m
 * @return a data point corresponding to the specified measure
 */
public DataPoint<T> newDataPoint(T measure) {

    TimeInterval effectiveTimeInterval = measure.getEffectiveTimeFrame().getTimeInterval();
    OffsetDateTime effectiveEndDateTime;

    if (effectiveTimeInterval != null) {
        if (effectiveTimeInterval.getEndDateTime() != null) {
            effectiveEndDateTime = effectiveTimeInterval.getEndDateTime();
        } else {
            // use the duration to calculate the end date time of the interval
            if (effectiveTimeInterval.getDuration() != null) {

                BiFunction<OffsetDateTime, Long, OffsetDateTime> plusFunction;

                switch (effectiveTimeInterval.getDuration().getTypedUnit()) {

                case SECOND:
                    plusFunction = OffsetDateTime::plusSeconds;
                    break;
                case MINUTE:
                    plusFunction = OffsetDateTime::plusMinutes;
                    break;
                case HOUR:
                    plusFunction = OffsetDateTime::plusHours;
                    break;
                case DAY:
                    plusFunction = OffsetDateTime::plusDays;
                    break;
                case WEEK:
                    plusFunction = OffsetDateTime::plusWeeks;
                    break;
                case MONTH:
                    plusFunction = OffsetDateTime::plusMonths;
                    break;
                case YEAR:
                    plusFunction = OffsetDateTime::plusYears;
                    break;
                default:
                    throw new IllegalStateException("A time interval duration type isn't supported.");
                }

                effectiveEndDateTime = plusFunction.apply(effectiveTimeInterval.getStartDateTime(),
                        effectiveTimeInterval.getDuration().getValue().longValue());
            } else {
                throw new IllegalStateException("An end date time can't be calculated without a duration.");
            }
        }
    } else { // if this is a point in time measure
        effectiveEndDateTime = measure.getEffectiveTimeFrame().getDateTime();
    }

    DataPointAcquisitionProvenance acquisitionProvenance = new DataPointAcquisitionProvenance.Builder(
            sourceName).setModality(SENSED).setSourceCreationDateTime(effectiveEndDateTime).build();

    DataPointHeader header = new DataPointHeader.Builder(randomUUID().toString(), measure.getSchemaId(),
            effectiveEndDateTime.plusMinutes(1)).setAcquisitionProvenance(acquisitionProvenance)
                    .setUserId(userId).build();

    return new DataPoint<>(header, measure);
}

From source file:org.ow2.proactive.scheduling.api.graphql.fetchers.DatabaseConnectionFetcher.java

/**
 * Adaptation of the algorithm defined in the GraphQL specification.
 * <p>//from w  w w  .  ja v  a 2  s.  c om
 * Please look at the following link for more details:
 * https://facebook.github.io/relay/graphql/connections.htm#sec-Pagination-algorithm
 * <p>
 * The opaque cursor that is returned to the client makes use of the entity ID internally.
 */
protected ExtendedConnection createPaginatedConnection(DataFetchingEnvironment environment,
        Class<E> entityClass, Function<Root<E>, Path<? extends Number>> entityId,
        Comparator<E> entityComparator, BiFunction<CriteriaBuilder, Root<E>, List<Predicate[]>> criteria,
        CursorMapper<T, Integer> cursorMapper) {

    Integer first = environment.getArgument(FIRST.getName());
    Integer last = environment.getArgument(LAST.getName());

    Integer after = cursorMapper.getOffsetFromCursor(environment.getArgument(AFTER.getName()));
    Integer before = cursorMapper.getOffsetFromCursor(environment.getArgument(BEFORE.getName()));

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<E> criteriaQuery = criteriaBuilder.createQuery(entityClass);
    Root<E> entityRoot = criteriaQuery.from(entityClass);
    Path<? extends Number> entityIdPath = entityId.apply(entityRoot);

    Predicate cursorPredicate = createCursorPredicate(criteriaBuilder, entityIdPath, after, before);

    int maxResults = applySlicing(criteriaQuery, criteriaBuilder, entityIdPath, first, last);

    CriteriaQuery<E> select = criteriaQuery.select(entityRoot);

    List<Predicate[]> predicates = criteria.apply(criteriaBuilder, entityRoot);

    Predicate[] wherePredicate = buildWherePredicate(predicates, cursorPredicate, criteriaBuilder);

    if (wherePredicate.length > 0) {
        select.where(wherePredicate);
    }

    TypedQuery<E> query = entityManager.createQuery(select);

    if (maxResults > -1) {
        query.setMaxResults(maxResults);
    }

    Stream<E> dataStream = query.getResultList().stream();

    // if last is provided, reverse the stream
    // in order to get results sorted in ascending order based on entities ID
    if (last != null) {
        dataStream = dataStream.sorted(entityComparator);
    }

    Stream<T> data = dataMapping(dataStream);

    ExtendedConnection connection = createRelayConnection(entityManager, entityClass, criteriaBuilder,
            wherePredicate, cursorMapper, data, first, last);

    return connection;
}

From source file:shuffle.fwk.data.simulation.SimulationTask.java

public NumberSpan getScoreModifier(ActivateComboEffect comboEffect) {
    NumberSpan compoundMultiplier = new NumberSpan(1);
    for (BiFunction<ActivateComboEffect, SimulationTask, NumberSpan> modifier : scoreModifiers) {
        if (modifier != null) {
            NumberSpan multiplier = modifier.apply(comboEffect, this);
            if (multiplier != null) {
                compoundMultiplier = compoundMultiplier.multiplyBy(multiplier);
            }//from   w w w .  jav  a2  s.  c  om
        }
    }
    PkmType type = getState().getSpeciesType(getEffectSpecies(comboEffect.getCoords()));
    Board.Status boardStatus = getState().getBoard().getStatus();
    return compoundMultiplier.multiplyBy(boardStatus.getMultiplier(type));
}

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

@Override
public void registerHandler(String type, BiFunction<Address, byte[], byte[]> handler, Executor executor) {
    handlers.put(type, (message, connection) -> executor.execute(() -> {
        byte[] responsePayload = null;
        InternalReply.Status status = InternalReply.Status.OK;
        try {/*www.  ja v a 2s .co  m*/
            responsePayload = handler.apply(message.sender(), message.payload());
        } catch (Exception e) {
            log.warn("An error occurred in a message handler: {}", e);
            status = InternalReply.Status.ERROR_HANDLER_EXCEPTION;
        }
        connection.reply(message, status, Optional.ofNullable(responsePayload));
    }));
}

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

protected <T> Vector combineVectors(Class<? extends T> cls, Vector other,
        BiFunction<? super T, ? super T, ?> combiner, Builder builder) {
    Index thisIndex = getIndex();/*from   w  w w  . ja  va 2s  . com*/
    Index otherIndex = Objects.requireNonNull(other, "require other vector").getIndex();
    if (otherIndex instanceof IntIndex) {
        int size = Math.min(size(), other.size());
        for (int i = 0; i < size; i++) {
            builder.set(thisIndex.get(i), combiner.apply(loc().get(cls, i), other.loc().get(cls, i)));
        }
    } else {
        HashSet<Object> keys = new HashSet<>();
        keys.addAll(thisIndex.keySet());
        keys.addAll(otherIndex.keySet());
        for (Object key : keys) {
            boolean thisIndexContainsKey = thisIndex.contains(key);
            boolean otherIndexContainsKey = otherIndex.contains(key);
            if (thisIndexContainsKey && otherIndexContainsKey) {
                builder.set(key, combiner.apply(get(cls, key), other.get(cls, key)));
            } else if (thisIndexContainsKey) {
                builder.set(key, this, key);
            } else {
                builder.set(key, other, key);
            }
        }
    }
    return builder.build();
}

From source file:net.minecraftforge.common.crafting.CraftingHelper.java

public static boolean findFiles(ModContainer mod, String base, Function<Path, Boolean> preprocessor,
        BiFunction<Path, Path, Boolean> processor) {
    FileSystem fs = null;/*from  www. j  av  a2s. com*/
    try {
        File source = mod.getSource();

        if ("minecraft".equals(mod.getModId()) && DEBUG_LOAD_MINECRAFT) {
            try {
                URI tmp = CraftingManager.class.getResource("/assets/.mcassetsroot").toURI();
                source = new File(tmp.resolve("..").getPath());
            } catch (URISyntaxException e) {
                FMLLog.log.error("Error finding Minecraft jar: ", e);
                return false;
            }
        }

        Path root = null;
        if (source.isFile()) {
            try {
                fs = FileSystems.newFileSystem(source.toPath(), null);
                root = fs.getPath("/" + base);
            } catch (IOException e) {
                FMLLog.log.error("Error loading FileSystem from jar: ", e);
                return false;
            }
        } else if (source.isDirectory()) {
            root = source.toPath().resolve(base);
        }

        if (root == null || !Files.exists(root))
            return false;

        if (preprocessor != null) {
            Boolean cont = preprocessor.apply(root);
            if (cont == null || !cont.booleanValue())
                return false;
        }

        if (processor != null) {
            Iterator<Path> itr = null;
            try {
                itr = Files.walk(root).iterator();
            } catch (IOException e) {
                FMLLog.log.error("Error iterating filesystem for: {}", mod.getModId(), e);
                return false;
            }

            while (itr != null && itr.hasNext()) {
                Boolean cont = processor.apply(root, itr.next());
                if (cont == null || !cont.booleanValue())
                    return false;
            }
        }

        return true;
    } finally {
        IOUtils.closeQuietly(fs);
    }
}

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

@Test
public void testMetricDefinitions() 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", "metricType").has("__eid", id)
                .cast(Vertex.class);

        assert q.hasNext();

        MetricType md = inventory.tenants().get(tenantId).metricTypes().get(id).entity();
        assert md.getId().equals(id);

        return null;
    };/* w w w .ja va  2  s .c o  m*/

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

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

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

@Test
public void testResourceTypes() 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", "resourceType").has("__eid", id)
                .has("__version", "1.0").cast(Vertex.class);

        assert q.hasNext();

        ResourceType rt = inventory.tenants().get(tenantId).resourceTypes().get(id).entity();
        assert rt.getId().equals(id);

        return null;
    };//from w  ww .j  a v a  2  s . c o  m

    test.apply("com.acme.tenant", "URL");
    test.apply("com.example.tenant", "Kachna");
    test.apply("com.example.tenant", "Playroom");

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