Example usage for java.util.concurrent CompletableFuture completeExceptionally

List of usage examples for java.util.concurrent CompletableFuture completeExceptionally

Introduction

In this page you can find the example usage for java.util.concurrent CompletableFuture completeExceptionally.

Prototype

public boolean completeExceptionally(Throwable ex) 

Source Link

Document

If not already completed, causes invocations of #get() and related methods to throw the given exception.

Usage

From source file:io.pravega.controller.store.stream.InMemoryStream.java

@Override
CompletableFuture<Void> deleteEpochNode(int epoch) {
    CompletableFuture<Void> result = new CompletableFuture<>();
    synchronized (txnsLock) {
        if (epochTxnMap.getOrDefault(epoch, Collections.emptySet()).isEmpty()) {
            epochTxnMap.remove(epoch);/*from w  w  w .  j  a  v  a  2  s  . co  m*/
            result.complete(null);
        } else {
            result.completeExceptionally(StoreException.create(StoreException.Type.DATA_CONTAINS_ELEMENTS,
                    "Stream: " + getName() + " Epoch: " + epoch));
        }
    }
    return result;
}

From source file:io.pravega.controller.store.stream.InMemoryStream.java

@Override
CompletableFuture<Void> setStateData(Data<Integer> newState) {
    Preconditions.checkNotNull(newState);

    CompletableFuture<Void> result = new CompletableFuture<>();
    synchronized (lock) {
        if (Objects.equals(this.state.getVersion(), newState.getVersion())) {
            this.state = new Data<>(newState.getData(), newState.getVersion() + 1);
            result.complete(null);//from  w ww.j a  va 2s  .co m
        } else {
            result.completeExceptionally(StoreException.create(StoreException.Type.WRITE_CONFLICT, getName()));
        }
    }

    return result;
}

From source file:io.pravega.controller.store.stream.ZKStream.java

@Override
CompletableFuture<Data<Integer>> getMarkerData(int segmentNumber) {
    final CompletableFuture<Data<Integer>> result = new CompletableFuture<>();
    final String path = ZKPaths.makePath(markerPath, String.format("%d", segmentNumber));
    cache.getCachedData(path).whenComplete((res, ex) -> {
        if (ex != null) {
            Throwable cause = ExceptionHelpers.getRealException(ex);
            if (cause instanceof StoreException.DataNotFoundException) {
                result.complete(null);//from  www.  j  a  v  a  2  s.  c om
            } else {
                result.completeExceptionally(cause);
            }
        } else {
            result.complete(res);
        }
    });

    return result;
}

From source file:com.ikanow.aleph2.management_db.mongodb.services.TestIkanowV1SyncService_LibraryJars.java

