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:org.apache.hadoop.hbase.client.RawAsyncHBaseAdmin.java

@Override
public CompletableFuture<Void> removeReplicationPeerTableCFs(String id, Map<TableName, List<String>> tableCfs) {
    if (tableCfs == null) {
        return failedFuture(new ReplicationException("tableCfs is null"));
    }/* ww  w  . jav a  2s . co  m*/

    CompletableFuture<Void> future = new CompletableFuture<Void>();
    addListener(getReplicationPeerConfig(id), (peerConfig, error) -> {
        if (!completeExceptionally(future, error)) {
            ReplicationPeerConfig newPeerConfig = null;
            try {
                newPeerConfig = ReplicationPeerConfigUtil.removeTableCFsFromReplicationPeerConfig(tableCfs,
                        peerConfig, id);
            } catch (ReplicationException e) {
                future.completeExceptionally(e);
                return;
            }
            addListener(updateReplicationPeerConfig(id, newPeerConfig), (result, err) -> {
                if (!completeExceptionally(future, error)) {
                    future.complete(result);
                }
            });
        }
    });
    return future;
}

From source file:org.apache.hadoop.hbase.client.RawAsyncHBaseAdmin.java

@Override
public CompletableFuture<Void> snapshot(SnapshotDescription snapshotDesc) {
    SnapshotProtos.SnapshotDescription snapshot = ProtobufUtil.createHBaseProtosSnapshotDesc(snapshotDesc);
    try {/*  w  ww . j a v a 2  s .c o m*/
        ClientSnapshotDescriptionUtils.assertSnapshotRequestIsValid(snapshot);
    } catch (IllegalArgumentException e) {
        return failedFuture(e);
    }
    CompletableFuture<Void> future = new CompletableFuture<>();
    final SnapshotRequest request = SnapshotRequest.newBuilder().setSnapshot(snapshot).build();
    addListener(this.<Long>newMasterCaller()
            .action((controller, stub) -> this.<SnapshotRequest, SnapshotResponse, Long>call(controller, stub,
                    request, (s, c, req, done) -> s.snapshot(c, req, done), resp -> resp.getExpectedTimeout()))
            .call(), (expectedTimeout, err) -> {
                if (err != null) {
                    future.completeExceptionally(err);
                    return;
                }
                TimerTask pollingTask = new TimerTask() {
                    int tries = 0;
                    long startTime = EnvironmentEdgeManager.currentTime();
                    long endTime = startTime + expectedTimeout;
                    long maxPauseTime = expectedTimeout / maxAttempts;

                    @Override
                    public void run(Timeout timeout) throws Exception {
                        if (EnvironmentEdgeManager.currentTime() < endTime) {
                            addListener(isSnapshotFinished(snapshotDesc), (done, err2) -> {
                                if (err2 != null) {
                                    future.completeExceptionally(err2);
                                } else if (done) {
                                    future.complete(null);
                                } else {
                                    // retry again after pauseTime.
                                    long pauseTime = ConnectionUtils
                                            .getPauseTime(TimeUnit.NANOSECONDS.toMillis(pauseNs), ++tries);
                                    pauseTime = Math.min(pauseTime, maxPauseTime);
                                    AsyncConnectionImpl.RETRY_TIMER.newTimeout(this, pauseTime,
                                            TimeUnit.MILLISECONDS);
                                }
                            });
                        } else {
                            future.completeExceptionally(new SnapshotCreationException(
                                    "Snapshot '" + snapshot.getName() + "' wasn't completed in expectedTime:"
                                            + expectedTimeout + " ms",
                                    snapshotDesc));
                        }
                    }
                };
                AsyncConnectionImpl.RETRY_TIMER.newTimeout(pollingTask, 1, TimeUnit.MILLISECONDS);
            });
    return future;
}

From source file:org.apache.hadoop.hbase.client.RawAsyncHBaseAdmin.java

