Example usage for java.util.concurrent CompletableFuture CompletableFuture

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

Introduction

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

Prototype

public CompletableFuture() 

Source Link

Document

Creates a new incomplete CompletableFuture.

Usage

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

@Override
public CompletableFuture<Void> unassign(byte[] regionName, boolean forcible) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    addListener(getRegionInfo(regionName), (regionInfo, err) -> {
        if (err != null) {
            future.completeExceptionally(err);
            return;
        }//from   ww  w .  j  a  va 2 s . com
        addListener(this.<Void>newMasterCaller().priority(regionInfo.getTable())
                .action(((controller, stub) -> this.<UnassignRegionRequest, UnassignRegionResponse, Void>call(
                        controller, stub,
                        RequestConverter.buildUnassignRegionRequest(regionInfo.getRegionName(), forcible),
                        (s, c, req, done) -> s.unassignRegion(c, req, done), resp -> null)))
                .call(), (ret, err2) -> {
                    if (err2 != null) {
                        future.completeExceptionally(err2);
                    } else {
                        future.complete(ret);
                    }
                });
    });
    return future;
}

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

@Override
public CompletableFuture<Void> offline(byte[] regionName) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    addListener(getRegionInfo(regionName), (regionInfo, err) -> {
        if (err != null) {
            future.completeExceptionally(err);
            return;
        }/* ww w.  j av a2  s  .  com*/
        addListener(this.<Void>newMasterCaller().priority(regionInfo.getTable())
                .action(((controller, stub) -> this.<OfflineRegionRequest, OfflineRegionResponse, Void>call(
                        controller, stub,
                        RequestConverter.buildOfflineRegionRequest(regionInfo.getRegionName()),
                        (s, c, req, done) -> s.offlineRegion(c, req, done), resp -> null)))
                .call(), (ret, err2) -> {
                    if (err2 != null) {
                        future.completeExceptionally(err2);
                    } else {
                        future.complete(ret);
                    }
                });
    });
    return future;
}

From source file:org.apache.pulsar.broker.service.persistent.PersistentTopic.java

public synchronized void triggerOffload(MessageIdImpl messageId) throws AlreadyRunningException {
    if (currentOffload.isDone()) {
        CompletableFuture<MessageIdImpl> promise = currentOffload = new CompletableFuture<>();
        getManagedLedger().asyncOffloadPrefix(PositionImpl.get(messageId.getLedgerId(), messageId.getEntryId()),
                new OffloadCallback() {
                    @Override/*from  w  w  w.  ja  va2  s .com*/
                    public void offloadComplete(Position pos, Object ctx) {
                        PositionImpl impl = (PositionImpl) pos;

                        promise.complete(new MessageIdImpl(impl.getLedgerId(), impl.getEntryId(), -1));
                    }

                    @Override
                    public void offloadFailed(ManagedLedgerException exception, Object ctx) {
                        promise.completeExceptionally(exception);
                    }
                }, null);
    } else {
        throw new AlreadyRunningException("Offload already in progress");
    }
}

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

@Override
public CompletableFuture<Void> move(byte[] regionName) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    addListener(getRegionInfo(regionName), (regionInfo, err) -> {
        if (err != null) {
            future.completeExceptionally(err);
            return;
        }// www.  j a  va 2 s.c  o m
        addListener(
                moveRegion(regionInfo,
                        RequestConverter.buildMoveRegionRequest(regionInfo.getEncodedNameAsBytes(), null)),
                (ret, err2) -> {
                    if (err2 != null) {
                        future.completeExceptionally(err2);
                    } else {
                        future.complete(ret);
                    }
                });
    });
    return future;
}

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

@Override
public CompletableFuture<Void> move(byte[] regionName, ServerName destServerName) {
    Preconditions.checkNotNull(destServerName,
            "destServerName is null. If you don't specify a destServerName, use move(byte[]) instead");
    CompletableFuture<Void> future = new CompletableFuture<>();
    addListener(getRegionInfo(regionName), (regionInfo, err) -> {
        if (err != null) {
            future.completeExceptionally(err);
            return;
        }// ww  w. j  a  v  a  2  s .co m
        addListener(
                moveRegion(regionInfo, RequestConverter
                        .buildMoveRegionRequest(regionInfo.getEncodedNameAsBytes(), destServerName)),
                (ret, err2) -> {
                    if (err2 != null) {
                        future.completeExceptionally(err2);
                    } else {
                        future.complete(ret);
                    }
                });
    });
    return future;
}

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

@Override
public CompletableFuture<List<QuotaSettings>> getQuota(QuotaFilter filter) {
    CompletableFuture<List<QuotaSettings>> future = new CompletableFuture<>();
    Scan scan = QuotaTableUtil.makeScan(filter);
    this.connection.getTableBuilder(QuotaTableUtil.QUOTA_TABLE_NAME).build().scan(scan,
            new AdvancedScanResultConsumer() {
                List<QuotaSettings> settings = new ArrayList<>();

                @Override//www . j a  v a2  s. c o  m
                public void onNext(Result[] results, ScanController controller) {
                    for (Result result : results) {
                        try {
                            QuotaTableUtil.parseResultToCollection(result, settings);
                        } catch (IOException e) {
                            controller.terminate();
                            future.completeExceptionally(e);
                        }
                    }
                }

                @Override
                public void onError(Throwable error) {
                    future.completeExceptionally(error);
                }

                @Override
                public void onComplete() {
                    future.complete(settings);
                }
            });
    return future;
}

