List of usage examples for java.util.concurrent CompletableFuture completeExceptionally
public boolean completeExceptionally(Throwable ex)
From source file:org.apache.pulsar.tests.integration.utils.DockerUtils.java
public static ContainerExecResultBytes runCommandWithRawOutput(DockerClient docker, String containerId, String... cmd) throws ContainerExecException { CompletableFuture<Boolean> future = new CompletableFuture<>(); String execid = docker.execCreateCmd(containerId).withCmd(cmd).withAttachStderr(true).withAttachStdout(true) .exec().getId();// w w w. j a v a2 s. c o m String cmdString = Arrays.stream(cmd).collect(Collectors.joining(" ")); ByteBuf stdout = Unpooled.buffer(); ByteBuf stderr = Unpooled.buffer(); docker.execStartCmd(execid).withDetach(false).exec(new ResultCallback<Frame>() { @Override public void close() { } @Override public void onStart(Closeable closeable) { LOG.info("DOCKER.exec({}:{}): Executing...", containerId, cmdString); } @Override public void onNext(Frame object) { if (StreamType.STDOUT == object.getStreamType()) { stdout.writeBytes(object.getPayload()); } else if (StreamType.STDERR == object.getStreamType()) { stderr.writeBytes(object.getPayload()); } } @Override public void onError(Throwable throwable) { future.completeExceptionally(throwable); } @Override public void onComplete() { LOG.info("DOCKER.exec({}:{}): Done", containerId, cmdString); future.complete(true); } }); future.join(); InspectExecResponse resp = docker.inspectExecCmd(execid).exec(); while (resp.isRunning()) { try { Thread.sleep(200); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RuntimeException(ie); } resp = docker.inspectExecCmd(execid).exec(); } int retCode = resp.getExitCode(); byte[] stdoutBytes = new byte[stdout.readableBytes()]; stdout.readBytes(stdoutBytes); byte[] stderrBytes = new byte[stderr.readableBytes()]; stderr.readBytes(stderrBytes); ContainerExecResultBytes result = ContainerExecResultBytes.of(retCode, stdoutBytes, stderrBytes); LOG.info("DOCKER.exec({}:{}): completed with {}", containerId, cmdString, retCode); if (retCode != 0) { throw new ContainerExecException(cmdString, containerId, null); } return result; }
From source file:org.apache.samza.table.caching.TestCachingTable.java
/** * Testing caching in a more realistic scenario with Guava cache + remote table *///from w ww .j av a 2s . co m @Test public void testGuavaCacheAndRemoteTable() throws Exception { String tableId = "testGuavaCacheAndRemoteTable"; Cache<String, String> guavaCache = CacheBuilder.newBuilder().initialCapacity(100).build(); final ReadWriteTable<String, String> guavaTable = new GuavaCacheTable<>(tableId + "-cache", guavaCache); // It is okay to share rateLimitHelper and async helper for read/write in test TableRateLimiter<String, String> rateLimitHelper = mock(TableRateLimiter.class); TableReadFunction<String, String> readFn = mock(TableReadFunction.class); TableWriteFunction<String, String> writeFn = mock(TableWriteFunction.class); final RemoteTable<String, String> remoteTable = new RemoteTable<>(tableId + "-remote", readFn, writeFn, rateLimitHelper, rateLimitHelper, Executors.newSingleThreadExecutor(), null, null, null, Executors.newSingleThreadExecutor()); final CachingTable<String, String> cachingTable = new CachingTable<>(tableId, remoteTable, guavaTable, false); initTables(cachingTable, guavaTable, remoteTable); // 3 per readable table (9) // 5 per read/write table (15) verify(metricsRegistry, times(24)).newCounter(any(), anyString()); // 2 per readable table (6) // 5 per read/write table (15) // 1 per remote readable table (1) // 1 per remote read/write table (1) verify(metricsRegistry, times(23)).newTimer(any(), anyString()); // 1 per guava table (1) // 3 per caching table (2) verify(metricsRegistry, times(4)).newGauge(anyString(), any()); // GET doReturn(CompletableFuture.completedFuture("bar")).when(readFn).getAsync(any()); Assert.assertEquals(cachingTable.getAsync("foo").get(), "bar"); // Ensure cache is updated Assert.assertEquals(guavaCache.getIfPresent("foo"), "bar"); // PUT doReturn(CompletableFuture.completedFuture(null)).when(writeFn).putAsync(any(), any()); cachingTable.putAsync("foo", "baz").get(); // Ensure cache is updated Assert.assertEquals(guavaCache.getIfPresent("foo"), "baz"); // DELETE doReturn(CompletableFuture.completedFuture(null)).when(writeFn).deleteAsync(any()); cachingTable.deleteAsync("foo").get(); // Ensure cache is updated Assert.assertNull(guavaCache.getIfPresent("foo")); // GET-ALL Map<String, String> records = new HashMap<>(); records.put("foo1", "bar1"); records.put("foo2", "bar2"); doReturn(CompletableFuture.completedFuture(records)).when(readFn).getAllAsync(any()); Assert.assertEquals(cachingTable.getAllAsync(Arrays.asList("foo1", "foo2")).get(), records); // Ensure cache is updated Assert.assertEquals(guavaCache.getIfPresent("foo1"), "bar1"); Assert.assertEquals(guavaCache.getIfPresent("foo2"), "bar2"); // GET-ALL with partial miss doReturn(CompletableFuture.completedFuture(Collections.singletonMap("foo3", "bar3"))).when(readFn) .getAllAsync(any()); records = cachingTable.getAllAsync(Arrays.asList("foo1", "foo2", "foo3")).get(); Assert.assertEquals(records.get("foo3"), "bar3"); // Ensure cache is updated Assert.assertEquals(guavaCache.getIfPresent("foo3"), "bar3"); // Calling again for the same keys should not trigger IO, ie. no exception is thrown CompletableFuture<String> exFuture = new CompletableFuture<>(); exFuture.completeExceptionally(new RuntimeException("Test exception")); doReturn(exFuture).when(readFn).getAllAsync(any()); cachingTable.getAllAsync(Arrays.asList("foo1", "foo2", "foo3")).get(); // Partial results should throw try { cachingTable.getAllAsync(Arrays.asList("foo1", "foo2", "foo5")).get(); Assert.fail(); } catch (Exception e) { } // PUT-ALL doReturn(CompletableFuture.completedFuture(null)).when(writeFn).putAllAsync(any()); List<Entry<String, String>> entries = new ArrayList<>(); entries.add(new Entry<>("foo1", "bar111")); entries.add(new Entry<>("foo2", "bar222")); cachingTable.putAllAsync(entries).get(); // Ensure cache is updated Assert.assertEquals(guavaCache.getIfPresent("foo1"), "bar111"); Assert.assertEquals(guavaCache.getIfPresent("foo2"), "bar222"); // PUT-ALL with delete doReturn(CompletableFuture.completedFuture(null)).when(writeFn).putAllAsync(any()); doReturn(CompletableFuture.completedFuture(null)).when(writeFn).deleteAllAsync(any()); entries = new ArrayList<>(); entries.add(new Entry<>("foo1", "bar111")); entries.add(new Entry<>("foo2", null)); cachingTable.putAllAsync(entries).get(); // Ensure cache is updated Assert.assertNull(guavaCache.getIfPresent("foo2")); // At this point, foo1 and foo3 should still exist Assert.assertNotNull(guavaCache.getIfPresent("foo1")); Assert.assertNotNull(guavaCache.getIfPresent("foo3")); // DELETE-ALL doReturn(CompletableFuture.completedFuture(null)).when(writeFn).deleteAllAsync(any()); cachingTable.deleteAllAsync(Arrays.asList("foo1", "foo3")).get(); // Ensure foo1 and foo3 are gone Assert.assertNull(guavaCache.getIfPresent("foo1")); Assert.assertNull(guavaCache.getIfPresent("foo3")); }
From source file:org.apache.samza.table.remote.couchbase.CouchbaseTableReadFunction.java
@Override public CompletableFuture<V> getAsync(String key) { Preconditions.checkArgument(StringUtils.isNotBlank(key), "key must not be null, empty or blank"); CompletableFuture<V> future = new CompletableFuture<>(); Single<? extends Document<?>> singleObservable = bucket.async() .get(key, documentType, timeout.toMillis(), TimeUnit.MILLISECONDS).toSingle(); singleObservable.subscribe(new SingleSubscriber<Document<?>>() { @Override//ww w. j av a 2 s .c om public void onSuccess(Document<?> document) { if (document != null) { if (document instanceof BinaryDocument) { handleGetAsyncBinaryDocument((BinaryDocument) document, future, key); } else { // V is of type JsonObject future.complete((V) document.content()); } } else { // The Couchbase async client should not return null future.completeExceptionally( new SamzaException(String.format("Got unexpected null value from key %s", key))); } } @Override public void onError(Throwable throwable) { if (throwable instanceof NoSuchElementException) { // There is no element returned by the observable, meaning the key doesn't exist. future.complete(null); } else { future.completeExceptionally( new SamzaException(String.format("Failed to get key %s", key), throwable)); } } }); return future; }
From source file:org.apache.samza.table.remote.couchbase.CouchbaseTableReadFunction.java
/** * Helper method to read bytes from binaryDocument and release the buffer. *//* w ww . j av a2s. co m*/ private void handleGetAsyncBinaryDocument(BinaryDocument binaryDocument, CompletableFuture<V> future, String key) { ByteBuf buffer = binaryDocument.content(); try { byte[] bytes; if (buffer.hasArray() && buffer.arrayOffset() == 0 && buffer.readableBytes() == buffer.array().length) { bytes = buffer.array(); } else { bytes = new byte[buffer.readableBytes()]; buffer.readBytes(bytes); } future.complete(valueSerde.fromBytes(bytes)); } catch (Exception e) { future.completeExceptionally(new SamzaException( String.format("Failed to deserialize value of key %s with given serde", key), e)); } finally { ReferenceCountUtil.release(buffer); } }
From source file:org.apache.samza.table.remote.couchbase.CouchbaseTableWriteFunction.java
/** * Helper method for putAsync and deleteAsync to convert Single to CompletableFuture. *//*from ww w . j a va 2 s . c o m*/ private CompletableFuture<Void> asyncWriteHelper(Single<? extends Document<?>> single, String errorMessage) { CompletableFuture<Void> future = new CompletableFuture<>(); single.subscribe(new SingleSubscriber<Document>() { @Override public void onSuccess(Document v) { future.complete(null); } @Override public void onError(Throwable error) { future.completeExceptionally(new SamzaException(errorMessage, error)); } }); return future; }
From source file:org.apache.servicecomb.foundation.vertx.http.ReadStreamPart.java
protected void onFileOpened(File file, AsyncResult<AsyncFile> ar, CompletableFuture<File> future) { if (ar.failed()) { future.completeExceptionally(ar.cause()); return;/* w ww . j a va 2 s . com*/ } AsyncFile asyncFile = ar.result(); CompletableFuture<Void> saveFuture = saveToWriteStream(asyncFile); saveFuture.whenComplete((v, saveException) -> { asyncFile.close(closeAr -> { if (closeAr.failed()) { LOGGER.error("Failed to close file {}.", file); } // whatever close success or failed // will not affect to result // result just only related to write if (saveException == null) { future.complete(file); return; } future.completeExceptionally(saveException); }); }); }
From source file:org.apache.servicecomb.foundation.vertx.stream.PumpFromPart.java
private CompletableFuture<ReadStream<Buffer>> prepareReadStream() { CompletableFuture<ReadStream<Buffer>> future = new CompletableFuture<>(); if (ReadStreamPart.class.isInstance(part)) { future.complete(((ReadStreamPart) part).getReadStream()); return future; }/*from ww w. j av a2s . co m*/ try { InputStream inputStream = part.getInputStream(); InputStreamToReadStream inputStreamToReadStream = new InputStreamToReadStream(context, inputStream, true); inputStreamToReadStream.pause(); future.complete(inputStreamToReadStream); } catch (IOException e) { future.completeExceptionally(e); } return future; }
From source file:org.apache.servicecomb.foundation.vertx.stream.PumpFromPart.java
private CompletableFuture<Void> toOutputStreamSync(OutputStream outputStream, boolean autoCloseOutputStream) { CompletableFuture<Void> future = new CompletableFuture<>(); try (InputStream inputStream = part.getInputStream()) { IOUtils.copyLarge(inputStream, outputStream); } catch (Throwable e) { future.completeExceptionally(e); }//from ww w . ja v a 2s.com if (autoCloseOutputStream) { try { outputStream.close(); } catch (Throwable e) { future.completeExceptionally(e); } } future.complete(null); return future; }
From source file:org.apache.servicecomb.foundation.vertx.VertxUtils.java
public static CompletableFuture<Void> closeVertxByName(String name) { LOGGER.info("Closing vertx {}.", name); CompletableFuture<Void> future = new CompletableFuture<>(); Vertx vertx = vertxMap.remove(name); if (vertx == null) { LOGGER.info("Vertx {} not exist.", name); future.complete(null);//ww w. j av a2s . com return future; } vertx.close(ar -> { if (ar.succeeded()) { LOGGER.info("Success to close vertx {}.", name); future.complete(null); return; } future.completeExceptionally(ar.cause()); }); return future; }
From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.java
/** * Evaluate a script and allow for the submission of alteration to the entire evaluation execution lifecycle. * * @param script the script to evaluate/* w w w . j a v a 2s . co m*/ * @param language the language to evaluate it in * @param boundVars the bindings to evaluate in the context of the script * @param lifeCycle a set of functions that can be applied at various stages of the evaluation process */ public CompletableFuture<Object> eval(final String script, final String language, final Bindings boundVars, final LifeCycle lifeCycle) { final String lang = Optional.ofNullable(language).orElse("gremlin-groovy"); logger.debug("Preparing to evaluate script - {} - in thread [{}]", script, Thread.currentThread().getName()); final Bindings bindings = new SimpleBindings(); bindings.putAll(globalBindings); bindings.putAll(boundVars); final CompletableFuture<Object> evaluationFuture = new CompletableFuture<>(); final FutureTask<Void> f = new FutureTask<>(() -> { try { lifeCycle.getBeforeEval().orElse(beforeEval).accept(bindings); logger.debug("Evaluating script - {} - in thread [{}]", script, Thread.currentThread().getName()); final Object o = scriptEngines.eval(script, bindings, lang); // apply a transformation before sending back the result - useful when trying to force serialization // in the same thread that the eval took place given ThreadLocal nature of graphs as well as some // transactional constraints final Object result = lifeCycle.getTransformResult().isPresent() ? lifeCycle.getTransformResult().get().apply(o) : o; // a mechanism for taking the final result and doing something with it in the same thread, but // AFTER the eval and transform are done and that future completed. this provides a final means // for working with the result in the same thread as it was eval'd if (lifeCycle.getWithResult().isPresent()) lifeCycle.getWithResult().get().accept(result); lifeCycle.getAfterSuccess().orElse(afterSuccess).accept(bindings); // the evaluationFuture must be completed after all processing as an exception in lifecycle events // that must raise as an exception to the caller who has the returned evaluationFuture. in other words, // if it occurs before this point, then the handle() method won't be called again if there is an // exception that ends up below trying to completeExceptionally() evaluationFuture.complete(result); } catch (Throwable ex) { final Throwable root = null == ex.getCause() ? ex : ExceptionUtils.getRootCause(ex); // thread interruptions will typically come as the result of a timeout, so in those cases, // check for that situation and convert to TimeoutException if (root instanceof InterruptedException) evaluationFuture.completeExceptionally(new TimeoutException(String.format( "Script evaluation exceeded the configured 'scriptEvaluationTimeout' threshold of %s ms for request [%s]: %s", scriptEvaluationTimeout, script, root.getMessage()))); else { lifeCycle.getAfterFailure().orElse(afterFailure).accept(bindings, root); evaluationFuture.completeExceptionally(root); } } return null; }); executorService.execute(f); if (scriptEvaluationTimeout > 0) { // Schedule a timeout in the thread pool for future execution final ScheduledFuture<?> sf = scheduledExecutorService.schedule(() -> { logger.warn("Timing out script - {} - in thread [{}]", script, Thread.currentThread().getName()); if (!f.isDone()) { lifeCycle.getAfterTimeout().orElse(afterTimeout).accept(bindings); f.cancel(true); } }, scriptEvaluationTimeout, TimeUnit.MILLISECONDS); // Cancel the scheduled timeout if the eval future is complete or the script evaluation failed // with exception evaluationFuture.handleAsync((v, t) -> { logger.debug( "Killing scheduled timeout on script evaluation as the eval completed (possibly with exception)."); return sf.cancel(true); }); } return evaluationFuture; }