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.AsyncHBaseAdmin.java

private void getProcedureResult(final long procId, CompletableFuture<Void> future) {
    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().whenComplete((response, error) -> {
                if (error != null) {
                    LOG.warn("failed to get the procedure result procId=" + procId,
                            ConnectionUtils.translateException(error));
                    connection.RETRY_TIMER.newTimeout(t -> getProcedureResult(procId, future), pauseNs,
                            TimeUnit.NANOSECONDS);
                    return;
                }//from   w ww .ja v  a  2s . co  m
                if (response.getState() == GetProcedureResultResponse.State.RUNNING) {
                    connection.RETRY_TIMER.newTimeout(t -> getProcedureResult(procId, future), pauseNs,
                            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.AsyncHBaseAdmin.java

private <T> CompletableFuture<T> failedFuture(Throwable error) {
    CompletableFuture<T> future = new CompletableFuture<>();
    future.completeExceptionally(error);
    return future;
}

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

private void complete(TableName tableName, LocateRequest req, HRegionLocation loc, Throwable error) {
    if (error != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Failed to locate region in '" + tableName + "', row='" + Bytes.toStringBinary(req.row)
                    + "', locateType=" + req.locateType, error);
        }//from w w w . ja  va2 s  .c o  m
    }
    LocateRequest toSend = null;
    TableCache tableCache = getTableCache(tableName);
    if (loc != null) {
        if (!addToCache(tableCache, loc)) {
            // someone is ahead of us.
            synchronized (tableCache) {
                tableCache.pendingRequests.remove(req);
            }
            return;
        }
    }
    synchronized (tableCache) {
        tableCache.pendingRequests.remove(req);
        if (error instanceof DoNotRetryIOException) {
            CompletableFuture<?> future = tableCache.allRequests.remove(req);
            if (future != null) {
                future.completeExceptionally(error);
            }
        }
        if (loc != null) {
            for (Iterator<Map.Entry<LocateRequest, CompletableFuture<HRegionLocation>>> iter = tableCache.allRequests
                    .entrySet().iterator(); iter.hasNext();) {
                Map.Entry<LocateRequest, CompletableFuture<HRegionLocation>> entry = iter.next();
                if (tryComplete(entry.getKey(), entry.getValue(), loc)) {
                    iter.remove();
                }
            }
        }
        if (!tableCache.allRequests.isEmpty() && tableCache.hasQuota(maxConcurrentLocateRequestPerTable)) {
            LocateRequest[] candidates = tableCache.allRequests.keySet().stream()
                    .filter(r -> !tableCache.isPending(r)).toArray(LocateRequest[]::new);
            if (candidates.length > 0) {
                // TODO: use a better algorithm to send a request which is more likely to fetch a new
                // location.
                toSend = candidates[ThreadLocalRandom.current().nextInt(candidates.length)];
                tableCache.send(toSend);
            }
        }
    }
    if (toSend != null) {
        locateInMeta(tableName, toSend);
    }
}

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

CompletableFuture<HRegionLocation> getRegionLocation(TableName tableName, byte[] row, boolean reload) {
    CompletableFuture<HRegionLocation> future = new CompletableFuture<>();
    try {/*from   ww w.ja va  2  s. com*/
        future.complete(conn.getRegionLocation(tableName, row, reload));
    } catch (IOException e) {
        future.completeExceptionally(e);
    }
    return future;
}

From source file:org.apache.hadoop.hbase.client.example.AsyncClientExample.java

private CompletableFuture<AsyncConnection> getConn() {
    CompletableFuture<AsyncConnection> f = future.get();
    if (f != null) {
        return f;
    }//from w ww .j  a  v  a2 s. c  o  m
    for (;;) {
        if (future.compareAndSet(null, new CompletableFuture<>())) {
            CompletableFuture<AsyncConnection> toComplete = future.get();
            addListener(ConnectionFactory.createAsyncConnection(getConf()), (conn, error) -> {
                if (error != null) {
                    toComplete.completeExceptionally(error);
                    // we need to reset the future holder so we will get a chance to recreate an async
                    // connection at next try.
                    future.set(null);
                    return;
                }
                toComplete.complete(conn);
            });
            return toComplete;
        } else {
            f = future.get();
            if (f != null) {
                return f;
            }
        }
    }
}

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

private <PREQ, PRESP, RESP> CompletableFuture<RESP> adminCall(HBaseRpcController controller,
        AdminService.Interface stub, PREQ preq, AdminRpcCall<PRESP, PREQ> rpcCall,
        Converter<RESP, PRESP> respConverter) {
    CompletableFuture<RESP> future = new CompletableFuture<>();
    rpcCall.call(stub, controller, preq, new RpcCallback<PRESP>() {

        @Override/*  www  . ja  va 2  s  .c  om*/
        public void run(PRESP resp) {
            if (controller.failed()) {
                future.completeExceptionally(controller.getFailed());
            } else {
                try {
                    future.complete(respConverter.convert(resp));
                } catch (IOException e) {
                    future.completeExceptionally(e);
                }
            }
        }
    });
    return future;
}

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

@Override
public CompletableFuture<TableDescriptor> getDescriptor(TableName tableName) {
    CompletableFuture<TableDescriptor> future = new CompletableFuture<>();
    addListener(this.<List<TableSchema>>newMasterCaller().priority(tableName)
            .action((controller, stub) -> this
                    .<GetTableDescriptorsRequest, GetTableDescriptorsResponse, List<TableSchema>>call(
                            controller, stub, RequestConverter.buildGetTableDescriptorsRequest(tableName),
                            (s, c, req, done) -> s.getTableDescriptors(c, req, done),
                            (resp) -> resp.getTableSchemaList()))
            .call(), (tableSchemas, error) -> {
                if (error != null) {
                    future.completeExceptionally(error);
                    return;
                }/*from   w  w  w .j  a  v  a 2  s  .c  o m*/
                if (!tableSchemas.isEmpty()) {
                    future.complete(ProtobufUtil.toTableDescriptor(tableSchemas.get(0)));
                } else {
                    future.completeExceptionally(new TableNotFoundException(tableName.getNameAsString()));
                }
            });
    return future;
}

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

@Override
public CompletableFuture<Boolean> isTableEnabled(TableName tableName) {
    if (TableName.isMetaTableName(tableName)) {
        return CompletableFuture.completedFuture(true);
    }/*  ww  w  .  j a  v a  2  s .  c o m*/
    CompletableFuture<Boolean> future = new CompletableFuture<>();
    addListener(AsyncMetaTableAccessor.getTableState(metaTable, tableName), (state, error) -> {
        if (error != null) {
            future.completeExceptionally(error);
            return;
        }
        if (state.isPresent()) {
            future.complete(state.get().inStates(TableState.State.ENABLED));
        } else {
            future.completeExceptionally(new TableNotFoundException(tableName));
        }
    });
    return future;
}

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

@Override
public CompletableFuture<Boolean> isTableDisabled(TableName tableName) {
    if (TableName.isMetaTableName(tableName)) {
        return CompletableFuture.completedFuture(false);
    }/*from  w ww.  j a  v a2  s .  com*/
    CompletableFuture<Boolean> future = new CompletableFuture<>();
    addListener(AsyncMetaTableAccessor.getTableState(metaTable, tableName), (state, error) -> {
        if (error != null) {
            future.completeExceptionally(error);
            return;
        }
        if (state.isPresent()) {
            future.complete(state.get().inStates(TableState.State.DISABLED));
        } else {
            future.completeExceptionally(new TableNotFoundException(tableName));
        }
    });
    return future;
}

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

private CompletableFuture<Boolean> isTableAvailable(TableName tableName, Optional<byte[][]> splitKeys) {
    if (TableName.isMetaTableName(tableName)) {
        return connection.registry.getMetaRegionLocation().thenApply(locs -> Stream
                .of(locs.getRegionLocations()).allMatch(loc -> loc != null && loc.getServerName() != null));
    }/*from   ww  w.  j a v  a 2s.c  o m*/
    CompletableFuture<Boolean> future = new CompletableFuture<>();
    addListener(isTableEnabled(tableName), (enabled, error) -> {
        if (error != null) {
            if (error instanceof TableNotFoundException) {
                future.complete(false);
            } else {
                future.completeExceptionally(error);
            }
            return;
        }
        if (!enabled) {
            future.complete(false);
        } else {
            addListener(AsyncMetaTableAccessor.getTableHRegionLocations(metaTable, Optional.of(tableName)),
                    (locations, error1) -> {
                        if (error1 != null) {
                            future.completeExceptionally(error1);
                            return;
                        }
                        List<HRegionLocation> notDeployedRegions = locations.stream()
                                .filter(loc -> loc.getServerName() == null).collect(Collectors.toList());
                        if (notDeployedRegions.size() > 0) {
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("Table " + tableName + " has " + notDeployedRegions.size()
                                        + " regions");
                            }
                            future.complete(false);
                            return;
                        }

                        Optional<Boolean> available = splitKeys
                                .map(keys -> compareRegionsWithSplitKeys(locations, keys));
                        future.complete(available.orElse(true));
                    });
        }
    });
    return future;
}