本文整理汇总了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);
}
示例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();
}
示例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();
}
}
示例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()]));
}
示例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"));
}
示例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);
}
示例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();
}
示例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");
}
示例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));
}
示例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);
}
示例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));
}
示例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());
}
示例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;
}
示例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));
}
示例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());
}