Java Code Examples for io.vavr.control.Try#isSuccess()

The following examples show how to use io.vavr.control.Try#isSuccess() . 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: HttpUtils.java    From QVisual with Apache License 2.0 6 votes vote down vote up
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 2
Source File: HttpUtils.java    From QVisual with Apache License 2.0 6 votes vote down vote up
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 3
Source File: SnapShoter.java    From QVisual with Apache License 2.0 6 votes vote down vote up
private static void createSnapshot(String locators, boolean fullScreen, Snapshot snapshot, WebDriver driver) {
    try {
        String elements = (locators != null && locators.length() > 0) ? getElements(locators, driver) : null;
        String screenPath = uploadImage(fullScreen, snapshot.getDatetime(), driver);

        snapshot.setElements(elements);
        snapshot.setUrl(screenPath);

        Try<String> snapshotJson = writeAsString(snapshot);
        if (snapshotJson.isSuccess()) {
            post(BACKEND_DOMAIN + "/snapshots/create", snapshotJson.get());
        }
    } catch (Exception e) {
        logger.error("[create snapshot]", e);
    }
}
 
Example 4
Source File: SnapshotApiService.java    From QVisual with Apache License 2.0 6 votes vote down vote up
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: CircuitBreaker.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a supplier which is decorated by a CircuitBreaker.
 *
 * @param circuitBreaker the CircuitBreaker
 * @param supplier       the original function
 * @param <T>            the type of results supplied by this supplier
 * @return a retryable function
 */
static <T> Supplier<Try<T>> decorateTrySupplier(CircuitBreaker circuitBreaker,
    Supplier<Try<T>> supplier) {
    return () -> {
        if (circuitBreaker.tryAcquirePermission()) {
            long start = System.nanoTime();
            Try<T> result = supplier.get();
            long durationInNanos = System.nanoTime() - start;
            if (result.isSuccess()) {
                circuitBreaker.onSuccess(durationInNanos, TimeUnit.NANOSECONDS);
                return result;
            } else {
                circuitBreaker
                    .onError(durationInNanos, TimeUnit.NANOSECONDS, result.getCause());
                return result;
            }
        } else {
            return Try.failure(
                CallNotPermittedException.createCallNotPermittedException(circuitBreaker));
        }
    };
}
 
Example 6
Source File: JsonTransformer.java    From QVisual with Apache License 2.0 5 votes vote down vote up
@Override
public String render(Object model) {
    Try<String> rendered = writeAsString(model);
    if (rendered.isSuccess()) {
        return rendered.get();
    } else {
        return null;
    }
}
 
Example 7
Source File: DataColumnCollection.java    From java-datatable with Apache License 2.0 5 votes vote down vote up
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 8
Source File: Retry.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a retryable supplier.
 *
 * @param retry    the retry context
 * @param supplier the original function
 * @param <T>      the type of results supplied by this supplier
 * @return a retryable function
 */
static <T> Supplier<Try<T>> decorateTrySupplier(Retry retry, Supplier<Try<T>> supplier) {
    return () -> {
        Retry.Context<T> context = retry.context();
        do {
            Try<T> result = supplier.get();
            if (result.isSuccess()) {
                final boolean validationOfResult = context.onResult(result.get());
                if (!validationOfResult) {
                    context.onComplete();
                    return result;
                }
            } else {
                Throwable cause = result.getCause();
                if (cause instanceof Exception) {
                    try {
                        context.onError((Exception) result.getCause());
                    } catch (Exception e) {
                        return result;
                    }
                } else {
                    return result;
                }
            }
        } while (true);
    };
}
 
Example 9
Source File: RetrofitRateLimiter.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@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 10
Source File: DisplayNameHelper.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
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();
}
 
Example 11
Source File: DataRow.java    From java-datatable with Apache License 2.0 4 votes vote down vote up
private Try<Object> columnToValue(Try<IDataColumn> column) {
    return column.isSuccess()
            ? Try.success(column.get().valueAt(this.rowIdx))
            : Try.failure(column.getCause());
}
 
Example 12
Source File: Jackson.java    From ts-reaktive with MIT License 4 votes vote down vote up
public <T> Stream<T> parse(JsonParser input, Reader<JSONEvent, T> reader) {
    reader.reset();
    
    Iterator<T> iterator = new Iterator<T>() {
        private Option<T> next = parse();
        
        private Option<T> parse() {
            for (Option<JSONEvent> evt = nextEvent(); evt.isDefined(); evt = nextEvent()) {
                Try<T> read = reader.apply(evt.get());
                if (read.isSuccess()) {
                    return read.toOption();
                } else if (read.isFailure() && !ReadProtocol.isNone(read)) {
                    throw (RuntimeException) read.failed().get();
                }
            }
            return Option.none();
        }
        
        private Option<JSONEvent> nextEvent() {
            try {
                if (input.nextToken() != null) {
                    return some(getEvent(input));
                } else {
                    return none(); // end of stream
                }
            } catch (IOException e) {
                throw new IllegalArgumentException(e);
            }
        }
        
        @Override
        public boolean hasNext() {
            return next.isDefined();
        }

        @Override
        public T next() {
            T elmt = next.get();
            next = parse();
            return elmt;
        }
    };
    
    return StreamSupport.stream(
        Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED),
        false);
}