java.util.function.Consumer Java Examples

The following examples show how to use java.util.function.Consumer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: TreeMap.java    License: GNU General Public License v2.0 6 votes vote down vote up
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();
    }
}
 
Example #2
Source Project: Shadbot   Author: Shadorc   File: InviteCmd.java    License: GNU General Public License v3.0 6 votes vote down vote up
@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();
}
 
Example #3
Source Project: cyclops   Author: aol   File: FlowableManaged.java    License: Apache License 2.0 6 votes vote down vote up
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;
            }
        };
    }
 
Example #4
Source Project: hottub   Author: dsrg-uoft   File: SpliteratorCollisions.java    License: GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example #5
Source Project: hono   Author: eclipse   File: ReceiverTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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";
}
 
Example #6
Source Project: pnc   Author: project-ncl   File: StatusUpdatesTest.java    License: Apache License 2.0 6 votes vote down vote up
@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));
    });
}
 
Example #7
Source Project: cava   Author: ConsenSys   File: RLP.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #8
Source Project: Real-World-Software-Development   Author: Iteratr-Learning   File: DatabaseTwootRepository.java    License: Apache License 2.0 6 votes vote down vote up
@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)));
}
 
Example #9
Source Project: j2objc   Author: google   File: LinkedBlockingDeque.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #10
Source Project: datakernel   Author: softindex   File: Config.java    License: Apache License 2.0 5 votes vote down vote up
static <T> Consumer<T> ifNotDefault(T defaultValue, Consumer<T> setter) {
	return value -> {
		if (!Objects.equals(value, defaultValue)) {
			setter.accept(value);
		}
	};
}
 
Example #11
/**
 * @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);
    };
}
 
Example #12
Source Project: incubator-ratis   Author: apache   File: RaftStorageTestUtils.java    License: Apache License 2.0 5 votes vote down vote up
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());
  }
}
 
Example #13
Source Project: beatoraja   Author: exch-bms2   File: Skin.java    License: GNU General Public License v3.0 5 votes vote down vote up
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;
	}
}
 
Example #14
Source Project: xtext-core   Author: eclipse   File: GeneratedJavaFileAccess.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #15
Source Project: ods-provisioning-app   Author: opendevstack   File: JenkinsPipelineAdapter.java    License: Apache License 2.0 5 votes vote down vote up
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));
}
 
Example #16
Source Project: jdk8u_jdk   Author: JetBrains   File: TreeMap.java    License: GNU General Public License v2.0 5 votes vote down vote up
public boolean tryAdvance(Consumer<? super K> action) {
    if (hasNext()) {
        action.accept(next());
        return true;
    }
    return false;
}
 
Example #17
Source Project: bisq   Author: bisq-network   File: BondingViewUtils.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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);
        }
    }
}
 
Example #18
Source Project: xtext-xtend   Author: eclipse   File: AnnotationReferenceBuildContextImpl.java    License: Eclipse Public License 2.0 5 votes vote down vote up
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);
}
 
Example #19
Source Project: mug   Author: google   File: GraphWalker.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #20
Source Project: jdk8u60   Author: chenghanpeng   File: SpinedBuffer.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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);
    }
}
 
Example #21
Source Project: riposte   Author: Nike-Inc   File: CodahaleMetricsCollector.java    License: Apache License 2.0 5 votes vote down vote up
@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);
    }

}
 
Example #22
Source Project: symja_android_library   Author: axkr   File: IOFunctions.java    License: GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example #23
Source Project: lams   Author: lamsfoundation   File: ProcedureParameterMetadata.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visitRegistrations(Consumer<QueryParameter> action) {
	for ( ProcedureParameterImplementor parameter : parameters ) {
		action.accept( parameter );
	}

}
 
Example #24
Source Project: jeddict   Author: jeddict   File: EJSUtil.java    License: Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #25
Source Project: amidst   Author: toolbox4minecraft   File: CachedWorldIconProducer.java    License: GNU General Public License v3.0 5 votes vote down vote up
@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);
		}
	}
}
 
Example #26
Source Project: styx   Author: spotify   File: BackfillTriggerManager.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #27
Source Project: phoebus   Author: ControlSystemStudio   File: AlarmLogSearchJob.java    License: Eclipse Public License 1.0 5 votes vote down vote up
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));
}
 
Example #28
Source Project: beam   Author: apache   File: JobInvocation.java    License: Apache License 2.0 5 votes vote down vote up
/** 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);
}
 
Example #29
Source Project: ngAndroid   Author: davityle   File: CollectionUtils.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #30
Source Project: cava   Author: ConsenSys   File: ByteBufferRLPWriter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void writeList(Consumer<RLPWriter> fn) {
  requireNonNull(fn);
  AccumulatingRLPWriter listWriter = new AccumulatingRLPWriter();
  fn.accept(listWriter);
  writeEncodedValuesAsList(listWriter.values());
}