@Test
public void test_updateV1SourceStatus()
        throws JsonProcessingException, IOException, InterruptedException, ExecutionException, ParseException {
    @SuppressWarnings("unchecked")
    ICrudService<JsonNode> v1_share_db = this._service_context.getCoreManagementDbService()
            .getUnderlyingPlatformDriver(ICrudService.class, Optional.of("social.share")).get();

    final DBCollection dbc = v1_share_db.getUnderlyingPlatformDriver(DBCollection.class, Optional.empty())
            .get();//w ww . jav  a 2s.  c  o  m

    v1_share_db.deleteDatastore().get();

    IManagementCrudService<SharedLibraryBean> library_db = this._service_context.getCoreManagementDbService()
            .getSharedLibraryStore();

    library_db.deleteDatastore().get();

    final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty());

    final ObjectNode v1_share_1 = (ObjectNode) mapper
            .readTree(this.getClass().getResourceAsStream("test_v1_sync_sample_share.json"));
    final DBObject v1_share_1_dbo = (DBObject) JSON.parse(v1_share_1.toString());
    v1_share_1_dbo.put("_id", new ObjectId(v1_share_1.get("_id").asText()));

    assertEquals(0L, (long) v1_share_db.countObjects().get());
    dbc.save(v1_share_1_dbo);
    //v1_share_db.storeObjects(Arrays.asList(v1_share_1)).get();
    assertEquals(1L, (long) v1_share_db.countObjects().get());

    final SharedLibraryBean share1 = IkanowV1SyncService_LibraryJars.getLibraryBeanFromV1Share(v1_share_1);

    assertEquals(0L, (long) library_db.countObjects().get());
    library_db.storeObjects(Arrays.asList(share1)).get();
    assertEquals(1L, (long) library_db.countObjects().get());

    // No error - create
    {
        final ManagementFuture<?> test_1 = FutureUtils.createManagementFuture(
                CompletableFuture.completedFuture(Unit.unit()),
                CompletableFuture.completedFuture(Arrays.asList(ErrorUtils.buildSuccessMessage("", "", "", ""))) // (single non error)                                       
        );

        final CompletableFuture<Boolean> res = IkanowV1SyncService_LibraryJars.updateV1ShareErrorStatus_top(
                "555d44e3347d336b3e8c4cbe", test_1, library_db, v1_share_db, true);

        assertEquals(false, res.get());

        ObjectNode unchanged = (ObjectNode) v1_share_db.getRawService()
                .getObjectById(new ObjectId("555d44e3347d336b3e8c4cbe")).get().get();

        assertEquals(v1_share_1.without("_id").toString(), unchanged.without("_id").toString());
    }

    // DB call throws exception
    {
        final CompletableFuture<?> error_out = new CompletableFuture<>();
        error_out.completeExceptionally(new RuntimeException("test"));

        final ManagementFuture<?> test_1 = FutureUtils.createManagementFuture(error_out);

        final CompletableFuture<Boolean> res = IkanowV1SyncService_LibraryJars.updateV1ShareErrorStatus_top(
                "555d44e3347d336b3e8c4cbe", test_1, library_db, v1_share_db, true);

        assertEquals(true, res.get());

        JsonNode changed = v1_share_db.getRawService().getObjectById(new ObjectId("555d44e3347d336b3e8c4cbe"))
                .get().get();

        assertTrue(changed.get("description").asText()
                .contains("] (unknown) ((unknown)): ERROR: [java.lang.RuntimeException: test"));
        // This shouldn't yet pe present
        assertFalse("Description error time travels: " + changed.get("description").asText(),
                changed.get("description").asText().contains("] (test) (unknown): ERROR: test"));
    }

    // db call throws exception, object doesn't exist (code coverage!)
    {
        final CompletableFuture<?> error_out = new CompletableFuture<>();
        error_out.completeExceptionally(new RuntimeException("test"));

        final ManagementFuture<?> test_1 = FutureUtils.createManagementFuture(error_out);

        final CompletableFuture<Boolean> res = IkanowV1SyncService_LibraryJars.updateV1ShareErrorStatus_top(
                "555d44e3347d336b3e8c4cbf", test_1, library_db, v1_share_db, true);

        assertEquals(false, res.get());
    }

    // User errors (+update not create)
    {
        final ManagementFuture<?> test_1 = FutureUtils.createManagementFuture(
                CompletableFuture.completedFuture(Unit.unit()), CompletableFuture.completedFuture(
                        Arrays.asList(ErrorUtils.buildErrorMessage("test", "test", "test", "test"))) // (single non error)                                       
        );

        final CompletableFuture<Boolean> res = IkanowV1SyncService_LibraryJars.updateV1ShareErrorStatus_top(
                "555d44e3347d336b3e8c4cbe", test_1, library_db, v1_share_db, false);

        assertEquals(true, res.get());

        JsonNode changed = v1_share_db.getRawService().getObjectById(new ObjectId("555d44e3347d336b3e8c4cbe"))
                .get().get();

        SharedLibraryBean v2_version = library_db.getObjectById("v1_555d44e3347d336b3e8c4cbe").get().get();
        assertTrue("v2 lib bean needed updating: " + v2_version.modified(),
                new Date().getTime() - v2_version.modified().getTime() < 5000L);

        // Still has the old error
        assertTrue("Description missing errors: " + changed.get("description").asText(),
                changed.get("description").asText()
                        .contains("] (unknown) ((unknown)): ERROR: [java.lang.RuntimeException: test"));
        // Now has the new error
        assertTrue("Description missing errors: " + changed.get("description").asText(),
                changed.get("description").asText().contains("] test (test): ERROR: test"));
    }

}

