io.vavr.control.Try Java Examples
The following examples show how to use
io.vavr.control.Try.
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: ResilienceHandler.java From cloud-espm-cloud-native with Apache License 2.0 | 7 votes |
/** * This method returns a desired Tax(taxAmount, taxPercentage) value when the TaxService is up. * If the TaxService is down, it applies a combination of following fault tolerance patterns * in a sequence: TimeLimiter, CircuitBreaker and Retry using a Callable. When all the attempts * are exhausted it calls a fallback method to recover from failure and offers the default tax value. * * @param amount * @return */ public Tax applyResiliencePatterns(BigDecimal amount) { CircuitBreaker circuitBreaker = configureCircuitBreaker(); TimeLimiter timeLimiter = configureTimeLimiter(); Retry retry = configureRetry(); Supplier<CompletableFuture<Tax>> futureSupplier = () -> CompletableFuture.supplyAsync(() -> salesOrderService.supplyTax(amount)); Callable<Tax> callable = TimeLimiter.decorateFutureSupplier(timeLimiter, futureSupplier); callable = CircuitBreaker.decorateCallable(circuitBreaker, callable); callable = Retry.decorateCallable(retry, callable); //Executing the decorated callable and recovering from any exception by calling the fallback method Try<Tax> result = Try.ofCallable(callable).recover(throwable -> taxServiceFallback(amount)); return result.get(); }
Example #2
Source File: WwPersonDisplayNameTest.java From timbuctoo with GNU General Public License v3.0 | 6 votes |
@Test public void parsesPersonNamesAsDisplayNameIfPresent() { final String expectedName = "person names"; Graph graph = newGraph() .withVertex(v -> v .withType("person") .withVre("ww") .withProperty("wwperson_names", getPersonName("person", "names")) ).build(); WwPersonDisplayName instance = new WwPersonDisplayName(); Try<JsonNode> result = graph.traversal().V().union(instance.traversalJson()).next(); assertThat(result.get().asText(), equalTo(expectedName)); }
Example #3
Source File: DecoratorsTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void testDecoratorBuilderWithRateLimiter() { given(helloWorldService.returnHelloWorld()).willReturn("Hello world"); RateLimiterConfig config = RateLimiterConfig.custom() .timeoutDuration(Duration.ofMillis(100)) .limitRefreshPeriod(Duration.ofSeconds(1)) .limitForPeriod(1) .build(); RateLimiter rateLimiter = RateLimiter.of("backendName", config); CheckedFunction0<String> restrictedSupplier = Decorators .ofCheckedSupplier(() -> helloWorldService.returnHelloWorld()) .withRateLimiter(rateLimiter) .decorate(); alignTime(rateLimiter); Try<String> firstTry = Try.of(restrictedSupplier); Try<String> secondTry = Try.of(restrictedSupplier); assertThat(firstTry.isSuccess()).isTrue(); assertThat(secondTry.isFailure()).isTrue(); assertThat(secondTry.getCause()).isInstanceOf(RequestNotPermitted.class); then(helloWorldService).should(times(1)).returnHelloWorld(); }
Example #4
Source File: CircuitBreakerTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldDecorateCheckedRunnableAndReturnWithException() throws Throwable { CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.ofDefaults(); CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("testName"); CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics(); assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(0); CheckedRunnable checkedRunnable = circuitBreaker.decorateCheckedRunnable(() -> { throw new RuntimeException("BAM!"); }); Try<Void> result = Try.run(checkedRunnable); assertThat(result.isFailure()).isTrue(); assertThat(result.failed().get()).isInstanceOf(RuntimeException.class); assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1); assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(1); assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(0); }
Example #5
Source File: BulkheadTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldReturnFailureWithBulkheadFullException() { // tag::bulkheadFullException[] BulkheadConfig config = BulkheadConfig.custom().maxConcurrentCalls(2).build(); Bulkhead bulkhead = Bulkhead.of("test", config); bulkhead.tryAcquirePermission(); bulkhead.tryAcquirePermission(); CheckedRunnable checkedRunnable = Bulkhead.decorateCheckedRunnable(bulkhead, () -> { throw new RuntimeException("BAM!"); }); Try result = Try.run(checkedRunnable); assertThat(result.isFailure()).isTrue(); assertThat(result.failed().get()).isInstanceOf(BulkheadFullException.class); // end::bulkheadFullException[] }
Example #6
Source File: ZAPStepDefinitions.java From IridiumApplicationTesting with MIT License | 6 votes |
/** * Sets the attack strength * @param strength The ZAP attack strength */ @Given("the attack strength is set to \"(.*?)\"") public void setAttackStrength(final String strength) { final ClientApi clientApi = getClientApi(); SCANNER_IDS.entrySet().stream() .filter(a -> StringUtils.isNotBlank(a.getValue())) .forEach(a -> Arrays.asList(a.getValue().split(",")).stream() .forEach(t -> Try.run(() -> clientApi.ascan.setScannerAttackStrength( Constants.ZAP_API_KEY, t, strength.toUpperCase(), null) ) ) ); }
Example #7
Source File: AriEventProcessing.java From ari-proxy with GNU Affero General Public License v3.0 | 6 votes |
private static Try<Source<ProducerRecord<String, String>, NotUsed>> createSource( String kafkaCommandsTopic, String kafkaEventsAndResponsesTopic, AriMessageType type, LoggingAdapter log, String callContext, JsonNode messageBody) { final AriMessageEnvelope envelope = new AriMessageEnvelope( type, kafkaCommandsTopic, messageBody, callContext ); return Try.of(() -> writer.writeValueAsString(envelope)) .map(marshalledEnvelope -> { log.debug("[ARI MESSAGE TYPE] {}", envelope.getType()); return Source.single(new ProducerRecord<>( kafkaEventsAndResponsesTopic, callContext, marshalledEnvelope )); }); }
Example #8
Source File: BulkheadTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldInvokeMap() { // tag::shouldInvokeMap[] Bulkhead bulkhead = Bulkhead.of("testName", config); // When I decorate my function CheckedFunction0<String> decoratedSupplier = Bulkhead.decorateCheckedSupplier(bulkhead, () -> "This can be any method which returns: 'Hello"); // and chain an other function with map Try<String> result = Try.of(decoratedSupplier) .map(value -> value + " world'"); // Then the Try Monad returns a Success<String>, if all functions ran successfully. assertThat(result.isSuccess()).isTrue(); assertThat(result.get()).isEqualTo("This can be any method which returns: 'Hello world'"); assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1); // end::shouldInvokeMap[] }
Example #9
Source File: CQLKeyColumnValueStore.java From grakn with GNU Affero General Public License v3.0 | 6 votes |
@Override public KeyIterator getKeys(SliceQuery query, StoreTransaction txh) throws BackendException { if (this.storeManager.getFeatures().hasOrderedScan()) { throw new PermanentBackendException("This operation is only allowed when a random partitioner (md5 or murmur3) is used."); } return Try.of(() -> new CQLResultSetKeyIterator( query, this.getter, this.storeManager.executeOnSession(this.getKeysAll.bind() .setByteBuffer(SLICE_START_BINDING, query.getSliceStart().asByteBuffer()) .setByteBuffer(SLICE_END_BINDING, query.getSliceEnd().asByteBuffer()) .setPageSize(this.pageSize) .setConsistencyLevel(getTransaction(txh).getReadConsistencyLevel())))) .getOrElseThrow(EXCEPTION_MAPPER); }
Example #10
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 #11
Source File: HttpUtils.java From QVisual with Apache License 2.0 | 6 votes |
public static String post(String url, String fileName, String json) { Try<String> uploadedFile = Try.of(() -> { HttpClient client = HttpClientBuilder.create().build(); HttpEntity entity = MultipartEntityBuilder .create() .setCharset(UTF_8) .setMode(BROWSER_COMPATIBLE) .addBinaryBody("file", json.getBytes(UTF_8), ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), UTF_8), fileName) .build(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(entity); HttpResponse response = client.execute(httpPost); return new BasicResponseHandler().handleResponse(response); }).onFailure(t -> logger.error("[POST json]", t)); return (uploadedFile.isSuccess()) ? uploadedFile.get() : null; }
Example #12
Source File: CircuitBreakerTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldChainDecoratedFunctions() { // tag::shouldChainDecoratedFunctions[] CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("testName"); CircuitBreaker anotherCircuitBreaker = CircuitBreaker.ofDefaults("anotherTestName"); // When I create a Supplier and a Function which are decorated by different CircuitBreakers CheckedFunction0<String> decoratedSupplier = CircuitBreaker .decorateCheckedSupplier(circuitBreaker, () -> "Hello"); CheckedFunction1<String, String> decoratedFunction = CircuitBreaker .decorateCheckedFunction(anotherCircuitBreaker, (input) -> input + " world"); // and I chain a function with map Try<String> result = Try.of(decoratedSupplier) .mapTry(decoratedFunction); assertThat(result.isSuccess()).isTrue(); assertThat(result.get()).isEqualTo("Hello world"); // end::shouldChainDecoratedFunctions[] CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics(); assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1); assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(0); CircuitBreaker.Metrics metrics2 = anotherCircuitBreaker.getMetrics(); assertThat(metrics2.getNumberOfBufferedCalls()).isEqualTo(1); assertThat(metrics2.getNumberOfFailedCalls()).isEqualTo(0); }
Example #13
Source File: RateLimiterTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void decorateCheckedFunction() throws Throwable { CheckedFunction1<Integer, String> function = mock(CheckedFunction1.class); CheckedFunction1<Integer, String> decorated = RateLimiter .decorateCheckedFunction(limit, function); given(limit.acquirePermission(1)).willReturn(false); Try<String> decoratedFunctionResult = Try.success(1).mapTry(decorated); assertThat(decoratedFunctionResult.isFailure()).isTrue(); assertThat(decoratedFunctionResult.getCause()).isInstanceOf(RequestNotPermitted.class); then(function).should(never()).apply(any()); given(limit.acquirePermission(1)).willReturn(true); Try secondFunctionResult = Try.success(1).mapTry(decorated); assertThat(secondFunctionResult.isSuccess()).isTrue(); then(function).should().apply(1); }
Example #14
Source File: CollectionFactoryMethodsUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void givenAFailureObject_whenEvaluated_thenExceptionThrown() { Try<Integer> failure = Failure(new Exception("Exception X encapsulated here")); try { Integer i = failure.get();// evaluate a failure raise the exception System.out.println(i);// not executed } catch (Exception e) { assertEquals(e.getMessage(), "Exception X encapsulated here"); } }
Example #15
Source File: ArtifactResolver.java From pgpverify-maven-plugin with Apache License 2.0 | 5 votes |
private boolean matchSurefireVersion(Plugin plugin) { return Try.of(() -> repositorySystem.createPluginArtifact(plugin).getSelectedVersion()) .map(SUREFIRE_PLUGIN_VERSION_RANGE::containsVersion) .onFailure(e -> LOG.debug("Found build plug-in with overly constrained version specification.", e)) .getOrElse(false); }
Example #16
Source File: RunnableRetryTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void shouldReturnAfterOneAttempt() { willThrow(new HelloWorldException()).given(helloWorldService).sayHelloWorld(); RetryConfig config = RetryConfig.custom().maxAttempts(1).build(); Retry retry = Retry.of("id", config); CheckedRunnable retryableRunnable = Retry .decorateCheckedRunnable(retry, helloWorldService::sayHelloWorld); Try<Void> result = Try.run(retryableRunnable); then(helloWorldService).should().sayHelloWorld(); assertThat(result.isFailure()).isTrue(); assertThat(result.failed().get()).isInstanceOf(HelloWorldException.class); assertThat(sleptTime).isEqualTo(0); }
Example #17
Source File: SupplierRetryTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void shouldIgnoreExceptionOfDecoratedTry() { given(helloWorldService.returnTry()).willReturn(Try.failure(new HelloWorldException())); final RetryConfig tryAgain = RetryConfig.<String>custom() .ignoreExceptions(HelloWorldException.class) .maxAttempts(2).build(); Retry retry = Retry.of("id", tryAgain); Try<String> result = retry.executeTrySupplier(helloWorldService::returnTry); then(helloWorldService).should().returnTry(); assertThat(result.isFailure()).isTrue(); assertThat(result.getCause()).isInstanceOf(HelloWorldException.class); }
Example #18
Source File: DataVerticle.java From djl-demo with Apache License 2.0 | 5 votes |
private void setPerformance() { Try.run(() -> { Metrics metrics = trainer.getMetrics(); trainer.getEvaluators().forEach(e -> { String metricName = EvaluatorTrainingListener.metricName(e, EvaluatorTrainingListener.TRAIN_PROGRESS); if (metrics.hasMetric(metricName)) { List<MetricInfo> mis = getMetrics(e.getName()); float y = metrics.latestMetric(metricName).getValue().floatValue(); mis.add(MetricInfo.builder().name(e.getName()).x(mis.size()).y(y).build()); setMetrics(e.getName(), mis); } }); }).onFailure(throwable -> LOGGER.error("", throwable)); }
Example #19
Source File: Reader.java From ts-reaktive with MIT License | 5 votes |
/** * Returns a reader that emits a result on every event, the result being the event itself. */ public static <T, E extends T> Reader<E,T> identity() { return new Reader<E, T>() { @Override public Try<T> reset() { return ReadProtocol.none(); } @Override public Try<T> apply(E event) { return Try.success(event); } }; }
Example #20
Source File: SupplierRetryTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void shouldReturnAfterOneAttempt() { given(helloWorldService.returnHelloWorld()).willThrow(new HelloWorldException()); RetryConfig config = RetryConfig.custom().maxAttempts(1).build(); Retry retry = Retry.of("id", config); CheckedFunction0<String> retryableSupplier = Retry .decorateCheckedSupplier(retry, helloWorldService::returnHelloWorld); Try<String> result = Try.of(retryableSupplier); then(helloWorldService).should().returnHelloWorld(); assertThat(result.isFailure()).isTrue(); assertThat(result.failed().get()).isInstanceOf(HelloWorldException.class); assertThat(sleptTime).isEqualTo(0); }
Example #21
Source File: DataColumnCollectionTests.java From java-datatable with Apache License 2.0 | 5 votes |
@Test public void testAddColumn() { DataTable oldTable = createDataTable(); IDataColumn newCol = createDoubleColumn(); Try<DataTable> newTable = oldTable.columns().add(newCol); assertTrue(newTable.isSuccess()); assertTrue(oldTable.columns().count() == 3); assertTrue(newTable.get().columns().count() == 4); assertTrue(newTable.get().column(3).name().equals("DoubleCol")); }
Example #22
Source File: DataRowTests.java From java-datatable with Apache License 2.0 | 5 votes |
@Test public void testDataRowGetItemAsUntypedByColIndex() { DataTable table = createDataTable(); DataRow row = table.row(1); Try<Object> itemData = row.get(1); assertTrue(itemData.isSuccess()); assertTrue((Integer)itemData.get() == 7); }
Example #23
Source File: RemoteTestsUtilsImpl.java From IridiumApplicationTesting with MIT License | 5 votes |
@Override public Option<String> getSessionID() { return Try.of(() -> State.getThreadDesiredCapabilityMap().getWebDriverForThread()) .mapTry(RemoteWebDriver.class::cast) .map(RemoteWebDriver::toString) .map(SESSION_ID_REGEX::matcher) .filter(Matcher::find) .map(Matcher::group) .toOption(); }
Example #24
Source File: DataColumnCollection.java From java-datatable with Apache License 2.0 | 5 votes |
private Try<DataTable> checkColumnsAndBuild(String changeType, Supplier<Try<Vector<IDataColumn>>> columns) { // Calculate the new column collection then try and build a DataTable from it. Try<DataTable> result = columns.get() .flatMap(cols -> DataTable.build(this.table.name(), cols)); return result.isSuccess() ? result : error("Error " + changeType + " column at specified index.", result.getCause()); }
Example #25
Source File: LabelsAddedToVertexDatabaseCheck.java From timbuctoo with GNU General Public License v3.0 | 5 votes |
@Override public ValidationResult check(Vertex vertex) { if (!(vertex instanceof Neo4jVertex)) { return new ElementValidationResult(false, "Is not a Neo4jVertex."); } if (vertex.property("types").isPresent()) { Set<String> types = new HashSet<>(Arrays.asList(getEntityTypes(vertex) .orElseGet(() -> Try.success(new String[0])) .getOrElse(() -> new String[0]))); Sets.SetView<String> difference = Sets.difference(types, ((Neo4jVertex) vertex).labels()); if (!difference.isEmpty()) { return new ElementValidationResult( false, String.format("Vertex with tim_id %s misses labels %s\n", getProp(vertex, "tim_id", String.class).orElse("<UNKNOWN>"), difference ) ); } } return new ElementValidationResult(true, String.format("Vertex with tim_id %s is valid.", getProp(vertex, "tim_id", String.class).orElse("<UNKNOWN>")) ); }
Example #26
Source File: PublicKeyUtils.java From pgpverify-maven-plugin with Apache License 2.0 | 5 votes |
/** * Validate signatures for subKeys in given key ring. * * @param publicKeyRing * keys to verify */ private static void verifyPublicKeyRing(PGPPublicKeyRing publicKeyRing) { StreamSupport.stream(publicKeyRing.spliterator(), false) .filter(key -> !key.isMasterKey()) .forEach(key -> Try.run(() -> verifySigForSubKey(key, publicKeyRing)).get()); }
Example #27
Source File: CircuitBreakerTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void shouldExecuteTrySupplierAndReturnWithSuccess() { CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("testName"); CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics(); assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(0); given(helloWorldService.returnTry()).willReturn(Try.success("Hello world")); Try<String> result = circuitBreaker.executeTrySupplier(helloWorldService::returnTry); assertThat(result).contains("Hello world"); assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1); assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(0); assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(1); then(helloWorldService).should().returnTry(); }
Example #28
Source File: DataRowModificationTests.java From java-datatable with Apache License 2.0 | 5 votes |
@Test public void testDataInsertRowWithInvalidValueCount() { DataTable table = createDataTable(); // Insert data where the number of values doesn't match the number of columns. Object[] rowValues = { "ZZ" }; Try<DataTable> result = table.rows().insert(2, rowValues); assertTrue(result.isFailure()); assertTrue(result.getCause().getMessage().equals("Number of values does not match number of columns.")); }
Example #29
Source File: DataRowCollectionModifiable.java From java-datatable with Apache License 2.0 | 5 votes |
/** * Returns a new DataTable with the additional row appended. * * @param rowValues The values to append to the row. * @return Returns a new DataTable with the row appended. */ public Try<DataTable> add(Object[] rowValues) { return Match(mapValuesToColumns(Stream.of(rowValues))).of( Case($Success($()), this::addRow), Case($Failure($()), Try::failure) ); }
Example #30
Source File: DataColumnCollection.java From java-datatable with Apache License 2.0 | 5 votes |
/** * Returns the IDataColumn by name. * Performs column name check, returns results in a Try. * * @param columnName The name of the IDataColumn. * @return Returns the IDataColumn. */ public Try<IDataColumn> tryGet(String columnName) { Integer idx = columnIdxByName(columnName); return idx < 0 ? DataTableException.tryError("Invalid column name.") : Try.success(get(idx)); }