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:com.ikanow.aleph2.security.db.AbstractDb.java

public Object loadById(Object id) {
    Session s = null;/*from www . ja  v  a  2s.  com*/
    try {
        Optional<JsonNode> ojs = getStore().getObjectById(id).get();
        if (ojs.isPresent()) {
            s = (Session) deserialize(ojs.get());
        }
    } catch (Exception e) {
        logger.error("Caught Exception loading from db:", e);
    }
    return s;
}

From source file:org.openmhealth.shim.fitbit.mapper.FitbitSleepDurationDataPointMapper.java

@Override
protected Optional<DataPoint<SleepDuration>> asDataPoint(JsonNode node) {

    DurationUnitValue unitValue = new DurationUnitValue(MINUTE, asRequiredDouble(node, "minutesAsleep"));
    SleepDuration.Builder sleepDurationBuilder = new SleepDuration.Builder(unitValue);

    Optional<LocalDateTime> localStartTime = asOptionalLocalDateTime(node, "startTime");

    if (localStartTime.isPresent()) {

        OffsetDateTime offsetStartDateTime = combineDateTimeAndTimezone(localStartTime.get());
        Optional<Double> timeInBed = asOptionalDouble(node, "timeInBed");

        if (timeInBed.isPresent()) {
            sleepDurationBuilder.setEffectiveTimeFrame(TimeInterval.ofStartDateTimeAndDuration(
                    offsetStartDateTime, new DurationUnitValue(MINUTE, timeInBed.get())));
        } else {/*from   ww w.ja v a 2 s.com*/
            // in this case, there is no "time in bed" value, however we still have a start time, so we can set
            // the data point to a single date time point
            sleepDurationBuilder.setEffectiveTimeFrame(offsetStartDateTime);
        }
    }

    SleepDuration measure = sleepDurationBuilder.build();

    Optional<Long> externalId = asOptionalLong(node, "logId");

    return Optional.of(newDataPoint(measure, externalId.orElse(null)));
}

From source file:cats.twitter.webapp.controller.module.ApiController.java

/**
 * Modules have to query here when they want to retrieve a corpus.
 * @param token The token sent in the initialisation request (/init)
 * @param from (not required) Pagination
 * @param to (not required) Pagination/*w w  w  .j  av a2s  .  c om*/
 * @return The list of tweets of the corpus in JSON
 */
// @CrossOrigin(origins = "http://localhost:3000")
@RequestMapping(value = "/api", method = RequestMethod.GET)
public List<Tweet> api(@RequestHeader("token") String token,
        @RequestParam(value = "from", required = false) Integer from,
        @RequestParam(value = "to", required = false) Integer to) {
    Optional<Request> req = reqRepository.findOneByToken(token);
    if (!req.isPresent()) {
        throw new IllegalAccessError("Please verify your token!");
    }
    Corpus corpus = req.get().getCorpus();

    if (from == null)
        from = 0;
    if (to == null)
        to = Math.toIntExact(tweetRepository.countByCorpusId(corpus.getId()));

    return tweetRepository.findByCorpusId(corpus.getId(), new ChunkRequest(from, to - from)).getContent();

}

From source file:fi.hsl.parkandride.back.LockDao.java

@Override
@Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.SERIALIZABLE)
public Lock acquireLock(String lockName, Duration lockDuration) {
    Optional<Lock> lock = selectLockIfExists(lockName);
    if (lock.isPresent()) {
        Lock existingLock = lock.get();
        if (!existingLock.validUntil.isAfter(DateTime.now())) {
            return claimExpiredLock(existingLock, lockDuration);
        } else {//from   w ww  .ja  v  a  2s. c  o  m
            throw new LockAcquireFailedException("Existing lock " + existingLock + " is still valid");
        }
    }
    return insertLock(lockName, lockDuration);
}

From source file:org.openmhealth.shim.ihealth.mapper.IHealthStepCountDataPointMapper.java

