当前位置: 首页>>代码示例>>Java>>正文


Java Optional类代码示例

本文整理汇总了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();
    }
}
 
开发者ID:kamax-io,项目名称:mxisd,代码行数:18,代码来源:BridgeFetcher.java

示例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);
}
 
开发者ID:AppertaFoundation,项目名称:Code4Health-Platform,代码行数:25,代码来源:UserService.java

示例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);
}
 
开发者ID:shlee89,项目名称:athena,代码行数:9,代码来源:EncodableDiscreteResources.java

示例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;
                }
            }));
}
 
开发者ID:millross,项目名称:pac4j-async,代码行数:26,代码来源:AsyncBaseClient.java

示例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;
}
 
开发者ID:dbiir,项目名称:paraflow,代码行数:22,代码来源:GetStorageFormatNameAction.java

示例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();
  }
}
 
开发者ID:osswangxining,项目名称:iotplatform,代码行数:21,代码来源:SendMailAction.java

示例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;
  }
}
 
开发者ID:HubSpot,项目名称:NioSmtpClient,代码行数:19,代码来源:SmtpSession.java

示例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();
}
 
开发者ID:aws,项目名称:aws-sdk-java-v2,代码行数:9,代码来源:SdkHttpServiceProviderChain.java

示例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));
}
 
开发者ID:oneops,项目名称:secrets-proxy,代码行数:25,代码来源:SecretSeries.java

示例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);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:22,代码来源:MultiModuleJavadocForBinaryQueryImpl.java

示例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 ) );
}
 
开发者ID:u2032,项目名称:wall-t,代码行数:19,代码来源:ApiControllerTest.java

示例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());
}
 
开发者ID:ocadotechnology,项目名称:newrelic-alerts-configurator,代码行数:24,代码来源:PolicyConfigurator.java

示例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();
}
 
开发者ID:V0idWa1k3r,项目名称:ExPetrum,代码行数:24,代码来源:IWeightProvider.java

示例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();
}
 
开发者ID:GastonMauroDiaz,项目名称:buenojo,代码行数:13,代码来源:UserServiceTest.java

示例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);
}
 
开发者ID:OvercastNetwork,项目名称:ProjectAres,代码行数:30,代码来源:MarkupParser.java


注:本文中的java.util.Optional类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。