Example usage for java.util Optional isPresent

List of usage examples for java.util Optional isPresent

Introduction

In this page you can find the example usage for java.util Optional isPresent.

Prototype

public boolean isPresent() 

Source Link

Document

If a value is present, returns true , otherwise false .

Usage

From source file:io.gravitee.gateway.env.GatewayConfigurationTest.java

@Test
public void shouldReturnTenantWithPrecedence() {
    System.setProperty(GatewayConfiguration.MULTI_TENANT_SYSTEM_PROPERTY, "asia");
    Mockito.when(environment.getProperty(GatewayConfiguration.MULTI_TENANT_CONFIGURATION)).thenReturn("europe");
    gatewayConfiguration.afterPropertiesSet();

    Optional<String> tenantOpt = gatewayConfiguration.tenant();
    Assert.assertTrue(tenantOpt.isPresent());

    Assert.assertEquals("asia", tenantOpt.get());
}

From source file:io.gravitee.gateway.handlers.api.policy.security.PlanBasedSecurityProviderFilter.java

@Override
public List<SecurityProvider> filter(List<SecurityProvider> securityProviders) {
    logger.debug("Filtering security providers according to published API's plans");

    List<SecurityProvider> providers = new ArrayList<>();

    // Look into all plans for required authentication providers.
    Collection<Plan> plans = api.getPlans();
    securityProviders.stream().forEach(provider -> {
        Optional<Plan> first = plans.stream()
                .filter(plan -> provider.name().equalsIgnoreCase(plan.getSecurity())).findFirst();
        if (first.isPresent()) {
            logger.debug("Security provider [{}] is required by, at least, one plan. Installing...",
                    provider.name());//from ww  w.j av  a  2s.  c  o m
            providers.add(new PlanBasedSecurityProvider(provider, first.get().getId()));
        }
    });

    if (!providers.isEmpty()) {
        logger.info("API [{} ({})] requires the following security providers:", api.getName(),
                api.getVersion());
        providers.stream()
                .forEach(authenticationProvider -> logger.info("\t* {}", authenticationProvider.name()));
    } else {
        logger.warn("No security provider is provided for API [{} ({})]", api.getName(), api.getVersion());
    }
    return providers;
}

From source file:com.galenframework.storage.controllers.api.PageApiController.java

private Page findOrCreatePage(Long projectId, String pageName) {
    Optional<Page> page = pageRepository.findPage(projectId, pageName);
    if (page.isPresent()) {
        return page.get();
    } else {/*from   ww w  .j a v a2 s  .  com*/
        Page p = new Page(pageName);
        p.setProjectId(projectId);
        Long pageId = pageRepository.createPage(p);
        p.setPageId(pageId);
        return p;
    }
}

From source file:com.galenframework.storage.controllers.api.PageApiController.java

private Long obtainProjectId(String projectName) {
    Optional<Project> project = projectRepository.findProject(projectName);
    if (project.isPresent()) {
        return project.get().getProjectId();
    } else {//from  w  w  w . jav a2 s  .  com
        throw new RuntimeException("Missing project: " + projectName);
    }
}

From source file:com.github.achatain.catalog.service.impl.CollectionServiceImpl.java

private String findUniqueCollectionId(final String userId, final String baseCollectionId) {
    final Optional<Collection> optionalCollection = collectionDao.findById(userId, baseCollectionId);

    if (optionalCollection.isPresent()) {
        int suffix = 1;
        while (collectionDao.findById(userId, format("%s%s", baseCollectionId, suffix)).isPresent()) {
            suffix++;//from  www  . ja v a 2 s. c  o  m
        }
        return format("%s%s", baseCollectionId, suffix);
    } else {
        return baseCollectionId;
    }
}

From source file:it.polimi.diceH2020.SPACE4CloudWS.core.DataProcessor.java

private long calculateMetric(@NonNull List<SolutionPerJob> spjList,
        BiConsumer<SolutionPerJob, Double> resultSaver, Consumer<SolutionPerJob> ifEmpty) {
    //to support also parallel stream.
    AtomicLong executionTime = new AtomicLong();

    spjList.forEach(spj -> {//ww w  . j  a  v  a  2s.  co  m
        Pair<Optional<Double>, Long> result = simulateClass(spj);
        executionTime.addAndGet(result.getRight());
        Optional<Double> optionalValue = result.getLeft();
        if (optionalValue.isPresent())
            resultSaver.accept(spj, optionalValue.get());
        else
            ifEmpty.accept(spj);
    });

    return executionTime.get();
}

From source file:com.dickthedeployer.dick.web.service.ProjectServiceTest.java

