下面列出了怎么用java.util.function.Supplier的API类实例代码及写法,或者点击链接到github查看源代码。
public SecurityRealmService(final Consumer<SecurityRealm> securityRealmConsumer,
final Supplier<SubjectSupplementalService> subjectSupplementalSupplier,
final Supplier<CallbackHandlerFactory> secretCallbackFactorySupplier,
final Supplier<KeytabIdentityFactoryService> keytabFactorySupplier,
final Supplier<SSLContext> sslContextSupplier,
final Supplier<String> tmpDirPathSupplier,
final Set<Supplier<CallbackHandlerService>> callbackHandlerServices,
final String name, final boolean mapGroupsToRoles) {
this.securityRealmConsumer = securityRealmConsumer;
this.subjectSupplementalSupplier = subjectSupplementalSupplier;
this.secretCallbackFactorySupplier = secretCallbackFactorySupplier;
this.keytabFactorySupplier = keytabFactorySupplier;
this.sslContextSupplier = sslContextSupplier;
this.tmpDirPathSupplier = tmpDirPathSupplier;
this.callbackHandlerServices = callbackHandlerServices;
this.name = name;
this.mapGroupsToRoles = mapGroupsToRoles;
}
@Test
void shouldExecuteSubStepWithParameters()
{
@SuppressWarnings("unchecked")
Supplier<String> parameterProvider = mock(Supplier.class);
when(parameterProvider.get()).thenReturn("parameters");
StepResult stepResult = mock(StepResult.class);
Step compositeStep = mock(Step.class);
when(step.getComposedSteps()).thenReturn(List.of(compositeStep, compositeStep));
when(compositeStep.perform(storyReporter, null)).thenReturn(stepResult);
InOrder ordered = inOrder(subStepsListener, step, parameterProvider, stepResult);
when(step.perform(storyReporter, null)).thenReturn(stepResult);
Keywords keywords = mock(Keywords.class);
when(configuration.keywords()).thenReturn(keywords);
when(step.asString(keywords)).thenReturn("step");
subSteps.execute(Optional.of(parameterProvider));
ordered.verify(subStepsListener).beforeSubSteps();
ordered.verify(parameterProvider).get();
ordered.verify(stepResult).withParameterValues("step [parameters]");
ordered.verify(stepResult).describeTo(storyReporter);
ordered.verify(subStepsListener).afterSubSteps();
ordered.verifyNoMoreInteractions();
}
private String demoNoBlock() {
CompletableFuture<String> resultCompletableFuture = CompletableFuture.supplyAsync(new Supplier<String>() {
public String get() {
try {
TimeUnit.SECONDS.sleep(6);
//int i = 1/0; 如果有异常,则永远也不返回,即永远得不到结果
System.out.println("执行线程:"+Thread.currentThread().getName());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "hello";
}
}, executor);
resultCompletableFuture.thenAcceptAsync(new Consumer<String>() {
@Override
public void accept(String t) {
System.out.println(t);
System.out.println("回调线程:"+Thread.currentThread().getName());
frame.setTitle(t);
}
}, executor);
System.out.println("直接不阻塞返回了######");
return "直接不阻塞返回了######";
}
private static <T, S extends Spliterator<T>> void testSplitOnce(
Collection<T> exp,
Supplier<S> supplier,
UnaryOperator<Consumer<T>> boxingAdapter) {
S spliterator = supplier.get();
long sizeIfKnown = spliterator.getExactSizeIfKnown();
boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
ArrayList<T> fromSplit = new ArrayList<>();
Spliterator<T> s1 = supplier.get();
Spliterator<T> s2 = s1.trySplit();
long s1Size = s1.getExactSizeIfKnown();
long s2Size = (s2 != null) ? s2.getExactSizeIfKnown() : 0;
Consumer<T> addToFromSplit = boxingAdapter.apply(fromSplit::add);
if (s2 != null)
s2.forEachRemaining(addToFromSplit);
s1.forEachRemaining(addToFromSplit);
if (sizeIfKnown >= 0) {
assertEquals(sizeIfKnown, fromSplit.size());
if (s1Size >= 0 && s2Size >= 0)
assertEquals(sizeIfKnown, s1Size + s2Size);
}
assertContents(fromSplit, exp, isOrdered);
}
@Override
public Supplier<T> supplier() {
return () -> {
if (iterator.hasNext())
return (T) iterator.next();
else
if (cycle) {
this.iterator = iterable.iterator();
return (T) iterator.next();
}
else {
if (after == null) {
return null;
}
return (T) after.get();
}
};
}
/**
*
* Perform an async call
*
* @param action
* @param success
* @param error
*/
public static <T extends Object> void doAsyncWork(Supplier<T> action, Consumer<T> success,
Consumer<Throwable> error) {
Task<T> tarefaCargaPg = new Task<T>() {
@Override
protected T call() throws Exception {
return action.get();
}
@Override
protected void succeeded() {
success.accept(getValue());
}
@Override
protected void failed() {
error.accept(getException());
}
};
Thread t = new Thread(tarefaCargaPg);
t.setDaemon(true);
t.start();
}
static boolean getTableDoesntExist(ClaimChunk claimChunk,
Supplier<Connection> connection,
String databaseName,
String tableName) throws SQLException {
String sql = "SELECT count(*) FROM information_schema.TABLES WHERE (`TABLE_SCHEMA` = ?) AND (`TABLE_NAME` = ?)";
try (PreparedStatement statement = prep(claimChunk, connection, sql)) {
statement.setString(1, databaseName);
statement.setString(2, tableName);
try (ResultSet results = statement.executeQuery()) {
if (results.next()) {
return results.getInt(1) <= 0;
}
}
}
return true;
}
public static LogEvent of(long sequenceNumber,
boolean isLoggable, String name,
Logger.Level level, ResourceBundle bundle,
String key, Supplier<String> supplier,
Throwable thrown, Object... params) {
LogEvent evt = new LogEvent(sequenceNumber);
evt.loggerName = name;
evt.level = level;
evt.args = params;
evt.bundle = bundle;
evt.thrown = thrown;
evt.supplier = supplier;
evt.msg = key;
evt.isLoggable = isLoggable;
return evt;
}
@Parameters(name = "Selenium JS test: {1} (quirks-mode={2})")
public static Iterable<Object[]> sauceLabBrowsersToTest() {
final Collection<Object[]> browserList;
if (!System.getenv().containsKey(DRIVER_ENV_VAR)) {
browserList = Collections.emptyList();
} else if (SAUCE_DRIVER.equals(System.getenv().get(DRIVER_ENV_VAR))) {
browserList = SAUCE_BROWSER_LIST;
logger.info("Selenium test running on SauceLabs with these browsers:\n{}",
browserNameList(SAUCE_BROWSER_LIST));
} else if (BS_DRIVER.equals(System.getenv().get(DRIVER_ENV_VAR))) {
browserList = BS_BROWSER_LIST;
logger.info("Selenium test running on BrowserStack with these browsers:\n{}",
browserNameList(BS_BROWSER_LIST));
} else {
// Parameters are not used for non-sauce tests
browserList = ImmutableList.of(new Object[] {
(Supplier<DesiredCapabilities>) () -> LOCAL_RUN_CAPABILITIES, "Local JS test run"
});
}
// For each browser, we need to run in and out of quirks mode.
return browserList.stream()
.flatMap((browser) ->
ImmutableList.of(new Object[] { browser[0], browser[1], false },
new Object[] { browser[0], browser[1], true }).stream())
.collect(Collectors.toList());
}
@Override
public IView filterView(final IView view, final JSONFilterViewRequest filterViewRequest, Supplier<IViewsRepository> viewsRepo)
{
final CreateViewRequest.Builder filterViewBuilder = CreateViewRequest.filterViewBuilder(view, filterViewRequest);
if (view instanceof HUEditorView)
{
final HUEditorView huEditorView = HUEditorView.cast(view);
filterViewBuilder.setParameters(huEditorView.getParameters());
final ViewId parentViewId = huEditorView.getParentViewId();
final IView parentView = viewsRepo.get().getView(parentViewId);
if (parentView instanceof PickingSlotView)
{
final PickingSlotView pickingSlotView = PickingSlotView.cast(parentView);
filterViewBuilder.setParameter(HUsToPickViewFilters.PARAM_CurrentShipmentScheduleId, pickingSlotView.getCurrentShipmentScheduleId());
}
}
final CreateViewRequest createViewRequest = filterViewBuilder.build();
return createView(createViewRequest);
}
@Override
public Uni<SecurityIdentity> authenticate(TokenAuthenticationRequest request,
AuthenticationRequestContext context) {
ContextAwareTokenCredential credential = (ContextAwareTokenCredential) request.getToken();
RoutingContext vertxContext = credential.getContext();
return Uni.createFrom().deferred(new Supplier<Uni<SecurityIdentity>>() {
@Override
public Uni<SecurityIdentity> get() {
if (tenantResolver.isBlocking(vertxContext)) {
return context.runBlocking(new Supplier<SecurityIdentity>() {
@Override
public SecurityIdentity get() {
return authenticate(request, vertxContext).await().indefinitely();
}
});
}
return authenticate(request, vertxContext);
}
});
}
/**
* Create a message with the given payload and ack function.
* No metadata are associated with the message.
* Negative-acknowledgement is immediate.
*
* @param payload The payload, must not be {@code null}.
* @param ack The ack function, this will be invoked when the returned messages {@link #ack()} method is invoked.
* @param <T> the type of payload
* @return A message with the given payload, no metadata and ack function.
*/
static <T> Message<T> of(T payload, Supplier<CompletionStage<Void>> ack) {
if (payload == null) {
throw new IllegalArgumentException("`payload` must not be `null`");
}
return new Message<T>() {
@Override
public T getPayload() {
return payload;
}
@Override
public Metadata getMetadata() {
return Metadata.empty();
}
@Override
public Supplier<CompletionStage<Void>> getAck() {
return ack;
}
};
}
@Inject
public SessionHeartBeater(
Partitioner partitioner,
IntraServiceMessageBus intraServiceBus,
Supplier<Stream<PartitionedSession>> sessionSupplier
) {
this.sessionSupplier = sessionSupplier;
this.partitioner = partitioner;
this.intraServiceBus = intraServiceBus;
this.executor = Executors
.newSingleThreadScheduledExecutor(
ThreadPoolBuilder
.defaultFactoryBuilder()
.setNameFormat("ipcd-session-heartbeat")
.build()
);
this.heartbeatTimer = IrisMetrics.metrics("bridge.ipcd").timer("heartbeat");
}
public RelationAdapter(LayerSupportRegistry aLayerSupportRegistry,
FeatureSupportRegistry aFeatureSupportRegistry,
ApplicationEventPublisher aEventPublisher, AnnotationLayer aLayer,
String aTargetFeatureName, String aSourceFeatureName,
Supplier<Collection<AnnotationFeature>> aFeatures,
List<RelationLayerBehavior> aBehaviors)
{
super(aLayerSupportRegistry, aFeatureSupportRegistry, aEventPublisher, aLayer, aFeatures);
if (aBehaviors == null) {
behaviors = emptyList();
}
else {
List<RelationLayerBehavior> temp = new ArrayList<>(aBehaviors);
AnnotationAwareOrderComparator.sort(temp);
behaviors = temp;
}
sourceFeatureName = aSourceFeatureName;
targetFeatureName = aTargetFeatureName;
}
@Test
public void testPartition() {
Supplier<ReactiveSeq<Integer>> s = () -> of(1, 2, 3, 4, 5, 6);
assertEquals(asList(1, 3, 5), s.get().partition(i -> i % 2 != 0)._1().toList());
assertEquals(asList(2, 4, 6), s.get().partition(i -> i % 2 != 0)._2().toList());
assertEquals(asList(2, 4, 6), s.get().partition(i -> i % 2 == 0)._1().toList());
assertEquals(asList(1, 3, 5), s.get().partition(i -> i % 2 == 0)._2().toList());
assertEquals(asList(1, 2, 3), s.get().partition(i -> i <= 3)._1().toList());
assertEquals(asList(4, 5, 6), s.get().partition(i -> i <= 3)._2().toList());
assertEquals(asList(1, 2, 3, 4, 5, 6), s.get().partition(i -> true)._1().toList());
assertEquals(asList(), s.get().partition(i -> true)._2().toList());
assertEquals(asList(), s.get().partition(i -> false)._1().toList());
assertEquals(asList(1, 2, 3, 4, 5, 6), s.get().partition(i -> false)._2().toList());
}
/**
* Constructs a {@code TerminalOp} that implements a mutable reduce on
* {@code double} values.
*
* @param <R> the type of the result
* @param supplier a factory to produce a new accumulator of the result type
* @param accumulator a function to incorporate an int into an
* accumulator
* @param combiner a function to combine an accumulator into another
* @return a {@code TerminalOp} implementing the reduction
*/
public static <R> TerminalOp<Double, R>
makeDouble(Supplier<R> supplier,
ObjDoubleConsumer<R> accumulator,
BinaryOperator<R> combiner) {
Objects.requireNonNull(supplier);
Objects.requireNonNull(accumulator);
Objects.requireNonNull(combiner);
class ReducingSink extends Box<R>
implements AccumulatingSink<Double, R, ReducingSink>, Sink.OfDouble {
@Override
public void begin(long size) {
state = supplier.get();
}
@Override
public void accept(double t) {
accumulator.accept(state, t);
}
@Override
public void combine(ReducingSink other) {
state = combiner.apply(state, other.state);
}
}
return new ReduceOp<Double, R, ReducingSink>(StreamShape.DOUBLE_VALUE) {
@Override
public ReducingSink makeSink() {
return new ReducingSink();
}
};
}
private <T> T executeInContainer(final String plugin, final Supplier<T> supplier) {
final Thread thread = Thread.currentThread();
final ClassLoader old = thread.getContextClassLoader();
thread
.setContextClassLoader(
container.find(plugin).map(Container::getLoader).map(ClassLoader.class::cast).orElse(old));
try {
return supplier.get();
} finally {
thread.setContextClassLoader(old);
}
}
public GenericBackendDialogN5(
final Node n5RootNode,
final Node browseNode,
final String identifier,
final ObservableValue<Supplier<N5Writer>> writerSupplier,
final ExecutorService propagationExecutor)
{
this("_Dataset", n5RootNode, browseNode, identifier, writerSupplier, propagationExecutor);
}
private static Optional<LinkableItem> createRemediationItem(Supplier<ComponentVersionRemediatingFixesPreviousVulnerabilitiesView> getRemediationOption, String remediationLabel) {
ComponentVersionRemediatingFixesPreviousVulnerabilitiesView remediatingVersionView = getRemediationOption.get();
if (null != remediatingVersionView) {
String versionText = createRemediationVersionText(remediatingVersionView);
return Optional.of(new LinkableItem(remediationLabel, versionText, remediatingVersionView.getComponentVersion()));
}
return Optional.empty();
}
public Supplier<List<NetworkOperationFuture>> getSupplier() {
if(clusterOperationType == ClusterOperationType.READ_FROM_NODES_HA_IF_REPLICATED) {
return getReplicatedSupplier();
} else {
return getUnreplicatedSupplier();
}
}
/**
* @param msgSupplier
* A function, which when called, produces the desired log message
* @param throwable
* the exception to log
*/
@Override
public void info(Supplier<String> msgSupplier, Throwable throwable) {
if (isLoggable(Level.INFO) && isNotLimited(Level.INFO)) {
log2(null, fqcnCmn, Level.INFO, msgSupplier.get(), null, throwable);
}
}
public ShowLogPatternParserEditor(OtrosApplication otrosApplication,
String logPatternResourceName,
String actionName,
String shortDescription,
Icon icon, Supplier<LogPatternParserEditorBase> viewSupplier) {
super(otrosApplication);
this.viewSupplier = viewSupplier;
putValue(NAME, actionName);
putValue(SHORT_DESCRIPTION, shortDescription);
putValue(SMALL_ICON, icon);
logPatternText = loadDefaultText(logPatternResourceName);
}
private void addComponentsToView(Supplier<Stream<Module>> modules, ComponentView view, Options options,
Consumer<ComponentView> afterCleanup) {
modules.get().filter(options.getExclusions().negate()) //
.map(it -> getComponents(options).get(it)) //
.filter(options.getComponentFilter()).forEach(view::add);
// Remove filtered dependency types
DependencyType.allBut(options.getDependencyTypes()) //
.map(Object::toString) //
.forEach(it -> view.removeRelationshipsWithTag(it));
afterCleanup.accept(view);
// Filter outgoing relationships of target-only modules
modules.get().filter(options.getTargetOnly()) //
.forEach(module -> {
Component component = getComponents(options).get(module);
view.getRelationships().stream() //
.map(RelationshipView::getRelationship) //
.filter(it -> it.getSource().equals(component)) //
.forEach(it -> view.remove(it));
});
// … as well as all elements left without a relationship
view.removeElementsWithNoRelationships();
afterCleanup.accept(view);
// Remove default relationships if more qualified ones exist
view.getRelationships().stream() //
.map(RelationshipView::getRelationship) //
.collect(Collectors.groupingBy(Connection::of)) //
.values().stream() //
.forEach(it -> potentiallyRemoveDefaultRelationship(view, it));
}
private ValueSpec(Supplier<?> supplier, Predicate<Object> validator, BuilderContext context) {
Objects.requireNonNull(supplier, "Default supplier can not be null");
Objects.requireNonNull(validator, "Validator can not be null");
this.comment = context.hasComment() ? context.buildComment() : null;
this.langKey = context.getTranslationKey();
this.range = context.getRange();
this.worldRestart = context.needsWorldRestart();
this.clazz = context.getClazz();
this.supplier = supplier;
this.validator = validator;
}
public static String getOrCacheString(DataID dataID, UUID serverUUID, Supplier<String> stringSupplier) {
String identifier = dataID.of(serverUUID);
byte[] found = cache.getIfPresent(identifier);
if (found == null) {
String result = stringSupplier.get();
cache.put(identifier, result.getBytes(StandardCharsets.UTF_8));
return result;
}
return new String(found, StandardCharsets.UTF_8);
}
public static <T> Optional<T> optionally(Supplier<T> s) {
try {
return Optional.ofNullable(s.get());
} catch (EmptyResultDataAccessException | IllegalArgumentException | IllegalStateException e) {
return Optional.empty();
}
}
@RegistryServiceTest
public void testSmoke(Supplier<RegistryService> supplier) {
RegistryService service = supplier.get();
service.deleteAllGlobalRules();
Assertions.assertNotNull(service.toString());
Assertions.assertEquals(service.hashCode(), service.hashCode());
Assertions.assertEquals(service, service);
}
static void writeSomething(Supplier<Message> newMessage, MiniRaftCluster cluster) throws Exception {
try(final RaftClient client = cluster.createClient()) {
// write some messages
for(int i = 0; i < 10; i++) {
Assert.assertTrue(client.send(newMessage.get()).isSuccess());
}
}
}
protected void initDocument(BaseDocument doc) {
// doc.addLayer(new JavaDrawLayerFactory.JavaLayer(),
// JavaDrawLayerFactory.JAVA_LAYER_VISIBILITY);
doc.putProperty(SyntaxUpdateTokens.class,
new SyntaxUpdateTokens() {
private List tokenList = new ArrayList();
public void syntaxUpdateStart() {
tokenList.clear();
}
public List syntaxUpdateEnd() {
return tokenList;
}
public void syntaxUpdateToken(TokenID id, TokenContextPath contextPath, int offset, int length) {
if (JavaTokenContext.LINE_COMMENT == id) {
tokenList.add(new TokenInfo(id, contextPath, offset, length));
}
}
}
);
InputAttributes attrs = new InputAttributes();
attrs.setValue(JavaTokenId.language(), "fileName", (Supplier<String>) () -> { //NOI18N
FileObject fo = NbEditorUtilities.getFileObject(doc);
return fo != null ? fo.getNameExt() : null;
}, true);
attrs.setValue(JavaTokenId.language(), "version", (Supplier<String>) () -> { //NOI18N
return getSourceLevel(doc);
}, true);
doc.putProperty(InputAttributes.class, attrs);
}
@Test
public void isValidTrue() throws CheckedFutureException {
final List<Row> result = new ArrayList<>();
final String query = "SELECT 1";
final Supplier<Connection> sup = new ConnectionSupplier() {
@Override
BiFunction<String, List<Value<?>>, Exchange<List<Row>>> extendedQueryExchange() {
return (q, b) -> {
assertEquals(query, q);
return Exchange.value(result);
};
}
};
assertEquals(true, sup.get().isValid().get(timeout));
}