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


Java Optional.orElseThrow方法代码示例

本文整理汇总了Java中java.util.Optional.orElseThrow方法的典型用法代码示例。如果您正苦于以下问题:Java Optional.orElseThrow方法的具体用法?Java Optional.orElseThrow怎么用?Java Optional.orElseThrow使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.Optional的用法示例。


在下文中一共展示了Optional.orElseThrow方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: loadUserByUsername

import java.util.Optional; //导入方法依赖的package包/类
/**
 * Get user by username. Login process.
 *
 * @param username The user's name
 * @return UserDetails object
 * @throws UsernameNotFoundException No user found
 */
@Override
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
    log.info("Called with username {}", username);

    Optional<UserEntity> userOptional = userRepository.findByUsernameIgnoreCaseAndEnabledTrue(username);

    userOptional.orElseThrow(() -> new UsernameNotFoundException("No user found with username " + username));

    Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
    for(SecurityRole role : userOptional.get().getAuthorities()) {
        grantedAuthorities.add(new SimpleGrantedAuthority(role.toString()));
    }

    return new org.springframework.security.core.userdetails.User(userOptional.get().getUsername(),
                                                                  userOptional.get().getPassword(),
                                                                  grantedAuthorities);
}
 
开发者ID:JonkiPro,项目名称:REST-Web-Services,代码行数:25,代码来源:UserDetailsServiceImpl.java

示例2: getOne

import java.util.Optional; //导入方法依赖的package包/类
@RequestMapping(value = "/{tenantId}", method = RequestMethod.GET)
public Tenant getOne(@PathVariable final String tenantId) {
  Optional<Tenant> maybeTenant = this.tenantService.findById(tenantId);
  maybeTenant.orElseThrow(IllegalStateException::new);
  return maybeTenant.get();
}
 
开发者ID:Apereo-Learning-Analytics-Initiative,项目名称:OpenLRW,代码行数:7,代码来源:TenantController.java

示例3: getCsrfToken

import java.util.Optional; //导入方法依赖的package包/类
/**
 * get the csrf token from the login page's http form
 *
 * @return the csrf token
 *
 * @throws IOException
 * @param forwardedForHeader
 */
private String getCsrfToken(Header forwardedForHeader) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpGet httpGet = new HttpGet(configuration.getLoginUrl());
        httpGet.setHeader(forwardedForHeader);
        CloseableHttpResponse response1 = httpclient.execute(httpGet, context);
        try {
            logger.debug(response1.getStatusLine().toString());
            Optional<String> csrfTokenOpt = extractCsrfTokenAndCloseConnection(response1);
            return csrfTokenOpt.orElseThrow(
                    () -> new IllegalStateException("failed to extract csrf token."));
        } finally {
            response1.close();
        }
    } finally {
        httpclient.close();
    }
}
 
开发者ID:iteratec,项目名称:security-karate,代码行数:27,代码来源:LoginExecutor.java

示例4: provideExtractorForValue

import java.util.Optional; //导入方法依赖的package包/类
private <T> ValueExtractor provideExtractorForValue(Class<T> clazz, int target, List<String> chainOfProperties) {
    Class<?> propertyClass = clazz;
    List<ValueExtractor> chainedExtractors = Lists.newArrayList();

    for (String property : chainOfProperties) {
        Class<?> finalPropertyClass = propertyClass;

        Optional<Method> matchingMethod = Stream.of(property,
                "get" + WordUtils.capitalize(property),
                "is" + WordUtils.capitalize(property))
                .map(token -> MethodUtils.getMatchingMethod(finalPropertyClass, token))
                .findFirst();

        Method method = matchingMethod.orElseThrow(
                () -> new InvalidQueryException(
                        String.format("Cannot find appropriate method for property [%s] on class [%s]",
                                property, finalPropertyClass)));

        ReflectionExtractor extractor = new ReflectionExtractor(method.getName());
        chainedExtractors.add(extractor);
        propertyClass = method.getDeclaringClass();
    }

    return new ChainedExtractor(chainedExtractors.toArray(new ValueExtractor[chainedExtractors.size()]));
}
 
开发者ID:michalwojciechowski,项目名称:coherence-sql,代码行数:26,代码来源:ReflectionExtractorFactory.java

示例5: chooseBestProvider