@Test
public void shouldAllowCreatingTheSameProjectWithDifferentNamespace()
        throws NameTakenException, RepositoryUnavailableException, RepositoryParsingException {
    ProjectModel model = getProjectModel("test-namespace", "some-semi-random-name-3");
    projectService.createProject(model);

    model = getProjectModel("other-namespace", "some-semi-random-name");
    projectService.createProject(model);

    Optional<Project> project = projectDao.findByNamespaceNameAndName("test-namespace",
            "some-semi-random-name-3");
    assertThat(project.isPresent()).isTrue();
    project = projectDao.findByNamespaceNameAndName("other-namespace", "some-semi-random-name");
    assertThat(project.isPresent()).isTrue();
}

From source file:com.jeanchampemont.notedown.web.SettingsController.java

@RequestMapping(value = "/user", method = RequestMethod.POST)
public String updateUser(SettingsUserForm form, ModelMap model) {
    User user = authenticationService.getCurrentUser();

    boolean success = true;
    boolean hasChanged = false;
    if (!user.getEmail().equals(form.getEmail().toLowerCase())) {
        hasChanged = true;//from   w  ww  .j  av  a2 s.  c o  m
        Optional<User> existingUser = userService.getUserByEmail(form.getEmail());
        if (!existingUser.isPresent()) {
            success = userService.changeEmail(user, form.getEmail(), form.getOldPassword());
            if (!success) {
                model.put("wrongPassword", true);
            } else {
                //Changing email need new authentication
                authenticationService.newAuthentication(user.getEmail(), form.getOldPassword());
            }
        } else {
            success = false;
            model.put("emailExists", true);
        }
    }
    if (success && !StringUtils.isEmpty(form.getNewPassword())) {
        hasChanged = true;
        success = userService.changePassword(user, form.getOldPassword(), form.getNewPassword());
        if (!success) {
            model.put("wrongPassword", true);
        }
    }
    if (success && !user.getDisplayName().equals(form.getDisplayName())) {
        hasChanged = true;
        user.setDisplayName(form.getDisplayName());
        user = userService.update(user);
        success = true;
    }
    model.put("success", success && hasChanged);
    model.put("tab", "user");
    return user(model);
}

From source file:org.openmhealth.shim.withings.mapper.WithingsIntradayCaloriesBurnedDataPointMapper.java

/**
 * Maps an individual list node from the array in the Withings activity measure endpoint response into a {@link
 * CaloriesBurned} data point.//  w  ww  .  j a  va 2  s .c o m
 *
 * @param nodeWithCalorie activity node from the array "activites" contained in the "body" of the endpoint response
 * that has a calories field
 * @return a {@link DataPoint} object containing a {@link CaloriesBurned} measure with the appropriate values from
 * the JSON node parameter, wrapped as an {@link Optional}
 */
private Optional<DataPoint<CaloriesBurned>> asDataPoint(JsonNode nodeWithCalorie,
        Long startDateTimeInUnixEpochSeconds) {

    Long caloriesBurnedValue = asRequiredLong(nodeWithCalorie, "calories");
    CaloriesBurned.Builder caloriesBurnedBuilder = new CaloriesBurned.Builder(
            new KcalUnitValue(KcalUnit.KILOCALORIE, caloriesBurnedValue));

    Optional<Long> duration = asOptionalLong(nodeWithCalorie, "duration");
    if (duration.isPresent()) {
        OffsetDateTime offsetDateTime = OffsetDateTime
                .ofInstant(Instant.ofEpochSecond(startDateTimeInUnixEpochSeconds), ZoneId.of("Z"));
        caloriesBurnedBuilder.setEffectiveTimeFrame(TimeInterval.ofStartDateTimeAndDuration(offsetDateTime,
                new DurationUnitValue(DurationUnit.SECOND, duration.get())));
    }

    Optional<String> userComment = asOptionalString(nodeWithCalorie, "comment");
    if (userComment.isPresent()) {
        caloriesBurnedBuilder.setUserNotes(userComment.get());
    }

    CaloriesBurned calorieBurned = caloriesBurnedBuilder.build();
    return Optional.of(newDataPoint(calorieBurned, null, true, null));

}

From source file:com.minitwit.web.AuthenticationController.java

private LoginResult checkUser(User user) {
    LoginResult result = new LoginResult();
    Optional<User> userFound = twitSvc.getUserbyUsername(user.getUsername());
    if (!userFound.isPresent()) {
        result.setError("Invalid username");
    } else if (!PasswordUtil.verifyPassword(user.getPassword(), userFound.get().getPassword())) {
        result.setError("Invalid password");
    } else {/*from ww w  .j  a va  2  s . co  m*/
        result.setUser(userFound.get());
    }

    return result;
}