Java Code Examples for java.util.function.Supplier#get()

The following examples show how to use java.util.function.Supplier#get() . 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: DefaultProjectBuildFileParserFactory.java    From buck with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 2
Source File: ConcurrentFactoryMap.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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();
    }
  };
}
 
Example 3
Source File: DiffProcessor.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
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;
        }
    };
}
 
Example 4
Source File: SpliteratorTraversingAndSplittingTest.java    From TencentKona-8 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();

        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);
    }
}
 
Example 5
Source File: SemanticMetricBuilderFactory.java    From semantic-metrics with Apache License 2.0 5 votes vote down vote up
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);
        }
    };
}
 
Example 6
Source File: RingBuffer.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
private void fill(Supplier<E> eventFactory)
{
	for (int i = 0; i < bufferSize; i++)
	{
		entries[BUFFER_PAD + i] = eventFactory.get();
	}
}
 
Example 7
Source File: AbstractConfiguredObject.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 8
Source File: BlockedNamespacesTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@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);
}
 
Example 9
Source File: ConfigurationClassProcessingTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
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"));
}
 
Example 10
Source File: TypedMap.java    From swage with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example 11
Source File: ESTestCase.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 12
Source File: GuavaMemoizerUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
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)));
}
 
Example 13
Source File: VarbinaryDecoder.java    From presto with Apache License 2.0 5 votes vote down vote up
@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()));
    }
}
 
Example 14
Source File: SpliteratorLateBindingFailFastTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@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));
}
 
Example 15
Source File: SupplierUtilsTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 16
Source File: None.java    From INFDEV02-4 with MIT License 4 votes vote down vote up
public <U> U visit(Supplier<U> onNone, Function<T, U> onSome) {
    return onNone.get();
}
 
Example 17
Source File: DynamicLambdaTest.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
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();
}
 
Example 18
Source File: TestActions.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
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);
}
 
Example 19
Source File: Fixtures.java    From ocraft-s2client with MIT License 4 votes vote down vote up
@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;
}
 
Example 20
Source File: Future.java    From future with Apache License 2.0 3 votes vote down vote up
/**
 * 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);
  }
}