java.util.function.Supplier#get ( )源码实例Demo

下面列出了java.util.function.Supplier#get ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: consulo   文件: ConcurrentFactoryMap.java
@Nonnull
public static <K, V> ConcurrentMap<K, V> create(@Nonnull Function<? super K, ? extends V> computeValue, @Nonnull Supplier<? extends ConcurrentMap<K, V>> mapCreator) {
  return new ConcurrentFactoryMap<K, V>() {
    @Nullable
    @Override
    protected V create(K key) {
      return computeValue.fun(key);
    }

    @Nonnull
    @Override
    protected ConcurrentMap<K, V> createMap() {
      return mapCreator.get();
    }
  };
}
 
源代码2 项目: centraldogma   文件: DiffProcessor.java
DiffProcessor(ReplaceMode replaceMode, final Supplier<Map<JsonPointer, JsonNode>> unchangedValuesSupplier) {
    this.replaceMode = replaceMode;
    this.unchangedValuesSupplier = new Supplier<Map<JsonPointer, JsonNode>>() {

        @Nullable
        private Map<JsonPointer, JsonNode> unchangedValues;

        @Override
        public Map<JsonPointer, JsonNode> get() {
            if (unchangedValues == null) {
                unchangedValues = unchangedValuesSupplier.get();
            }
            return unchangedValues;
        }
    };
}
 
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();

        assertRootSpliterator(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);
    }
}
 
private ProjectBuildFileParser newPythonParser(
    Cell cell,
    TypeCoercerFactory typeCoercerFactory,
    Console console,
    BuckEventBus eventBus,
    ProjectBuildFileParserOptions buildFileParserOptions,
    boolean threadSafe,
    Optional<UserDefinedRuleLoader> udrLoader) {
  Supplier<ProjectBuildFileParser> parserSupplier =
      () ->
          new PythonDslProjectBuildFileParser(
              buildFileParserOptions,
              typeCoercerFactory,
              cell.getBuckConfig().getEnvironment(),
              eventBus,
              new DefaultProcessExecutor(console),
              processedBytes,
              udrLoader);
  if (!threadSafe) {
    return parserSupplier.get();
  }
  return new ConcurrentProjectBuildFileParser(parserSupplier);
}
 
源代码5 项目: tutorials   文件: GuavaMemoizerUnitTest.java
private <T> void assertSupplierGetExecutionResultAndDuration(Supplier<T> supplier,
                                                             T expectedValue,
                                                             double expectedDurationInMs) {
    Instant start = Instant.now();
    T value = supplier.get();
    Long durationInMs = Duration.between(start, Instant.now()).toMillis();
    double marginOfErrorInMs = 100D;

    assertThat(value, is(equalTo(expectedValue)));
    assertThat(durationInMs.doubleValue(), is(closeTo(expectedDurationInMs, marginOfErrorInMs)));
}
 
源代码6 项目: resilience4j   文件: SupplierUtilsTest.java
@Test(expected = RuntimeException.class)
public void shouldRethrowException2() {
    Supplier<String> supplier = () -> {
        throw new RuntimeException("BAM!");
    };
    Supplier<String> supplierWithRecovery = SupplierUtils.recover(supplier, IllegalArgumentException.class, (ex) -> "Bla");

    supplierWithRecovery.get();
}
 
@Test(dataProvider = "Source")
public <T> void lateBindingTestWithTryAdvance(String description, Supplier<Source<T>> ss) {
    Source<T> source = ss.get();
    Collection<T> c = source.asCollection();
    Spliterator<T> s = c.spliterator();

    source.update();

    Set<T> r = new HashSet<>();
    while (s.tryAdvance(r::add)) { }

    assertEquals(r, new HashSet<>(c));
}
 
源代码8 项目: presto   文件: VarbinaryDecoder.java
@Override
public void decode(SearchHit hit, Supplier<Object> getter, BlockBuilder output)
{
    Object value = getter.get();
    if (value == null) {
        output.appendNull();
    }
    else if (value instanceof String) {
        VARBINARY.writeSlice(output, Slices.wrappedBuffer(Base64.getDecoder().decode(value.toString())));
    }
    else {
        throw new PrestoException(TYPE_MISMATCH, format("Expected a string value for field '%s' of type VARBINARY: %s [%s]", path, value, value.getClass().getSimpleName()));
    }
}
 
