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

/**
 * Get the region info 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//from  ww w.j a v a  2s . co  m
 * @return region info, wrapped by a {@link CompletableFuture}
 */
private CompletableFuture<RegionInfo> getRegionInfo(byte[] regionNameOrEncodedRegionName) {
    if (regionNameOrEncodedRegionName == null) {
        return failedFuture(new IllegalArgumentException("Passed region name can't be null"));
    }

    if (Bytes.equals(regionNameOrEncodedRegionName, RegionInfoBuilder.FIRST_META_REGIONINFO.getRegionName())
            || Bytes.equals(regionNameOrEncodedRegionName,
                    RegionInfoBuilder.FIRST_META_REGIONINFO.getEncodedNameAsBytes())) {
        return CompletableFuture.completedFuture(RegionInfoBuilder.FIRST_META_REGIONINFO);
    }

    CompletableFuture<RegionInfo> future = new CompletableFuture<>();
    addListener(getRegionLocation(regionNameOrEncodedRegionName), (location, err) -> {
        if (err != null) {
            future.completeExceptionally(err);
        } else {
            future.complete(location.getRegion());
        }
    });
    return future;
}

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

private CompletableFuture<Void> waitProcedureResult(CompletableFuture<Long> procFuture) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    addListener(procFuture, (procId, error) -> {
        if (error != null) {
            future.completeExceptionally(error);
            return;
        }/*from ww w.  j  a v a  2s  . c o m*/
        getProcedureResult(procId, future, 0);
    });
    return future;
}

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

private void getProcedureResult(long procId, CompletableFuture<Void> future, int retries) {
    addListener(//from   w  w  w  .  j av a 2s.  co  m
            this.<GetProcedureResultResponse>newMasterCaller().action((controller, stub) -> this
                    .<GetProcedureResultRequest, GetProcedureResultResponse, GetProcedureResultResponse>call(
                            controller, stub, GetProcedureResultRequest.newBuilder().setProcId(procId).build(),
                            (s, c, req, done) -> s.getProcedureResult(c, req, done), (resp) -> resp))
                    .call(),
            (response, error) -> {
                if (error != null) {
                    LOG.warn("failed to get the procedure result procId={}", procId,
                            ConnectionUtils.translateException(error));
                    retryTimer.newTimeout(t -> getProcedureResult(procId, future, retries + 1),
                            ConnectionUtils.getPauseTime(pauseNs, retries), TimeUnit.NANOSECONDS);
                    return;
                }
                if (response.getState() == GetProcedureResultResponse.State.RUNNING) {
                    retryTimer.newTimeout(t -> getProcedureResult(procId, future, retries + 1),
                            ConnectionUtils.getPauseTime(pauseNs, retries), TimeUnit.NANOSECONDS);
                    return;
                }
                if (response.hasException()) {
                    IOException ioe = ForeignExceptionUtil.toIOException(response.getException());
                    future.completeExceptionally(ioe);
                } else {
                    future.complete(null);
                }
            });
}

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

private <T> boolean completeExceptionally(CompletableFuture<T> future, Throwable error) {
    if (error != null) {
        future.completeExceptionally(error);
        return true;
    }//  ww w  .  j a  va 2s  .  c o  m
    return false;
}

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

@Override
public CompletableFuture<Void> updateConfiguration() {
    CompletableFuture<Void> future = new CompletableFuture<Void>();
    addListener(getClusterMetrics(EnumSet.of(Option.LIVE_SERVERS, Option.MASTER, Option.BACKUP_MASTERS)),
            (status, err) -> {/*w ww . j  a  v a  2 s  .c o m*/
                if (err != null) {
                    future.completeExceptionally(err);
                } else {
                    List<CompletableFuture<Void>> futures = new ArrayList<>();
                    status.getLiveServerMetrics().keySet()
                            .forEach(server -> futures.add(updateConfiguration(server)));
                    futures.add(updateConfiguration(status.getMasterName()));
                    status.getBackupMasterNames().forEach(master -> futures.add(updateConfiguration(master)));
                    addListener(
                            CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[futures.size()])),
                            (result, err2) -> {
                                if (err2 != null) {
                                    future.completeExceptionally(err2);
                                } else {
                                    future.complete(result);
                                }
                            });
                }
            });
    return future;
}

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

