List of usage examples for java.util.function Supplier get
T get();
From source file:com.example.app.communication.service.NotificationService.java
/** * Send email.//from ww w .j a v a 2 s . c o m * * @param emailTemplate the email template * @param context the context * @param defaultFromNameSupplier the supplier for the name of the default sender. * @param delayMillis the delay millis */ public void sendEmail(EmailTemplate emailTemplate, EmailTemplateContext context, @Nullable Supplier<String> defaultFromNameSupplier, Long delayMillis) { try { Preconditions.checkArgument(delayMillis >= 0, "Invalid arg: delayAmount. Expecting a number >= 0"); final FileEntityMailDataHandler mdh = _emailTemplateProcessor.process(context, emailTemplate); StaticMailRequest smr = new StaticMailRequest(mdh); if (smr.getTo().length == 0) { final EmailTemplateRecipient recipientAttribute = context.getRecipientAttribute(); if (recipientAttribute != null) smr.setTo(new String[] { recipientAttribute.getEmailAddress().getAddress() }); } if (StringFactory.isEmptyString(smr.getFrom())) { UnparsedAddress from = new UnparsedAddress(_systemSender, defaultFromNameSupplier != null ? defaultFromNameSupplier.get() : null); smr.setFrom(from.getAddress()); } EmailTemplate et = (EmailTemplate) mdh.getAttribute(EmailTemplate.class); if (et != null) { smr.setMessageName(et.getProgrammaticName()); } smr.setScheduledTime(delayMillis == 0 ? new Date() : new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.toMillis(delayMillis))); _scheduledRequestProcessor.save(smr); } catch (MailDataHandlerException | EmailTemplateException e) { _logger.error("An unexpected error occurred while processing the email.", e); } }
From source file:enumj.Enumerator.java
/** * Returns an enumerator that enumerates over the iterator supplied lazily * the given number of times./*w w w . j a va2 s . c om*/ * * @param <E> type of enumerated element. * @param source supplier of the iterator to repeat. * @param count the number of times to repeat. * @return the repeated enumerator. * @exception IllegalArgumentException <code>source</code> is * null or <code>count</code> is negative. * @see #repeat(java.lang.Object, long) * @see #repeatAll(int) * @see #repeatEach(int) */ public static <E> Enumerator<E> repeatAll(Supplier<Iterator<E>> source, long count) { Checks.ensureNotNull(source, Messages.NULL_ENUMERATOR_SOURCE); Checks.ensureNonNegative(count, Messages.NEGATIVE_ENUMERATOR_EXPECTED_COUNT); return rangeLong(0, count).flatMap(l -> source.get()); }
From source file:com.joyent.manta.client.crypto.MantaEncryptedObjectInputStream.java
/** * Finds the correct HMAC instance based on the metadata supplied from the * encrypted object.// ww w . j av a2s. com * * @return HMAC instance or null when encrypted by a AEAD cipher */ private HMac findHmac() { if (this.cipherDetails.isAEADCipher() || !this.authenticateCiphertext) { return null; } String hmacString = getHeaderAsString(MantaHttpHeaders.ENCRYPTION_HMAC_TYPE); if (hmacString == null) { String msg = String.format("HMAC header metadata [%s] was missing from object", MantaHttpHeaders.ENCRYPTION_HMAC_TYPE); MantaClientEncryptionException e = new MantaClientEncryptionException(msg); annotateException(e); throw e; } if (hmacString.isEmpty()) { String msg = String.format("HMAC header metadata [%s] was empty on object", MantaHttpHeaders.ENCRYPTION_HMAC_TYPE); MantaClientEncryptionException e = new MantaClientEncryptionException(msg); annotateException(e); throw e; } Supplier<HMac> macSupplier = SupportedHmacsLookupMap.INSTANCE.get(hmacString); if (macSupplier == null) { String msg = String.format("HMAC stored in header metadata [%s] is unsupported", hmacString); MantaClientEncryptionException e = new MantaClientEncryptionException(msg); annotateException(e); throw e; } return macSupplier.get(); }
From source file:com.redhat.red.build.koji.KojiClient.java
private UrlBuilder sessionUrlBuilder(KojiSessionInfo session, Supplier<Map<String, Object>> paramEditor) { return (url) -> { if (session == null) { return new UrlBuildResult(url); }//from w w w .jav a2 s. c o m Map<String, String> params = new HashMap<>(); params.put(SESSION_ID_PARAM, Integer.toString(session.getSessionId())); params.put(SESSION_KEY_PARAM, session.getSessionKey()); params.put(CALL_NUMBER_PARAM, Integer.toString(callCount.getAndIncrement())); if (paramEditor != null) { Map<String, Object> extraParams = paramEditor.get(); if (extraParams != null) { MalformedURLException error = (MalformedURLException) extraParams.get(EMBEDDED_ERROR_PARAM); if (error != null) { return new UrlBuildResult(error); } else { extraParams.forEach((key, value) -> { params.put(key, String.valueOf(value)); }); } } } String result = UrlUtils.buildUrl(url, params); Logger logger = LoggerFactory.getLogger(KojiClient.class); logger.debug("\n\n\n\nBuild URL: {}\n\n\n\n", result); return new UrlBuildResult(result); }; }
From source file:com.ikanow.aleph2.shared.crud.mongodb.services.TestMongoDbCrudService.java
@Test public void testCreateSingleObject_ObjectId() throws InterruptedException, ExecutionException { final MongoDbCrudService<TestObjectIdBean, ObjectId> service = getTestService( "testCreateSingleObject_ObjectId", TestObjectIdBean.class, ObjectId.class); assertEquals(0, service._state.orig_coll.count()); // 1) Add a new object to an empty DB final TestObjectIdBean test = new TestObjectIdBean(); final Future<Supplier<Object>> result = service.storeObject(test); assertEquals(1, service._state.orig_coll.count()); final Supplier<Object> val = result.get(); ObjectId id = (ObjectId) val.get(); final DBObject retval = service._state.orig_coll.findOne(id); assertEquals(new BasicDBObject("_id", id), retval); }
From source file:com.thinkbiganalytics.metadata.rest.client.MetadataClient.java
private <R> R nullable(Supplier<R> supplier) { try {/*from w w w . ja v a 2 s.co m*/ return supplier.get(); } catch (HttpClientErrorException e) { if (e.getStatusCode() == HttpStatus.NOT_FOUND) { return null; } else { throw e; } } }
From source file:io.pravega.segmentstore.server.containers.StreamSegmentMapperTests.java
/** * Tests the ability of the StreamSegmentMapper to generate/return the Id of an existing StreamSegment, as well as * retrieving existing attributes.//from w w w . j a v a2s . c om */ @Test public void testGetOrAssignStreamSegmentId() { final int segmentCount = 10; final int transactionsPerSegment = 5; final long noSegmentId = ContainerMetadata.NO_STREAM_SEGMENT_ID; AtomicLong currentSegmentId = new AtomicLong(Integer.MAX_VALUE); Supplier<Long> nextSegmentId = () -> currentSegmentId.decrementAndGet() % 2 == 0 ? noSegmentId : currentSegmentId.get(); @Cleanup TestContext context = new TestContext(); HashSet<String> storageSegments = new HashSet<>(); for (int i = 0; i < segmentCount; i++) { String segmentName = getName(i); storageSegments.add(segmentName); setAttributes(segmentName, nextSegmentId.get(), storageSegments.size() % ATTRIBUTE_COUNT, context); for (int j = 0; j < transactionsPerSegment; j++) { // There is a small chance of a name conflict here, but we don't care. As long as we get at least one // Transaction per segment, we should be fine. String transactionName = StreamSegmentNameUtils.getTransactionNameFromId(segmentName, UUID.randomUUID()); storageSegments.add(transactionName); setAttributes(transactionName, nextSegmentId.get(), storageSegments.size() % ATTRIBUTE_COUNT, context); } } // We setup all necessary handlers, except the one for create. We do not need to create new Segments here. setupOperationLog(context); Predicate<String> isSealed = segmentName -> segmentName.hashCode() % 2 == 0; Function<String, Long> getInitialLength = segmentName -> (long) Math.abs(segmentName.hashCode()); setupStorageGetHandler(context, storageSegments, segmentName -> new StreamSegmentInformation(segmentName, getInitialLength.apply(segmentName), isSealed.test(segmentName), false, new ImmutableDate())); // First, map all the parents (stand-alone segments). for (String name : storageSegments) { if (StreamSegmentNameUtils.getParentStreamSegmentName(name) == null) { long id = context.mapper.getOrAssignStreamSegmentId(name, TIMEOUT).join(); Assert.assertNotEquals("No id was assigned for StreamSegment " + name, ContainerMetadata.NO_STREAM_SEGMENT_ID, id); SegmentMetadata sm = context.metadata.getStreamSegmentMetadata(id); Assert.assertNotNull("No metadata was created for StreamSegment " + name, sm); long expectedLength = getInitialLength.apply(name); boolean expectedSeal = isSealed.test(name); Assert.assertEquals("Metadata does not have the expected length for StreamSegment " + name, expectedLength, sm.getDurableLogLength()); Assert.assertEquals( "Metadata does not have the expected value for isSealed for StreamSegment " + name, expectedSeal, sm.isSealed()); val segmentState = context.stateStore.get(name, TIMEOUT).join(); Map<UUID, Long> expectedAttributes = segmentState == null ? null : segmentState.getAttributes(); SegmentMetadataComparer.assertSameAttributes( "Unexpected attributes in metadata for StreamSegment " + name, expectedAttributes, sm); } } // Now, map all the Transactions. for (String name : storageSegments) { String parentName = StreamSegmentNameUtils.getParentStreamSegmentName(name); if (parentName != null) { long id = context.mapper.getOrAssignStreamSegmentId(name, TIMEOUT).join(); Assert.assertNotEquals("No id was assigned for Transaction " + name, ContainerMetadata.NO_STREAM_SEGMENT_ID, id); SegmentMetadata sm = context.metadata.getStreamSegmentMetadata(id); Assert.assertNotNull("No metadata was created for Transaction " + name, sm); long expectedLength = getInitialLength.apply(name); boolean expectedSeal = isSealed.test(name); Assert.assertEquals("Metadata does not have the expected length for Transaction " + name, expectedLength, sm.getDurableLogLength()); Assert.assertEquals( "Metadata does not have the expected value for isSealed for Transaction " + name, expectedSeal, sm.isSealed()); val segmentState = context.stateStore.get(name, TIMEOUT).join(); Map<UUID, Long> expectedAttributes = segmentState == null ? null : segmentState.getAttributes(); SegmentMetadataComparer.assertSameAttributes( "Unexpected attributes in metadata for Transaction " + name, expectedAttributes, sm); // Check parenthood. Assert.assertNotEquals("No parent defined in metadata for Transaction " + name, ContainerMetadata.NO_STREAM_SEGMENT_ID, sm.getParentId()); long parentId = context.metadata.getStreamSegmentId(parentName, false); Assert.assertEquals("Unexpected parent defined in metadata for Transaction " + name, parentId, sm.getParentId()); } } }
From source file:com.thinkbiganalytics.metadata.rest.client.MetadataClient.java
private <R> Optional<R> optinal(Supplier<R> supplier) { try {/*w w w. j av a 2 s . c o m*/ return Optional.ofNullable(supplier.get()); } catch (HttpClientErrorException e) { if (e.getStatusCode() == HttpStatus.NOT_FOUND) { return Optional.empty(); } else { throw e; } } }
From source file:com.ikanow.aleph2.shared.crud.mongodb.services.TestMongoDbCrudService.java
@Test public void testCreateSingleObject() throws InterruptedException, ExecutionException { final MongoDbCrudService<TestBean, String> service = getTestService("testCreateSingleObject", TestBean.class, String.class); assertEquals(0, service._state.orig_coll.count()); // 1) Add a new object to an empty DB final TestBean test = new TestBean(); test._id = "_id_1"; test.test_string = "test_string_1"; final Future<Supplier<Object>> result = service.storeObject(test); final Supplier<Object> val = result.get(); assertEquals("_id_1", val.get()); final DBObject retval = service._state.orig_coll.findOne(); assertEquals(1, service._state.orig_coll.count()); assertEquals("{ \"_id\" : \"_id_1\" , \"test_string\" : \"test_string_1\"}", retval.toString()); // 2) Add the _id again, should fail final TestBean test2 = BeanTemplateUtils.clone(test).with("test_string", "test_string_2").done(); final Future<Supplier<Object>> result2 = service.storeObject(test2); Exception expected_ex = null; try {//from w ww.j a v a2s .c o m result2.get(); fail("Should have thrown exception on duplicate insert"); } catch (Exception e) { expected_ex = e; } if (null != expected_ex) assertThat(expected_ex.getCause(), instanceOf(MongoException.class)); assertEquals(1, service._state.orig_coll.count()); final DBObject retval2 = service._state.orig_coll.findOne(); assertEquals("{ \"_id\" : \"_id_1\" , \"test_string\" : \"test_string_1\"}", retval2.toString()); // 3) Add the same with override set @SuppressWarnings("unused") final Future<Supplier<Object>> result3 = service.storeObject(test2, true); assertEquals(1, service._state.orig_coll.count()); final DBObject retval3 = service._state.orig_coll.findOne(); assertEquals("{ \"_id\" : \"_id_1\" , \"test_string\" : \"test_string_2\"}", retval3.toString()); //4) add with no id final TestBean test4 = new TestBean(); test4.test_string = "test_string_4"; final Future<Supplier<Object>> result4 = service.storeObject(test4, true); assertEquals(2, service._state.orig_coll.count()); final String id = result4.get().get().toString(); final DBObject retval4 = service._state.orig_coll.findOne(id); assertEquals("test_string_4", retval4.get("test_string")); }
From source file:com.ikanow.aleph2.analytics.services.DeduplicationService.java
@SuppressWarnings("unchecked") @Override//from w ww. ja v a 2 s .co m public void onStageComplete(final boolean is_original) { _custom_handler.optional().ifPresent(handler -> handler.onStageComplete(true)); final Supplier<String> subsystem_builder = () -> (_is_system_dedup_stage.get() ? "" : ("." + _control.get().name() + Optional.ofNullable("no_name"))); final Supplier<String> command_builder = () -> (_is_system_dedup_stage.get() ? "system" : _control.get().name() + Optional.ofNullable("no_name")); _logger.optional().ifPresent(l -> l.log(Level.DEBUG, ErrorUtils.lazyBuildMessage(true, () -> "DeduplicationService" + subsystem_builder.get(), () -> command_builder.get() + ".onStageComplete", () -> null, () -> ErrorUtils.get( "Job {0} completed deduplication: nondup_keys={1}, dup_keys={2}, dups_inc={3}, dups_db={4}, del={5}", command_builder.get(), Integer.toString(_mutable_stats.nonduplicate_keys), Integer.toString(_mutable_stats.duplicate_keys), Integer.toString(_mutable_stats.duplicates_incoming), Integer.toString(_mutable_stats.duplicates_existing), Integer.toString(_mutable_stats.deleted)), () -> (Map<String, Object>) _mapper.convertValue(_mutable_stats, Map.class)))); if (!mutable_uncompleted_deletes.isEmpty()) { try { CompletableFuture.allOf(mutable_uncompleted_deletes.stream().toArray(CompletableFuture[]::new)) .get(60, TimeUnit.SECONDS); } catch (Exception e) { _logger.optional().ifPresent(l -> l.log(Level.ERROR, ErrorUtils.lazyBuildMessage(false, () -> "DeduplicationService" + subsystem_builder.get(), () -> command_builder.get() + ".onStageComplete", () -> null, () -> ErrorUtils.get("Job {0}: error completing deleted ids: {1}", command_builder.get(), e.getMessage()), () -> null))); } } _logger.optional().ifPresent(Lambdas.wrap_consumer_u(l -> l.flush().get(60, TimeUnit.SECONDS))); }