Search in sources :

Example 26 with CompletionException

use of java.util.concurrent.CompletionException in project pravega by pravega.

the class ClientAdapterBase method delete.

@Override
public CompletableFuture<Void> delete(String streamName, Duration timeout) {
    ensureRunning();
    String parentName = StreamSegmentNameUtils.getParentStreamSegmentName(streamName);
    if (isTransaction(streamName, parentName)) {
        // We have a transaction to abort.
        return abortTransaction(streamName, timeout);
    } else {
        return CompletableFuture.runAsync(() -> {
            if (getStreamManager().deleteStream(SCOPE, streamName)) {
                closeWriters(streamName);
            } else {
                throw new CompletionException(new StreamingException(String.format("Unable to delete stream '%s'.", streamName)));
            }
        }, this.testExecutor);
    }
}
Also used : StreamingException(io.pravega.segmentstore.contracts.StreamingException) CompletionException(java.util.concurrent.CompletionException)

Example 27 with CompletionException

use of java.util.concurrent.CompletionException in project atomix by atomix.

the class LeaderRole method onTransfer.

@Override
public CompletableFuture<TransferResponse> onTransfer(final TransferRequest request) {
    logRequest(request);
    RaftMemberContext member = raft.getCluster().getMemberState(request.member());
    if (member == null) {
        return CompletableFuture.completedFuture(logResponse(TransferResponse.builder().withStatus(RaftResponse.Status.ERROR).withError(RaftError.Type.ILLEGAL_MEMBER_STATE).build()));
    }
    transferring = true;
    CompletableFuture<TransferResponse> future = new CompletableFuture<>();
    appender.appendEntries(raft.getLogWriter().getLastIndex()).whenComplete((result, error) -> {
        if (isRunning()) {
            if (error == null) {
                log.debug("Transferring leadership to {}", request.member());
                raft.transition(RaftServer.Role.FOLLOWER);
                future.complete(logResponse(TransferResponse.builder().withStatus(RaftResponse.Status.OK).build()));
            } else if (error instanceof CompletionException && error.getCause() instanceof RaftException) {
                future.complete(logResponse(TransferResponse.builder().withStatus(RaftResponse.Status.ERROR).withError(((RaftException) error.getCause()).getType(), error.getMessage()).build()));
            } else if (error instanceof RaftException) {
                future.complete(logResponse(TransferResponse.builder().withStatus(RaftResponse.Status.ERROR).withError(((RaftException) error).getType(), error.getMessage()).build()));
            } else {
                future.complete(logResponse(TransferResponse.builder().withStatus(RaftResponse.Status.ERROR).withError(RaftError.Type.PROTOCOL_ERROR, error.getMessage()).build()));
            }
        } else {
            future.complete(logResponse(TransferResponse.builder().withStatus(RaftResponse.Status.ERROR).withError(RaftError.Type.ILLEGAL_MEMBER_STATE).build()));
        }
    });
    return future;
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) RaftException(io.atomix.protocols.raft.RaftException) RaftMemberContext(io.atomix.protocols.raft.cluster.impl.RaftMemberContext) TransferResponse(io.atomix.protocols.raft.protocol.TransferResponse) CompletionException(java.util.concurrent.CompletionException)

Example 28 with CompletionException

use of java.util.concurrent.CompletionException in project atomix by atomix.

the class LeaderRole method onKeepAlive.