@Override
public CompletableFuture<CompactionState> getCompactionState(TableName tableName, CompactType compactType) {
    CompletableFuture<CompactionState> future = new CompletableFuture<>();

    switch (compactType) {
    case MOB://from   ww  w.ja  va  2  s  .  c  om
        addListener(connection.registry.getMasterAddress(), (serverName, err) -> {
            if (err != null) {
                future.completeExceptionally(err);
                return;
            }
            RegionInfo regionInfo = RegionInfo.createMobRegionInfo(tableName);

            addListener(this.<GetRegionInfoResponse>newAdminCaller().serverName(serverName)
                    .action((controller, stub) -> this
                            .<GetRegionInfoRequest, GetRegionInfoResponse, GetRegionInfoResponse>adminCall(
                                    controller, stub,
                                    RequestConverter.buildGetRegionInfoRequest(regionInfo.getRegionName(),
                                            true),
                                    (s, c, req, done) -> s.getRegionInfo(controller, req, done), resp -> resp))
                    .call(), (resp2, err2) -> {
                        if (err2 != null) {
                            future.completeExceptionally(err2);
                        } else {
                            if (resp2.hasCompactionState()) {
                                future.complete(ProtobufUtil.createCompactionState(resp2.getCompactionState()));
                            } else {
                                future.complete(CompactionState.NONE);
                            }
                        }
                    });
        });
        break;
    case NORMAL:
        addListener(getTableHRegionLocations(tableName), (locations, err) -> {
            if (err != null) {
                future.completeExceptionally(err);
                return;
            }
            ConcurrentLinkedQueue<CompactionState> regionStates = new ConcurrentLinkedQueue<>();
            List<CompletableFuture<CompactionState>> futures = new ArrayList<>();
            locations.stream().filter(loc -> loc.getServerName() != null).filter(loc -> loc.getRegion() != null)
                    .filter(loc -> !loc.getRegion().isOffline()).map(loc -> loc.getRegion().getRegionName())
                    .forEach(region -> {
                        futures.add(getCompactionStateForRegion(region).whenComplete((regionState, err2) -> {
                            // If any region compaction state is MAJOR_AND_MINOR
                            // the table compaction state is MAJOR_AND_MINOR, too.
                            if (err2 != null) {
                                future.completeExceptionally(unwrapCompletionException(err2));
                            } else if (regionState == CompactionState.MAJOR_AND_MINOR) {
                                future.complete(regionState);
                            } else {
                                regionStates.add(regionState);
                            }
                        }));
                    });
            addListener(CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[futures.size()])),
                    (ret, err3) -> {
                        // If future not completed, check all regions's compaction state
                        if (!future.isCompletedExceptionally() && !future.isDone()) {
                            CompactionState state = CompactionState.NONE;
                            for (CompactionState regionState : regionStates) {
                                switch (regionState) {
                                case MAJOR:
                                    if (state == CompactionState.MINOR) {
                                        future.complete(CompactionState.MAJOR_AND_MINOR);
                                    } else {
                                        state = CompactionState.MAJOR;
                                    }
                                    break;
                                case MINOR:
                                    if (state == CompactionState.MAJOR) {
                                        future.complete(CompactionState.MAJOR_AND_MINOR);
                                    } else {
                                        state = CompactionState.MINOR;
                                    }
                                    break;
                                case NONE:
                                default:
                                }
                            }
                            if (!future.isDone()) {
                                future.complete(state);
                            }
                        }
                    });
        });
        break;
    default:
        throw new IllegalArgumentException("Unknown compactType: " + compactType);
    }

    return future;
}

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

@Override
public CompletableFuture<CompactionState> getCompactionStateForRegion(byte[] regionName) {
    CompletableFuture<CompactionState> future = new CompletableFuture<>();
    addListener(getRegionLocation(regionName), (location, err) -> {
        if (err != null) {
            future.completeExceptionally(err);
            return;
        }/*from  www  . j  a v a2 s.c om*/
        ServerName serverName = location.getServerName();
        if (serverName == null) {
            future.completeExceptionally(new NoServerForRegionException(Bytes.toStringBinary(regionName)));
            return;
        }
        addListener(this.<GetRegionInfoResponse>newAdminCaller().action((controller, stub) -> this
                .<GetRegionInfoRequest, GetRegionInfoResponse, GetRegionInfoResponse>adminCall(controller, stub,
                        RequestConverter.buildGetRegionInfoRequest(location.getRegion().getRegionName(), true),
                        (s, c, req, done) -> s.getRegionInfo(controller, req, done), resp -> resp))
                .serverName(serverName).call(), (resp2, err2) -> {
                    if (err2 != null) {
                        future.completeExceptionally(err2);
                    } else {
                        if (resp2.hasCompactionState()) {
                            future.complete(ProtobufUtil.createCompactionState(resp2.getCompactionState()));
                        } else {
                            future.complete(CompactionState.NONE);
                        }
                    }
                });
    });
    return future;
}

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