import java.util.Optional; //导入方法依赖的package包/类
private TranslationProvider chooseBestProvider(Boolean isFast, String langpair, String domain) {

        // Search for a perfect match
        Optional<? extends TranslationProvider> provider = providers.stream()
                .filter(p -> p.isFast() == isFast)
                .filter(p -> p.getLang().equals(langpair))
                .filter(p -> p.getDomain().equals(domain))
                .min(Comparator.comparingInt(TranslationProvider::load));

        if (provider.isPresent()) {
            return provider.get();
        }

        // Search for a partial match ignoring GPU/CPU preference
        provider = providers.stream()
                .filter(p -> p.getLang().equals(langpair))
                .filter(p -> p.getDomain().equals(domain))
                .min(Comparator.comparingInt(TranslationProvider::load));

        return provider.orElseThrow(() -> new NoProviderException("No suitable translation provider found"));
    }
 
开发者ID:TartuNLP,项目名称:sauron,代码行数:22,代码来源:TranslationServiceImpl.java

示例6: map

import java.util.Optional; //导入方法依赖的package包/类
@Override
@SuppressWarnings("unchecked")
protected CollectionRoutes map(
	CollectionRouter collectionRouter,
	ServiceReference<CollectionRouter> serviceReference,
	Class<?> modelClass) {

	ProvideFunction provideFunction =
		httpServletRequest -> clazz -> _providerManager.provideOptional(
			clazz, httpServletRequest);

	Optional<String> optional = _nameManager.getNameOptional(
		modelClass.getName());

	String name = optional.orElseThrow(
		() -> new MustHaveValidGenericType(modelClass));

	Builder builder = new Builder<>(modelClass, name, provideFunction);

	return collectionRouter.collectionRoutes(builder);
}
 
开发者ID:liferay,项目名称:com-liferay-apio-architect,代码行数:22,代码来源:CollectionRouterManagerImpl.java

示例7: loadUserByUsername

import java.util.Optional; //导入方法依赖的package包/类
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
	
	Optional<DbUser> dbUser = userRepo.findByUsername(username);
	
	System.out.println(username);
	System.out.println(Json.toJson(dbUser));
	
	dbUser 
		.orElseThrow(() -> new UsernameNotFoundException("Username not found"));
	return dbUser
		.map(CustomUserDetails::new).get();
}
 
开发者ID:vishal1997,项目名称:DiscussionPortal,代码行数:14,代码来源:CustomUserDetailsService.java

示例8: validateAccountUser

import java.util.Optional; //导入方法依赖的package包/类
@RequestMapping(value = "/login", method = RequestMethod.POST)
public GenericResponse validateAccountUser(@RequestParam("username") String username, @RequestParam("password") String password) {
    final Optional<AccountUser> optAccountUserer = accountUserRepository.findByUsername(username);
    final AccountUser accountUser = optAccountUserer.orElseThrow(AccountUserNotFoundException::new);
    if (!password.equals(accountUser.getPassword()))
        throw new AccountUserNotFoundException();
    return new GenericResponse("success");
}
 
开发者ID:sweIhm,项目名称:sweiproject-tg2b-1,代码行数:9,代码来源:ActivityController.java

示例9: getServerURL

import java.util.Optional; //导入方法依赖的package包/类
/**
 * Returns the server URL, or throws a {@link MustHaveProvider} developer
 * error.
 *
 * @return the server URL
 */
protected ServerURL getServerURL() {
	Optional<ServerURL> optional = _providerManager.provideOptional(
		ServerURL.class, _httpServletRequest);

	return optional.orElseThrow(
		() -> new MustHaveProvider(ServerURL.class));
}
 
开发者ID:liferay,项目名称:com-liferay-apio-architect,代码行数:14,代码来源:FormMessageBodyWriter.java

示例10: map

import java.util.Optional; //导入方法依赖的package包/类
@Override
@SuppressWarnings("unchecked")
protected NestedCollectionRoutes map(
	NestedCollectionRouter nestedCollectionRouter,
	ServiceReference<NestedCollectionRouter> serviceReference,
	Class<?> modelClass) {

	Class<?> parentClass = getGenericClassFromPropertyOrElse(
		serviceReference, PARENT_MODEL_CLASS,
		() -> getTypeParamOrFail(
			nestedCollectionRouter, NestedCollectionRouter.class, 1));

	Class<?> identifierClass = getGenericClassFromPropertyOrElse(
		serviceReference, PARENT_IDENTIFIER_CLASS,
		() -> getTypeParamOrFail(
			nestedCollectionRouter, NestedCollectionRouter.class, 2));

	ProvideFunction provideFunction =
		httpServletRequest -> clazz -> _providerManager.provideOptional(
			clazz, httpServletRequest);

	Optional<String> nameOptional = _nameManager.getNameOptional(
		modelClass.getName());

	String name = nameOptional.orElseThrow(
		() -> new MustHaveValidGenericType(modelClass));

	Optional<String> nestedNameOptional = _nameManager.getNameOptional(
		parentClass.getName());

	String nestedName = nestedNameOptional.orElseThrow(
		() -> new MustHaveValidGenericType(modelClass));

	Builder builder = new Builder<>(
		modelClass, name, nestedName, identifierClass, provideFunction);

	return nestedCollectionRouter.collectionRoutes(builder);
}
 
