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:com.synopsys.integration.blackduck.service.CodeLocationService.java

public Optional<CodeLocationView> getCodeLocationByName(String codeLocationName) throws IntegrationException {
    if (StringUtils.isNotBlank(codeLocationName)) {
        Optional<BlackDuckQuery> blackDuckQuery = BlackDuckQuery.createQuery("name", codeLocationName);
        Request.Builder requestBuilder = RequestFactory.createCommonGetRequestBuilder(blackDuckQuery);
        List<CodeLocationView> codeLocations = blackDuckService
                .getAllResponses(ApiDiscovery.CODELOCATIONS_LINK_RESPONSE, requestBuilder);
        for (CodeLocationView codeLocation : codeLocations) {
            if (codeLocationName.equals(codeLocation.getName())) {
                return Optional.of(codeLocation);
            }//from   ww  w  . j  ava  2s . c  o m
        }
        return codeLocations.stream()
                .filter(codeLocationView -> codeLocationName.equals(codeLocationView.getName())).findFirst();
    }

    logger.error(String.format("The code location (%s) does not exist.", codeLocationName));
    return Optional.empty();
}

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

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

    String activityName = asRequiredString(listEntryNode, "SportName");

    if (activityName.isEmpty()) {

        return Optional.empty();
    }/*ww w  . j  ava 2s.c  o  m*/

    PhysicalActivity.Builder physicalActivityBuilder = new PhysicalActivity.Builder(activityName);

    Optional<Long> startTimeUnixEpochSecs = asOptionalLong(listEntryNode, "SportStartTime");
    Optional<Long> endTimeUnixEpochSecs = asOptionalLong(listEntryNode, "SportEndTime");
    Optional<Integer> timeZoneOffset = asOptionalInteger(listEntryNode, "TimeZone");

    if (startTimeUnixEpochSecs.isPresent() && endTimeUnixEpochSecs.isPresent() && timeZoneOffset.isPresent()) {

        Integer timeZoneOffsetValue = timeZoneOffset.get();
        String timeZoneString = timeZoneOffsetValue.toString();

        // Zone offset cannot parse a positive string offset that's missing a '+' sign (i.e., "0200" vs "+0200")
        if (timeZoneOffsetValue >= 0) {
            timeZoneString = "+" + timeZoneOffsetValue.toString();
        }

        physicalActivityBuilder.setEffectiveTimeFrame(ofStartDateTimeAndEndDateTime(
                getDateTimeWithCorrectOffset(startTimeUnixEpochSecs.get(), ZoneOffset.of(timeZoneString)),
                getDateTimeWithCorrectOffset(endTimeUnixEpochSecs.get(), ZoneOffset.of(timeZoneString))));
    }

    asOptionalDouble(listEntryNode, "Calories").ifPresent(
            calories -> physicalActivityBuilder.setCaloriesBurned(new KcalUnitValue(KILOCALORIE, calories)));

    PhysicalActivity physicalActivity = physicalActivityBuilder.build();

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

From source file:alfio.controller.api.ReservationApiController.java

@RequestMapping(value = "/event/{eventName}/ticket/{ticketIdentifier}/assign", method = RequestMethod.POST, headers = "X-Requested-With=XMLHttpRequest")
public Map<String, Object> assignTicketToPerson(@PathVariable("eventName") String eventName,
        @PathVariable("ticketIdentifier") String ticketIdentifier,
        @RequestParam(value = "single-ticket", required = false, defaultValue = "false") boolean singleTicket,
        UpdateTicketOwnerForm updateTicketOwner, BindingResult bindingResult, HttpServletRequest request,
        Model model, Authentication authentication) throws Exception {

    Optional<UserDetails> userDetails = Optional.ofNullable(authentication).map(Authentication::getPrincipal)
            .filter(UserDetails.class::isInstance).map(UserDetails.class::cast);

    Optional<Triple<ValidationResult, Event, Ticket>> assignmentResult = ticketHelper.assignTicket(eventName,
            ticketIdentifier, updateTicketOwner, Optional.of(bindingResult), request, t -> {
                Locale requestLocale = RequestContextUtils.getLocale(request);
                model.addAttribute("ticketFieldConfiguration",
                        ticketHelper.findTicketFieldConfigurationAndValue(t.getMiddle().getId(), t.getRight(),
                                requestLocale));
                model.addAttribute("value", t.getRight());
                model.addAttribute("validationResult", t.getLeft());
                model.addAttribute("countries", TicketHelper.getLocalizedCountries(requestLocale));
                model.addAttribute("event", t.getMiddle());
                model.addAttribute("useFirstAndLastName", t.getMiddle().mustUseFirstAndLastName());
                model.addAttribute("availableLanguages", i18nManager.getEventLanguages(eventName).stream()
                        .map(ContentLanguage.toLanguage(requestLocale)).collect(Collectors.toList()));
                String uuid = t.getRight().getUuid();
                model.addAttribute("urlSuffix", singleTicket ? "ticket/" + uuid + "/view" : uuid);
                model.addAttribute("elementNamePrefix", "");
            }, userDetails);//from ww  w . ja v  a2 s. c o m
    Map<String, Object> result = new HashMap<>();

    Optional<ValidationResult> validationResult = assignmentResult.map(Triple::getLeft);
    if (validationResult.isPresent() && validationResult.get().isSuccess()) {
        result.put("partial",
                templateManager.renderServletContextResource("/WEB-INF/templates/event/assign-ticket-result.ms",
                        model.asMap(), request, TemplateManager.TemplateOutput.HTML));
    }
    result.put("validationResult", validationResult.orElse(
            ValidationResult.failed(new ValidationResult.ErrorDescriptor("fullName", "error.fullname"))));
    return result;
}

