Java Code Examples for java.util.Optional#filter()
The following examples show how to use
java.util.Optional#filter() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PendingPeerRequest.java From besu with Apache License 2.0 | 6 votes |
/** * 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(); } }
Example 2
Source File: BatchClientFactoryImpl.java From pravega with Apache License 2.0 | 6 votes |
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); }
Example 3
Source File: OptionalTest.java From j2objc with Apache License 2.0 | 6 votes |
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()); }
Example 4
Source File: NetworkConfig.java From teku with Apache License 2.0 | 5 votes |
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; }
Example 5
Source File: KubernetesDockerRunner.java From styx with Apache License 2.0 | 5 votes |
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)); }
Example 6
Source File: CsvExportStrategy.java From find with MIT License | 5 votes |
@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())); }
Example 7
Source File: BuscadorConteudo.java From portal-de-servicos with MIT License | 5 votes |
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); }
Example 8
Source File: AbstractReflectionReverseRouter.java From commercetools-sunrise-java with Apache License 2.0 | 5 votes |
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)); }
Example 9
Source File: PlanNodeDecorrelator.java From presto with Apache License 2.0 | 4 votes |
@Override public Optional<DecorrelationResult> visitEnforceSingleRow(EnforceSingleRowNode node, Void context) { Optional<DecorrelationResult> childDecorrelationResultOptional = node.getSource().accept(this, null); return childDecorrelationResultOptional.filter(result -> result.atMostSingleRow); }
Example 10
Source File: GroupId.java From liiklus with MIT License | 4 votes |
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)); }
Example 11
Source File: OptionalForFactory.java From soabase-halva with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") @Override public Optional filter(Optional m, Predicate predicate) { return m.filter(predicate); }
Example 12
Source File: OptionalForFactory.java From soabase-halva with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") @Override public Optional filter(Optional m, Predicate predicate) { return m.filter(predicate); }
Example 13
Source File: Emailer.java From james-project with Apache License 2.0 | 4 votes |
private Optional<String> replaceIfNeeded(Optional<String> value) { return value.filter(s -> !s.isEmpty()); }
Example 14
Source File: ContentManager.java From uyuni with GNU General Public License v2.0 | 2 votes |
/** * 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())); }