Java Code Examples for java.util.Optional#flatMap()
The following examples show how to use
java.util.Optional#flatMap() .
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: RoundChangeArtifacts.java From besu with Apache License 2.0 | 6 votes |
public static RoundChangeArtifacts create(final Collection<RoundChange> roundChanges) { final Comparator<RoundChange> preparedRoundComparator = (o1, o2) -> { if (!o1.getPreparedCertificateRound().isPresent()) { return -1; } if (!o2.getPreparedCertificateRound().isPresent()) { return 1; } return o1.getPreparedCertificateRound() .get() .compareTo(o2.getPreparedCertificateRound().get()); }; final List<SignedData<RoundChangePayload>> payloads = roundChanges.stream().map(RoundChange::getSignedPayload).collect(Collectors.toList()); final Optional<RoundChange> roundChangeWithNewestPrepare = roundChanges.stream().max(preparedRoundComparator); final Optional<Block> proposedBlock = roundChangeWithNewestPrepare.flatMap(RoundChange::getProposedBlock); return new RoundChangeArtifacts(proposedBlock, payloads); }
Example 2
Source File: KnowledgeBaseServiceImpl.java From inception with Apache License 2.0 | 6 votes |
@Override public Optional<KBObject> readItem(KnowledgeBase aKb, String aIdentifier) { try (StopWatch watch = new StopWatch(log, "readItem(%s)", aIdentifier)) { Optional<KBConcept> kbConcept = readConcept(aKb, aIdentifier, false); if (kbConcept.isPresent()) { return kbConcept.flatMap((c) -> Optional.of(c)); } // In case we don't get the identifier as a concept we look for property/instance Optional<KBProperty> kbProperty = readProperty(aKb, aIdentifier); if (kbProperty.isPresent()) { return kbProperty.flatMap((p) -> Optional.of(p)); } Optional<KBInstance> kbInstance = readInstance(aKb, aIdentifier); if (kbInstance.isPresent()) { return kbInstance.flatMap((i) -> Optional.of(i)); } return Optional.empty(); } }
Example 3
Source File: RegisterMinionEventMessageAction.java From uyuni with GNU General Public License v2.0 | 6 votes |
private static Optional<Channel> lookupBaseChannel(SUSEProduct sp, ChannelArch arch) { Optional<EssentialChannelDto> productBaseChannelDto = ofNullable(DistUpgradeManager.getProductBaseChannelDto(sp.getId(), arch)); Optional<Channel> baseChannel = productBaseChannelDto.flatMap(base -> { return ofNullable(ChannelFactory.lookupById(base.getId())).map(c -> { LOG.info("Base channel " + c.getName() + " found for OS: " + sp.getName() + ", version: " + sp.getVersion() + ", arch: " + arch.getName()); return c; }); }); if (!baseChannel.isPresent()) { LOG.warn("Product Base channel not found - refresh SCC sync?"); return empty(); } return baseChannel; }
Example 4
Source File: Java8Example.java From pragmatic-java-engineer with GNU General Public License v3.0 | 6 votes |
public static void main(String[] args) { User user = new User(); user.setName("testUser"); Optional<User> optional = Optional.of(user); user = optional.orElse(new User()); user = optional.orElseThrow(RuntimeException::new); user = optional.orElseGet(User::new); Optional<TestUser> testUserOptional = optional.filter(u -> u.getName() != null) .map(u -> { TestUser testUser = new TestUser(); testUser.setName(u.getName()); return testUser; }); Optional<User> userOptional = testUserOptional.flatMap(tu -> { User curUser = new User(); curUser.setName(tu.getName()); return Optional.of(curUser); }); }
Example 5
Source File: BuilderOwnerClassFinder.java From SparkBuilderGenerator with MIT License | 5 votes |
private Optional<TypeDeclaration> getTypeAtCurrentSelection(ICompilationUnit iCompilationUnit, CompilationUnit compilationUnit) { try { Optional<String> className = currentlySelectedApplicableClassesClassNameProvider.provideCurrentlySelectedClassName(iCompilationUnit); Optional<TypeDeclaration> foundType = className.flatMap(internalClassName -> findClassWithClassName(compilationUnit, internalClassName)); if (foundType.isPresent()) { foundType = ofNullable(postProcessFoundType(foundType.get())); } return foundType; } catch (Exception e) { pluginLogger.warn("Cannot extract currently selected class based on offset", e); return Optional.empty(); } }
Example 6
Source File: AstUtils.java From j2cl with Apache License 2.0 | 5 votes |
/** Returns an Optional.empty() if optionalSourcePosition is empty or unnamed */ public static Optional<SourcePosition> emptySourcePositionIfNotNamed( Optional<SourcePosition> optionalSourcePosition) { return optionalSourcePosition.flatMap( sourcePosition -> sourcePosition.getName() == null ? Optional.empty() : Optional.of(sourcePosition)); }
Example 7
Source File: ExampleNamespace.java From datacollector with Apache License 2.0 | 5 votes |
@Override public Optional<MethodInvocationHandler> getInvocationHandler(NodeId methodId) { Optional<ServerNode> node = server.getNodeMap().getNode(methodId); return node.flatMap(n -> { if (n instanceof UaMethodNode) { return ((UaMethodNode) n).getInvocationHandler(); } else { return Optional.empty(); } }); }
Example 8
Source File: AllureCitrus.java From allure-java with Apache License 2.0 | 5 votes |
private void startTestCase(final TestCase testCase) { final String uuid = createUuid(testCase); final TestResult result = new TestResult() .setUuid(uuid) .setName(testCase.getName()) .setStage(Stage.RUNNING); result.getLabels().addAll(getProvidedLabels()); final Optional<? extends Class<?>> testClass = Optional.ofNullable(testCase.getTestClass()); testClass.map(this::getLabels).ifPresent(result.getLabels()::addAll); testClass.map(this::getLinks).ifPresent(result.getLinks()::addAll); result.getLabels().addAll(Arrays.asList( createHostLabel(), createThreadLabel(), createFrameworkLabel("citrus"), createLanguageLabel("java") )); testClass.ifPresent(aClass -> { final String suiteName = aClass.getCanonicalName(); result.getLabels().add(createSuiteLabel(suiteName)); }); final Optional<String> classDescription = testClass.flatMap(this::getDescription); final String description = Stream.of(classDescription) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.joining("\n\n")); result.setDescription(description); getLifecycle().scheduleTestCase(result); getLifecycle().startTestCase(uuid); }
Example 9
Source File: PantsUtil.java From intellij-pants-plugin with Apache License 2.0 | 5 votes |
public static Optional<VirtualFile> getFileInSelectedEditor(@Nullable Project project) { Optional<Editor> editor = Optional.ofNullable(project) .flatMap(p -> Optional.ofNullable(FileEditorManager.getInstance(p).getSelectedTextEditor())); Optional<EditorImpl> editorImpl = editor .flatMap(e -> e instanceof EditorImpl ? Optional.of((EditorImpl) e) : Optional.empty()); return editorImpl.map(EditorImpl::getVirtualFile); }
Example 10
Source File: ResourceMapperUtils.java From dcos-commons with Apache License 2.0 | 5 votes |
/** * @param taskResourceNamespace This is the namespace label from the Mesos * @return If the taskResourceNamespace is non-empty, it MUST match with the namespace the scheduler is in. * If the taskResourceNamespace is empty, we should NOT add a label now. * This is applicable only in the "UPDATE" flow. During creating of new resources, we use the Scheduler namespace. */ static Optional<String> getNamespaceLabel( Optional<String> taskResourceNamespace, Optional<String> resourceNamespace) { return taskResourceNamespace.flatMap(x -> { if (!resourceNamespace.isPresent() || !resourceNamespace.get().equals(x)) { LOGGER.error("Resource has [{}] namespace label but scheduler is in [{}] namespace", x, resourceNamespace); return Optional.empty(); } else { return taskResourceNamespace; } }); }
Example 11
Source File: PlanNodeDecorrelator.java From presto with Apache License 2.0 | 5 votes |
public Optional<DecorrelatedNode> decorrelateFilters(PlanNode node, List<Symbol> correlation) { if (correlation.isEmpty()) { return Optional.of(new DecorrelatedNode(ImmutableList.of(), node)); } Optional<DecorrelationResult> decorrelationResultOptional = node.accept(new DecorrelatingVisitor(metadata, correlation), null); return decorrelationResultOptional.flatMap(decorrelationResult -> decorrelatedNode( decorrelationResult.correlatedPredicates, decorrelationResult.node, correlation)); }
Example 12
Source File: JanusPreviousPropertyStepStrategy.java From grakn with GNU Affero General Public License v3.0 | 5 votes |
private Optional<String> labelFromWhereEqPredicate(WherePredicateStep<Vertex> whereStep) { Optional<P<?>> optionalPredicate = whereStep.getPredicate(); return optionalPredicate.flatMap(predicate -> { if (!predicate.getBiPredicate().equals(Compare.eq)) return Optional.empty(); return Optional.of((String) predicate.getValue()); }); }
Example 13
Source File: ApplicationActivity.java From vespa with Apache License 2.0 | 5 votes |
public static ApplicationActivity from(Collection<Deployment> deployments) { Optional<DeploymentActivity> lastActivityByQuery = lastActivityBy(DeploymentActivity::lastQueried, deployments); Optional<DeploymentActivity> lastActivityByWrite = lastActivityBy(DeploymentActivity::lastWritten, deployments); if (lastActivityByQuery.isEmpty() && lastActivityByWrite.isEmpty()) { return none; } return new ApplicationActivity(lastActivityByQuery.flatMap(DeploymentActivity::lastQueried), lastActivityByWrite.flatMap(DeploymentActivity::lastWritten), lastActivityByQuery.map(DeploymentActivity::lastQueriesPerSecond) .orElseGet(OptionalDouble::empty), lastActivityByWrite.map(DeploymentActivity::lastWritesPerSecond) .orElseGet(OptionalDouble::empty)); }
Example 14
Source File: HiveMetadata.java From presto with Apache License 2.0 | 5 votes |
@Override public Optional<PrestoPrincipal> getSchemaOwner(ConnectorSession session, CatalogSchemaName schemaName) { checkState(filterSchema(schemaName.getSchemaName()), "Schema is not accessible: %s", schemaName); Optional<Database> database = metastore.getDatabase(schemaName.getSchemaName()); if (database.isPresent()) { return database.flatMap(db -> Optional.of(new PrestoPrincipal(db.getOwnerType(), db.getOwnerName()))); } throw new SchemaNotFoundException(schemaName.getSchemaName()); }
Example 15
Source File: CustomerServiceImpl.java From pizzeria with MIT License | 4 votes |
@Override @Transactional(readOnly = true) public Optional<Customer> getCustomerByUsername(String username) { Optional<Account> accountOptional = accountDAO.findByUsername(username); return accountOptional.flatMap(account -> customerDAO.findById(account.getUser().getId())); }
Example 16
Source File: OptionalForFactory.java From soabase-halva with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") @Override public <A> Optional flatMap(Optional m, Function<A, ? extends Optional> flatMapper) { return m.flatMap(flatMapper); }
Example 17
Source File: CachedPlayer.java From Web-API with MIT License | 4 votes |
@JsonIgnore public Optional<User> getUser() { Optional<UserStorageService> optSrv = Sponge.getServiceManager().provide(UserStorageService.class); return optSrv.flatMap(srv -> srv.get(uuid)); }
Example 18
Source File: BuildLogHelper.java From buck with Apache License 2.0 | 4 votes |
private BuildLogEntry newBuildLogEntry(Path logFile) throws IOException { Optional<Path> machineReadableLogFile = Optional.of(logFile.resolveSibling(BuckConstant.BUCK_MACHINE_LOG_FILE_NAME)) .filter(path -> projectFilesystem.isFile(path)); Optional<Integer> exitCode = machineReadableLogFile.flatMap( machineFile -> readObjectFieldFromLog(machineFile, PREFIX_EXIT_CODE, "exitCode")); Optional<InvocationInfo> invocationInfo = machineReadableLogFile.flatMap( machineLogFile -> readObjectFromLog( machineLogFile, PREFIX_INVOCATION_INFO, new TypeReference<InvocationInfo>() {})); Optional<List<String>> commandArgs = invocationInfo.flatMap(iInfo -> Optional.ofNullable(iInfo.getUnexpandedCommandArgs())); Optional<List<String>> expandedCommandArgs = invocationInfo.flatMap(iInfo -> Optional.ofNullable(iInfo.getCommandArgs())); Optional<BuildId> buildId = machineReadableLogFile.map( machineLogFile -> invocationInfo.map(InvocationInfo::getBuildId).orElse(new BuildId("unknown"))); Optional<Long> startTimestampMs = invocationInfo.map(InvocationInfo::getTimestampMillis); Optional<Long> finishTimestampMs = machineReadableLogFile.flatMap( machineFile -> readObjectFieldFromLog(machineFile, PREFIX_BUILD_FINISHED, "timestamp")); OptionalInt buildTimeMs = finishTimestampMs.isPresent() && startTimestampMs.isPresent() ? OptionalInt.of((int) (finishTimestampMs.get() - startTimestampMs.get())) : OptionalInt.empty(); Optional<Path> ruleKeyLoggerFile = Optional.of(logFile.getParent().resolve(BuckConstant.RULE_KEY_LOGGER_FILE_NAME)) .filter(path -> projectFilesystem.isFile(path)); Optional<Path> ruleKeyDiagKeysFile = Optional.of(logFile.getParent().resolve(BuckConstant.RULE_KEY_DIAG_KEYS_FILE_NAME)) .filter(path -> projectFilesystem.isFile(path)); Optional<Path> ruleKeyDiagGraphFile = Optional.of(logFile.getParent().resolve(BuckConstant.RULE_KEY_DIAG_GRAPH_FILE_NAME)) .filter(path -> projectFilesystem.isFile(path)); Optional<Path> traceFile = projectFilesystem.asView() .getFilesUnderPath(logFile.getParent(), EnumSet.of(FileVisitOption.FOLLOW_LINKS)) .stream() .filter(input -> input.toString().endsWith(".trace")) .findFirst(); Optional<Path> configJsonFile = Optional.of(logFile.resolveSibling(BuckConstant.CONFIG_JSON_FILE_NAME)) .filter(projectFilesystem::isFile); Optional<Path> fixSpecFile = Optional.of(logFile.resolveSibling(BuckConstant.BUCK_FIX_SPEC_FILE_NAME)) .filter(projectFilesystem::isFile); return BuildLogEntry.of( logFile, buildId, commandArgs, expandedCommandArgs, exitCode.map(OptionalInt::of).orElseGet(OptionalInt::empty), buildTimeMs, ruleKeyLoggerFile, machineReadableLogFile, ruleKeyDiagKeysFile, ruleKeyDiagGraphFile, traceFile, configJsonFile, fixSpecFile, projectFilesystem.getFileSize(logFile), Date.from(projectFilesystem.getLastModifiedTime(logFile).toInstant())); }
Example 19
Source File: BlackDuckResponseCache.java From blackduck-alert with Apache License 2.0 | 4 votes |
public Optional<String> getProjectLink(String projectVersionUrl, String link) { Optional<ProjectVersionView> optionalProjectVersionFuture = getItem(ProjectVersionView.class, projectVersionUrl); return optionalProjectVersionFuture .flatMap(view -> view.getFirstLink(link)); }
Example 20
Source File: PantsUtil.java From intellij-pants-plugin with Apache License 2.0 | 4 votes |
private static Optional<VirtualFile> findFileRelativeToDirectory(@NotNull @Nls String fileOrDirPath, Optional<VirtualFile> directory) { return directory.flatMap(file -> Optional.ofNullable(file.findFileByRelativePath(fileOrDirPath))); }