@Override
public CompletableFuture<KeepAliveResponse> onKeepAlive(KeepAliveRequest request) {
    final long term = raft.getTerm();
    final long timestamp = System.currentTimeMillis();
    raft.checkThread();
    logRequest(request);
    CompletableFuture<KeepAliveResponse> future = new CompletableFuture<>();
    appendAndCompact(new KeepAliveEntry(term, timestamp, request.sessionIds(), request.commandSequenceNumbers(), request.eventIndexes())).whenCompleteAsync((entry, error) -> {
        if (error != null) {
            future.complete(logResponse(KeepAliveResponse.builder().withStatus(RaftResponse.Status.ERROR).withLeader(raft.getCluster().getMember().nodeId()).withError(RaftError.Type.PROTOCOL_ERROR).build()));
            return;
        }
        appender.appendEntries(entry.index()).whenComplete((commitIndex, commitError) -> {
            raft.checkThread();
            if (isRunning()) {
                if (commitError == null) {
                    raft.getServiceManager().<long[]>apply(entry.index()).whenCompleteAsync((sessionResult, sessionError) -> {
                        if (sessionError == null) {
                            future.complete(logResponse(KeepAliveResponse.builder().withStatus(RaftResponse.Status.OK).withLeader(raft.getCluster().getMember().nodeId()).withMembers(raft.getCluster().getMembers().stream().map(RaftMember::nodeId).filter(m -> m != null).collect(Collectors.toList())).withSessionIds(sessionResult).build()));
                        } else if (sessionError instanceof CompletionException && sessionError.getCause() instanceof RaftException) {
                            future.complete(logResponse(KeepAliveResponse.builder().withStatus(RaftResponse.Status.ERROR).withLeader(raft.getCluster().getMember().nodeId()).withError(((RaftException) sessionError.getCause()).getType(), sessionError.getMessage()).build()));
                        } else if (sessionError instanceof RaftException) {
                            future.complete(logResponse(KeepAliveResponse.builder().withStatus(RaftResponse.Status.ERROR).withLeader(raft.getCluster().getMember().nodeId()).withError(((RaftException) sessionError).getType(), sessionError.getMessage()).build()));
                        } else {
                            future.complete(logResponse(KeepAliveResponse.builder().withStatus(RaftResponse.Status.ERROR).withLeader(raft.getCluster().getMember().nodeId()).withError(RaftError.Type.PROTOCOL_ERROR, sessionError.getMessage()).build()));
                        }
                    }, raft.getThreadContext());
                } else {
                    future.complete(logResponse(KeepAliveResponse.builder().withStatus(RaftResponse.Status.ERROR).withLeader(raft.getCluster().getMember().nodeId()).withError(RaftError.Type.PROTOCOL_ERROR).build()));
                }
            } else {
                RaftMember leader = raft.getLeader();
                future.complete(logResponse(KeepAliveResponse.builder().withStatus(RaftResponse.Status.ERROR).withLeader(leader != null ? leader.nodeId() : null).withError(RaftError.Type.ILLEGAL_MEMBER_STATE).build()));
            }
        });
    }, raft.getThreadContext());
    return future;
}
Also used : KeepAliveResponse(io.atomix.protocols.raft.protocol.KeepAliveResponse) RaftMember(io.atomix.protocols.raft.cluster.RaftMember) DefaultRaftMember(io.atomix.protocols.raft.cluster.impl.DefaultRaftMember) CompletableFuture(java.util.concurrent.CompletableFuture) KeepAliveEntry(io.atomix.protocols.raft.storage.log.entry.KeepAliveEntry) RaftException(io.atomix.protocols.raft.RaftException) CompletionException(java.util.concurrent.CompletionException)

Example 29 with CompletionException

use of java.util.concurrent.CompletionException in project assertj-core by joel-costigliola.

the class StandardRepresentation method toStringOf.

protected String toStringOf(CompletableFuture<?> future) {
    String className = future.getClass().getSimpleName();
    if (!future.isDone())
        return concat(className, "[Incomplete]");
    try {
        Object joinResult = future.join();
        // avoid stack overflow error if future join on itself or another future that cycles back to the first
        Object joinResultRepresentation = joinResult instanceof CompletableFuture ? joinResult : toStringOf(joinResult);
        return concat(className, "[Completed: ", joinResultRepresentation, "]");
    } catch (CompletionException e) {
        return concat(className, "[Failed: ", toStringOf(e.getCause()), "]", String.format("%n%s", getStackTrace(e)));
    } catch (CancellationException e) {
        return concat(className, "[Cancelled]");
    }
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) CancellationException(java.util.concurrent.CancellationException) CompletionException(java.util.concurrent.CompletionException) Integer.toHexString(java.lang.Integer.toHexString)

Example 30 with CompletionException

use of java.util.concurrent.CompletionException in project photon-model by vmware.

the class TestAWSClientManagement method testAWSClientManagementArnRefresh.

/**
 * This test requires a minimum of 15 minutes waiting to ensure the ARN credentials refresh
 * occurs.
 */