开发者ID:liferay,项目名称:com-liferay-apio-architect,代码行数:39,代码来源:NestedCollectionRouterManagerImpl.java

示例11: _updatePerson

import java.util.Optional; //导入方法依赖的package包/类
private Person _updatePerson(Long personId, PersonForm personForm) {
	Optional<Person> optional = Person.updatePerson(
		personForm.getAddress(), personForm.getImage(),
		personForm.getBirthDate(), personForm.getEmail(),
		personForm.getGivenName(), personForm.getJobTitle(),
		personForm.getFamilyName(), personId);

	return optional.orElseThrow(
		() -> new NotFoundException("Unable to get person " + personId));
}
 
开发者ID:liferay,项目名称:com-liferay-apio-architect,代码行数:11,代码来源:PersonCollectionResource.java

示例12: ConnectionActionHandler

import java.util.Optional; //导入方法依赖的package包/类
public ConnectionActionHandler(final Connection connection, final VerificationConfigurationProperties config, EncryptionComponent encryptionComponent) {
    this.connection = connection;
    this.config = config;
    this.encryptionComponent = encryptionComponent;

    final Optional<Connector> maybeConnector = connection.getConnector();
    connector = maybeConnector.orElseThrow(() -> new EntityNotFoundException(
        "Connection with id `" + connection.getId() + "` does not have a Connector defined"));

    actions = connector.getActions().stream()
        .filter(ConnectorAction.class::isInstance)
        .map(ConnectorAction.class::cast)
        .collect(Collectors.toList());
}
 
开发者ID:syndesisio,项目名称:syndesis,代码行数:15,代码来源:ConnectionActionHandler.java

示例13: predict

import java.util.Optional; //导入方法依赖的package包/类
@Override
	public Result predict(String modelId, Input input) {
		validateInput(input);
		Optional<Model> modelSearch = kc.modelsList().getModels().stream().filter(m -> m.getId().equals(modelId)).findFirst();
		Model model = modelSearch.orElseThrow(() -> new IllegalArgumentException("Model " + modelId + " not found."));
		String providerId = model.getProvider();
		Result result = MLProviderFactory.getProvider(providerId).run(kc, model, input);
		// we should find some way to filter the prediction map because some datasets may have hundreds of labels
//		HashMap<String, Number> filteredPredictions = new HashMap<>();
//		result.getPredictions().entrySet().stream().filter(e -> e.getValue().doubleValue() != 0.0).forEach(e -> 
//			filteredPredictions.put(e.getKey(), e.getValue())
//		);
		return result;
	}
 
开发者ID:jesuino,项目名称:kie-ml,代码行数:15,代码来源:KieMLServiceImpl.java

示例14: getServerURL

import java.util.Optional; //导入方法依赖的package包/类
/**
 * Returns the server URL, or throws a {@link
 * ApioDeveloperError.MustHaveProvider} developer error.
 *
 * @return the server URL
 */
protected ServerURL getServerURL() {
	Optional<ServerURL> optional = _providerManager.provideOptional(
		ServerURL.class, _httpServletRequest);

	return optional.orElseThrow(
		() -> new ApioDeveloperError.MustHaveProvider(ServerURL.class));
}
 
开发者ID:liferay,项目名称:com-liferay-apio-architect,代码行数:14,代码来源:DocumentationMessageBodyWriter.java

示例15: handleExternalInputMessage

import java.util.Optional; //导入方法依赖的package包/类
@Override
public void handleExternalInputMessage(final String body, final String endpoint) {
  final Optional<BasicInboundConfiguration> configOpt = Optional
      .ofNullable(basicInboundCongurationRepository.findByEndpoint(GlobalKey.ENDPOINT, endpoint));

  final BasicInboundConfiguration config =
      configOpt.orElseThrow(() -> new IllegalArgumentException("No config found!"));
  parseSupervisorActor.tell(new ParseMessageCreateCommand(body, config.getId()),
      ActorRef.noSender());
}
 
开发者ID:stefanstaniAIM,项目名称:IPPR2016,代码行数:11,代码来源:ExternalCommunicatorServiceImpl.java


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