Java Code Examples for io.vavr.control.Try#get()
The following examples show how to use
io.vavr.control.Try#get() .
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: 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 3
Source File: HttpUtils.java From QVisual with Apache License 2.0 | 6 votes |
public static String post(String url, String fileName, BufferedImage image) { Try<String> uploadedFile = Try.of(() -> { HttpClient client = HttpClientBuilder.create().build(); HttpEntity entity = MultipartEntityBuilder .create() .setCharset(UTF_8) .setMode(BROWSER_COMPATIBLE) .addBinaryBody("file", getImageBytes(image), DEFAULT_BINARY, 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 image]", t)); return (uploadedFile.isSuccess()) ? uploadedFile.get() : null; }
Example 4
Source File: SnapshotApiService.java From QVisual with Apache License 2.0 | 6 votes |
private List<DiffElement> getDiffElements(boolean image, Snapshot actualElements, Snapshot expectedElements, Mat actualImage, Mat expectedImage, boolean isRetina, int inaccuracy, StringBuffer error) { Try<HashMap<String, Element>> actualTry = parseJson(actualElements.getElements(), new TypeReference<HashMap<String, Element>>() {}); Try<HashMap<String, Element>> expectedTry = parseJson(expectedElements.getElements(), new TypeReference<HashMap<String, Element>>() {}); if (actualTry.isSuccess() && expectedTry.isSuccess()) { HashMap<String, Element> actual = actualTry.get(); HashMap<String, Element> expected = expectedTry.get(); return compare(image, actual, expected, actualImage, expectedImage, isRetina, inaccuracy, error); } else { error.append("Could not parse elements json: actual " + actualElements.getElements()).append("\n") .append("expected " + expectedElements.getElements()).append("\n"); return new ArrayList<>(); } }
Example 5
Source File: DataRowModificationTests.java From java-datatable with Apache License 2.0 | 6 votes |
@Test public void testDataRemoveRow() { DataTable table = createDataTable(); // Remove row at row index 2. Try<DataTable> result = table.rows().remove(2); assertTrue(result.isSuccess()); DataTable newTable = result.get(); assertTrue(newTable.rowCount() == 3); assertTrue(newTable.column("StrCol").valueAt(0) == "AA"); assertTrue(newTable.column("StrCol").valueAt(1) == "BB"); assertTrue(newTable.column("StrCol").valueAt(2) == "DD"); assertTrue((int)newTable.column("IntCol").valueAt(0) == 3); assertTrue((int)newTable.column("IntCol").valueAt(1) == 5); assertTrue((int)newTable.column("IntCol").valueAt(2) == 11); assertTrue((boolean)newTable.column("BoolCol").valueAt(0)); assertTrue(!(boolean)newTable.column("BoolCol").valueAt(1)); assertTrue(!(boolean)newTable.column("BoolCol").valueAt(2)); }
Example 6
Source File: JsonTransformer.java From QVisual with Apache License 2.0 | 5 votes |
@Override public String render(Object model) { Try<String> rendered = writeAsString(model); if (rendered.isSuccess()) { return rendered.get(); } else { return null; } }
Example 7
Source File: RetrofitRateLimiter.java From resilience4j with Apache License 2.0 | 5 votes |
@Override public Response<T> execute() throws IOException { CheckedFunction0<Response<T>> restrictedSupplier = RateLimiter .decorateCheckedSupplier(rateLimiter, call::execute); final Try<Response<T>> response = Try.of(restrictedSupplier); return response.isSuccess() ? response.get() : handleFailure(response); }
Example 8
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 9
Source File: DisplayNameHelper.java From timbuctoo with GNU General Public License v3.0 | 5 votes |
public static Optional<String> getDisplayname(GraphTraversalSource traversalSource, Vertex vertex, Collection targetCollection) { ReadableProperty displayNameProperty = targetCollection.getDisplayName(); if (displayNameProperty != null) { GraphTraversal<Vertex, Try<JsonNode>> displayNameGetter = traversalSource.V(vertex.id()).union( targetCollection.getDisplayName().traversalJson() ); if (displayNameGetter.hasNext()) { Try<JsonNode> traversalResult = displayNameGetter.next(); if (!traversalResult.isSuccess()) { LOG.debug(databaseInvariant, "Retrieving displayname failed", traversalResult.getCause()); } else { if (traversalResult.get() == null) { LOG.debug(databaseInvariant, "Displayname was null"); } else { if (!traversalResult.get().isTextual()) { LOG.debug(databaseInvariant, "Displayname was not a string but " + traversalResult.get().toString()); } else { return Optional.of(traversalResult.get().asText()); } } } } else { LOG.debug(databaseInvariant, "Displayname traversal resulted in no results: " + displayNameGetter); } } else { LOG.debug("No displayname configured for " + targetCollection.getEntityTypeName()); //FIXME: deze wordt gegooid tijdens de finish. da's raar } return Optional.empty(); }