@Override
public CompletableFuture<Void> restoreSnapshot(String snapshotName, boolean takeFailSafeSnapshot,
        boolean restoreAcl) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    addListener(listSnapshots(Pattern.compile(snapshotName)), (snapshotDescriptions, err) -> {
        if (err != null) {
            future.completeExceptionally(err);
            return;
        }//from   w w  w.  j  a v  a 2 s.  c  o  m
        TableName tableName = null;
        if (snapshotDescriptions != null && !snapshotDescriptions.isEmpty()) {
            for (SnapshotDescription snap : snapshotDescriptions) {
                if (snap.getName().equals(snapshotName)) {
                    tableName = snap.getTableName();
                    break;
                }
            }
        }
        if (tableName == null) {
            future.completeExceptionally(
                    new RestoreSnapshotException("Unable to find the table name for snapshot=" + snapshotName));
            return;
        }
        final TableName finalTableName = tableName;
        addListener(tableExists(finalTableName), (exists, err2) -> {
            if (err2 != null) {
                future.completeExceptionally(err2);
            } else if (!exists) {
                // if table does not exist, then just clone snapshot into new table.
                completeConditionalOnFuture(future,
                        internalRestoreSnapshot(snapshotName, finalTableName, restoreAcl));
            } else {
                addListener(isTableDisabled(finalTableName), (disabled, err4) -> {
                    if (err4 != null) {
                        future.completeExceptionally(err4);
                    } else if (!disabled) {
                        future.completeExceptionally(new TableNotDisabledException(finalTableName));
                    } else {
                        completeConditionalOnFuture(future, restoreSnapshot(snapshotName, finalTableName,
                                takeFailSafeSnapshot, restoreAcl));
                    }
                });
            }
        });
    });
    return future;
}

From source file:org.apache.hadoop.hbase.client.RawAsyncHBaseAdmin.java

private CompletableFuture<Void> restoreSnapshot(String snapshotName, TableName tableName,
        boolean takeFailSafeSnapshot, boolean restoreAcl) {
    if (takeFailSafeSnapshot) {
        CompletableFuture<Void> future = new CompletableFuture<>();
        // Step.1 Take a snapshot of the current state
        String failSafeSnapshotSnapshotNameFormat = this.connection.getConfiguration().get(
                HConstants.SNAPSHOT_RESTORE_FAILSAFE_NAME, HConstants.DEFAULT_SNAPSHOT_RESTORE_FAILSAFE_NAME);
        final String failSafeSnapshotSnapshotName = failSafeSnapshotSnapshotNameFormat
                .replace("{snapshot.name}", snapshotName)
                .replace("{table.name}", tableName.toString().replace(TableName.NAMESPACE_DELIM, '.'))
                .replace("{restore.timestamp}", String.valueOf(EnvironmentEdgeManager.currentTime()));
        LOG.info("Taking restore-failsafe snapshot: " + failSafeSnapshotSnapshotName);
        addListener(snapshot(failSafeSnapshotSnapshotName, tableName), (ret, err) -> {
            if (err != null) {
                future.completeExceptionally(err);
            } else {
                // Step.2 Restore snapshot
                addListener(internalRestoreSnapshot(snapshotName, tableName, restoreAcl), (void2, err2) -> {
                    if (err2 != null) {
                        // Step.3.a Something went wrong during the restore and try to rollback.
                        addListener(//from  w ww .  j a  v  a  2s .c  o m
                                internalRestoreSnapshot(failSafeSnapshotSnapshotName, tableName, restoreAcl),
                                (void3, err3) -> {
                                    if (err3 != null) {
                                        future.completeExceptionally(err3);
                                    } else {
                                        String msg = "Restore snapshot=" + snapshotName
                                                + " failed. Rollback to snapshot="
                                                + failSafeSnapshotSnapshotName + " succeeded.";
                                        future.completeExceptionally(new RestoreSnapshotException(msg, err2));
                                    }
                                });
                    } else {
                        // Step.3.b If the restore is succeeded, delete the pre-restore snapshot.
                        LOG.info("Deleting restore-failsafe snapshot: " + failSafeSnapshotSnapshotName);
                        addListener(deleteSnapshot(failSafeSnapshotSnapshotName), (ret3, err3) -> {
                            if (err3 != null) {
                                LOG.error("Unable to remove the failsafe snapshot: "
                                        + failSafeSnapshotSnapshotName, err3);
                                future.completeExceptionally(err3);
                            } else {
                                future.complete(ret3);
                            }
                        });
                    }
                });
            }
        });
        return future;
    } else {
        return internalRestoreSnapshot(snapshotName, tableName, restoreAcl);
    }
}

From source file:org.apache.hadoop.hbase.client.RawAsyncHBaseAdmin.java