From source file:io.sqp.client.impl.SqpConnectionImpl.java

@Override
public CompletableFuture<String> registerTypeMapping(String name, String schema, String... keywords) {
    CompletableFuture<String> future = new CompletableFuture<>();
    if (!checkOpenAndNoErrors(future)) {
        return future;
    }//from w  w  w . j  a v  a2 s .co  m
    ObjectMapper objectMapper = JacksonObjectMapperFactory.objectMapper(_config.getProtocolFormat());
    JsonNode schemaNode;
    try {
        schemaNode = objectMapper.readTree(schema);
    } catch (IOException e) {
        SqpException error = new TypeConversionException("The schema could not be parsed: " + e.getMessage(),
                e);
        future.completeExceptionally(error);
        return future;
    }

    send(new TypeMappingMessage(name, schemaNode, Arrays.asList(keywords)), new ResponseHandler<>(future, m -> {
        if (m.isA(MessageType.ReadyMessage)) {
            return false; // just ignore them
        } else if (m.isA(MessageType.TypeMappingRegisteredMessage)) {
            TypeMappingRegisteredMessage response = m.secureCast();
            future.complete(response.getNative());
            return true;
        }
        throw new UnexpectedMessageException("waiting for information response", m);
    }));
    return future;
}

From source file:io.pravega.controller.store.stream.ZKStream.java

@Override
CompletableFuture<Integer> createNewTransaction(final UUID txId, final long timestamp,
        final long leaseExpiryTime, final long maxExecutionExpiryTime, final long scaleGracePeriod) {
    CompletableFuture<Integer> future = new CompletableFuture<>();
    createNewTransactionNode(txId, timestamp, leaseExpiryTime, maxExecutionExpiryTime, scaleGracePeriod)
            .whenComplete((value, ex) -> {
                if (ex != null) {
                    if (ExceptionHelpers.getRealException(ex) instanceof StoreException.DataNotFoundException) {
                        FutureHelpers.completeAfter(() -> createNewTransactionNode(txId, timestamp,
                                leaseExpiryTime, maxExecutionExpiryTime, scaleGracePeriod), future);
                    } else {
                        future.completeExceptionally(ex);
                    }/*from w  ww. j  a v  a2  s.  c om*/
                } else {
                    future.complete(value);
                }
            });
    return future;
}

From source file:io.pravega.controller.store.stream.InMemoryStream.java

@Override
CompletableFuture<Integer> createNewTransaction(UUID txId, long timestamp, long leaseExpiryTime,
        long maxExecutionExpiryTime, long scaleGracePeriod) {
    Preconditions.checkNotNull(txId);//from ww w.ja  v  a  2  s .  c  om

    final CompletableFuture<Integer> result = new CompletableFuture<>();
    final Data<Integer> txnData = new Data<>(new ActiveTxnRecord(timestamp, leaseExpiryTime,
            maxExecutionExpiryTime, scaleGracePeriod, TxnStatus.OPEN).toByteArray(), 0);
    synchronized (txnsLock) {
        activeTxns.putIfAbsent(txId.toString(), txnData);
    }
    int epoch = activeEpoch.get();
    synchronized (txnsLock) {
        if (!epochTxnMap.containsKey(epoch)) {
            result.completeExceptionally(StoreException.create(StoreException.Type.DATA_NOT_FOUND,
                    "Stream: " + getName() + " Transaction: " + txId.toString() + " Epoch: " + epoch));
        } else {
            epochTxnMap.compute(epoch, (x, y) -> {
                y.add(txId.toString());
                return y;
            });
            result.complete(epoch);
        }
    }

    return result;
}