public static SemanticMetricBuilder<Timer> timerWithReservoir(
    final Supplier<Reservoir> reservoirSupplier) {
    return new SemanticMetricBuilder<Timer>() {
        @Override
        public Timer newMetric() {
            return new Timer(reservoirSupplier.get());
        }

        @Override
        public boolean isInstance(final Metric metric) {
            return Timer.class.isInstance(metric);
        }
    };
}
 
源代码10 项目: crate   文件: ESTestCase.java
/**
 * helper to get a random value in a certain range that's different from the input
 */
public static <T> T randomValueOtherThanMany(Predicate<T> input, Supplier<T> randomSupplier) {
    T randomValue = null;
    do {
        randomValue = randomSupplier.get();
    } while (input.test(randomValue));
    return randomValue;
}
 
源代码11 项目: swage   文件: TypedMap.java
/**
 * Returns the data stored for the given key, or if not present the value from the supplier.
 * @param key the key to retrive data for
 * @param supplier a supplier for the default value
 * @param <T> the data type
 * @return the data stored for the key, or the default value from the supplier
 */
default <T> T getOrElseGet(Key<T> key, Supplier<T> supplier) {
    T value = get(key);
    if (value == null) {
        return supplier.get();
    } else {
        return value;
    }
}
 
private void aliasesAreRespected(Class<?> testClass, Supplier<TestBean> testBeanSupplier, String beanName) {
	TestBean testBean = testBeanSupplier.get();
	BeanFactory factory = initBeanFactory(testClass);

	assertSame(testBean, factory.getBean(beanName));
	Arrays.stream(factory.getAliases(beanName)).map(factory::getBean).forEach(alias -> assertSame(testBean, alias));

	// method name should not be registered
	assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
			factory.getBean("methodName"));
}
 
源代码13 项目: ditto   文件: BlockedNamespacesTest.java
@Test
public void startSeveralTimes() throws Exception {
    // This test simulates the situation where the root actor of a Ditto service restarts several times.

    // GIVEN: Many blocked-namespaces objects were obtained in the same actor system.
    final Supplier<BlockedNamespaces> blockedNamespacesSupplier = () -> BlockedNamespaces.of(actorSystem);
    for (int i = 0; i < 10; ++i) {
        blockedNamespacesSupplier.get();
    }

    // WHEN: Another blocked-namespaces object is obtained.
    // THEN: It fulfills its function.
    testCRUD(blockedNamespacesSupplier.get(), actorSystem);
}
 
源代码14 项目: qpid-broker-j   文件: AbstractConfiguredObject.java
private boolean isReferred(final ConfiguredObject<?> referee,
                           final Class<?> attributeValueType,
                           final Type attributeGenericType,
                           final Supplier<?> attributeValue)
{
    final Class<? extends ConfiguredObject> referrerCategory = referee.getCategoryClass();
    if (referrerCategory.isAssignableFrom(attributeValueType))
    {
        return attributeValue.get() == referee;
    }
    else if (hasParameterOfType(attributeGenericType, referrerCategory))
    {
        Object value = attributeValue.get();
        if (value instanceof Collection)
        {
            return ((Collection<?>) value).stream().anyMatch(m -> m == referee);
        }
        else if (value instanceof Object[])
        {
            return Arrays.stream((Object[]) value).anyMatch(m -> m == referee);
        }
        else if (value instanceof Map)
        {
            return ((Map<?, ?>) value).entrySet()
                                      .stream()
                                      .anyMatch(e -> e.getKey() == referee
                                                     || e.getValue() == referee);
        }
    }
    return false;
}
 
源代码15 项目: reactor-core   文件: RingBuffer.java
private void fill(Supplier<E> eventFactory)
{
	for (int i = 0; i < bufferSize; i++)
	{
		entries[BUFFER_PAD + i] = eventFactory.get();
	}
}
 
