List of usage examples for java.util.concurrent CompletableFuture CompletableFuture
public CompletableFuture()
From source file:org.apache.bookkeeper.client.BookKeeper.java
/** * Synchronous call to create ledger. Parameters match those of * {@link #asyncCreateLedger(int, int, int, DigestType, byte[], * AsyncCallback.CreateCallback, Object)} * * @param ensSize//ww w .jav a 2 s . com * @param writeQuorumSize * @param ackQuorumSize * @param digestType * @param passwd * @param customMetadata * @return a handle to the newly created ledger * @throws InterruptedException * @throws BKException */ public LedgerHandle createLedger(int ensSize, int writeQuorumSize, int ackQuorumSize, DigestType digestType, byte passwd[], final Map<String, byte[]> customMetadata) throws InterruptedException, BKException { CompletableFuture<LedgerHandle> counter = new CompletableFuture<>(); /* * Calls asynchronous version */ asyncCreateLedger(ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, new SyncCreateCallback(), counter, customMetadata); LedgerHandle lh = SynchCallbackUtils.waitForResult(counter); if (lh == null) { LOG.error("Unexpected condition : no ledger handle returned for a success ledger creation"); throw BKException.create(BKException.Code.UnexpectedConditionException); } return lh; }
From source file:org.apache.hadoop.hbase.client.AsyncHBaseAdmin.java
@Override public CompletableFuture<Void> closeRegion(byte[] regionName, String serverName) { CompletableFuture<Void> future = new CompletableFuture<>(); getRegion(regionName).whenComplete((p, err) -> { if (err != null) { future.completeExceptionally(err); return; }//w ww .j a v a2 s . com if (p == null || p.getFirst() == null) { future.completeExceptionally(new UnknownRegionException(Bytes.toStringBinary(regionName))); return; } if (serverName != null) { closeRegion(ServerName.valueOf(serverName), p.getFirst()).whenComplete((p2, err2) -> { if (err2 != null) { future.completeExceptionally(err2); } else { future.complete(null); } }); } else { if (p.getSecond() == null) { future.completeExceptionally(new NotServingRegionException(regionName)); } else { closeRegion(p.getSecond(), p.getFirst()).whenComplete((p2, err2) -> { if (err2 != null) { future.completeExceptionally(err2); } else { future.complete(null); } }); } } }); return future; }
From source file:com.microfocus.application.automation.tools.srf.run.RunFromSrfBuilder.java
@Override public boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher, BuildListener _listener) throws InterruptedException, IOException { this.logger = _listener.getLogger(); Dispatcher.TRACE = true;/* w w w . j a va 2 s . c o m*/ Dispatcher.TRACE_PER_REQUEST = true; this._token = null; // Important in order to get only this run events this.build = build; this.sseEventListener = new SseEventListener(this.logger); this.sseEventListener.addObserver(this); this.srfExecutionFuture = new CompletableFuture<>(); this.runningCount = new HashSet<>(); JSONObject conData = getSrfConnectionData(build, logger); if (conData == null) return false; _app = conData.getString("app"); _secret = conData.getString("secret"); _ftaasServerAddress = conData.getString("server"); _https = conData.getBoolean("https"); _tenant = conData.getString("tenant"); String srfProxy = conData.getString("proxy"); URL proxy = null; if ((srfProxy != null) && (srfProxy.length() != 0)) { proxy = new URL(srfProxy); String proxyHost = proxy.getHost(); String proxyPort = String.format("%d", proxy.getPort()); Properties systemProperties = System.getProperties(); systemProperties.setProperty("https.proxyHost", proxyHost); systemProperties.setProperty("http.proxyHost", proxyHost); systemProperties.setProperty("https.proxyPort", proxyPort); systemProperties.setProperty("http.proxyPort", proxyPort); } try { SSLContext sslContext = SSLContext.getInstance("TLS"); _trustMgr = new SrfTrustManager(); sslContext.init(null, new SrfTrustManager[] { _trustMgr }, null); SSLContext.setDefault(sslContext); _factory = sslContext.getSocketFactory(); this.srfClient = new SrfClient(_ftaasServerAddress, _tenant, _factory, proxy); } catch (NoSuchAlgorithmException | KeyManagementException e) { logger.print(e.getMessage()); logger.print("\n\r"); } jobIds = null; try { srfClient.login(_app, _secret); this._token = srfClient.getAccessToken(); initSrfEventListener(); jobIds = executeTestsSet(); } catch (UnknownHostException | ConnectException | SSLHandshakeException | IllegalArgumentException | AuthorizationException | AuthenticationException e) { cleanUp(); logger.println( String.format("ERROR: Failed logging into SRF server: %s %s", this._ftaasServerAddress, e)); return false; } catch (IOException | SrfException e) { cleanUp(); logger.println(String.format("ERROR: Failed executing test, %s", e)); return false; } try { boolean buildResult = this.srfExecutionFuture.get(); return buildResult; } catch (ExecutionException e) { e.printStackTrace(); return false; } catch (InterruptedException e) { e.printStackTrace(); build.setResult(Result.ABORTED); // TODO: Optimization instead of testrunid set maintain testrunid map with job info, in order to avoid already finished job cancellation if (!jobIds.isEmpty()) { for (int i = 0; i < jobIds.size(); i++) { String jobId = jobIds.get(i).toString(); try { srfClient.cancelJob(jobId); } catch (SrfException e1) { e1.printStackTrace(); } } } return false; } finally { cleanUp(); } }
From source file:org.apache.pulsar.broker.service.BrokerService.java
/** * It creates a topic async and returns CompletableFuture. It also throttles down configured max-concurrent topic * loading and puts them into queue once in-process topics are created. * /*from w ww .jav a 2 s. c o m*/ * @param topic persistent-topic name * @return CompletableFuture<Topic> * @throws RuntimeException */ protected CompletableFuture<Topic> createPersistentTopic(final String topic) throws RuntimeException { checkTopicNsOwnership(topic); final CompletableFuture<Topic> topicFuture = new CompletableFuture<>(); final Semaphore topicLoadSemaphore = topicLoadRequestSemaphore.get(); if (topicLoadSemaphore.tryAcquire()) { createPersistentTopic(topic, topicFuture); topicFuture.handle((persistentTopic, ex) -> { // release permit and process pending topic topicLoadSemaphore.release(); createPendingLoadTopic(); return null; }); } else { pendingTopicLoadingQueue.add(new ImmutablePair<String, CompletableFuture<Topic>>(topic, topicFuture)); if (log.isDebugEnabled()) { log.debug("topic-loading for {} added into pending queue", topic); } } return topicFuture; }
From source file:io.pravega.controller.task.Stream.StreamMetadataTasks.java
public CompletableFuture<Void> writeEvent(ControllerEvent event) { CompletableFuture<Void> result = new CompletableFuture<>(); getRequestWriter().writeEvent(event).whenComplete((r, e) -> { if (e != null) { log.warn("exception while posting event {} {}", e.getClass().getName(), e.getMessage()); if (e instanceof TaskExceptions.ProcessingDisabledException) { result.completeExceptionally(e); } else { // transform any other event write exception to retryable exception result.completeExceptionally(new TaskExceptions.PostEventException("Failed to post event", e)); }// w w w . j av a 2 s .c o m } else { log.info("event posted successfully"); result.complete(null); } }); return result; }
From source file:org.apache.bookkeeper.client.LedgerHandle.java
/** * Read a sequence of entries synchronously. * * @param firstEntry//from ww w .j av a 2s . c o m * id of first entry of sequence (included) * @param lastEntry * id of last entry of sequence (included) * * @see #asyncReadEntries(long, long, ReadCallback, Object) */ public Enumeration<LedgerEntry> readEntries(long firstEntry, long lastEntry) throws InterruptedException, BKException { CompletableFuture<Enumeration<LedgerEntry>> result = new CompletableFuture<>(); asyncReadEntries(firstEntry, lastEntry, new SyncReadCallback(result), null); return SyncCallbackUtils.waitForResult(result); }
From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java
private CompletableFuture<Void> startAcceptingConnections() { CompletableFuture<Void> future = new CompletableFuture<>(); ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_REUSEADDR, true); b.option(ChannelOption.SO_BACKLOG, 128); b.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(8 * 1024, 32 * 1024)); b.childOption(ChannelOption.SO_RCVBUF, 1024 * 1024); b.childOption(ChannelOption.SO_SNDBUF, 1024 * 1024); b.childOption(ChannelOption.SO_KEEPALIVE, true); b.childOption(ChannelOption.TCP_NODELAY, true); b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); b.group(serverGroup, clientGroup);//from w ww. jav a 2s. c om b.channel(serverChannelClass); if (enableNettyTls) { b.childHandler(new SslServerCommunicationChannelInitializer()); } else { b.childHandler(new BasicChannelInitializer()); } // Bind and start to accept incoming connections. b.bind(localAddress.port()).addListener((ChannelFutureListener) f -> { if (f.isSuccess()) { log.info("{} accepting incoming connections on port {}", localAddress.address(true), localAddress.port()); serverChannel = f.channel(); future.complete(null); } else { log.warn("{} failed to bind to port {} due to {}", localAddress.address(true), localAddress.port(), f.cause()); future.completeExceptionally(f.cause()); } }); return future; }
From source file:org.apache.bookkeeper.mledger.impl.OffloadPrefixTest.java
@Test public void testOffloadDelete() throws Exception { Set<Pair<Long, UUID>> deleted = ConcurrentHashMap.newKeySet(); CompletableFuture<Set<Long>> errorLedgers = new CompletableFuture<>(); Set<Pair<Long, UUID>> failedOffloads = ConcurrentHashMap.newKeySet(); MockLedgerOffloader offloader = new MockLedgerOffloader(); ManagedLedgerConfig config = new ManagedLedgerConfig(); config.setMaxEntriesPerLedger(10);//w ww .j a v a 2s . co m config.setMinimumRolloverTime(0, TimeUnit.SECONDS); config.setRetentionTime(0, TimeUnit.MINUTES); config.setLedgerOffloader(offloader); ManagedLedgerImpl ledger = (ManagedLedgerImpl) factory.open("my_test_ledger", config); ManagedCursor cursor = ledger.openCursor("foobar"); for (int i = 0; i < 15; i++) { String content = "entry-" + i; ledger.addEntry(content.getBytes()); } Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 2); ledger.offloadPrefix(ledger.getLastConfirmedEntry()); Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 2); Assert.assertEquals( ledger.getLedgersInfoAsList().stream().filter(e -> e.getOffloadContext().getComplete()).count(), 1); Assert.assertTrue(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getComplete()); long firstLedger = ledger.getLedgersInfoAsList().get(0).getLedgerId(); long secondLedger = ledger.getLedgersInfoAsList().get(1).getLedgerId(); cursor.markDelete(ledger.getLastConfirmedEntry()); assertEventuallyTrue(() -> ledger.getLedgersInfoAsList().size() == 1); Assert.assertEquals(ledger.getLedgersInfoAsList().get(0).getLedgerId(), secondLedger); assertEventuallyTrue(() -> offloader.deletedOffloads().contains(firstLedger)); }
From source file:org.apache.hadoop.hbase.client.AsyncHBaseAdmin.java
CompletableFuture<Pair<HRegionInfo, ServerName>> getRegion(byte[] regionName) { if (regionName == null) { return failedFuture(new IllegalArgumentException("Pass region name")); }/*from w w w .j a va 2 s .co m*/ CompletableFuture<Pair<HRegionInfo, ServerName>> future = new CompletableFuture<>(); AsyncMetaTableAccessor.getRegion(metaTable, regionName).whenComplete((p, err) -> { if (err != null) { future.completeExceptionally(err); } else if (p != null) { future.complete(p); } else { metaTable.scanAll(new Scan().setReadType(ReadType.PREAD).addFamily(HConstants.CATALOG_FAMILY)) .whenComplete((results, err2) -> { if (err2 != null) { future.completeExceptionally(err2); return; } String encodedName = Bytes.toString(regionName); if (results != null && !results.isEmpty()) { for (Result r : results) { if (r.isEmpty() || MetaTableAccessor.getHRegionInfo(r) == null) continue; RegionLocations rl = MetaTableAccessor.getRegionLocations(r); if (rl != null) { for (HRegionLocation h : rl.getRegionLocations()) { if (h != null && encodedName.equals(h.getRegionInfo().getEncodedName())) { future.complete(new Pair<>(h.getRegionInfo(), h.getServerName())); return; } } } } } future.complete(null); }); } }); return future; }
From source file:org.apache.bookkeeper.client.LedgerHandle.java
/** * Read a sequence of entries synchronously, allowing to read after the LastAddConfirmed range.<br> * This is the same of/*from w w w . j a v a 2s .c o m*/ * {@link #asyncReadUnconfirmedEntries(long, long, ReadCallback, Object) } * * @param firstEntry * id of first entry of sequence (included) * @param lastEntry * id of last entry of sequence (included) * * @see #readEntries(long, long) * @see #asyncReadUnconfirmedEntries(long, long, ReadCallback, java.lang.Object) * @see #asyncReadLastConfirmed(ReadLastConfirmedCallback, java.lang.Object) */ public Enumeration<LedgerEntry> readUnconfirmedEntries(long firstEntry, long lastEntry) throws InterruptedException, BKException { CompletableFuture<Enumeration<LedgerEntry>> result = new CompletableFuture<>(); asyncReadUnconfirmedEntries(firstEntry, lastEntry, new SyncReadCallback(result), null); return SyncCallbackUtils.waitForResult(result); }