本文整理汇总了Java中java.util.Optional类的典型用法代码示例。如果您正苦于以下问题:Java Optional类的具体用法?Java Optional怎么用?Java Optional使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Optional类属于java.util包,在下文中一共展示了Optional类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: find
import java.util.Optional; //导入依赖的package包/类
@Override
public Optional<SingleLookupReply> find(SingleLookupRequest request) {
Optional<String> mediumUrl = Optional.ofNullable(cfg.getMappings().get(request.getType()));
if (mediumUrl.isPresent() && !StringUtils.isBlank(mediumUrl.get())) {
log.info("Using specific medium bridge lookup URL {}", mediumUrl.get());
return fetcher.find(mediumUrl.get(), request);
} else if (!StringUtils.isBlank(cfg.getServer())) {
log.info("Using generic bridge lookup URL {}", cfg.getServer());
return fetcher.find(cfg.getServer(), request);
} else {
log.info("No bridge lookup URL found/configured, skipping");
return Optional.empty();
}
}
示例2: updateUser
import java.util.Optional; //导入依赖的package包/类
/**
* Update all information for a specific user, and return the modified user.
*/
public Optional<UserDTO> updateUser(UserDTO userDTO) {
return Optional.of(userRepository
.findOne(userDTO.getId()))
.map(user -> {
user.setLogin(userDTO.getLogin());
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
user.setEmail(userDTO.getEmail());
user.setImageUrl(userDTO.getImageUrl());
user.setActivated(userDTO.isActivated());
user.setLangKey(userDTO.getLangKey());
Set<Authority> managedAuthorities = user.getAuthorities();
managedAuthorities.clear();
userDTO.getAuthorities().stream()
.map(authorityRepository::findOne)
.forEach(managedAuthorities::add);
log.debug("Changed Information for User: {}", user);
return user;
})
.map(UserDTO::new);
}
示例3: lookup
import java.util.Optional; //导入依赖的package包/类
@Override
public Optional<DiscreteResource> lookup(DiscreteResourceId id) {
DiscreteResource resource = Resources.discrete(id).resource();
Class<?> cls = getClass(resource);
return Optional.ofNullable(values.get(cls))
.filter(x -> x.contains(resource))
.map(x -> resource);
}
示例4: retrieveCredentials
import java.util.Optional; //导入依赖的package包/类
/**
* Retrieve the credentials.
*
* @param context the web context
* @return the credentials
* @throws HttpAction whether an additional HTTP action is required
*/
protected CompletableFuture<C> retrieveCredentials(final AsyncWebContext context) throws HttpAction {
return this.credentialsExtractor.extract(context)
.thenCompose(creds -> {
return Optional.ofNullable(creds)
.map(c -> this.authenticator.validate(creds, context).thenApply(v -> creds))
.orElse(CompletableFuture.completedFuture(creds)); // The orElse leaves any null returns
})
// Now translate a CredentialsException to null
.handle(ExceptionSoftener.softenBiFunction((creds, throwable) -> {
// throwable being non-null means creds will be null, so we can make this check here
logger.info("In handle call");
if (throwable == null || throwable instanceof CredentialsException) {
return creds;
} else {
throw throwable;
}
}));
}
示例5: act
import java.util.Optional; //导入依赖的package包/类
@Override
public ActionResponse act(ActionResponse input, Connection connection) throws ParaFlowException
{
Optional<Object> sfIdOp = input.getProperties("sfId");
Optional<Object> paramOp = input.getParam();
if (paramOp.isPresent() && sfIdOp.isPresent()) {
long sfId = (long) sfIdOp.get();
String sqlStatement = SQLTemplate.findStorageFormatName(sfId);
ResultList resultList = connection.executeQuery(sqlStatement);
if (!resultList.isEmpty()) {
input.setProperties("sfName", resultList.get(0).get(0));
}
else {
throw new StorageFormatNotFoundException(String.valueOf(sfId));
}
}
else {
throw new ActionParamNotValidException();
}
return input;
}
示例6: convert
import java.util.Optional; //导入依赖的package包/类
@Override
public Optional<RuleToPluginMsg<?>> convert(RuleContext ctx, ToDeviceActorMsg toDeviceActorMsg,
RuleProcessingMetaData metadata) {
String sendFlag = configuration.getSendFlag();
if (StringUtils.isEmpty(sendFlag) || (Boolean) metadata.get(sendFlag).orElse(Boolean.FALSE)) {
VelocityContext context = VelocityUtils.createContext(metadata);
SendMailActionMsg.SendMailActionMsgBuilder builder = SendMailActionMsg.builder();
fromTemplate.ifPresent(t -> builder.from(VelocityUtils.merge(t, context)));
toTemplate.ifPresent(t -> builder.to(VelocityUtils.merge(t, context)));
ccTemplate.ifPresent(t -> builder.cc(VelocityUtils.merge(t, context)));
bccTemplate.ifPresent(t -> builder.bcc(VelocityUtils.merge(t, context)));
subjectTemplate.ifPresent(t -> builder.subject(VelocityUtils.merge(t, context)));
bodyTemplate.ifPresent(t -> builder.body(VelocityUtils.merge(t, context)));
return Optional.of(new SendMailRuleToPluginActionMsg(toDeviceActorMsg.getTenantId(),
toDeviceActorMsg.getCustomerId(), toDeviceActorMsg.getDeviceId(), builder.build()));
} else {
return Optional.empty();
}
}
示例7: sendPipelinedIfPossible
import java.util.Optional; //导入依赖的package包/类
private SendSequence sendPipelinedIfPossible(SmtpRequest mailRequest, Collection<String> recipients, SmtpRequest dataRequest, Optional<SendInterceptor> sequenceInterceptor) {
List<SmtpRequest> requests = Lists.newArrayListWithExpectedSize(2 + recipients.size());
requests.add(mailRequest);
requests.addAll(rpctCommands(recipients));
requests.add(dataRequest);
if (ehloResponse.isSupported(Extension.PIPELINING)) {
return beginSequence(sequenceInterceptor, requests.size(), requests.toArray());
} else {
SendSequence s = beginSequence(sequenceInterceptor, 1, requests.get(0));
for (int i = 1; i < requests.size(); i++) {
s.thenSend(requests.get(i));
}
return s;
}
}
示例8: loadService
import java.util.Optional; //导入依赖的package包/类
@Override
public Optional<T> loadService() {
return httpProviders.stream()
.map(SdkHttpServiceProvider::loadService)
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
}
示例9: of
import java.util.Optional; //导入依赖的package包/类
public static SecretSeries of(
long id,
String name,
@Nullable String description,
ApiDate createdAt,
@Nullable String createdBy,
ApiDate updatedAt,
@Nullable String updatedBy,
@Nullable String type,
@Nullable Map<String, String> generationOptions,
@Nullable Long currentVersion) {
ImmutableMap<String, String> options = (generationOptions == null) ? ImmutableMap.of() : ImmutableMap.copyOf(generationOptions);
return new AutoValue_SecretSeries(id,
name,
nullToEmpty(description),
createdAt,
nullToEmpty(createdBy),
updatedAt,
nullToEmpty(updatedBy),
Optional.ofNullable(type), options,
Optional.ofNullable(currentVersion));
}
示例10: getRoots
import java.util.Optional; //导入依赖的package包/类
@Override
public URL[] getRoots() {
URL[] res = cache.get();
if (res == null) {
final boolean exists = moduleExists();
res = Optional.ofNullable(exists ? evaluator.getProperty(jdocProperty) : null)
.filter((path) -> getOwner(evaluator, helper, artefact, new String[]{prop}) != null)
.map((path) -> FileUtil.urlForArchiveOrDir(helper.resolveFile(path)))
.map((url) -> new URL[]{url})
.orElse(EMPTY);
if (!cache.compareAndSet(null, res)) {
URL[] tmp = cache.get();
res = tmp != null ?
tmp :
res;
} else {
currentModuleExists.set(exists);
}
}
return Arrays.copyOf(res, res.length);
}
示例11: loadBuildTypeList_callback_dispatches_parent_project_on_event_bus
import java.util.Optional; //导入依赖的package包/类
@Test
public void loadBuildTypeList_callback_dispatches_parent_project_on_event_bus( ) throws Exception {
// Setup
final ProjectData project = new ProjectData( "p1", "pname", Optional.<String>empty( ) );
final ProjectData project2 = new ProjectData( "p2", "pname", Optional.<String>empty( ) );
_projectManager.registerProjects( ImmutableList.of( project, project2 ) );
final BuildTypeList buildTypelist = new BuildTypeList( );
buildTypelist.addBuildType( new BuildType( "bt1", "btName", "pname", "p2" ) );
when( _mockRequestController.sendRequest( getApiVersion( ), "buildTypes", BuildTypeList.class ) )
.thenReturn( Futures.immediateFuture( buildTypelist ) );
// Exercise
_apiController.loadBuildTypeList( );
// Verify
assertThat( _dispatchedObjects, not( hasItem( project ) ) );
assertThat( _dispatchedObjects, hasItem( project2 ) );
}
示例12: sync
import java.util.Optional; //导入依赖的package包/类
void sync(@NonNull PolicyConfiguration config) {
LOG.info("Synchronizing policy {}...", config.getPolicyName());
AlertsPolicy alertsPolicyFromConfig = AlertsPolicy.builder()
.name(config.getPolicyName())
.incidentPreference(config.getIncidentPreference().name())
.build();
Optional<AlertsPolicy> policy = api.getAlertsPoliciesApi().getByName(config.getPolicyName());
if (policy.isPresent()) {
AlertsPolicy oldPolicy = policy.get();
if (!StringUtils.equals(alertsPolicyFromConfig.getIncidentPreference(), oldPolicy.getIncidentPreference())) {
api.getAlertsPoliciesApi().delete(oldPolicy.getId());
api.getAlertsPoliciesApi().create(alertsPolicyFromConfig);
LOG.info(format("Policy %s updated", config.getPolicyName()));
}
} else {
api.getAlertsPoliciesApi().create(alertsPolicyFromConfig);
LOG.info("Policy {} created", config.getPolicyName());
}
LOG.info("Policy {} synchronized", config.getPolicyName());
}
示例13: tryGetRegisteredVolume
import java.util.Optional; //导入依赖的package包/类
static Optional<Pair<Byte, Byte>> tryGetRegisteredVolume(ItemStack is)
{
if (is.isEmpty())
{
return Optional.empty();
}
String name = is.getItem().getRegistryName().toString();
int meta = is.getMetadata();
Pair<String, Short> p = Pair.of(name, (short) meta);
if (configVolumes.containsKey(p))
{
return Optional.of(configVolumes.get(p));
}
Pair<String, Short> p2 = Pair.of(name, (short) OreDictionary.WILDCARD_VALUE);
if (configVolumes.containsKey(p2))
{
return Optional.of(configVolumes.get(p2));
}
return Optional.empty();
}
示例14: assertThatUserMustExistToResetPassword
import java.util.Optional; //导入依赖的package包/类
@Test
public void assertThatUserMustExistToResetPassword() {
Optional<User> maybeUser = userService.requestPasswordReset("[email protected]");
assertThat(maybeUser.isPresent()).isFalse();
maybeUser = userService.requestPasswordReset("[email protected]");
assertThat(maybeUser.isPresent()).isTrue();
assertThat(maybeUser.get().getEmail()).isEqualTo("[email protected]");
assertThat(maybeUser.get().getResetDate()).isNotNull();
assertThat(maybeUser.get().getResetKey()).isNotNull();
}
示例15: anchor
import java.util.Optional; //导入依赖的package包/类
BaseComponent anchor(Element el) {
final Optional<String> href = XML.attrValue(el, "href");
final Optional<BaseComponent> content = nonEmptyContent(el);
final String type = XML.attrValue(el, "type").orElse("url");
final Renderable<URI> uri;
try {
switch(type) {
case "user":
uri = new UserURI(href.orElse(""));
break;
case "home":
uri = Renderable.of(Links.homeUri(href.orElse("/")));
break;
case "url":
uri = Renderable.of(new URI(href.orElseThrow(() -> new MissingException("attribute", "href"))));
break;
default:
throw new ValueException("Unknown anchor type '" + type + "'");
}
} catch(URISyntaxException e) {
throw new ValueException(e.getMessage());
}
return new LinkComponent(uri, content);
}