下面列出了怎么用java.util.function.BiConsumer的API类实例代码及写法,或者点击链接到github查看源代码。
private void visitConfigurationRoute(final UiSpecService<Object> service, final Jsonb jsonb, final Route route,
final BiConsumer<String, String> onFile) throws IOException {
final String configId = route.getId().substring("component_server_configuration_details_en_".length());
// todo: resolve the parent since we have it in the route instead of using that hack
final String id = new String(Base64.getDecoder().decode(configId), StandardCharsets.UTF_8);
final String family = id.split("#")[1];
try (final InputStream stream = new ByteArrayInputStream(route.getContent())) {
try {
final ConfigTypeNodes nodes = jsonb.fromJson(stream, ConfigTypeNodes.class);
final Ui ui = service
.convert(family, "en", nodes.getNodes().values().iterator().next(), null)
.toCompletableFuture()
.get();
onFile.accept("configuration/" + configId, jsonb.toJson(ui));
} catch (final InterruptedException | ExecutionException e) {
throw new IllegalStateException(e);
}
}
}
/**
* Returns a new {@code Collector} described by the given {@code supplier},
* {@code accumulator}, {@code combiner}, and {@code finisher} functions.
*
* @param supplier The supplier function for the new collector
* @param accumulator The accumulator function for the new collector
* @param combiner The combiner function for the new collector
* @param finisher The finisher function for the new collector
* @param characteristics The collector characteristics for the new
* collector
* @param <T> The type of input elements for the new collector
* @param <A> The intermediate accumulation type of the new collector
* @param <R> The final result type of the new collector
* @throws NullPointerException if any argument is null
* @return the new {@code Collector}
*/
public static<T, A, R> Collector<T, A, R> of(Supplier<A> supplier,
BiConsumer<A, T> accumulator,
BinaryOperator<A> combiner,
Function<A, R> finisher,
Characteristics... characteristics) {
Objects.requireNonNull(supplier);
Objects.requireNonNull(accumulator);
Objects.requireNonNull(combiner);
Objects.requireNonNull(finisher);
Objects.requireNonNull(characteristics);
Set<Characteristics> cs = Collectors.CH_NOID;
if (characteristics.length > 0) {
cs = EnumSet.noneOf(Characteristics.class);
Collections.addAll(cs, characteristics);
cs = Collections.unmodifiableSet(cs);
}
return new Collectors.CollectorImpl<>(supplier, accumulator, combiner, finisher, cs);
}
/**
* Returns a new {@code Collector} described by the given {@code supplier},
* {@code accumulator}, {@code combiner}, and {@code finisher} functions.
*
* @param supplier The supplier function for the new collector
* @param accumulator The accumulator function for the new collector
* @param combiner The combiner function for the new collector
* @param finisher The finisher function for the new collector
* @param characteristics The collector characteristics for the new
* collector
* @param <T> The type of input elements for the new collector
* @param <A> The intermediate accumulation type of the new collector
* @param <R> The final result type of the new collector
* @throws NullPointerException if any argument is null
* @return the new {@code Collector}
*/
public static<T, A, R> Collector<T, A, R> of(Supplier<A> supplier,
BiConsumer<A, T> accumulator,
BinaryOperator<A> combiner,
Function<A, R> finisher,
Characteristics... characteristics) {
Objects.requireNonNull(supplier);
Objects.requireNonNull(accumulator);
Objects.requireNonNull(combiner);
Objects.requireNonNull(finisher);
Objects.requireNonNull(characteristics);
Set<Characteristics> cs = Collectors.CH_NOID;
if (characteristics.length > 0) {
cs = EnumSet.noneOf(Characteristics.class);
Collections.addAll(cs, characteristics);
cs = Collections.unmodifiableSet(cs);
}
return new Collectors.CollectorImpl<>(supplier, accumulator, combiner, finisher, cs);
}
@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
Node<K, V>[] tab;
if (action == null) {
throw new NullPointerException();
}
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (Node<K, V> e : tab) {
for (; e != null; e = e.next) {
action.accept(e.key, e.value);
}
}
if (modCount != mc) {
throw new ConcurrentModificationException();
}
}
}
void testDoubleBadOriginBound(BiConsumer<Double, Double> bi) {
executeAndCatchIAE(() -> bi.accept(17.0, 2.0));
executeAndCatchIAE(() -> bi.accept(0.0, 0.0));
executeAndCatchIAE(() -> bi.accept(Double.NaN, FINITE));
executeAndCatchIAE(() -> bi.accept(FINITE, Double.NaN));
executeAndCatchIAE(() -> bi.accept(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY));
// Returns NaN
// executeAndCatchIAE(() -> bi.accept(Double.NEGATIVE_INFINITY, FINITE));
// executeAndCatchIAE(() -> bi.accept(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY));
executeAndCatchIAE(() -> bi.accept(FINITE, Double.NEGATIVE_INFINITY));
// Returns Double.MAX_VALUE
// executeAndCatchIAE(() -> bi.accept(FINITE, Double.POSITIVE_INFINITY));
executeAndCatchIAE(() -> bi.accept(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY));
executeAndCatchIAE(() -> bi.accept(Double.POSITIVE_INFINITY, FINITE));
executeAndCatchIAE(() -> bi.accept(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY));
}
@SuppressWarnings("unchecked")
@Override
public void forEach(final BiConsumer<? super K, ? super V> action) {
Objects.requireNonNull(action);
final int expectedModCount = modCount;
final Entry<K, V>[] tab = getTable();
for (Entry<K, V> entry : tab) {
while (entry != null) {
final Object key = entry.get();
if (key != null) {
action.accept((K) SoftKeyHashMap.unmaskNull(key), entry.value);
}
entry = entry.next;
if (expectedModCount != modCount) {
throw new ConcurrentModificationException();
}
}
}
}
@SuppressWarnings("unchecked")
@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
Objects.requireNonNull(action);
int expectedModCount = modCount;
Object[] t = table;
for (int index = 0; index < t.length; index += 2) {
Object k = t[index];
if (k != null) {
action.accept((K) unmaskNull(k), (V) t[index + 1]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
}
/**
* Process each {@code CommandLineProgram}-derived class given a list of packages.
* @param packageList list of packages to search
* @param clpClassProcessor function to process each CommandLineProgram class found in {@code packageList} (note
* that the {@code CommandLineProgramProperties} argument may be null)
*/
public static void processAllCommandLinePrograms(
final List<String> packageList,
final BiConsumer<Class<?>, CommandLineProgramProperties> clpClassProcessor) {
final ClassFinder classFinder = new ClassFinder();
packageList.forEach(pkg -> classFinder.find(pkg, CommandLineProgram.class));
for (final Class<?> clazz : classFinder.getClasses()) {
// No interfaces, synthetic, primitive, local, or abstract classes.
if (!clazz.isInterface() && !clazz.isSynthetic() && !clazz.isPrimitive() && !clazz.isLocalClass()
&& !Modifier.isAbstract(clazz.getModifiers())
&& !clazz.isAnonymousClass() // skip anonymous (test) classes since they don't have annotations
&& clazz != PicardCommandLineProgramExecutor.class) {
final CommandLineProgramProperties clpProperties = Main.getProgramProperty(clazz);
clpClassProcessor.accept(clazz, clpProperties);
}
}
}
/**
* Read locks can be very deeply nested
*/
public void testDeeplyNestedReadLocks() {
final StampedLock lock = new StampedLock();
final int depth = 300;
final long[] stamps = new long[depth];
final List<Function<StampedLock, Long>> readLockers = readLockers();
final List<BiConsumer<StampedLock, Long>> readUnlockers = readUnlockers();
for (int i = 0; i < depth; i++) {
Function<StampedLock, Long> readLocker
= readLockers.get(i % readLockers.size());
long stamp = readLocker.apply(lock);
assertEquals(i + 1, lock.getReadLockCount());
assertTrue(lock.isReadLocked());
stamps[i] = stamp;
}
for (int i = 0; i < depth; i++) {
BiConsumer<StampedLock, Long> readUnlocker
= readUnlockers.get(i % readUnlockers.size());
assertEquals(depth - i, lock.getReadLockCount());
assertTrue(lock.isReadLocked());
readUnlocker.accept(lock, stamps[depth - 1 - i]);
}
assertUnlocked(lock);
}
/**
* @param <A>
* the input type class
* @param inputType
* the input type
* @param handler
* the callback
* @return the webserver handler for this ajax call.
*/
public static <A> Handler<RoutingContext> ajax(Class<A> inputType, BiConsumer<A, RoutingContext> handler) {
return context -> {
// Internet Explorer 11 caches ajax calls
context.response().putHeader("Cache-control", "none");
context.response().putHeader("Pragma", "none");
context.response().putHeader("Expires", "0");
context.response().putHeader("Content-Type", "application/json; charset=" + VertxUI.charset);
context.request().bodyHandler(body -> {
context.response().end();
handler.accept(in(inputType, body.toString()), context);
});
};
}
public ExecutionFlowBuilder<C, E, S> onReadOnlyCommand(Class<? extends C> command, BiConsumer<C, ReadOnlyFlowContext> handler) {
onCommand(command, (cmd, flowContext, state) -> {
handler.accept(cmd, flowContext);
return flowContext.done();
});
return this;
}
/**
* A variant of {@link Collectors#toMap(Function, Function)} for immutable maps.
*
* <p>Note this variant throws {@link IllegalArgumentException} upon duplicate keys, rather than
* {@link IllegalStateException}
*
* @param <T> type of the input elements
* @param <K> output type of the key mapping function
* @param <V> output type of the value mapping function
* @param keyMapper a mapping function to produce keys
* @param valueMapper a mapping function to produce values
* @return a {@code Collector} which collects elements into a {@code Map} whose keys and values
* are the result of applying mapping functions to the input elements
* @throws IllegalArgumentException upon duplicate keys
*/
public static <T, K, V>
Collector<T, ImmutableMap.Builder<K, V>, ImmutableMap<K, V>> immutableMapCollector(
Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper)
throws IllegalArgumentException {
return new Collector<T, ImmutableMap.Builder<K, V>, ImmutableMap<K, V>>() {
public Supplier<ImmutableMap.Builder<K, V>> supplier() {
return ImmutableMap.Builder<K, V>::new;
}
public BiConsumer<ImmutableMap.Builder<K, V>, T> accumulator() {
return (builder, element) -> {
K key = keyMapper.apply(element);
V value = valueMapper.apply(element);
builder.put(key, value);
};
}
public BinaryOperator<ImmutableMap.Builder<K, V>> combiner() {
return (builder1, builder2) -> {
builder1.putAll(builder2.build());
return builder1;
};
}
public Function<ImmutableMap.Builder<K, V>, ImmutableMap<K, V>> finisher() {
return ImmutableMap.Builder<K, V>::build;
}
public Set<Collector.Characteristics> characteristics() {
return ImmutableSet.of();
}
};
}
public TestNettyClientNoDupCommand(SimpleObjectPool<NettyClient> clientPool, ScheduledExecutorService scheduled,
AtomicReference<NettyClient> clientReference,
BiConsumer<NettyClient, AtomicReference<NettyClient>> consumer) {
super(clientPool, scheduled, MESSAGE_TYPE.MESSAGE, "test");
this.clientReference = clientReference;
this.consumer = consumer;
}
/**
* If a value is present in both {@code optional1} and {@code optional2}, performs the given
* action with the values, otherwise does nothing.
*/
public static <T, U> void ifAllPresent(
final Optional<T> optional1,
final Optional<U> optional2,
final BiConsumer<? super T, ? super U> action) {
checkNotNull(optional1);
checkNotNull(optional2);
checkNotNull(action);
optional1.ifPresent(value1 -> optional2.ifPresent(value2 -> action.accept(value1, value2)));
}
@ParameterizedTest
@MethodSource("sheetProcessors")
void testExcelSheetWithIndexHasRecords(BiConsumer<ExcelResponseValidationSteps, List<CellRecord>> consumer)
{
consumer.accept(steps, List.of(
record("A4:B5", "(Product|Price)\\d+\\s*"),
record("D2:D5", "\\d{2,4}\\.0"),
record("B3", "Price"),
record("C1:C5", null)
));
verify(softAssert).recordPassedAssertion("All records at ranges A4:B5, D2:D5, B3, C1:C5 are matched in"
+ " the document");
verifyNoMoreInteractions(softAssert);
}
@Override
public final <R> R collect(Supplier<R> supplier,
ObjIntConsumer<R> accumulator,
BiConsumer<R, R> combiner) {
BinaryOperator<R> operator = (left, right) -> {
combiner.accept(left, right);
return left;
};
return evaluate(ReduceOps.makeInt(supplier, accumulator, operator));
}
private static void supplyParsedPacketToConsumer(ByteBuffer readBuffer, InetSocketAddress address,
BiConsumer<Packet, InetSocketAddress> packetConsumer, String logId) {
int messageLength = readBuffer.position();
readBuffer.rewind();
ByteBuffer packetSize = readBuffer.slice();
packetSize.position(0);
packetSize.limit(2);
int size = Packet.FIELD_SIZE.value(packetSize);
if (messageLength == size) {
ByteBuffer packetType = readBuffer.slice();
packetType.position(32);
packetType.limit(34);
int type = Packet.FIELD_PACKET_TYPE.value(packetType);
PacketHandler<?> handler = PacketFactory.createHandler(type);
if (handler == null) {
LOGGER.trace("{} : Unknown packet type: {} (source: {})", logId, String.format("0x%02X", type),
address.toString());
} else {
Packet packet = handler.handle(readBuffer);
packetConsumer.accept(packet, address);
}
}
}
@Override
public void queryRaw(@Nonnull final String query,
@Nonnull final BiConsumer<Cancellable, String> onResponse,
@Nonnull final Consumer<? super Throwable> onError,
@Nonnull final Runnable onComplete) {
Arguments.checkNonEmpty(query, "query");
Arguments.checkNotNull(onResponse, "onNext");
Arguments.checkNotNull(onError, "onError");
Arguments.checkNotNull(onComplete, "onComplete");
queryRaw(query, null, onResponse, onError, onComplete);
}
@Override
public boolean runChildStep(ScenarioSpec scenarioSpec, BiConsumer testPassHandler) {
scenarioSpec.getSteps()
.forEach(step -> testPassHandler.accept(scenarioSpec.getScenarioName(), step.getName()));
return true;
}
/**
* Test the orderbook stream
*/
@Test(timeout=30000)
public void testOrderbookStream() {
final BitfinexWebsocketClient bitfinexClient = new SimpleBitfinexApiBroker(new BitfinexWebsocketConfiguration(), new BitfinexApiCallbackRegistry(), new SequenceNumberAuditor(), false);
// Await at least 10 callbacks
final CountDownLatch latch = new CountDownLatch(10);
try {
bitfinexClient.connect();
final BitfinexOrderBookSymbol orderbookConfiguration = BitfinexSymbols.orderBook(
BitfinexCurrencyPair.of("BTC","USD"), BitfinexOrderBookSymbol.Precision.P0, BitfinexOrderBookSymbol.Frequency.F0, 25);
final OrderbookManager orderbookManager = bitfinexClient.getOrderbookManager();
final BiConsumer<BitfinexOrderBookSymbol, BitfinexOrderBookEntry> callback = (c, o) -> {
Assert.assertTrue(o.getAmount().doubleValue() != 0);
Assert.assertTrue(o.getPrice().doubleValue() != 0);
Assert.assertTrue(o.getCount().doubleValue() != 0);
Assert.assertTrue(o.toString().length() > 0);
latch.countDown();
};
orderbookManager.registerOrderbookCallback(orderbookConfiguration, callback);
orderbookManager.subscribeOrderbook(orderbookConfiguration);
latch.await();
orderbookManager.unsubscribeOrderbook(orderbookConfiguration);
Assert.assertTrue(orderbookManager.removeOrderbookCallback(orderbookConfiguration, callback));
Assert.assertFalse(orderbookManager.removeOrderbookCallback(orderbookConfiguration, callback));
} catch (Exception e) {
// Should not happen
e.printStackTrace();
Assert.fail();
} finally {
bitfinexClient.close();
}
}
public static <R>
Collector<P4CommandRunner.ActionAnswer<R>, Answer<R>, Answer<R>>
collectActionErrors(@NotNull final List<VcsException> errors) {
return new Collector<P4CommandRunner.ActionAnswer<R>, Answer<R>, Answer<R>>() {
@Override
public Supplier<Answer<R>> supplier() {
return () -> Answer.resolve(null);
}
@Override
public BiConsumer<Answer<R>, P4CommandRunner.ActionAnswer<R>> accumulator() {
return (answer, action) -> answer.futureMap((r, sink) -> {
action
.whenCompleted(sink::resolve)
.whenServerError((e) -> {
errors.add(e);
sink.resolve(r);
})
.whenOffline(() -> sink.resolve(r));
});
}
@Override
public BinaryOperator<Answer<R>> combiner() {
return (a, b) -> a.mapAsync((x) -> b);
}
@Override
public Function<Answer<R>, Answer<R>> finisher() {
return i -> i;
}
@Override
public Set<Characteristics> characteristics() {
return Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH));
}
};
}
private MockedCrd(CustomResourceDefinition crd,
Class<T> crClass, Class<L> crListClass, Class<D> crDoneableClass,
Function<T, S> getStatus,
BiConsumer<T, S> setStatus) {
this.crd = crd;
this.crClass = crClass;
this.crListClass = crListClass;
this.crDoneableClass = crDoneableClass;
this.getStatus = getStatus;
this.setStatus = setStatus;
instances = db(emptySet(), crClass, crDoneableClass);
}
CollectorImpl(Supplier<A> supplier,
BiConsumer<A, T> accumulator,
BinaryOperator<A> combiner,
Function<A,R> finisher,
Set<Characteristics> characteristics) {
this.supplier = supplier;
this.accumulator = accumulator;
this.combiner = combiner;
this.finisher = finisher;
this.characteristics = characteristics;
}
MonoPeekTerminal(Mono<? extends T> source,
@Nullable Consumer<? super T> onSuccessCall,
@Nullable Consumer<? super Throwable> onErrorCall,
@Nullable BiConsumer<? super T, Throwable> onAfterTerminateCall) {
super(source);
this.onAfterTerminateCall = onAfterTerminateCall;
this.onSuccessCall = onSuccessCall;
this.onErrorCall = onErrorCall;
}
private <T> void testReadStream(
Function<InfinispanAsyncMap<JsonObject, Buffer>, ReadStream<T>> streamFactory,
BiConsumer<Map<JsonObject, Buffer>, List<T>> assertions
) {
Map<JsonObject, Buffer> map = genJsonToBuffer(100);
loadData(map, (vertx, asyncMap) -> {
List<T> items = new ArrayList<>();
ReadStream<T> stream = streamFactory.apply(InfinispanAsyncMap.unwrap(asyncMap));
AtomicInteger idx = new AtomicInteger();
long pause = 500;
long start = System.nanoTime();
stream.endHandler(end -> {
assertions.accept(map, items);
long duration = NANOSECONDS.toMillis(System.nanoTime() - start);
assertTrue(duration >= 3 * pause);
testComplete();
}).exceptionHandler(t -> {
fail(t);
}).handler(item -> {
items.add(item);
int j = idx.getAndIncrement();
if (j == 3 || j == 16 || j == 38) {
stream.pause();
int emitted = items.size();
vertx.setTimer(pause, tid -> {
assertTrue("Items emitted during pause", emitted == items.size());
stream.resume();
});
}
});
});
await();
}
private Input(ColumnPane root, String key, String desc, Supplier<E> create,
Function<E, R> mapper, BiConsumer<E, R> setter) {
this.editor = create.get();
this.mapper = mapper;
this.setter = setter;
this.key = key;
SubLabeled labeled = new SubLabeled(translate(key), translate(desc));
root.add(labeled, editor);
}
private static void runTestWithView(Function<Cleaner, Access> viewFactory,
BiConsumer<Access, ProofListIndexProxy<String>> listTest) {
IndicesTests.runTestWithView(
viewFactory,
LIST_NAME,
((address, access, serializer) -> access.getProofList(address, serializer)),
listTest
);
}
public void eachClass(BiConsumer<String, ClassLoader> consumer) {
FileSystemFinder finder = new FileSystemFinder(jarRootPath, ClassSource::pathIsClassFile);
for (Path path : finder) {
consumer.accept(ClassSource.makeClassName(jarRootPath.relativize(path).normalize()), classLoader);
}
}
void wrapMethodMessageHandler(Message<?> message, MessageHandler messageHandler,
BiConsumer<Span, Message<?>> messageSpanTagger) {
MessageConsumerRequest request = new MessageConsumerRequest(message, this.getter);
TraceContextOrSamplingFlags extracted = extractAndClearHeaders(request);
Span consumerSpan = tracer.nextSpan(extracted);
Span listenerSpan = tracer.newChild(consumerSpan.context());
if (!consumerSpan.isNoop()) {
consumerSpan.name("next-message").kind(CONSUMER);
if (messageSpanTagger != null) {
messageSpanTagger.accept(consumerSpan, message);
}
// incur timestamp overhead only once
long timestamp = tracing.clock(consumerSpan.context())
.currentTimeMicroseconds();
consumerSpan.start(timestamp);
long consumerFinish = timestamp + 1L; // save a clock reading
consumerSpan.finish(consumerFinish);
// not using scoped span as we want to start with a pre-configured time
listenerSpan.name("on-message").start(consumerFinish);
}
try (Tracer.SpanInScope ws = tracer.withSpanInScope(listenerSpan)) {
messageHandler.handleMessage(message);
}
catch (Throwable t) {
listenerSpan.error(t);
throw t;
}
finally {
listenerSpan.finish();
}
}
public PentahoOrcInputFormat( NamedCluster namedCluster ) {
if ( namedCluster == null ) {
conf = new Configuration();
} else {
conf = inClassloader( () -> {
Configuration confProxy = new ConfigurationProxy();
confProxy.addResource( "hive-site.xml" );
BiConsumer<InputStream, String> consumer = ( is, filename ) -> confProxy.addResource( is, filename );
ShimConfigsLoader.addConfigsAsResources( namedCluster, consumer );
return confProxy;
} );
}
}