From source file:org.apache.bookkeeper.mledger.impl.ManagedLedgerTest.java

/**
 * It verifies that asyncRead timesout if it doesn't receive response from bk-client in configured timeout
 * /*from  ww  w  .  j av  a 2 s.c  om*/
 * @throws Exception
 */
@Test
public void testManagedLedgerWithReadEntryTimeOut() throws Exception {
    ManagedLedgerConfig config = new ManagedLedgerConfig().setReadEntryTimeoutSeconds(1);
    ManagedLedgerImpl ledger = (ManagedLedgerImpl) factory.open("timeout_ledger_test", config);

    BookKeeper bk = mock(BookKeeper.class);
    doNothing().when(bk).asyncCreateLedger(anyInt(), anyInt(), anyInt(), any(), any(), any(), any(), any());
    AtomicReference<ManagedLedgerException> responseException1 = new AtomicReference<>();
    CountDownLatch latch1 = new CountDownLatch(1);

    CompletableFuture<LedgerEntries> entriesFuture = new CompletableFuture<>();
    ReadHandle ledgerHandle = mock(ReadHandle.class);
    doReturn(entriesFuture).when(ledgerHandle).readAsync(PositionImpl.earliest.getLedgerId(),
            PositionImpl.earliest.getEntryId());

    // (1) test read-timeout for: ManagedLedger.asyncReadEntry(..)
    ledger.asyncReadEntry(ledgerHandle, PositionImpl.earliest, new ReadEntryCallback() {
        @Override
        public void readEntryComplete(Entry entry, Object ctx) {
            responseException1.set(null);
            latch1.countDown();
        }

        @Override
        public void readEntryFailed(ManagedLedgerException exception, Object ctx) {
            responseException1.set(exception);
            latch1.countDown();
        }
    }, null);
    ledger.asyncCreateLedger(bk, config, null, new CreateCallback() {
        @Override
        public void createComplete(int rc, LedgerHandle lh, Object ctx) {

        }
    }, Collections.emptyMap());
    latch1.await(config.getReadEntryTimeoutSeconds() + 2, TimeUnit.SECONDS);
    assertNotNull(responseException1.get());
    assertEquals(responseException1.get().getMessage(),
            BKException.getMessage(BKException.Code.TimeoutException));

    // (2) test read-timeout for: ManagedLedger.asyncReadEntry(..)
    CountDownLatch latch2 = new CountDownLatch(1);
    AtomicReference<ManagedLedgerException> responseException2 = new AtomicReference<>();
    PositionImpl readPositionRef = PositionImpl.earliest;
    ManagedCursorImpl cursor = new ManagedCursorImpl(bk, config, ledger, "cursor1");
    OpReadEntry opReadEntry = OpReadEntry.create(cursor, readPositionRef, 1, new ReadEntriesCallback() {

        @Override
        public void readEntriesComplete(List<Entry> entries, Object ctx) {
            latch2.countDown();
        }

        @Override
        public void readEntriesFailed(ManagedLedgerException exception, Object ctx) {
            responseException2.set(exception);
            latch2.countDown();
        }

    }, null);
    ledger.asyncReadEntry(ledgerHandle, PositionImpl.earliest.getEntryId(), PositionImpl.earliest.getEntryId(),
            false, opReadEntry, null);
    latch2.await(config.getReadEntryTimeoutSeconds() + 2, TimeUnit.SECONDS);
    assertNotNull(responseException2.get());
    assertEquals(responseException2.get().getMessage(),
            BKException.getMessage(BKException.Code.TimeoutException));

    ledger.close();
}

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

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

    CompletableFuture<Void> future = new CompletableFuture<Void>();
    addListener(getReplicationPeerConfig(id), (peerConfig, error) -> {
        if (!completeExceptionally(future, error)) {
            ReplicationPeerConfig newPeerConfig = ReplicationPeerConfigUtil
                    .appendTableCFsToReplicationPeerConfig(tableCfs, peerConfig);
            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> removeReplicationPeerTableCFs(String id, Map<TableName, List<String>> tableCfs) {
    if (tableCfs == null) {
        return failedFuture(new ReplicationException("tableCfs is null"));
    }//w  w w.ja v a 2 s  .  c  o 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<List<TableCFs>> listReplicatedTableCFs() {
    CompletableFuture<List<TableCFs>> future = new CompletableFuture<List<TableCFs>>();
    addListener(listTableDescriptors(), (tables, error) -> {
        if (!completeExceptionally(future, error)) {
            List<TableCFs> replicatedTableCFs = new ArrayList<>();
            tables.forEach(table -> {
                Map<String, Integer> cfs = new HashMap<>();
                Stream.of(table.getColumnFamilies())
                        .filter(column -> column.getScope() != HConstants.REPLICATION_SCOPE_LOCAL)
                        .forEach(column -> {
                            cfs.put(column.getNameAsString(), column.getScope());
                        });//ww w .  j  av a2s.  c  o  m
                if (!cfs.isEmpty()) {
                    replicatedTableCFs.add(new TableCFs(table.getTableName(), cfs));
                }
            });
            future.complete(replicatedTableCFs);
        }
    });
    return future;
}