下面列出了java.util.function.Supplier#get ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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();
}
};
}
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);
}
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)));
}
@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));
}
@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);
}
};
}
/**
* 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;
}
/**
* 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"));
}
@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);
}
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;
}
private void fill(Supplier<E> eventFactory)
{
for (int i = 0; i < bufferSize; i++)
{
entries[BUFFER_PAD + i] = eventFactory.get();
}
}
@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;
}
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);
}
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();
}
public <U> U visit(Supplier<U> onNone, Function<T, U> onSome) {
return onNone.get();
}
/**
* 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);
}
}