From source file:io.sqp.client.impl.SqpConnectionImpl.java

private <T> CompletableFuture<T> getInformation(Class<T> infoType, InformationSubject subject, String detail) {
    CompletableFuture<T> future = new CompletableFuture<>();
    if (!checkOpenAndNoErrors(future)) {
        return future;
    }/*from w  w  w  .j  a  v a 2s .  c o m*/
    send(new InformationRequestMessage(subject, detail), new ResponseHandler<>(future, m -> {
        if (m.isA(MessageType.ReadyMessage)) {
            return false; // just ignore them
        } else if (m.isA(MessageType.InformationResponseMessage)) {
            InformationResponseMessage response = m.secureCast();
            Object value = response.getValue();
            if (!response.getResponseType().isCompatibleTo(infoType)) {
                future.completeExceptionally(new UnexpectedResultTypeException(value, infoType));
            } else {
                future.complete(infoType.cast(value));
            }
            return true;
        }
        throw new UnexpectedMessageException("waiting for information response", m);
    }));
    return future;
}

From source file:io.pravega.controller.task.Stream.StreamMetadataTasks.java

public CompletableFuture<Void> writeEvent(ControllerEvent event) {
    CompletableFuture<Void> result = new CompletableFuture<>();

    getRequestWriter().writeEvent(event).whenComplete((r, e) -> {
        if (e != null) {
            log.warn("exception while posting event {} {}", e.getClass().getName(), e.getMessage());
            if (e instanceof TaskExceptions.ProcessingDisabledException) {
                result.completeExceptionally(e);
            } else {
                // transform any other event write exception to retryable exception
                result.completeExceptionally(new TaskExceptions.PostEventException("Failed to post event", e));
            }/* w w  w  .j  a v  a2  s  . c o  m*/
        } else {
            log.info("event posted successfully");
            result.complete(null);
        }
    });

    return result;

}

From source file:com.android.tools.idea.diagnostics.crash.GoogleCrash.java

@NotNull
@Override/* www.ja  va  2  s  . c o m*/
public CompletableFuture<String> submit(@NotNull final HttpEntity requestEntity) {
    CompletableFuture<String> future = new CompletableFuture<>();

    try {
        ourExecutor.submit(() -> {
            try {
                HttpClient client = HttpClients.createDefault();

                HttpEntity entity = requestEntity;
                if (!UNIT_TEST_MODE) {
                    // The test server used in testing doesn't handle gzip compression (netty requires jcraft jzlib for gzip decompression)
                    entity = new GzipCompressingEntity(requestEntity);
                }

                HttpPost post = new HttpPost(myCrashUrl);
                post.setEntity(entity);

                HttpResponse response = client.execute(post);
                StatusLine statusLine = response.getStatusLine();
                if (statusLine.getStatusCode() >= 300) {
                    future.completeExceptionally(new HttpResponseException(statusLine.getStatusCode(),
                            statusLine.getReasonPhrase()));
                    return;
                }

                entity = response.getEntity();
                if (entity == null) {
                    future.completeExceptionally(new NullPointerException("Empty response entity"));
                    return;
                }

                String reportId = EntityUtils.toString(entity);
                if (DEBUG_BUILD) {
                    //noinspection UseOfSystemOutOrSystemErr
                    System.out.println("Report submitted: http://go/crash-staging/" + reportId);
                }
                future.complete(reportId);
            } catch (IOException e) {
                future.completeExceptionally(e);
            }
        });
    } catch (RejectedExecutionException ignore) {
        // handled by the rejected execution handler associated with ourExecutor
    }

    return future;
}