@Ignore
@Test
public void testAWSClientManagementArnRefresh() throws Throwable {
    this.ec2ClientReferenceCount = getClientReferenceCount(AwsClientType.EC2);
    this.host.setTimeoutSeconds(1200);
    // Getting a reference to client managers in the test
    AWSClientManager ec2ClientManager = getClientManager(AwsClientType.EC2);
    ec2ClientManager.cleanUpArnCache();
    assertEquals(this.ec2ClientReferenceCount + 1, getClientReferenceCount(AwsClientType.EC2));
    this.creds = new AuthCredentialsServiceState();
    this.creds.customProperties = new HashMap<>();
    this.creds.customProperties.put(ARN_KEY, this.arn);
    this.creds.customProperties.put(EXTERNAL_ID_KEY, this.externalId);
    TestContext waitContext = new TestContext(1, Duration.ofSeconds(30L));
    ec2ClientManager.getOrCreateEC2ClientAsync(this.creds, TestAWSSetupUtils.regionId, this.instanceService).exceptionally(t -> {
        waitContext.fail(t);
        throw new CompletionException(t);
    }).thenAccept(ec2Client -> {
        this.client = ec2Client;
        waitContext.complete();
    });
    waitContext.await();
    this.clientCacheCount = ec2ClientManager.getCacheCount();
    host.log(Level.INFO, "Waiting 16 minutes for the current set of credentials to expire.");
    Thread.sleep(TimeUnit.MINUTES.toMillis(16));
    host.log(Level.INFO, "Retrieving the ec2 client with a refreshed set of credentials.");
    // Requesting the EC2 client will generate a new client as the original client's credentials
    // are now expired.
    AmazonEC2AsyncClient oldClient = this.client;
    TestContext nextContext = new TestContext(1, Duration.ofSeconds(30L));
    ec2ClientManager.getOrCreateEC2ClientAsync(this.creds, TestAWSSetupUtils.regionId, this.instanceService).exceptionally(t -> {
        nextContext.fail(t);
        throw new CompletionException(t);
    }).thenAccept(ec2Client -> {
        this.client = ec2Client;
        this.clientCacheCount++;
        nextContext.complete();
    });
    nextContext.await();
    assertNotEquals(oldClient, this.client);
    assertEquals(this.clientCacheCount, ec2ClientManager.getCacheCount());
}
Also used : AuthCredentialsServiceState(com.vmware.xenon.services.common.AuthCredentialsService.AuthCredentialsServiceState) BeforeClass(org.junit.BeforeClass) HashMap(java.util.HashMap) AWSClientManagerFactory.returnClientManager(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManagerFactory.returnClientManager) AWSClientManagerFactory.getClientManager(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManagerFactory.getClientManager) AWSClientManagerFactory.getClientReferenceCount(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManagerFactory.getClientReferenceCount) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) CommandLineArgumentParser(com.vmware.xenon.common.CommandLineArgumentParser) AWSSecurityTokenServiceException(com.amazonaws.services.securitytoken.model.AWSSecurityTokenServiceException) Duration(java.time.Duration) After(org.junit.After) EXTERNAL_ID_KEY(com.vmware.photon.controller.model.adapterapi.EndpointConfigRequest.EXTERNAL_ID_KEY) AWS_ARN_DEFAULT_SESSION_DURATION_SECONDS_PROPERTY(com.vmware.photon.controller.model.adapters.awsadapter.AWSUtils.AWS_ARN_DEFAULT_SESSION_DURATION_SECONDS_PROPERTY) AwsClientType(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AwsClientType) BasicReusableHostTestCase(com.vmware.xenon.common.BasicReusableHostTestCase) AWSClientManager(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManager) Before(org.junit.Before) StatelessService(com.vmware.xenon.common.StatelessService) AWS_MASTER_ACCOUNT_ACCESS_KEY_PROPERTY(com.vmware.photon.controller.model.adapters.awsadapter.AWSUtils.AWS_MASTER_ACCOUNT_ACCESS_KEY_PROPERTY) Operation(com.vmware.xenon.common.Operation) CompletionException(java.util.concurrent.CompletionException) Test(org.junit.Test) AmazonS3Client(com.amazonaws.services.s3.AmazonS3Client) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) AWS_MASTER_ACCOUNT_SECRET_KEY_PROPERTY(com.vmware.photon.controller.model.adapters.awsadapter.AWSUtils.AWS_MASTER_ACCOUNT_SECRET_KEY_PROPERTY) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) TestContext(com.vmware.xenon.common.test.TestContext) Ignore(org.junit.Ignore) ARN_KEY(com.vmware.photon.controller.model.adapterapi.EndpointConfigRequest.ARN_KEY) UriUtils(com.vmware.xenon.common.UriUtils) Assume.assumeTrue(org.junit.Assume.assumeTrue) AWSClientManagerFactory(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManagerFactory) Assert(org.junit.Assert) Assert.assertEquals(org.junit.Assert.assertEquals) AmazonEC2AsyncClient(com.amazonaws.services.ec2.AmazonEC2AsyncClient) AWSClientManager(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManager) AuthCredentialsServiceState(com.vmware.xenon.services.common.AuthCredentialsService.AuthCredentialsServiceState) AmazonEC2AsyncClient(com.amazonaws.services.ec2.AmazonEC2AsyncClient) TestContext(com.vmware.xenon.common.test.TestContext) CompletionException(java.util.concurrent.CompletionException) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

CompletionException (java.util.concurrent.CompletionException)199 Test (org.junit.Test)80 CompletableFuture (java.util.concurrent.CompletableFuture)62 List (java.util.List)52 ArrayList (java.util.ArrayList)51 IOException (java.io.IOException)45 Map (java.util.Map)39 Collection (java.util.Collection)31 ExecutionException (java.util.concurrent.ExecutionException)31 HashMap (java.util.HashMap)30 Collections (java.util.Collections)24 TimeUnit (java.util.concurrent.TimeUnit)22 Collectors (java.util.stream.Collectors)22 FlinkException (org.apache.flink.util.FlinkException)22 Before (org.junit.Before)21 Duration (java.time.Duration)19 Arrays (java.util.Arrays)19 BeforeClass (org.junit.BeforeClass)19 ExecutorService (java.util.concurrent.ExecutorService)18 Nonnull (javax.annotation.Nonnull)17