下面列出了java.util.Optional#filter ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Attempts to find an available peer and execute the peer request.
*
* @return true if the request should be removed from the pending list, otherwise false.
*/
public boolean attemptExecution() {
if (result.isDone()) {
return true;
}
final Optional<EthPeer> leastBusySuitablePeer = getLeastBusySuitablePeer();
if (!leastBusySuitablePeer.isPresent()) {
// No peers have the required height.
result.completeExceptionally(new NoAvailablePeersException());
return true;
} else {
// At least one peer has the required height, but we not be able to use it if it's busy
final Optional<EthPeer> selectedPeer =
leastBusySuitablePeer.filter(EthPeer::hasAvailableRequestCapacity);
selectedPeer.ifPresent(this::sendRequest);
return selectedPeer.isPresent();
}
}
private StreamSegmentsIterator listSegments(final Stream stream, final Optional<StreamCut> startStreamCut,
final Optional<StreamCut> endStreamCut) {
val startCut = startStreamCut.filter(sc -> !sc.equals(StreamCut.UNBOUNDED));
val endCut = endStreamCut.filter(sc -> !sc.equals(StreamCut.UNBOUNDED));
//Validate that the stream cuts are for the requested stream.
startCut.ifPresent(streamCut -> Preconditions.checkArgument(stream.equals(streamCut.asImpl().getStream())));
endCut.ifPresent(streamCut -> Preconditions.checkArgument(stream.equals(streamCut.asImpl().getStream())));
// if startStreamCut is not provided use the streamCut at the start of the stream.
// if toStreamCut is not provided obtain a streamCut at the tail of the stream.
CompletableFuture<StreamCut> startSCFuture = startCut.isPresent() ?
CompletableFuture.completedFuture(startCut.get()) : streamCutHelper.fetchHeadStreamCut(stream);
CompletableFuture<StreamCut> endSCFuture = endCut.isPresent() ?
CompletableFuture.completedFuture(endCut.get()) : streamCutHelper.fetchTailStreamCut(stream);
//fetch the StreamSegmentsInfo based on start and end streamCuts.
CompletableFuture<StreamSegmentsIterator> streamSegmentInfo = startSCFuture.thenCombine(endSCFuture,
(startSC, endSC) -> getStreamSegmentInfo(stream, startSC, endSC));
return getAndHandleExceptions(streamSegmentInfo, RuntimeException::new);
}
public void testFilter() {
Optional<String> empty = Optional.empty();
Optional<String> ofNull = Optional.ofNullable(null);
Predicate<String> alwaysFail = s -> { fail(); return true; };
// If isPresent() == false, optional always returns itself (!!).
assertSame(empty, empty.filter(alwaysFail));
assertSame(empty, empty.filter(alwaysFail));
assertSame(ofNull, ofNull.filter(alwaysFail));
assertSame(ofNull, ofNull.filter(alwaysFail));
final String foo = "foo";
Optional<String> optionalFoo = Optional.of(foo);
Predicate<String> alwaysTrue = s -> true;
Predicate<String> alwaysFalse = s -> false;
assertSame(empty, optionalFoo.filter(alwaysFalse));
assertSame(optionalFoo, optionalFoo.filter(alwaysTrue));
final AtomicReference<String> reference = new AtomicReference<>();
optionalFoo.filter(s -> { reference.set(s); return true; });
assertSame(foo, reference.get());
}
public NetworkConfig(
final PrivKey privateKey,
final String networkInterface,
final Optional<String> advertisedIp,
final int listenPort,
final OptionalInt advertisedPort,
final List<String> staticPeers,
final boolean isDiscoveryEnabled,
final List<String> bootnodes,
final TargetPeerRange targetPeerRange,
final GossipConfig gossipConfig,
final WireLogsConfig wireLogsConfig) {
this.privateKey = privateKey;
this.networkInterface = networkInterface;
this.advertisedIp = advertisedIp.filter(ip -> !ip.isBlank());
if (this.advertisedIp.map(ip -> !isInetAddress(ip)).orElse(false)) {
throw new IllegalArgumentException("Advertised ip is set incorrectly.");
}
this.listenPort = listenPort;
this.advertisedPort = advertisedPort;
this.staticPeers = staticPeers;
this.isDiscoveryEnabled = isDiscoveryEnabled;
this.bootnodes = bootnodes;
this.targetPeerRange = targetPeerRange;
this.gossipConfig = gossipConfig;
this.wireLogsConfig = wireLogsConfig;
}
private Optional<RunState> lookupPodRunState(Pod pod, WorkflowInstance workflowInstance) {
final Optional<RunState> runStateOpt = stateManager.getActiveState(workflowInstance);
if (runStateOpt.isEmpty()) {
LOG.debug("Pod event for unknown or inactive workflow instance {}", workflowInstance);
return Optional.empty();
}
return runStateOpt.filter(runState -> isPodRunState(pod, runState));
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public Optional<FieldInfo<?>> getFieldInfoForNode(final String nodeName, final Collection<String> selectedFieldIds) {
final Optional<FieldInfo<?>> maybeFieldInfo = Optional.ofNullable(getFieldsInfo().getFieldConfigByName().get(fieldPathNormaliser.normaliseFieldPath(nodeName)));
return maybeFieldInfo
.filter(fieldInfo -> selected(selectedFieldIds, fieldInfo.getId()));
}
private Page<PaginaEstatica> executaQuery(Optional<String> termoBuscado, Integer paginaAtual,
Integer quantidadeDeResultados, Function<String, QueryBuilder> criaQuery) {
Optional<String> termo = termoBuscado.filter(t -> !t.isEmpty());
PageRequest pageable = new PageRequest(paginaAtual, quantidadeDeResultados);
return termo.map(criaQuery)
.map(q -> et.query(
new NativeSearchQueryBuilder()
.withIndices(PORTAL_DE_SERVICOS_INDEX)
.withTypes(ORGAO.getNome(), PAGINA_TEMATICA.getNome(), SERVICO.getNome())
.withFields("id", "tipoConteudo", "nome", "conteudo", "descricao")
.withQuery(q)
.withPageable(pageable)
.build(),
r -> new FacetedPageImpl<>(Stream.of(r.getHits().getHits())
.map(h -> new PaginaEstatica()
.withId(h.field("id").value())
.withTipoConteudo((String) Optional.ofNullable(h.field("tipoConteudo"))
.filter(Objects::nonNull)
.map(SearchHitField::value)
.orElse("servico"))
.withNome(h.field("nome").value())
.withConteudo(Optional.ofNullable(h.field("descricao"))
.orElse(h.field("conteudo"))
.value()))
.collect(toList()), pageable, r.getHits().totalHits())))
.orElse(SEM_RESULTADOS);
}
private Optional<ReverseCaller> findReverseCallerForSunriseRoute(final String sunriseRouteTag, final ParsedRoute parsedRoute, final Method routerMethod) {
final Class<?> controllerClass = parsedRoute.getControllerClass();
final Optional<Method> methodMatchingRouteOpt = findControllerMethodMatchingSunriseRoute(sunriseRouteTag, controllerClass);
final Optional<Method> methodMatchingRouteAndParametersOpt = methodMatchingRouteOpt
.filter(method -> Arrays.equals(method.getParameterTypes(), routerMethod.getParameterTypes()));
if (methodMatchingRouteOpt.isPresent() && !methodMatchingRouteAndParametersOpt.isPresent()) {
logger.warn("Annotation @SunriseRoute {} assigned to a method not matching parameters", sunriseRouteTag);
}
return methodMatchingRouteAndParametersOpt
.flatMap(matchingMethod -> createReverseCaller(matchingMethod, controllerClass));
}
@Override
public Optional<DecorrelationResult> visitEnforceSingleRow(EnforceSingleRowNode node, Void context)
{
Optional<DecorrelationResult> childDecorrelationResultOptional = node.getSource().accept(this, null);
return childDecorrelationResultOptional.filter(result -> result.atMostSingleRow);
}
public static GroupId of(String name, Optional<Integer> version) {
if (version.orElse(0) < 0) {
throw new IllegalArgumentException("version must be >= 0");
}
return new GroupId(name, version.filter(it -> it != 0));
}
@SuppressWarnings("unchecked")
@Override
public Optional filter(Optional m, Predicate predicate)
{
return m.filter(predicate);
}
@SuppressWarnings("unchecked")
@Override
public Optional filter(Optional m, Predicate predicate)
{
return m.filter(predicate);
}
private Optional<String> replaceIfNeeded(Optional<String> value) {
return value.filter(s -> !s.isEmpty());
}
/**
* Look up filter by id and user
*
* @param id the id
* @param user the user
* @return the matching filter
*/
public static Optional<ContentFilter> lookupFilterById(Long id, User user) {
Optional<ContentFilter> filter = ContentProjectFactory.lookupFilterById(id);
return filter.filter(f -> f.getOrg().equals(user.getOrg()));
}