源代码16 项目: ocraft-s2client   文件: Fixtures.java
@SafeVarargs
public static <T> T without(Supplier<T> supplier, Consumer<T>... clear) {
    T builder = supplier.get();
    stream(clear).forEach(c -> c.accept(builder));
    return builder;
}
 
源代码17 项目: alfresco-remote-api   文件: TestActions.java
private void checkSorting(
        Supplier<List<Pair<String, String>>> expectedFun,
        CheckedBiFunction<PublicApiClient.Paging, Map<String, String>, ListResponse<ActionDefinition>, PublicApiException> actionsFun,
        String sortField)
        throws PublicApiException
{
    // Retrieve all the actions directly using the ActionService and sorted appropriately.
    List<Pair<String, String>> expectedActions = expectedFun.get();

    // Retrieve all action defs using the REST API - then check that they match
    // the list retrieved directly from the ActionService.
    PublicApiClient.Paging paging = getPaging(0, Integer.MAX_VALUE);

    // Retrieve all the results, sorted, on one page
    Map<String, String> orderBy = Collections.singletonMap("orderBy", sortField);
    ListResponse<ActionDefinition> actionDefs = actionsFun.apply(paging, orderBy);

    List<Pair<String, String>> retrievedActions = actionDefs.getList().stream().
            map(act -> new Pair<>(act.getName(), act.getTitle())).
            collect(Collectors.toList());

    // Check the whole lists match
    assertEquals(expectedActions, retrievedActions);

    // Again, by sortField, but with explicit ascending sort order
    orderBy = Collections.singletonMap("orderBy", sortField + " asc");
    actionDefs = actionsFun.apply(paging, orderBy);

    retrievedActions = actionDefs.getList().stream().
            map(act -> new Pair<>(act.getName(), act.getTitle())).
            collect(Collectors.toList());

    // Check the whole lists match
    assertEquals(expectedActions, retrievedActions);
    
    // Descending sort order
    orderBy = Collections.singletonMap("orderBy", sortField + " desc");
    actionDefs = actionsFun.apply(paging, orderBy);

    retrievedActions = actionDefs.getList().stream().
            map(act -> new Pair<>(act.getName(), act.getTitle())).
            collect(Collectors.toList());

    // Check the whole lists match
    Collections.reverse(expectedActions);
    assertEquals(expectedActions, retrievedActions);

    // Combine paging with sorting by sortField, descending.
    final int pageSize = 2;
    paging = getPaging(pageSize, pageSize);
    actionDefs = actionsFun.apply(paging, orderBy);

    retrievedActions = actionDefs.getList().stream().
            map(act -> new Pair<>(act.getName(), act.getTitle())).
            collect(Collectors.toList());

    assertEquals(expectedActions.subList(pageSize, pageSize*2), retrievedActions);
}
 
源代码18 项目: ProjectAres   文件: DynamicLambdaTest.java
public void testWidenReturnType() throws Exception {
    class C { String woot() { return null; } }
    final Supplier<Object> lambda = Methods.lambda(new TypeToken<Supplier<Object>>(){}, C.class.getDeclaredMethod("woot"), new C());
    lambda.get();
}
 
源代码19 项目: INFDEV02-4   文件: None.java
public <U> U visit(Supplier<U> onNone, Function<T, U> onSome) {
    return onNone.get();
}
 
源代码20 项目: future   文件: Future.java
/**
 * Applies the provided supplier and flattens the result. This method is useful
 * to apply a supplier safely without having to catch possible synchronous exceptions
 * that the supplier may throw.
 * 
 * @param s     a supplier that may throw an exception
 * @return the  future produced by the supplier or a failed future if the supplier 
 *              throws a synchronous exception (not a failed Future)
 */
public static <T> Future<T> flatApply(final Supplier<Future<T>> s) {
  try {
    return s.get();
  } catch (final Throwable ex) {
    return new ExceptionFuture<>(ex);
  }
}
 
 方法所在类
 同类方法