@Override
public CompletableFuture<Optional<Long>> getLastMajorCompactionTimestampForRegion(byte[] regionName) {
    CompletableFuture<Optional<Long>> future = new CompletableFuture<>();
    // regionName may be a full region name or encoded region name, so getRegionInfo(byte[]) first
    addListener(getRegionInfo(regionName), (region, err) -> {
        if (err != null) {
            future.completeExceptionally(err);
            return;
        }//from ww  w .  j  av a 2s.c o m
        MajorCompactionTimestampForRegionRequest.Builder builder = MajorCompactionTimestampForRegionRequest
                .newBuilder();
        builder.setRegion(RequestConverter.buildRegionSpecifier(RegionSpecifierType.REGION_NAME, regionName));
        addListener(this.<Optional<Long>>newMasterCaller().action((controller, stub) -> this
                .<MajorCompactionTimestampForRegionRequest, MajorCompactionTimestampResponse, Optional<Long>>call(
                        controller, stub, builder.build(),
                        (s, c, req, done) -> s.getLastMajorCompactionTimestampForRegion(c, req, done),
                        ProtobufUtil::toOptionalTimestamp))
                .call(), (timestamp, err2) -> {
                    if (err2 != null) {
                        future.completeExceptionally(err2);
                    } else {
                        future.complete(timestamp);
                    }
                });
    });
    return future;
}

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

@Override
public CompletableFuture<Map<ServerName, Boolean>> compactionSwitch(boolean switchState,
        List<String> serverNamesList) {
    CompletableFuture<Map<ServerName, Boolean>> future = new CompletableFuture<>();
    addListener(getRegionServerList(serverNamesList), (serverNames, err) -> {
        if (err != null) {
            future.completeExceptionally(err);
            return;
        }//from  w  w  w  .ja  v a2  s .  co m
        // Accessed by multiple threads.
        Map<ServerName, Boolean> serverStates = new ConcurrentHashMap<>(serverNames.size());
        List<CompletableFuture<Boolean>> futures = new ArrayList<>(serverNames.size());
        serverNames.stream().forEach(serverName -> {
            futures.add(switchCompact(serverName, switchState).whenComplete((serverState, err2) -> {
                if (err2 != null) {
                    future.completeExceptionally(unwrapCompletionException(err2));
                } else {
                    serverStates.put(serverName, serverState);
                }
            }));
        });
        addListener(CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[futures.size()])),
                (ret, err3) -> {
                    if (!future.isCompletedExceptionally()) {
                        if (err3 != null) {
                            future.completeExceptionally(err3);
                        } else {
                            future.complete(serverStates);
                        }
                    }
                });
    });
    return future;
}

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

private CompletableFuture<List<ServerName>> getRegionServerList(List<String> serverNamesList) {
    CompletableFuture<List<ServerName>> future = new CompletableFuture<>();
    if (serverNamesList.isEmpty()) {
        CompletableFuture<ClusterMetrics> clusterMetricsCompletableFuture = getClusterMetrics(
                EnumSet.of(Option.LIVE_SERVERS));
        addListener(clusterMetricsCompletableFuture, (clusterMetrics, err) -> {
            if (err != null) {
                future.completeExceptionally(err);
            } else {
                future.complete(new ArrayList<>(clusterMetrics.getLiveServerMetrics().keySet()));
            }/* w  w w.j  a  va2  s . c om*/
        });
        return future;
    } else {
        List<ServerName> serverList = new ArrayList<>();
        for (String regionServerName : serverNamesList) {
            ServerName serverName = null;
            try {
                serverName = ServerName.valueOf(regionServerName);
            } catch (Exception e) {
                future.completeExceptionally(
                        new IllegalArgumentException(String.format("ServerName format: %s", regionServerName)));
            }
            if (serverName == null) {
                future.completeExceptionally(
                        new IllegalArgumentException(String.format("Null ServerName: %s", regionServerName)));
            }
        }
        future.complete(serverList);
    }
    return future;
}