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 File: FlowableManaged.java    From cyclops with 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 #2
Source File: StatusUpdatesTest.java    From pnc with 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 #3
Source File: TreeMap.java    From openjdk-jdk9 with 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 #4
Source File: DatabaseTwootRepository.java    From Real-World-Software-Development with 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 #5
Source File: SpliteratorCollisions.java    From hottub with 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 #6
Source File: InviteCmd.java    From Shadbot with 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 #7
Source File: ReceiverTest.java    From hono with 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 #8
Source File: RLP.java    From cava with 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 #9
Source File: AnnotationReferenceBuildContextImpl.java    From xtext-xtend with 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 #10
Source File: SpinedBuffer.java    From jdk8u60 with 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 #11
Source File: GraphWalker.java    From mug with 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 #12
Source File: ThrowingConsumer.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Helper to package a {@link ThrowingConsumer} as a {@link Consumer} and apply it on action
 * expecting the latter. Checked exceptions thrown by the former are tunneled inside unchecked
 * exceptions and re-raised.
 */
static <T, E extends Exception> void wrapAsUnchecked(
    Consumer<Consumer<T>> consumerConsumer, ThrowingConsumer<T, E> consumer) throws E {

  // Setup an consumer which runs the given checked consumer, catches the checked exception,
  // packages it in an unchecked exception, and re-throws it.
  Consumer<T> uncheckedConsumer =
      new Consumer<T>() {
        @Override
        public void accept(T t) {
          try {
            consumer.accept(t);
          } catch (Exception exception) {
            // exception: E | RuntimeException | Error
            Throwables.throwIfUnchecked(exception);
            // exception: E
            throw new TunneledException(exception, this);
          }
        }
      };

  // Run the above unchecked consumer, un-packaging any checked exceptions and re-throwing them.
  try {
    consumerConsumer.accept(uncheckedConsumer);
  } catch (TunneledException e) {
    // This tunneled exception doesn't belong to us, so re-throw.
    if (e.owner != uncheckedConsumer) {
      throw e;
    }
    @SuppressWarnings("unchecked")
    E cause = (E) e.getCause();
    throw cause;
  }
}
 
Example #13
Source File: ContinuousQueryWithTransformerRemoteSecurityContextCheckTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @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 #14
Source File: BondingViewUtils.java    From bisq with 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 #15
Source File: RaftStorageTestUtils.java    From incubator-ratis with 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 #16
Source File: StreamSpliterators.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void forEachRemaining(Consumer<? super T> action) {
    s.forEachRemaining(t -> {
        if (seen.putIfAbsent(mapNull(t), Boolean.TRUE) == null) {
            action.accept(t);
        }
    });
}
 
Example #17
Source File: JenkinsPipelineAdapter.java    From ods-provisioning-app with 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 #18
Source File: TreeMap.java    From jdk8u_jdk with 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 #19
Source File: LinkedBlockingDeque.java    From j2objc with 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 #20
Source File: CodahaleMetricsCollector.java    From riposte with 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 #21
Source File: DarkTabbedPaneUI.java    From darklaf with MIT License 5 votes vote down vote up
protected void installComponent(final String key, final Consumer<Component> setter) {
    Component comp = PropertyUtil.getObject(tabPane, key, Component.class);
    if (comp != null) {
        Component wrapped = wrapClientComponent(comp);
        setter.accept(wrapped);
        tabPane.add(wrapped);
    }
}
 
Example #22
Source File: IOFunctions.java    From symja_android_library with 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 File: ProcedureParameterMetadata.java    From lams with 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 File: EJSUtil.java    From jeddict with 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 File: CachedWorldIconProducer.java    From amidst with 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 File: BackfillTriggerManager.java    From styx with 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 File: AlarmLogSearchJob.java    From phoebus with 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 File: ByteBufferRLPWriter.java    From cava with 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());
}
 
Example #29
Source File: CollectionUtils.java    From ngAndroid with 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 File: JobInvocation.java    From beam with 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);
}