private <T> void completeConditionalOnFuture(CompletableFuture<T> dependentFuture,
        CompletableFuture<T> parentFuture) {
    addListener(parentFuture, (res, err) -> {
        if (err != null) {
            dependentFuture.completeExceptionally(err);
        } else {/*from  w  ww .j av a2 s .  c o  m*/
            dependentFuture.complete(res);
        }
    });
}

From source file:org.apache.hadoop.hbase.client.RawAsyncHBaseAdmin.java

@Override
public CompletableFuture<Void> cloneSnapshot(String snapshotName, TableName tableName, boolean restoreAcl) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    addListener(tableExists(tableName), (exists, err) -> {
        if (err != null) {
            future.completeExceptionally(err);
        } else if (exists) {
            future.completeExceptionally(new TableExistsException(tableName));
        } else {/* ww w .j a v a 2s.  co m*/
            completeConditionalOnFuture(future, internalRestoreSnapshot(snapshotName, tableName, restoreAcl));
        }
    });
    return future;
}

From source file:org.apache.hadoop.hbase.client.RawAsyncHBaseAdmin.java

private CompletableFuture<List<SnapshotDescription>> getCompletedSnapshots(Pattern tableNamePattern,
        Pattern snapshotNamePattern) {
    CompletableFuture<List<SnapshotDescription>> future = new CompletableFuture<>();
    addListener(listTableNames(tableNamePattern, false), (tableNames, err) -> {
        if (err != null) {
            future.completeExceptionally(err);
            return;
        }/*w  w  w.j av  a 2 s  .  com*/
        if (tableNames == null || tableNames.size() <= 0) {
            future.complete(Collections.emptyList());
            return;
        }
        addListener(getCompletedSnapshots(snapshotNamePattern), (snapshotDescList, err2) -> {
            if (err2 != null) {
                future.completeExceptionally(err2);
                return;
            }
            if (snapshotDescList == null || snapshotDescList.isEmpty()) {
                future.complete(Collections.emptyList());
                return;
            }
            future.complete(snapshotDescList.stream()
                    .filter(snap -> (snap != null && tableNames.contains(snap.getTableName())))
                    .collect(Collectors.toList()));
        });
    });
    return future;
}

From source file:org.apache.hadoop.hbase.client.RawAsyncHBaseAdmin.java

private CompletableFuture<Void> internalDeleteSnapshots(Pattern tableNamePattern, Pattern snapshotNamePattern) {
    CompletableFuture<List<SnapshotDescription>> listSnapshotsFuture;
    if (tableNamePattern == null) {
        listSnapshotsFuture = getCompletedSnapshots(snapshotNamePattern);
    } else {/*from  ww  w.j  av a2s .  c om*/
        listSnapshotsFuture = getCompletedSnapshots(tableNamePattern, snapshotNamePattern);
    }
    CompletableFuture<Void> future = new CompletableFuture<>();
    addListener(listSnapshotsFuture, ((snapshotDescriptions, err) -> {
        if (err != null) {
            future.completeExceptionally(err);
            return;
        }
        if (snapshotDescriptions == null || snapshotDescriptions.isEmpty()) {
            future.complete(null);
            return;
        }
        addListener(CompletableFuture.allOf(snapshotDescriptions.stream().map(this::internalDeleteSnapshot)
                .toArray(CompletableFuture[]::new)), (v, e) -> {
                    if (e != null) {
                        future.completeExceptionally(e);
                    } else {
                        future.complete(v);
                    }
                });
    }));
    return future;
}

From source file:org.apache.hadoop.hbase.client.RawAsyncHBaseAdmin.java

