本文整理汇总了Java中java.util.Optional.orElseGet方法的典型用法代码示例。如果您正苦于以下问题:Java Optional.orElseGet方法的具体用法?Java Optional.orElseGet怎么用?Java Optional.orElseGet使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.Optional
的用法示例。
在下文中一共展示了Optional.orElseGet方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: findOrCreateFrom
import java.util.Optional; //导入方法依赖的package包/类
public FacebookUser findOrCreateFrom(OAuth2AccessToken accessToken) {
Map<String, String> userInfo = userInfoService.getUserInfoFor(accessToken);
Optional<FacebookUser> userAuth = repository.findByFacebookId(userInfo.get("id"));
FacebookUser user = userAuth.orElseGet(() -> {
FacebookLoginData loginData = new FacebookLoginData();
loginData.setName(userInfo.get("name"));
loginData.setId(userInfo.get("id"));
loginData.setExpirationTime(accessToken.getExpiration().getTime());
loginData.setToken(accessToken.getValue());
return new FacebookUser(loginData);
});
return user;
}
示例2: _getExceptionMessage
import java.util.Optional; //导入方法依赖的package包/类
private String _getExceptionMessage(APIError apiError) {
Optional<String> optional = apiError.getDescription();
return optional.orElseGet(
() -> {
Exception exception = apiError.getException();
String message = exception.getMessage();
if ((message != null) && !message.isEmpty()) {
return message;
}
return apiError.toString();
});
}
示例3: getFrom
import java.util.Optional; //导入方法依赖的package包/类
public AuthenticatedPerson getFrom(Person person) {
Optional<User> userOptional = userService.findByPersonalCode(person.getPersonalCode());
User user = userOptional.orElseGet(() -> createUser(person));
if (!user.getActive()) {
log.info("Failed to login inactive user with personal code {}", person.getPersonalCode());
throw new InvalidRequestException("INACTIVE_USER");
}
return AuthenticatedPerson.builder()
.firstName(person.getFirstName())
.lastName(person.getLastName())
.personalCode(person.getPersonalCode())
.userId(user.getId())
.build();
}
示例4: DeploymentSpec
import java.util.Optional; //导入方法依赖的package包/类
/**
* Creates a new instance.
* This constructor automatically adds {@link ServerEmbeddedEndpoints
* embedded transport endpoints} to the Artemis core configuration and
* uses Artemis's default security manager and MBean server if none are
* provided.
* @param configBuilder builds the core configuration.
* @param securityManagerBuilder builds the security manager to install.
* @param mBeanServer the MBean server to install or empty to use Artemis's
* default.
* @throws NullPointerException if any argument is {@code null}.
*/
public <T extends ActiveMQSecurityManager> DeploymentSpec(
Builder<Void, Configuration> configBuilder,
Builder<Void, T> securityManagerBuilder,
Optional<MBeanServer> mBeanServer) {
requireNonNull(configBuilder, "configBuilder");
requireNonNull(securityManagerBuilder, "securityManagerBuilder");
requireNonNull(mBeanServer, "mBeanServer");
this.embeddedEndpoints = new ServerEmbeddedEndpoints();
this.config = configBuilder
.with(embeddedEndpoints::transportConfig)
.apply(null);
this.securityManager = securityManagerBuilder.apply(null);
this.mBeanServer = mBeanServer // (*)
.orElseGet(ManagementFactory::getPlatformMBeanServer);
}
示例5: modifyJavaClass
import java.util.Optional; //导入方法依赖的package包/类
public static void modifyJavaClass(Project project, String className, Optional<String> packageName,
JavaClassSourceDecorator decorator) {
final String packageLocation = packageName.orElseGet(() -> project.getFacet(MetadataFacet.class).getProjectGroupName());
final JavaSourceFacet sourceFacet = project.getFacet(JavaSourceFacet.class);
final DirectoryResource targetPackage = sourceFacet.getPackage(packageLocation);
final JavaResource sbAppResource = targetPackage.getChild(className).as(JavaResource.class);
if (sbAppResource.exists()) {
JavaClassSource sbApp = Roaster.parse(JavaClassSource.class, sbAppResource.getResourceInputStream());
decorator.modify(sbApp);
sourceFacet.saveJavaSource(sbApp);
}
}
示例6: _getExceptionMessage
import java.util.Optional; //导入方法依赖的package包/类
private String _getExceptionMessage(APIError apiError) {
Optional<String> optional = apiError.getDescription();
return optional.orElseGet(
() -> {
Exception exception = apiError.getException();
String message = exception.getMessage();
if (Validator.isNotNull(message)) {
return message;
}
return apiError.toString();
});
}
示例7: findCustomisationHook
import java.util.Optional; //导入方法依赖的package包/类
private Method findCustomisationHook(Use use) {
Optional<Method> opt = Arrays.asList(use.service().getDeclaredMethods()).stream()
.filter(m -> m.isAnnotationPresent(ContainerBuilder.class)
&& Modifier.isPublic(m.getModifiers())
&& !Modifier.isStatic(m.getModifiers())
&& m.getParameterCount() == 1
&& m.getParameterTypes()[0].equals(CreateContainerCmd.class)
&& m.getReturnType().equals(CreateContainerCmd.class))
.findFirst();
return opt.orElseGet(() -> null);
}
示例8: resolveErrorView
import java.util.Optional; //导入方法依赖的package包/类
@Override
public ModelAndView resolveErrorView(final HttpServletRequest request,
final HttpStatus status, final Map<String, Object> map) {
final Optional<ModelAndView> mv = DelegatedClientAuthenticationAction.hasDelegationRequestFailed(request, status.value());
return mv.orElseGet(() -> conventionErrorViewResolver.resolveErrorView(request, status, map));
}
示例9: enforceEnrollment
import java.util.Optional; //导入方法依赖的package包/类
public List<CourseLevelSession> enforceEnrollment(Long courseId) throws BuenOjoInconsistencyException
{
Enrollment currentEnrollment=null;
Optional<Enrollment> enrollment;
Optional<User> optionalUser = userRepository.findOneByLogin( ((CustomUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
User user = optionalUser.orElseThrow(() -> new BuenOjoInconsistencyException("No hay un usuario logueado"));
Course course;
removeAllByCourseAndCurrentUser(courseId);
createAllCourseLevelSessionByCourseAndCurrentUser(courseId);
try {
enrollment = enrollmentRepository.findByUserIsCurrentUserAndCourse(courseId);
} catch (Exception e){
throw new BuenOjoInconsistencyException("Existe mas de un Enrollment para el usuario '"+ user.getLogin()+"'");
}
course = courseRepository.findOne(courseId);
if (course == null) {
throw new BuenOjoInconsistencyException("no existe un curso con el ID '"+"'");
}
currentEnrollment = enrollment.orElseGet(() -> {
return enrollmentSimpleFactory.getEnrollment(user, course, EnrollmentStatus.Started);
});
if (currentEnrollment.getCurrentLevel() == null) {
CourseLevelMap map = courseLevelMapRepository.findOneByCourse_IdAndParentIsNull(courseId).orElseThrow(() -> new BuenOjoInconsistencyException("El curso '"+courseId+"' no tiene un nivel inicial"));
currentEnrollment.setCurrentLevel(map.getLevel());
}
currentEnrollment.setStatus(EnrollmentStatus.Started);
enrollmentRepository.saveAndFlush(currentEnrollment);
return courseLevelSessionRepository.findByUserIsCurrentUser();
}
示例10: snapshotRecorder
import java.util.Optional; //导入方法依赖的package包/类
@Bean
AggregateListener snapshotRecorder(ViewQuery<Order> orderViewRepository, // View Query with Function Specs
EventRepository orderEventRepository, // Event Repository to mark failed events
OrderRepository orderRepository, // Jpa Repository to record snapshots
Optional<List<RollbackSpec>> rollbackSpecs // Custom Rollback Specs for Event Failures
) {
return new AggregateListener(orderViewRepository, orderEventRepository, orderRepository, rollbackSpecs.orElseGet(ArrayList::new), objectMapper);
}
示例11: getField
import java.util.Optional; //导入方法依赖的package包/类
/**
* 获取属性值
* @param bean 实例
* @param targetClass 属性所属class
* @param fieldName 属性名
* @return Field
* @throws IllegalAccessException .{@link IllegalAccessException}
*/
public static Field getField(Object bean, Class targetClass, String fieldName) throws IllegalAccessException {
List<Field> fields = Lists.newArrayList();
getAllFields(bean.getClass(), fields);
// 第一次类型和属性名都满足才返回
Optional<Field> oneNewFields = fields.stream()
.filter(field -> field.getName().equals(fieldName) && field.getType() == targetClass)
.findFirst();
// 第2次类型和属性名满足一个即返回
Optional<Field> twoNewFields = fields.stream()
.filter(field -> field.getName().equals(fieldName) || field.getType() == targetClass)
.findFirst();
return oneNewFields.orElseGet(() -> twoNewFields.orElse(null));
}
示例12: onProductAdded
import java.util.Optional; //导入方法依赖的package包/类
/**
* Creates a new {@link InventoryItem} for the product that was added.
*
* @param message will never be {@literal null}.
*/
@KafkaListener(topics = "products")
public void onProductAdded(ProductAdded message) throws IOException {
Optional<InventoryItem> item = inventory.findByProductId(message.getProductId());
if (item.isPresent()) {
log.info("Inventory item for product {} already available!", message.getProductId());
return;
}
log.info("Creating inventory item for product {}.", message.getProductId());
item.orElseGet(() -> inventory.save(InventoryItem.of(message.getProductId(), message.getName(), 0L)));
}
示例13: getKey
import java.util.Optional; //导入方法依赖的package包/类
private static Key<?> getKey(Optional<Class<?>> containingElement, Parameter parameter) {
Class<?> clazz =
containingElement.orElseGet(() -> parameter.getDeclaringExecutable().getDeclaringClass());
TypeToken<?> classType = TypeToken.of(clazz);
Type resolvedType = classType.resolveType(parameter.getParameterizedType()).getType();
Optional<Key<?>> key =
getOnlyBindingAnnotation(parameter).map(annotation -> Key.get(resolvedType, annotation));
return key.orElse(Key.get(resolvedType));
}
示例14: destination
import java.util.Optional; //导入方法依赖的package包/类
private String destination(Optional<String> defaultReplyChannel) {
return defaultReplyChannel.orElseGet(() -> {
throw new RuntimeException();
});
}
示例15: read
import java.util.Optional; //导入方法依赖的package包/类
public static <T> T read(Gson gson, File file, Type type, Supplier<T> def) {
Optional<T> ret = read(gson, file, type);
return ret.orElseGet(def);
}