@Override
protected Optional<DataPoint<StepCount>> asDataPoint(JsonNode listEntryNode, Integer measureUnitMagicNumber) {

    BigDecimal steps = asRequiredBigDecimal(listEntryNode, "Steps");

    if (steps.intValue() == 0) {
        return Optional.empty();
    }/* w ww .  j  a v a 2s .  c  om*/

    StepCount.Builder stepCountBuilder = new StepCount.Builder(steps);

    Optional<Long> dateTimeString = asOptionalLong(listEntryNode, "MDate");

    if (dateTimeString.isPresent()) {

        Optional<String> timeZone = asOptionalString(listEntryNode, "TimeZone");

        if (timeZone.isPresent()) {

            /* iHealth provides daily summaries for step counts and timestamp the datapoint at either the end of
            the day (23:50) or at the latest time that datapoint was synced */
            stepCountBuilder.setEffectiveTimeFrame(ofStartDateTimeAndDuration(
                    getDateTimeAtStartOfDayWithCorrectOffset(dateTimeString.get(), timeZone.get()),
                    new DurationUnitValue(DAY, 1)));
        }
    }

    getUserNoteIfExists(listEntryNode).ifPresent(stepCountBuilder::setUserNotes);

    StepCount stepCount = stepCountBuilder.build();

    return Optional.of(new DataPoint<>(createDataPointHeader(listEntryNode, stepCount), stepCount));
}

From source file:mtsar.processors.task.InverseCountAllocatorTest.java

@Test
public void testEmpty() {
    when(countDAO.getCountsSQL(anyString())).thenReturn(Collections.emptyList());
    final TaskAllocator allocator = new InverseCountAllocator(stage, dbi, taskDAO, answerDAO);
    final Optional<TaskAllocation> optional = allocator.allocate(worker);
    assertThat(optional.isPresent()).isFalse();
}

From source file:io.gravitee.management.idp.repository.lookup.RepositoryIdentityLookup.java

@Override
public io.gravitee.management.idp.api.identity.User retrieve(String id) {
    try {/*from  w w  w  . jav a  2  s .com*/
        Optional<io.gravitee.repository.management.model.User> optUser = userRepository.findByUsername(id);

        if (optUser.isPresent()) {
            return convert(optUser.get());
        }
    } catch (TechnicalException te) {
        LOGGER.error("Unexpected error while looking for a user with id " + id, te);
    }
    return null;
}

From source file:com.ikanow.aleph2.security.db.AbstractDb.java

public Object loadBySpec(QueryComponent<JsonNode> spec) {
    Session s = null;/*from w  w w .ja v a  2  s.  c  o m*/
    try {
        Optional<JsonNode> ojs = getStore().getObjectBySpec(spec).get();
        if (ojs.isPresent()) {
            s = (Session) deserialize(ojs.get());
        }
    } catch (Exception e) {
        logger.error("Caught Exception loading from db:", e);
    }
    return s;
}

From source file:org.openmhealth.dsu.repository.ClientDetailsRepositoryIntegrationTests.java

@Test
public void findOneShouldReturnSavedClientDetails() {

    SimpleClientDetails expected = clientDetailsRepository.save(newClientDetails());

    Optional<SimpleClientDetails> actual = clientDetailsRepository.findOne(TEST_CLIENT_ID);

    assertThat(actual.isPresent(), equalTo(true));
    assertThat(actual.get(), equalTo(expected));
}

From source file:com.nike.cerberus.operation.vault.LoadDefaultVaultPoliciesOperation.java

@Override
public void run(final LoadDefaultVaultPoliciesCommand command) {
    logger.info("Getting client for Vault leader.");
    final Optional<VaultAdminClient> leaderClient = vaultAdminClientFactory.getClientForLeader();

    if (leaderClient.isPresent()) {
        for (Map.Entry<String, VaultPolicy> entry : getDefaultPolicies().entrySet()) {
            logger.info("Loading policy, {}.", entry.getKey());
            leaderClient.get().putPolicy(entry.getKey(), entry.getValue());
        }/*w w  w .ja va 2 s.c o  m*/

        logger.info("All default policies loaded.");
    } else {
        throw new IllegalStateException("Unable to determine Vault leader, aborting...");
    }
}