下面列出了java.util.Optional#flatMap ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
});
}
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);
}
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;
}
@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();
}
}
@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();
}
});
}
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));
}
@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());
}
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));
}
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());
});
}
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();
}
}
/**
* @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;
}
});
}
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);
}
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);
}
/** 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));
}
private static Optional<VirtualFile> findFileRelativeToDirectory(@NotNull @Nls String fileOrDirPath, Optional<VirtualFile> directory) {
return directory.flatMap(file -> Optional.ofNullable(file.findFileByRelativePath(fileOrDirPath)));
}
public Optional<String> getProjectLink(String projectVersionUrl, String link) {
Optional<ProjectVersionView> optionalProjectVersionFuture = getItem(ProjectVersionView.class, projectVersionUrl);
return optionalProjectVersionFuture
.flatMap(view -> view.getFirstLink(link));
}
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()));
}
@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()));
}
@SuppressWarnings("unchecked")
@Override
public <A> Optional flatMap(Optional m, Function<A, ? extends Optional> flatMapper)
{
return m.flatMap(flatMapper);
}
@JsonIgnore
public Optional<User> getUser() {
Optional<UserStorageService> optSrv = Sponge.getServiceManager().provide(UserStorageService.class);
return optSrv.flatMap(srv -> srv.get(uuid));
}