當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。