io.vavr.concurrent.Future Java Examples
The following examples show how to use
io.vavr.concurrent.Future.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AriCommandResponseKafkaProcessor.java From ari-proxy with GNU Affero General Public License v3.0 | 6 votes |
private static CompletionStage<Tuple2<AriResponse, CallContextAndCommandId>> toAriResponse( Tuple2<HttpResponse, CallContextAndCommandId> responseWithContext, Materializer materializer) { final HttpResponse response = responseWithContext._1; final long contentLength = response .entity() .getContentLengthOption() .orElseThrow(() -> new RuntimeException("failed to get content length")); return response .entity() .toStrict(contentLength, materializer) .thenCompose(strictText -> Option.of(StringUtils.trimToNull(strictText.getData().decodeString(Charset.defaultCharset()))) .map(rawBody -> Try .of(() -> genericReader.readTree(rawBody)) .map(jsonBody -> new AriResponse( response.status().intValue(), jsonBody)) .map(res -> responseWithContext.map1(httpResponse -> res)) .map(tuple -> CompletableFuture.completedFuture(tuple)) .getOrElseGet(t -> Future.<Tuple2<AriResponse, CallContextAndCommandId>>failed(t).toCompletableFuture())) .getOrElse(CompletableFuture.completedFuture(responseWithContext.map1(httpResponse -> new AriResponse(response.status().intValue(), null)))) ); }
Example #2
Source File: CallContextProvider.java From ari-proxy with GNU Affero General Public License v3.0 | 6 votes |
private void provideCallContextHandler(ProvideCallContext cmd) { log().debug("Got command: {}", cmd); final ActorRef sender = sender(); final Future<CallContextProvided> response = query(cmd.resourceId()) .flatMap(option -> option .map(callContext -> Future.successful(new CallContextProvided(callContext))) .getOrElse(() -> ProviderPolicy.CREATE_IF_MISSING.equals(cmd.policy()) ? update(cmd.resourceId(), UUID.randomUUID().toString()) .map(setDone -> new CallContextProvided(setDone.getValue())) : Future.failed(new CallContextLookupError("Failed to lookup call context..."))) ) .await(); PatternsAdapter.pipeTo(response, sender, context().dispatcher()); }
Example #3
Source File: AriEventProcessingTest.java From ari-proxy with GNU Affero General Public License v3.0 | 6 votes |
@Test void verifyGetCallContextWorksAsExpected() { new TestKit(system) { { final Future<Try<String>> callContext = Future.of(() -> AriEventProcessing.getCallContext("RESOURCE_ID", getRef(), ProviderPolicy.CREATE_IF_MISSING)); final ProvideCallContext provideCallContext = expectMsgClass(ProvideCallContext.class); assertThat(provideCallContext.policy(), is(ProviderPolicy.CREATE_IF_MISSING)); assertThat(provideCallContext.resourceId(), is("RESOURCE_ID")); reply(new CallContextProvided("CALL_CONTEXT")); assertThat(callContext.await().get().get(), is("CALL_CONTEXT")); } }; }
Example #4
Source File: CQLStoreManager.java From grakn with GNU Affero General Public License v3.0 | 5 votes |
@Override public void clearStorage() throws BackendException { if (this.storageConfig.get(DROP_ON_CLEAR)) { this.session.execute(dropKeyspace(this.keyspace).build()); } else if (this.exists()) { Future<Seq<AsyncResultSet>> result = Future.sequence( Iterator.ofAll(this.session.getMetadata().getKeyspace(this.keyspace).get().getTables().values()) .map(table -> Future.fromJavaFuture(this.session.executeAsync(truncate(this.keyspace, table.getName().toString()).build()) .toCompletableFuture()))); result.await(); } else { LOGGER.info("Keyspace {} does not exist in the cluster", this.keyspace); } }
Example #5
Source File: FutureUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenBothFuturesFail_thenGetErrorMessage() { Future<String> f1 = Future.of(() -> "Hello".substring(-1)); Future<String> f2 = Future.of(() -> "Hello".substring(-2)); Future<String> errorMessageFuture = f1.fallbackTo(f2); Future<Throwable> errorMessage = errorMessageFuture.failed(); assertThat( errorMessage.get().getMessage()) .isEqualTo("String index out of range: -1"); }
Example #6
Source File: FutureUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenChangeExecutorService_thenCorrect() { String result = Future.of(newSingleThreadExecutor(), () -> HELLO) .getOrElse(error); assertThat(result) .isEqualTo(HELLO); }
Example #7
Source File: FutureUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenAppendData_thenCorrect1() { String result = Future.of(() -> HELLO) .getOrElse(error); assertThat(result) .isEqualTo(HELLO); }
Example #8
Source File: FutureUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenAppendData_thenCorrect2() { Future<String> resultFuture = Future.of(() -> HELLO) .await(); Option<Try<String>> futureOption = resultFuture.getValue(); String result = futureOption.get().getOrElse(error); assertThat(result) .isEqualTo(HELLO); }
Example #9
Source File: FutureUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenAppendData_thenSuccess() { String result = Future.of(() -> HELLO) .onSuccess(finalResult -> System.out.println("Successfully Completed - Result: " + finalResult)) .onFailure(finalResult -> System.out.println("Failed - Result: " + finalResult)) .getOrElse(error); assertThat(result) .isEqualTo(HELLO); }
Example #10
Source File: FutureUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenTransform_thenCorrect() { Future<Object> future = Future.of(() -> 5) .transformValue(result -> Try.of(() -> HELLO + result.get())); assertThat(future.get()).isEqualTo(HELLO + 5); }
Example #11
Source File: FutureUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenCallAwait_thenCorrect() { Future<String> resultFuture = Future.of(() -> HELLO) .await(); String result = resultFuture.getValue().get().getOrElse(error); assertThat(result) .isEqualTo(HELLO); }
Example #12
Source File: FutureUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenDivideByZero_thenGetThrowable1() { Future<Integer> resultFuture = Future.of(() -> 10 / 0); assertThatThrownBy(resultFuture::get) .isInstanceOf(ArithmeticException.class); }
Example #13
Source File: FutureUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenDivideByZero_thenGetThrowable2() { Future<Integer> resultFuture = Future.of(() -> 10 / 0) .await(); assertThat(resultFuture.getCause().get().getMessage()) .isEqualTo("/ by zero"); }
Example #14
Source File: FutureUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenDivideByZero_thenCorrect() { Future<Integer> resultFuture = Future.of(() -> 10 / 0) .await(); assertThat(resultFuture.isCompleted()).isTrue(); assertThat(resultFuture.isSuccess()).isFalse(); assertThat(resultFuture.isFailure()).isTrue(); }
Example #15
Source File: FutureUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenAppendData_thenFutureNotEmpty() { Future<String> resultFuture = Future.of(() -> HELLO) .await(); assertThat(resultFuture.isEmpty()) .isFalse(); }
Example #16
Source File: FutureUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenCallZip_thenCorrect() { Future<String> f1 = Future.of(() -> "hello1"); Future<String> f2 = Future.of(() -> "hello2"); assertThat(f1.zip(f2).get()) .isEqualTo(Tuple.of("hello1", "hello2")); }
Example #17
Source File: FutureUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenConvertToCompletableFuture_thenCorrect() throws InterruptedException, ExecutionException { CompletableFuture<String> convertedFuture = Future.of(() -> HELLO) .toCompletableFuture(); assertThat(convertedFuture.get()) .isEqualTo(HELLO); }
Example #18
Source File: FutureUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenCallMap_thenCorrect() { Future<String> futureResult = Future.of(() -> "from Baeldung") .map(a -> "Hello " + a) .await(); assertThat(futureResult.get()) .isEqualTo("Hello from Baeldung"); }
Example #19
Source File: FutureUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenCallFlatMap_thenCorrect() { Future<Object> futureMap = Future.of(() -> 1) .flatMap((i) -> Future.of(() -> "Hello: " + i)); assertThat(futureMap.get()).isEqualTo("Hello: 1"); }
Example #20
Source File: FutureUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenFutureFails_thenGetErrorMessage() { Future<String> future = Future.of(() -> "Hello".substring(-1)) .recover(x -> "fallback value"); assertThat(future.get()) .isEqualTo("fallback value"); }
Example #21
Source File: FutureUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenFutureFails_thenGetAnotherFuture() { Future<String> future = Future.of(() -> "Hello".substring(-1)) .recoverWith(x -> Future.of(() -> "fallback value")); assertThat(future.get()) .isEqualTo("fallback value"); }
Example #22
Source File: InMemoryPersistenceStore.java From ari-proxy with GNU Affero General Public License v3.0 | 5 votes |
@Override public Future<String> set(String key, String value) { if (key.contains("failure")) { return Future.failed(new Exception("Failed to set value for key")); } store = store.put(key, value); return Future.successful(value); }
Example #23
Source File: RedisPersistenceStore.java From ari-proxy with GNU Affero General Public License v3.0 | 5 votes |
private <T> Future<T> executeRedisCommand(Function<RedisCommands<String, String>, T> f) { return Future.of(() -> { try (StatefulRedisConnection<String, String> connection = redisClient.connect()) { return f.apply(connection.sync()); } }); }
Example #24
Source File: PersistentCache.java From ari-proxy with GNU Affero General Public License v3.0 | 5 votes |
protected Future<SetDone> update(String key, String value) { final String prefixedKey = keyPrefix() + ":" + key; final String metricsContext = UUID.randomUUID().toString(); metricsService.tell(new RedisUpdateTimerStart(metricsContext), self()); cache.put(prefixedKey, Future.successful(Some(value))); return persistenceStore.set(prefixedKey, value).map(v -> new SetDone(prefixedKey, value)) .andThen(done -> metricsService.tell(new RedisUpdateTimerStop(metricsContext), self())); }
Example #25
Source File: PersistentCache.java From ari-proxy with GNU Affero General Public License v3.0 | 5 votes |
protected Future<HealthReport> provideHealthReport(final String key) { final String testValue = StringUtils.reverse(key); return persistenceStore.set(key, testValue).flatMap(v -> persistenceStore.get(key)).transformValue(tryOfValue -> tryOfValue .map(maybeValue -> maybeValue.map(v -> testValue.equals(v) ? Try.success(HealthReport.ok()) : Try.success(HealthReport.error(String.format("RedisCheck: %s does not match expected %s", v, testValue))) ) .getOrElse(() -> Try.success(HealthReport.error("RedisCheck: empty result on get()")))) .getOrElseGet(t -> Try.success(HealthReport.error("RedisCheck: " + t.getMessage())))); }
Example #26
Source File: HealthService.java From ari-proxy with GNU Affero General Public License v3.0 | 5 votes |
@Override public void preStart() throws Exception { this.binding = startHttpServer(); context().system().eventStream().subscribe(self(), ProvideMonitoring.class); Future.fromCompletableFuture(binding.toCompletableFuture()).onFailure(t -> System.exit(-1)); super.preStart(); }
Example #27
Source File: PatternsAdapter.java From ari-proxy with GNU Affero General Public License v3.0 | 5 votes |
@SuppressWarnings("unchecked") public static <T> Future<T> ask(final ActorRef actor, final Object message, final long timeoutMillis) { return CustomFutureConverters.fromScala(Patterns.ask( actor, message, timeoutMillis )) .map(o -> (T) o); }
Example #28
Source File: AriEventProcessingTest.java From ari-proxy with GNU Affero General Public License v3.0 | 5 votes |
@DisplayName("Verify processing of both channel and playback events results in the expected kafka producer record") @ParameterizedTest @ValueSource(strings = { stasisStartEvent, playbackFinishedEvent, recordingFinishedEvent }) void generateProducerRecordFromAllAriMessageTypes(String ariEvent) { new TestKit(system) { { final Future<Source<ProducerRecord<String, String>, NotUsed>> wsToKafkaProcessor = Future.of( () -> AriEventProcessing .generateProducerRecordFromEvent(fakeCommandsTopic, fakeEventsAndResponsesTopic, new Strict(ariEvent), getRef(), system.log(), genApplicationReplacedHandler.apply(getRef())) ); expectMsgClass(ProvideCallContext.class); reply(new CallContextProvided("CALL_CONTEXT")); final ProducerRecord<String, String> record = wsToKafkaProcessor .flatMap(source -> Future.fromCompletableFuture(source.runWith( Sink.last(), ActorMaterializer.create(ActorMaterializerSettings.create(system), system)) .toCompletableFuture()) ) .await() .get(); assertThat(record.key(), is("CALL_CONTEXT")); assertThat(record.topic(), is(fakeEventsAndResponsesTopic)); } }; }
Example #29
Source File: AriEventProcessingTest.java From ari-proxy with GNU Affero General Public License v3.0 | 5 votes |
@Test void checkApplicationReplacedHandlerIsTriggered() { new TestKit(system) { { final Future<Source<ProducerRecord<String, String>, NotUsed>> wsToKafkaProcessor = Future.of( () -> AriEventProcessing .generateProducerRecordFromEvent(fakeCommandsTopic, fakeEventsAndResponsesTopic, new Strict(applicationReplacedEvent), getRef(), system.log(), genApplicationReplacedHandler.apply(getRef())) ); assertThat(expectMsgClass(String.class), is("Shutdown triggered!")); assertThat(wsToKafkaProcessor.await().get(), is(Source.empty())); } }; }
Example #30
Source File: FutureUnitTest.java From tutorials with MIT License | 4 votes |
@Test public void whenChainingCallbacks_thenCorrect() { Future.of(() -> HELLO) .andThen(r -> System.out.println("Completed - 1: " + r)) .andThen(r -> System.out.println("Completed - 2: " + r)); }