类java.util.function.Supplier源码实例Demo

下面列出了怎么用java.util.function.Supplier的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: wildfly-core   文件: SecurityRealmService.java
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;
}
 
源代码2 项目: vividus   文件: SubStepsTests.java
@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();
}
 
源代码3 项目: xyTalk-pc   文件: CompletableFutureDemo.java
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);
}
 
源代码5 项目: mockneat   文件: Seq.java
@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();
            }
    };
}
 
源代码6 项目: java-ml-projects   文件: AppUtils.java
/**
 * 
 * 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();
}
 
源代码7 项目: ClaimChunk   文件: SqlBacking.java
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;
}
 
源代码8 项目: openjdk-jdk9   文件: TestLoggerFinder.java
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;
}
 
源代码9 项目: divolte-collector   文件: SeleniumTestBase.java
@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);
}
 
源代码11 项目: quarkus   文件: OidcIdentityProvider.java
@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);
        }
    });

}
 
源代码12 项目: smallrye-reactive-messaging   文件: Message.java
/**
 * 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;
        }
    };
}
 
源代码13 项目: arcusplatform   文件: SessionHeartBeater.java
@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");
}
 
源代码14 项目: webanno   文件: RelationAdapter.java
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;
}
 
源代码15 项目: cyclops   文件: AsyncRSPartitionAndSplittingTest.java
@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());
}
 
源代码16 项目: jdk8u-jdk   文件: ReduceOps.java
/**
 * 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();
        }
    };
}
 
源代码17 项目: component-runtime   文件: ComponentManager.java
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);
    }
}
 
源代码18 项目: paintera   文件: GenericBackendDialogN5.java
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);
}
 
源代码19 项目: blackduck-alert   文件: VulnerabilityUtil.java
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();
}
 
源代码20 项目: bboxdb   文件: AbtractClusterFutureBuilder.java
public Supplier<List<NetworkOperationFuture>> getSupplier() {
	
	if(clusterOperationType == ClusterOperationType.READ_FROM_NODES_HA_IF_REPLICATED) {
		return getReplicatedSupplier();
	} else {
		return getUnreplicatedSupplier();
	}
}
 
源代码21 项目: uima-uimaj   文件: Logger_common_impl.java
/**
 * @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);

}
 
源代码23 项目: moduliths   文件: Documenter.java
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));
}
 
源代码24 项目: patchwork-api   文件: ForgeConfigSpec.java
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;
}
 
源代码25 项目: Plan   文件: JSONCache.java
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);
}
 
源代码26 项目: alf.io   文件: Wrappers.java
public static <T> Optional<T> optionally(Supplier<T> s) {
    try {
        return Optional.ofNullable(s.get());
    } catch (EmptyResultDataAccessException | IllegalArgumentException | IllegalStateException e) {
        return Optional.empty();
    }
}
 
源代码27 项目: apicurio-registry   文件: RegistryClientTest.java
@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);
}
 
源代码28 项目: ratis   文件: ServerRestartTests.java
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());
    }
  }
}
 
源代码29 项目: netbeans   文件: JavaKit.java
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);
      }
 
源代码30 项目: ndbc   文件: ConnectionTest.java
@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));
}
 
 类所在包
 类方法
 同包方法