From source file:tds.assessment.web.endpoints.AssessmentControllerIntegrationTests.java

@Test
public void shouldReturnAssessmentByKey() throws Exception {
    EnhancedRandom rand = EnhancedRandomBuilder.aNewEnhancedRandomBuilder().collectionSizeRange(2, 5)
            .stringLengthRange(1, 20).build();
    Assessment assessment = rand.nextObject(Assessment.class);
    assessment.setKey("(SBAC_PT)IRP-Perf-ELA-11-Summer-2015-2016");
    assessment.setAssessmentId("IRP-Perf-ELA-11");
    assessment.setSelectionAlgorithm(Algorithm.VIRTUAL);
    assessment.setSubject("ELA");
    assessment.setStartAbility(50F);// w  w  w.j  av  a2s . c om
    assessment.setDeleteUnansweredItems(true);

    when(assessmentSegmentService.findAssessment("SBAC_PT", "(SBAC_PT)IRP-Perf-ELA-11-Summer-2015-2016"))
            .thenReturn(Optional.of(assessment));

    URI uri = UriComponentsBuilder
            .fromUriString("/SBAC_PT/assessments/(SBAC_PT)IRP-Perf-ELA-11-Summer-2015-2016").build().toUri();

    MvcResult result = http.perform(get(uri).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
            .andExpect(jsonPath("key", is("(SBAC_PT)IRP-Perf-ELA-11-Summer-2015-2016")))
            .andExpect(jsonPath("assessmentId", is("IRP-Perf-ELA-11")))
            .andExpect(jsonPath("subject", is("ELA")))
            .andExpect(jsonPath("selectionAlgorithm", is(Algorithm.VIRTUAL.name()))).andReturn();

    Assessment parsedAssessment = objectMapper.readValue(result.getResponse().getContentAsByteArray(),
            Assessment.class);
    assertThat(parsedAssessment).isEqualTo(assessment);
}

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

@Test
public void testCreateWorkflows() throws IOException {
    MultipartFile file = mock(MultipartFile.class);
    when(file.getBytes()).thenReturn(null);
    workflowController.create(1L, Optional.empty(), Optional.of("zip"), file);
    verify(workflowService, times(1)).createWorkflows(1L, Optional.empty(), null);
}

From source file:org.ulyssis.ipp.snapshot.Snapshot.java

public Optional<Long> getEventId() {
    if (eventId != -1)
        return Optional.of(eventId);
    else// w ww . j  a va  2  s.  co m
        return Optional.empty();
}

From source file:org.openwms.tms.ChangeStateDocumentation.java

@Ignore("Test runs on OSX and Jenkins@Linux but not on TravisCI. Needs further investigation")
public @Test void createAnNewOneWhenOneIsAlreadyStarted() throws Exception {
    // setup .../* www  .  ja  va  2 s .co  m*/
    CreateTransportOrderVO vo = createTO();
    postTOAndValidate(vo, NOTLOGGED);
    // create a second one that shall wait in INITIALIZED
    CreateTransportOrderVO vo2 = createTO();
    postTOAndValidate(vo2, NOTLOGGED);
    vo2.setState(TransportOrderState.STARTED.toString());
    given(commonGateway.getTransportUnit(KNOWN))
            .willReturn(Optional.of(new TransportUnit(KNOWN, INIT_LOC, ERR_LOC_STRING)));

    LOGGER.debug("Calling API with:" + vo2);
    // test ...
    mockMvc.perform(patch(TMSConstants.ROOT_ENTITIES).contentType(MediaType.APPLICATION_JSON)
            .content(objectMapper.writeValueAsString(vo2))).andExpect(status().isBadRequest())
            .andExpect(jsonPath("messageKey", is(TMSMessageCodes.START_TO_NOT_ALLOWED_ALREADY_STARTED_ONE)))
            .andDo(document("to-patch-state-change-start-no-allowed-one-exists"));
}

From source file:io.github.binout.jaxrs.csv.CsvMessageBodyProvider.java

private Optional<Class> objectClass(Object o, Class<?> aClass) {
    Optional<Class> csvClass;
    if (o instanceof Collection) {
        Collection collection = (Collection) o;
        if (collection.isEmpty()) {
            csvClass = Optional.empty();
        } else {//  w ww . j  a  v  a2  s . c  om
            csvClass = Optional.of(collection.iterator().next().getClass());
        }
    } else {
        csvClass = Optional.of(aClass);
    }
    return csvClass;
}

From source file:co.runrightfast.core.utils.ConfigUtils.java

static Optional<Number> getNumber(final Config config, final String path, final String... paths) {
    if (!hasPath(config, path, paths)) {
        return Optional.empty();
    }//from   ww w  .  ja va  2  s  . c  o  m
    return Optional.of(config.getNumber(configPath(path, paths)));
}