java.util.function.BiConsumer Java Examples

The following examples show how to use java.util.function.BiConsumer. 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: StaticUiSpecGenerator.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
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);
        }
    }
}
 
Example #2
Source File: Collector.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #3
Source File: Collector.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #4
Source File: HashMap.java    From aion with MIT License 6 votes vote down vote up
@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();
        }
    }
}
 
Example #5
Source File: ThreadLocalRandomTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
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));
    }
 
Example #6
Source File: SoftKeyHashMap.java    From chart-fx with Apache License 2.0 6 votes vote down vote up
@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();
            }
        }
    }
}
 
Example #7
Source File: IdentityHashMap.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
@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();
        }
    }
}
 
Example #8
Source File: MainTest.java    From gatk with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example #9
Source File: StampedLockTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #10
Source File: Pojofy.java    From vertxui with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @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);
		});
	};
}
 
Example #11
Source File: ExecutionFlow.java    From spring-boot-akka-event-sourcing-starter with Apache License 2.0 5 votes vote down vote up
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;
		}
 
Example #12
Source File: MapUtils.java    From BungeeChat2 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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();
    }
  };
}
 
Example #13
Source File: TestAbstractSubscribeTest.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #14
Source File: OptionalUtils.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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)));
}
 
Example #15
Source File: ExcelResponseValidationStepsTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #16
Source File: IntPipeline.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
@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));
}
 
Example #17
Source File: LifxSelectorUtil.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
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);
        }
    }
}
 
Example #18
Source File: FluxApiImpl.java    From influxdb-client-java with MIT License 5 votes vote down vote up
@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);
}
 
Example #19
Source File: ZeroCodeMultiStepsScenarioRunnerImpl.java    From zerocode with Apache License 2.0 5 votes vote down vote up
@Override
public boolean runChildStep(ScenarioSpec scenarioSpec, BiConsumer testPassHandler) {

    scenarioSpec.getSteps()
            .forEach(step -> testPassHandler.accept(scenarioSpec.getScenarioName(), step.getName()));

    return true;
}
 
Example #20
Source File: IntegrationTest.java    From bitfinex-v2-wss-api-java with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
	}
}
 
Example #21
Source File: ErrorCollectors.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
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));
        }
    };
}
 
Example #22
Source File: MockKube.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #23
Source File: Collectors.java    From desugar_jdk_libs with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example #24
Source File: MonoPeekTerminal.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #25
Source File: InfinispanClusteredAsyncMapTest.java    From vertx-infinispan with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #26
Source File: SearchPane.java    From Recaf with MIT License 5 votes vote down vote up
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);
}
 
Example #27
Source File: ProofListIndexProxyIntegrationTest.java    From exonum-java-binding with Apache License 2.0 5 votes vote down vote up
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
  );
}
 
Example #28
Source File: JarFileSource.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example #29
Source File: TracingMethodMessageHandlerAdapter.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
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();
	}
}
 
Example #30
Source File: PentahoOrcInputFormat.java    From pentaho-hadoop-shims with Apache License 2.0 5 votes vote down vote up
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;
    } );
  }
}