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


Java Optional.orElseGet方法代码示例

本文整理汇总了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;
    }
 
开发者ID:PacktPublishing,项目名称:OAuth-2.0-Cookbook,代码行数:17,代码来源:FacebookUserIdentity.java

示例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();
		});
}
 
开发者ID:liferay,项目名称:com-liferay-apio-architect,代码行数:17,代码来源:ApioLoggerImpl.java

示例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();

    }
 
开发者ID:TulevaEE,项目名称:onboarding-service,代码行数:20,代码来源:PrincipalService.java

示例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);
}
 
开发者ID:openmicroscopy,项目名称:omero-ms-queue,代码行数:29,代码来源:DeploymentSpec.java

示例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);
   }
}
 
开发者ID:forge,项目名称:springboot-addon,代码行数:17,代码来源:SpringBootHelper.java

示例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();
		});
}
 
开发者ID:liferay,项目名称:com-liferay-apio-architect,代码行数:17,代码来源:ApioLoggerImpl.java

示例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);
}
 
开发者ID:qzagarese,项目名称:dockerunit,代码行数:12,代码来源:DefaultDependencyDescriptorBuilder.java

示例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));
}
 
开发者ID:mrluo735,项目名称:cas-5.1.0,代码行数:8,代码来源:Pac4jErrorViewResolver.java

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

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

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

示例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)));
}
 
开发者ID:olivergierke,项目名称:sos,代码行数:20,代码来源:KafkaIntegration.java

示例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));
}
 
开发者ID:JeffreyFalgout,项目名称:junit5-extensions,代码行数:11,代码来源:GuiceExtension.java

示例14: destination

import java.util.Optional; //导入方法依赖的package包/类
private String destination(Optional<String> defaultReplyChannel) {
  return defaultReplyChannel.orElseGet(() -> {
    throw new RuntimeException();
  });
}
 
开发者ID:networknt,项目名称:light-tram-4j,代码行数:6,代码来源:CommandDispatcher.java

示例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);
}
 
开发者ID:EntryPointKR,项目名称:MCLibrary,代码行数:5,代码来源:GsonUtils.java


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