Example usage for java.util Optional of

List of usage examples for java.util Optional of

Introduction

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

Prototype

public static <T> Optional<T> of(T value) 

Source Link

Document

Returns an Optional describing the given non- null value.

Usage

From source file:spring.travel.site.services.UserServiceTest.java

@Test
public void shouldReturnUserWithAnAddress() throws Exception {
    stubGet("/user?id=123",
            new User("123", "Fred", "Flintstone", "freddyf", Optional.of(new Address("345 Stonecave Road",
                    "Bedrock", "70777", "US", new Location(5290307, 36.128551, -112.036070)))));

    HandOff<Optional<User>> handOff = new HandOff<>();

    userService.user(Optional.of("123")).whenComplete((user, t) -> handOff.put(user));

    Optional<User> optionalUser = handOff.get(1);
    assertNotEquals(Optional.empty(), optionalUser);

    User user = optionalUser.get();/*  ww  w. jav  a  2  s.  c  o  m*/
    assertEquals("Fred", user.getFirstName());
    assertNotEquals(Optional.empty(), user.getAddress());

    Address address = user.getAddress().get();
    assertEquals("345 Stonecave Road", address.getFirstLine());
    assertEquals(5290307, address.getLocation().getCityId());
}

From source file:ddf.catalog.validation.impl.validator.ISO3CountryCodeValidator.java

/**
 * {@inheritDoc}/*from  w  w w.j a v a  2  s. c  o  m*/
 *
 * <p>Validates only the values of {@code attribute} that are {@link String}s.
 */
@Override
public Optional<AttributeValidationReport> validate(Attribute attribute) {
    Preconditions.checkArgument(attribute != null, "The attribute cannot be null.");

    AttributeValidationReport report = buildReport(attribute);

    return report.getAttributeValidationViolations().isEmpty() ? Optional.empty() : Optional.of(report);
}

From source file:com.orange.ngsi2.model.Notification.java

@JsonIgnore
public void setHeader(String key, String value) {
    if (this.headers == null) {
        this.headers = Optional.of(new HashMap<>());
    }/*w  w w  . j  a v a2 s  .co m*/
    this.headers.get().put(key, value);
}

From source file:net.sf.jabref.logic.journals.JournalAbbreviationRepository.java

/**
 * Attempts to get the abbreviated name of the journal given. May contain dots.
 *
 * @param journalName The journal name to abbreviate.
 * @return The abbreviated name/*  w w w . jav a 2 s  . c o m*/
 */
public Optional<Abbreviation> getAbbreviation(String journalName) {
    String nameKey = Objects.requireNonNull(journalName).toLowerCase(Locale.ENGLISH).trim();

    if (fullNameLowerCase2Abbreviation.containsKey(nameKey)) {
        return Optional.of(fullNameLowerCase2Abbreviation.get(nameKey));
    } else if (isoLowerCase2Abbreviation.containsKey(nameKey)) {
        return Optional.of(isoLowerCase2Abbreviation.get(nameKey));
    } else if (medlineLowerCase2Abbreviation.containsKey(nameKey)) {
        return Optional.of(medlineLowerCase2Abbreviation.get(nameKey));
    } else {
        return Optional.empty();
    }
}

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

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

    BigDecimal stepCountValue = asRequiredBigDecimal(listEntryNode, "value");

    if (stepCountValue.intValue() == 0) {
        return Optional.empty();
    }/*from w  w  w.  jav a  2s  . c o  m*/

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

    Optional<LocalDate> dateFromParent = getDateFromSummaryForDay();

    if (dateFromParent.isPresent()) {

        // Set the effective time frame only if we have access to the date and time
        asOptionalString(listEntryNode, "time").ifPresent(time -> stepCountBuilder.setEffectiveTimeFrame(
                ofStartDateTimeAndDuration(dateFromParent.get().atTime(LocalTime.parse(time)).atOffset(UTC),
                        new DurationUnitValue(MINUTE, 1)))); // We use 1 minute since the shim requests data at 1 minute granularity
    }

    return Optional.of(newDataPoint(stepCountBuilder.build(), null));
}

From source file:fi.helsinki.opintoni.security.CustomAuthenticationSuccessHandlerTest.java

@Test
public void thatOldUserDoesNotResultInNewUser() throws Exception {
    Optional<User> user = Optional.of(new User());
    HttpServletResponse response = mockResponse();

    when(userService.findFirstByEduPersonPrincipalName(EDU_PRINCIPAL_NAME)).thenReturn(user);

    handler.onAuthenticationSuccess(mock(HttpServletRequest.class), response, authentication);

    verify(userService, never()).createNewUser(any(AppUser.class));
}

From source file:org.ow2.proactive.workflow_catalog.rest.controller.BucketControllerTest.java

@Test
public void testListWithOwner() throws Exception {
    Pageable mockedPageable = mock(Pageable.class);
    PagedResourcesAssembler mockedAssembler = mock(PagedResourcesAssembler.class);
    final Optional<String> owner = Optional.of("toto");
    bucketController.list(owner, mockedPageable, mockedAssembler);
    verify(bucketService, times(1)).listBuckets(owner, mockedPageable, mockedAssembler);
}

From source file:se.omegapoint.facepalm.infrastructure.JPAImageRepository.java

@Override
public Optional<se.omegapoint.facepalm.domain.ImagePost> findById(String id) {
    notBlank(id);//from  ww  w .  j a  va  2  s. co m

    final String query = String.format("SELECT * FROM IMAGE_POSTS WHERE id = %s", id);

    eventService.publish(new GenericEvent("Searching for image post with query: " + query));

    final List<ImagePost> imagePosts = entityManager.createNativeQuery(query, ImagePost.class).getResultList();

    return imagePosts.size() == 1 ? Optional.of(convertToDomain(imagePosts.get(0))) : Optional.empty();
}

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

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

    BigDecimal bloodOxygenValue = asRequiredBigDecimal(listEntryNode, "BO");

    // iHealth has stated that missing values would most likely be represented as a 0 value for the field
    if (bloodOxygenValue.compareTo(ZERO) == 0) {
        return Optional.empty();
    }/*from w  w w.ja  va2 s  . co  m*/

    OxygenSaturation.Builder oxygenSaturationBuilder = new OxygenSaturation.Builder(
            new TypedUnitValue<>(PERCENT, bloodOxygenValue)).setMeasurementMethod(PULSE_OXIMETRY)
                    .setMeasurementSystem(PERIPHERAL_CAPILLARY);

    getEffectiveTimeFrameAsDateTime(listEntryNode).ifPresent(oxygenSaturationBuilder::setEffectiveTimeFrame);
    getUserNoteIfExists(listEntryNode).ifPresent(oxygenSaturationBuilder::setUserNotes);

    OxygenSaturation oxygenSaturation = oxygenSaturationBuilder.build();

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

From source file:ch.ralscha.extdirectspring.provider.RemoteProviderOptional.java

@ExtDirectMethod(group = "optional")
public Optional<String> method5(Optional<Integer> id, @RequestHeader("anotherName") Optional<String> header) {
    return Optional.of(id.get() + ";" + header.get());
}