List of usage examples for java.util Optional of
public static <T> Optional<T> of(T value)
From source file:spring.travel.site.services.UserServiceTest.java
@Test public void shouldReturnUserWithNoAddress() throws Exception { stubGet("/user?id=123", new User("123", "Fred", "Flintstone", "freddyf", Optional.<Address>empty())); 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();// w w w . ja va 2 s.c o m assertEquals("Fred", user.getFirstName()); assertEquals(Optional.empty(), user.getAddress()); }
From source file:com.arpnetworking.metrics.common.tailer.FilePositionStore.java
/** * {@inheritDoc}/* www. java 2s . com*/ */ @Override public Optional<Long> getPosition(final String identifier) { final Descriptor descriptor = _state.get(identifier); if (descriptor == null) { return Optional.empty(); } return Optional.of(descriptor.getPosition()); }
From source file:tds.assessment.services.impl.AssessmentServiceImplIntegrationTests.java
@Test public void shouldReturnCachedAssessment() { final String clientName = "SBAC_PT"; Assessment assessment = new Assessment(); assessment.setKey("theKey"); Segment fixedFormSegment = new Segment(assessment.getKey(), Algorithm.FIXED_FORM); assessment.setSegments(Collections.singletonList(fixedFormSegment)); when(assessmentQueryRepository.findAssessmentByKey(clientName, assessment.getKey())) .thenReturn(Optional.of(assessment)); Optional<Assessment> maybeAssessment1 = service.findAssessment(clientName, assessment.getKey()); // Get the cached value - only a single repo call should result from the two service calls Optional<Assessment> maybeAssessment2 = service.findAssessment(clientName, assessment.getKey()); verify(assessmentQueryRepository, times(1)).findAssessmentByKey(clientName, assessment.getKey()); assertThat(maybeAssessment1).isEqualTo(maybeAssessment2); }
From source file:se.omegapoint.facepalm.client.adapters.UserAdapter.java
public Optional<Profile> profileFor(final String username) { final Result<User, UserFailure> result = userService.getUserWith(username); return result.isSuccess() ? Optional.of(new Profile(result.success())) : Optional.empty(); }
From source file:com.ikanow.aleph2.data_model.utils.TestJsonUtils.java
@Test public void test_foldTuple() { final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty()); LinkedHashMap<String, Object> test1 = new LinkedHashMap<String, Object>(); test1.put("long", 10L); test1.put("double", 1.1); test1.put("string", "val"); test1.put("json", "{\"misc\":true,\"long\":1, \"string\":\"\"}"); final JsonNode j1 = JsonUtils.foldTuple(test1, mapper, Optional.empty()); assertEquals("{\"misc\":true,\"long\":10,\"string\":\"val\",\"double\":1.1}", j1.toString()); LinkedHashMap<String, Object> test2 = new LinkedHashMap<String, Object>(); test2.put("misc", false); test2.put("long", 10L); test2.put("json", "{\"misc\":true,\"long\":1, \"string\":\"\"}"); test2.put("double", 1.1); test2.put("string", "val"); final JsonNode j2 = JsonUtils.foldTuple(test2, mapper, Optional.of("json")); assertEquals("{\"misc\":false,\"long\":10,\"string\":\"val\",\"double\":1.1}", j2.toString()); LinkedHashMap<String, Object> test3 = new LinkedHashMap<String, Object>(); test3.put("long", mapper.createObjectNode()); test3.put("double", mapper.createArrayNode()); test3.put("string", BeanTemplateUtils.build(TestBean.class).with("test1", 4).done().get()); test3.put("json", "{\"misc\":true,\"long\":1, \"string\":\"\"}"); final JsonNode j3 = JsonUtils.foldTuple(test3, mapper, Optional.of("json")); assertEquals("{\"misc\":true,\"long\":{},\"string\":{\"test1\":4},\"double\":[]}", j3.toString()); LinkedHashMap<String, Object> test4 = new LinkedHashMap<String, Object>(); test4.put("misc", BigDecimal.ONE); test4.put("long", (int) 10); test4.put("double", (float) 1.1); test4.put("json", "{\"misc\":true,\"long\":1, \"string\":\"\"}"); test4.put("string", "val"); final JsonNode j4 = JsonUtils.foldTuple(test4, mapper, Optional.of("json")); assertEquals("{\"misc\":1,\"long\":10,\"string\":\"val\",\"double\":1.1}", j4.toString().replaceFirst("1[.]1[0]{6,}[0-9]+", "1.1")); try {/*from w w w . j a v a 2s .c om*/ test4.put("json", "{\"misc\":true,\"long\":1, string\":\"\"}"); // (Added json error) JsonUtils.foldTuple(test4, mapper, Optional.of("json")); fail("Should have thrown JSON exception"); } catch (Exception e) { } // json error, check new JsonUtils(); // (just for coverage) }
From source file:org.openwms.tms.RedirectTODocumentation.java
public @Test void testRedirectToUnknownLocationButLocGroup() throws Exception { // setup ...//w w w .ja v a 2 s. co m CreateTransportOrderVO vo = createTO(); postTOAndValidate(vo, NOTLOGGED); vo.setTarget(UNKNOWN); given(commonGateway.getLocationGroup(UNKNOWN)).willReturn(Optional.of(ERR_LOCGRB)); given(commonGateway.getLocation(UNKNOWN)).willReturn(Optional.empty()); // test ... sendPatch(vo, status().isNoContent(), "to-patch-target-unknown-locgb"); }
From source file:io.pravega.controller.store.stream.tables.IndexRecord.java
private static Pair<Integer, Optional<IndexRecord>> binarySearchIndex(final int lower, final int upper, final long timestamp, final byte[] indexTable) { if (upper < lower || indexTable.length == 0) { return new ImmutablePair<>(0, Optional.empty()); }//from w w w. j a v a2 s .c o m final int offset = ((lower + upper) / 2) * IndexRecord.INDEX_RECORD_SIZE; final IndexRecord record = IndexRecord.readRecord(indexTable, offset).get(); final Optional<IndexRecord> next = IndexRecord.fetchNext(indexTable, offset); if (record.getEventTime() <= timestamp) { if (!next.isPresent() || (next.get().getEventTime() > timestamp)) { return new ImmutablePair<>(offset, Optional.of(record)); } else { return binarySearchIndex((lower + upper) / 2 + 1, upper, timestamp, indexTable); } } else { return binarySearchIndex(lower, (lower + upper) / 2 - 1, timestamp, indexTable); } }
From source file:org.openmhealth.shim.ihealth.mapper.IHealthBodyMassIndexDataPointMapper.java
@Override protected Optional<DataPoint<BodyMassIndex>> asDataPoint(JsonNode listEntryNode, Integer measureUnitMagicNumber) { Double bmiValue = asRequiredDouble(listEntryNode, "BMI"); if (bmiValue == 0) { return Optional.empty(); }/* w w w . j ava 2s . co m*/ BodyMassIndex.Builder bodyMassIndexBuilder = new BodyMassIndex.Builder( new TypedUnitValue<>(KILOGRAMS_PER_SQUARE_METER, bmiValue)); getEffectiveTimeFrameAsDateTime(listEntryNode).ifPresent(bodyMassIndexBuilder::setEffectiveTimeFrame); getUserNoteIfExists(listEntryNode).ifPresent(bodyMassIndexBuilder::setUserNotes); BodyMassIndex bodyMassIndex = bodyMassIndexBuilder.build(); return Optional.of(new DataPoint<>(createDataPointHeader(listEntryNode, bodyMassIndex), bodyMassIndex)); }
From source file:org.openmhealth.shim.withings.mapper.WithingsBloodPressureDataPointMapper.java
@Override public Optional<Measure.Builder<BloodPressure, ?>> newMeasureBuilder(JsonNode measuresNode) { Optional<BigDecimal> systolicValue = getValueForMeasureType(measuresNode, SYSTOLIC_BLOOD_PRESSURE); Optional<BigDecimal> diastolicValue = getValueForMeasureType(measuresNode, DIASTOLIC_BLOOD_PRESSURE); if (!systolicValue.isPresent() && !diastolicValue.isPresent()) { return empty(); }// www.jav a2 s .c o m if (!systolicValue.isPresent() || !diastolicValue.isPresent()) { logger.warn("The Withings measure node {} doesn't contain both systolic and diastolic measures.", measuresNode); return empty(); } return Optional.of(new BloodPressure.Builder(new SystolicBloodPressure(MM_OF_MERCURY, systolicValue.get()), new DiastolicBloodPressure(MM_OF_MERCURY, diastolicValue.get()))); }
From source file:com.formkiq.core.service.propertystore.PropertyStoreDatabase.java
@Override public Optional<KeyPair> retrieveKeyPair() throws GeneralSecurityException { Optional<KeyPair> result = Optional.empty(); String pubkey = this.propertyService.getProperty(null, PUBLIC_KEY); String privkey = this.propertyService.getProperty(null, PRIVATE_KEY); if (!isEmpty(pubkey) && !isEmpty(privkey)) { KeyGenerator keygen = new KeyGenerator(); RSAPublicKey publickey = keygen.stringToPublicKey(pubkey); RSAPrivateKey privatekey = keygen.stringToPrivateKey(privkey); result = Optional.of(new KeyPair(publickey, privatekey)); }//from w w w .j a v a2s . com return result; }