下面列出了怎么用java.util.function.Consumer的API类实例代码及写法,或者点击链接到github查看源代码。
public void forEachRemaining(Consumer<? super Map.Entry<K, V>> action) {
if (action == null)
throw new NullPointerException();
if (est < 0)
getEstimate(); // force initialization
TreeMap.Entry<K,V> f = fence, e, p, pl;
if ((e = current) != null && e != f) {
current = f; // exhaust
do {
action.accept(e);
if ((p = e.right) != null) {
while ((pl = p.left) != null)
p = pl;
}
else {
while ((p = e.parent) != null && e == p.right)
e = p;
}
} while ((e = p) != null && e != f);
if (tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
@Override
public Mono<Void> execute(Context context) {
final Consumer<EmbedCreateSpec> embedConsumer = ShadbotUtils.getDefaultEmbed()
.andThen(embed -> embed.setAuthor("Links", Config.INVITE_URL, context.getAvatarUrl())
.setDescription("I'm glad you're willing to invite **Shadbot** in your own server, thank you!" +
"\nHere are some useful links for you." +
"\nIf you have any questions or issues, **do not hesitate to join the Support Server and ask!**" +
"\nIf you want to help keep running the bot, you can also follow the **Donation** link to get more " +
"information. Even small donations are really helpful. " + Emoji.HEARTS)
.addField("Invite", Config.INVITE_URL, false)
.addField("Support Server", Config.SUPPORT_SERVER_URL, false)
.addField("Donation", Config.PATREON_URL, false));
return context.getChannel()
.flatMap(channel -> DiscordUtils.sendMessage(embedConsumer, channel))
.then();
}
public static <T> Managed<T> of(IO<T> acquire, Consumer<T> cleanup){
return new FlowableManaged<T>(){
public <R> IO<R> apply(Function<? super T,? extends IO<R>> fn){
IO<R> y = IO.Comprehensions.forEach(acquire, t1 -> {
IO<? extends Try<? extends IO<R>, Throwable>> res1 = FlowableIO.withCatch(() -> fn.apply(t1), Throwable.class);
return res1;
}, t2 -> {
Try<? extends IO<R>, Throwable> tr = t2._2();
IO<R> res = tr.fold(r -> r, e -> FlowableIO.of(Future.ofError(e)));
cleanup.accept(t2._1());
return res;
});
return y;
}
};
}
private static <T, S extends Spliterator<T>> void testSplitSixDeep(
Collection<T> exp,
Supplier<S> supplier,
UnaryOperator<Consumer<T>> boxingAdapter) {
S spliterator = supplier.get();
boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
for (int depth=0; depth < 6; depth++) {
List<T> dest = new ArrayList<>();
spliterator = supplier.get();
assertSpliterator(spliterator);
// verify splitting with forEach
visit(depth, 0, dest, spliterator, boxingAdapter, spliterator.characteristics(), false);
assertContents(dest, exp, isOrdered);
// verify splitting with tryAdvance
dest.clear();
spliterator = supplier.get();
visit(depth, 0, dest, spliterator, boxingAdapter, spliterator.characteristics(), true);
assertContents(dest, exp, isOrdered);
}
}
/**
* Sets up the receiver with mocks.
*
*/
@SuppressWarnings("unchecked")
@BeforeEach
public void setup() {
final Vertx vertx = mock(Vertx.class);
when(vertx.getOrCreateContext()).thenReturn(mock(Context.class));
final ApplicationClientFactory connection = mock(ApplicationClientFactory.class);
when(connection.connect()).thenReturn(Future.succeededFuture(mock(HonoConnection.class)));
when(connection.createTelemetryConsumer(anyString(), any(Consumer.class), any(Handler.class)))
.thenReturn(Future.succeededFuture(mock(MessageConsumer.class)));
when(connection.createEventConsumer(anyString(), any(Consumer.class), any(Handler.class)))
.thenReturn(Future.succeededFuture(mock(MessageConsumer.class)));
receiver = new Receiver();
receiver.setApplicationClientFactory(connection);
receiver.setVertx(vertx);
receiver.tenantId = "TEST_TENANT";
}
@Test
@InSequence(30)
public void BuildTaskCallbacksShouldBeCalled() throws DatastoreException, CoreException {
User user = User.Builder.newBuilder().id(3).username("test-user-3").build();
Set<BuildTask> buildTasks = initializeBuildTaskSet(configurationBuilder, user, (buildConfigSetRecord) -> {})
.getBuildTasks();
Set<Integer> tasksIds = buildTasks.stream().map((BuildTask::getId)).collect(Collectors.toSet());
Set<Integer> receivedUpdatesForId = new HashSet<>();
Consumer<BuildStatusChangedEvent> statusChangeEventConsumer = (statusChangedEvent) -> {
receivedUpdatesForId.add(Integer.valueOf(statusChangedEvent.getBuild().getId()));
};
tasksIds.forEach((id) -> {
buildStatusNotifications.subscribe(new BuildCallBack(id, statusChangeEventConsumer));
});
buildTasks.forEach((bt) -> {
buildCoordinator.updateBuildTaskStatus(bt, BuildCoordinationStatus.DONE);
});
tasksIds.forEach((id) -> {
Assert.assertTrue("Did not receive update for task " + id, receivedUpdatesForId.contains(id));
});
}
static void encodeByteArray(byte[] value, Consumer<byte[]> appender) {
requireNonNull(value);
int size = value.length;
if (size == 0) {
appender.accept(EMPTY_VALUE);
return;
}
if (size == 1) {
byte b = value[0];
if ((b & 0xFF) <= 0x7f) {
appender.accept(value);
return;
}
}
appender.accept(encodeLength(size, 0x80));
appender.accept(value);
}
@Override
public void query(final TwootQuery twootQuery, final Consumer<Twoot> callback) {
if (!twootQuery.hasUsers()) {
return;
}
var lastSeenPosition = twootQuery.getLastSeenPosition();
var inUsers = twootQuery.getInUsers();
statementRunner.query(
"SELECT * " +
"FROM twoots " +
"WHERE senderId IN " + usersTuple(inUsers) +
"AND twoots.position > " + lastSeenPosition.getValue(), rs ->
callback.accept(extractTwoot(rs)));
}
public boolean tryAdvance(Consumer<? super E> action) {
if (action == null) throw new NullPointerException();
final LinkedBlockingDeque<E> q = this.queue;
final ReentrantLock lock = q.lock;
if (!exhausted) {
E e = null;
lock.lock();
try {
if (current == null)
current = q.first;
while (current != null) {
e = current.item;
current = current.next;
if (e != null)
break;
}
} finally {
lock.unlock();
}
if (current == null)
exhausted = true;
if (e != null) {
action.accept(e);
return true;
}
}
return false;
}
static <T> Consumer<T> ifNotDefault(T defaultValue, Consumer<T> setter) {
return value -> {
if (!Objects.equals(value, defaultValue)) {
setter.accept(value);
}
};
}
/**
* @param c Consumer that setups a {@link ContinuousQueryWithTransformer}.
* @param init True if needing put data to a cache before openning a cursor.
* @return Test operation.
*/
private IgniteRunnable operation(Consumer<ContinuousQueryWithTransformer<Integer, Integer, Integer>> c,
boolean init) {
return () -> {
VERIFIER.register(OPERATION_OPEN_CQ);
ContinuousQueryWithTransformer<Integer, Integer, Integer> cq = new ContinuousQueryWithTransformer<>();
c.accept(cq);
executeQuery(cq, init);
};
}
static void printLog(RaftLog log, Consumer<String> println) {
if (log == null) {
println.accept("log == null");
return;
}
final TermIndex last;
final long flushed, committed;
try(AutoCloseableLock readlock = log.readLock()) {
last = log.getLastEntryTermIndex();
flushed = log.getFlushIndex();
committed = log.getLastCommittedIndex();
}
final StringBuilder b = new StringBuilder();
for(long i = 0; i <= last.getIndex(); i++) {
b.setLength(0);
b.append(i == flushed? 'f': ' ');
b.append(i == committed? 'c': ' ');
b.append(String.format("%3d: ", i));
try {
b.append(ServerProtoUtils.toLogEntryString(log.get(i)));
} catch (RaftLogIOException e) {
b.append(e);
}
println.accept(b.toString());
}
}
private void preDraw(Consumer<ShaderProgram> shaderVariableSetter) {
if(shaders[current] != shaders[type]) {
sprite.setShader(shaders[type]);
current = type;
}
if (shaders[type] != null && shaderVariableSetter != null) {
// シェーダの変数を変更する場合はバッチを切る
// (shader.begin() - end() で囲うのは正しく動作しないため不可)
sprite.flush();
shaderVariableSetter.accept(shaders[type]);
}
switch (blend) {
case 2:
sprite.setBlendFunction(GL11.GL_SRC_ALPHA, GL11.GL_ONE);
break;
case 3:
// TODO 減算描画は難しいか?
Gdx.gl.glBlendEquation(GL20.GL_FUNC_SUBTRACT);
sprite.setBlendFunction(GL11.GL_SRC_ALPHA, GL11.GL_ONE);
Gdx.gl.glBlendEquation(GL20.GL_FUNC_ADD);
break;
case 4:
sprite.setBlendFunction(GL11.GL_ZERO, GL11.GL_SRC_COLOR);
break;
case 9:
sprite.setBlendFunction(GL11.GL_ONE_MINUS_DST_COLOR, GL11.GL_ZERO);
break;
}
if(color != null) {
orgcolor = sprite.getColor();
sprite.setColor(color);
} else {
orgcolor = null;
}
}
/**
* Prepends the addition of required imports of the employed annotations.
* Since the 'typeComment' is a {@link JavaFileAccess.JavaTypeAwareStringConcatenation}
* any optionally required imports are already processed and tracked in {@link #imports}.
*/
@Override
public CharSequence getContent() {
CharSequence _xblockexpression = null;
{
final Consumer<IClassAnnotation> _function = (IClassAnnotation it) -> {
this.importType(it.getAnnotationImport());
};
this.getClassAnnotations().forEach(_function);
_xblockexpression = super.getContent();
}
return _xblockexpression;
}
private static void validateComponentName(
List<Consumer<Map<String, String>>> validators, String componentName) {
HashMap<String, String> quickstarters = new HashMap();
quickstarters.put(OpenProjectData.COMPONENT_ID_KEY, componentName);
validateQuickstarters(validators, Arrays.asList(quickstarters));
}
public boolean tryAdvance(Consumer<? super K> action) {
if (hasNext()) {
action.accept(next());
return true;
}
return false;
}
private void lockupBond(byte[] hash, Coin lockupAmount, int lockupTime, LockupReason lockupReason,
Consumer<String> resultHandler) {
if (GUIUtil.isReadyForTxBroadcastOrShowPopup(p2PService, walletsSetup)) {
if (!DevEnv.isDevMode()) {
try {
Tuple2<Coin, Integer> miningFeeAndTxSize = daoFacade.getLockupTxMiningFeeAndTxSize(lockupAmount, lockupTime, lockupReason, hash);
Coin miningFee = miningFeeAndTxSize.first;
int txSize = miningFeeAndTxSize.second;
String duration = FormattingUtils.formatDurationAsWords(lockupTime * 10 * 60 * 1000L, false, false);
new Popup().headLine(Res.get("dao.bond.reputation.lockup.headline"))
.confirmation(Res.get("dao.bond.reputation.lockup.details",
bsqFormatter.formatCoinWithCode(lockupAmount),
lockupTime,
duration,
bsqFormatter.formatBTCWithCode(miningFee),
CoinUtil.getFeePerByte(miningFee, txSize),
txSize / 1000d
))
.actionButtonText(Res.get("shared.yes"))
.onAction(() -> publishLockupTx(lockupAmount, lockupTime, lockupReason, hash, resultHandler))
.closeButtonText(Res.get("shared.cancel"))
.show();
} catch (Throwable e) {
log.error(e.toString());
e.printStackTrace();
new Popup().warning(e.getMessage()).show();
}
} else {
publishLockupTx(lockupAmount, lockupTime, lockupReason, hash, resultHandler);
}
}
}
protected void _setValue(final JvmFloatAnnotationValue it, final long[] value, final String componentType, final boolean mustBeArray) {
final Consumer<Long> _function = (Long v) -> {
EList<Float> _values = it.getValues();
_values.add(Float.valueOf(((float) (v).longValue())));
};
((List<Long>)Conversions.doWrapArray(value)).forEach(_function);
}
Stream<N> startPostOrder(Iterable<? extends N> startNodes, Consumer<N> foundCycle) {
Walk<N> walk = new Walk<>(
findSuccessors,
node -> {
boolean newNode = tracker.test(node);
if (newNode) {
currentPath.add(node);
} else if (currentPath.contains(node)) {
foundCycle.accept(node);
}
return newNode;
});
return walk.postOrder(startNodes).peek(currentPath::remove);
}
@Override
public void forEach(Consumer<? super Integer> consumer) {
if (consumer instanceof IntConsumer) {
forEach((IntConsumer) consumer);
}
else {
if (Tripwire.ENABLED)
Tripwire.trip(getClass(), "{0} calling SpinedBuffer.OfInt.forEach(Consumer)");
spliterator().forEachRemaining(consumer);
}
}
@Override
public <T> void counted(@NotNull Consumer<T> c, T arg, @NotNull String counterName, long delta) {
final Counter counter = getNamedCounter(counterName);
try {
c.accept(arg);
}
finally {
processCounter(counter, delta);
}
}
private static JButton createButton(JDialog dialog, Container container, String label, IExpr action,
final Consumer<IExpr> consumer, IExpr[] result, EvalEngine engine) {
JButton button = new JButton(label);
container.add(button);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
consumer.accept(action);
}
});
return button;
}
@Override
public void visitRegistrations(Consumer<QueryParameter> action) {
for ( ProcedureParameterImplementor parameter : parameters ) {
action.accept( parameter );
}
}
public static void copyDynamicResource(Consumer<FileTypeStream> parserManager, String inputResource, FileObject webRoot, Function<String, String> pathResolver, ProgressHandler handler) throws IOException {
InputStream inputStream = loadResource(inputResource);
try (ZipInputStream zipInputStream = new ZipInputStream(inputStream)) {
ZipEntry entry;
while ((entry = zipInputStream.getNextEntry()) != null) {
if(entry.isDirectory()){
continue;
}
boolean skipParsing = true;
String entryName = entry.getName();
if (entryName.endsWith(".ejs")) {
skipParsing = false;
entryName = entryName.substring(0, entryName.lastIndexOf("."));
}
String targetPath = pathResolver.apply(entryName);
if (targetPath == null) {
continue;
}
handler.progress(targetPath);
FileObject target = org.openide.filesystems.FileUtil.createData(webRoot, targetPath);
FileLock lock = target.lock();
try (OutputStream outputStream = target.getOutputStream(lock)) {
parserManager.accept(new FileTypeStream(entryName, zipInputStream, outputStream, skipParsing));
zipInputStream.closeEntry();
} finally {
lock.releaseLock();
}
}
} catch (Throwable ex) {
Exceptions.printStackTrace(ex);
System.out.println("InputResource : " + inputResource);
}
}
@Override
public void produce(CoordinatesInWorld corner, Consumer<WorldIcon> consumer, Void additionalData) {
for (WorldIcon icon : getCache()) {
if (icon.getCoordinates().isInBoundsOf(corner, Fragment.SIZE)) {
consumer.accept(icon);
}
}
}
@VisibleForTesting
BackfillTriggerManager(StateManager stateManager,
Storage storage,
TriggerListener triggerListener,
Stats stats,
Time time,
Consumer<List<Backfill>> shuffler) {
this.stateManager = Objects.requireNonNull(stateManager);
this.storage = Objects.requireNonNull(storage);
this.triggerListener = Objects.requireNonNull(triggerListener);
this.stats = Objects.requireNonNull(stats);
this.time = Objects.requireNonNull(time);
this.shuffler = Objects.requireNonNull(shuffler);
}
public static Job submit(RestHighLevelClient client, final String pattern, Boolean isNodeTable, ObservableMap<Keys, String> searchParameters,
final Consumer<List<AlarmLogTableType>> alarmMessageHandler,
final BiConsumer<String, Exception> errorHandler) {
return JobManager.schedule("searching alarm log messages for : " + pattern,
new AlarmLogSearchJob(client, pattern, isNodeTable, searchParameters, alarmMessageHandler, errorHandler));
}
/** Listen for job state changes with a {@link Consumer}. */
public synchronized void addStateListener(Consumer<JobStateEvent> stateStreamObserver) {
for (JobStateEvent event : stateHistory) {
stateStreamObserver.accept(event);
}
stateObservers.add(stateStreamObserver);
}
public <T, R> Collection<R> flatMap(final Iterable<T> it, final Function<T, Collection<R>> f) {
final ArrayList<R> arrayList = new ArrayList<>();
it.forEach(new Consumer<T>() {
@Override
public void accept(T t) {
arrayList.addAll(f.apply(t));
}
});
return arrayList;
}
@Override
public void writeList(Consumer<RLPWriter> fn) {
requireNonNull(fn);
AccumulatingRLPWriter listWriter = new AccumulatingRLPWriter();
fn.accept(listWriter);
writeEncodedValuesAsList(listWriter.values());
}