@Override
public CompletableFuture<Void> execProcedure(String signature, String instance, Map<String, String> props) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    ProcedureDescription procDesc = ProtobufUtil.buildProcedureDescription(signature, instance, props);
    addListener(this.<Long>newMasterCaller()
            .action((controller, stub) -> this.<ExecProcedureRequest, ExecProcedureResponse, Long>call(
                    controller, stub, ExecProcedureRequest.newBuilder().setProcedure(procDesc).build(),
                    (s, c, req, done) -> s.execProcedure(c, req, done), resp -> resp.getExpectedTimeout()))
            .call(), (expectedTimeout, err) -> {
                if (err != null) {
                    future.completeExceptionally(err);
                    return;
                }//from w  w w . j a  v  a2 s  .  c om
                TimerTask pollingTask = new TimerTask() {
                    int tries = 0;
                    long startTime = EnvironmentEdgeManager.currentTime();
                    long endTime = startTime + expectedTimeout;
                    long maxPauseTime = expectedTimeout / maxAttempts;

                    @Override
                    public void run(Timeout timeout) throws Exception {
                        if (EnvironmentEdgeManager.currentTime() < endTime) {
                            addListener(isProcedureFinished(signature, instance, props), (done, err2) -> {
                                if (err2 != null) {
                                    future.completeExceptionally(err2);
                                    return;
                                }
                                if (done) {
                                    future.complete(null);
                                } else {
                                    // retry again after pauseTime.
                                    long pauseTime = ConnectionUtils
                                            .getPauseTime(TimeUnit.NANOSECONDS.toMillis(pauseNs), ++tries);
                                    pauseTime = Math.min(pauseTime, maxPauseTime);
                                    AsyncConnectionImpl.RETRY_TIMER.newTimeout(this, pauseTime,
                                            TimeUnit.MICROSECONDS);
                                }
                            });
                        } else {
                            future.completeExceptionally(
                                    new IOException("Procedure '" + signature + " : " + instance
                                            + "' wasn't completed in expectedTime:" + expectedTimeout + " ms"));
                        }
                    }
                };
                // Queue the polling task into RETRY_TIMER to poll procedure state asynchronously.
                AsyncConnectionImpl.RETRY_TIMER.newTimeout(pollingTask, 1, TimeUnit.MILLISECONDS);
            });
    return future;
}

From source file:org.apache.hadoop.hbase.client.RawAsyncHBaseAdmin.java

/**
 * Get the region location for the passed region name. The region name may be a full region name
 * or encoded region name. If the region does not found, then it'll throw an
 * UnknownRegionException wrapped by a {@link CompletableFuture}
 * @param regionNameOrEncodedRegionName region name or encoded region name
 * @return region location, wrapped by a {@link CompletableFuture}
 *//*  w  ww  . j  a  va 2s .c o m*/
@VisibleForTesting
CompletableFuture<HRegionLocation> getRegionLocation(byte[] regionNameOrEncodedRegionName) {
    if (regionNameOrEncodedRegionName == null) {
        return failedFuture(new IllegalArgumentException("Passed region name can't be null"));
    }
    try {
        CompletableFuture<Optional<HRegionLocation>> future;
        if (RegionInfo.isEncodedRegionName(regionNameOrEncodedRegionName)) {
            String encodedName = Bytes.toString(regionNameOrEncodedRegionName);
            if (encodedName.length() < RegionInfo.MD5_HEX_LENGTH) {
                // old format encodedName, should be meta region
                future = connection.registry.getMetaRegionLocation()
                        .thenApply(locs -> Stream.of(locs.getRegionLocations())
                                .filter(loc -> loc.getRegion().getEncodedName().equals(encodedName))
                                .findFirst());
            } else {
                future = AsyncMetaTableAccessor.getRegionLocationWithEncodedName(metaTable,
                        regionNameOrEncodedRegionName);
            }
        } else {
            RegionInfo regionInfo = MetaTableAccessor
                    .parseRegionInfoFromRegionName(regionNameOrEncodedRegionName);
            if (regionInfo.isMetaRegion()) {
                future = connection.registry.getMetaRegionLocation()
                        .thenApply(locs -> Stream.of(locs.getRegionLocations())
                                .filter(loc -> loc.getRegion().getReplicaId() == regionInfo.getReplicaId())
                                .findFirst());
            } else {
                future = AsyncMetaTableAccessor.getRegionLocation(metaTable, regionNameOrEncodedRegionName);
            }
        }

        CompletableFuture<HRegionLocation> returnedFuture = new CompletableFuture<>();
        addListener(future, (location, err) -> {
            if (err != null) {
                returnedFuture.completeExceptionally(err);
                return;
            }
            if (!location.isPresent() || location.get().getRegion() == null) {
                returnedFuture.completeExceptionally(
                        new UnknownRegionException("Invalid region name or encoded region name: "
                                + Bytes.toStringBinary(regionNameOrEncodedRegionName)));
            } else {
                returnedFuture.complete(location.get());
            }
        });
        return returnedFuture;
    } catch (IOException e) {
        return failedFuture(e);
    }
}