java.util.Optional#filter ( )源码实例Demo

下面列出了java.util.Optional#filter ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: besu   文件: PendingPeerRequest.java
/**
 * 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();
  }
}
 
源代码2 项目: pravega   文件: BatchClientFactoryImpl.java
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);
}
 
源代码3 项目: j2objc   文件: OptionalTest.java
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());
}
 
源代码4 项目: teku   文件: NetworkConfig.java
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;
}
 
源代码5 项目: styx   文件: KubernetesDockerRunner.java
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));
}
 
源代码6 项目: find   文件: CsvExportStrategy.java
@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()));
}
 
源代码7 项目: portal-de-servicos   文件: BuscadorConteudo.java
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));
}
 
源代码9 项目: presto   文件: PlanNodeDecorrelator.java
@Override
public Optional<DecorrelationResult> visitEnforceSingleRow(EnforceSingleRowNode node, Void context)
{
    Optional<DecorrelationResult> childDecorrelationResultOptional = node.getSource().accept(this, null);
    return childDecorrelationResultOptional.filter(result -> result.atMostSingleRow);
}
 
源代码10 项目: liiklus   文件: GroupId.java
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));
}
 
源代码11 项目: soabase-halva   文件: OptionalForFactory.java
@SuppressWarnings("unchecked")
@Override
public Optional filter(Optional m, Predicate predicate)
{
    return m.filter(predicate);
}
 
源代码12 项目: soabase-halva   文件: OptionalForFactory.java
@SuppressWarnings("unchecked")
@Override
public Optional filter(Optional m, Predicate predicate)
{
    return m.filter(predicate);
}
 
源代码13 项目: james-project   文件: Emailer.java
private Optional<String> replaceIfNeeded(Optional<String> value) {
    return value.filter(s -> !s.isEmpty());
}
 
源代码14 项目: uyuni   文件: ContentManager.java
/**
 * 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()));
}