List of usage examples for java.util.concurrent CompletableFuture get
@SuppressWarnings("unchecked") public T get() throws InterruptedException, ExecutionException
From source file:org.apache.pulsar.functions.worker.rest.api.ComponentImpl.java
public void deregisterFunction(final String tenant, final String namespace, final String componentName, final String clientRole) { if (!isWorkerServiceAvailable()) { throwUnavailableException();//from ww w . j a va2 s . c o m } try { if (!isAuthorizedRole(tenant, clientRole)) { log.error("{}/{}/{} Client [{}] is not admin and authorized to deregister {}", tenant, namespace, componentName, clientRole, componentType); throw new RestException(Status.UNAUTHORIZED, "client is not authorize to perform operation"); } } catch (PulsarAdminException e) { log.error("{}/{}/{} Failed to authorize [{}]", tenant, namespace, componentName, e); throw new RestException(Status.INTERNAL_SERVER_ERROR, e.getMessage()); } // delete state table if (null != worker().getStateStoreAdminClient()) { final String tableNs = StateUtils.getStateNamespace(tenant, namespace); final String tableName = componentName; try { FutureUtils.result(worker().getStateStoreAdminClient().deleteStream(tableNs, tableName)); } catch (NamespaceNotFoundException | StreamNotFoundException e) { // ignored if the state table doesn't exist } catch (Exception e) { log.error("{}/{}/{} Failed to delete state table", e); throw new RestException(Status.INTERNAL_SERVER_ERROR, e.getMessage()); } } // validate parameters try { validateDeregisterRequestParams(tenant, namespace, componentName, componentType); } catch (IllegalArgumentException e) { log.error("Invalid deregister {} request @ /{}/{}/{}", componentType, tenant, namespace, componentName, e); throw new RestException(Status.BAD_REQUEST, e.getMessage()); } FunctionMetaDataManager functionMetaDataManager = worker().getFunctionMetaDataManager(); if (!functionMetaDataManager.containsFunction(tenant, namespace, componentName)) { log.error("{} to deregister does not exist @ /{}/{}/{}", componentType, tenant, namespace, componentName); throw new RestException(Status.NOT_FOUND, String.format("%s %s doesn't exist", componentType, componentName)); } FunctionMetaData functionMetaData = functionMetaDataManager.getFunctionMetaData(tenant, namespace, componentName); if (!calculateSubjectType(functionMetaData).equals(componentType)) { log.error("{}/{}/{} is not a {}", tenant, namespace, componentName, componentType); throw new RestException(Status.NOT_FOUND, String.format("%s %s doesn't exist", componentType, componentName)); } CompletableFuture<RequestResult> completableFuture = functionMetaDataManager.deregisterFunction(tenant, namespace, componentName); RequestResult requestResult = null; try { requestResult = completableFuture.get(); if (!requestResult.isSuccess()) { throw new RestException(Status.BAD_REQUEST, requestResult.getMessage()); } } catch (ExecutionException e) { log.error("Execution Exception while deregistering {} @ /{}/{}/{}", componentType, tenant, namespace, componentName, e); throw new RestException(Status.INTERNAL_SERVER_ERROR, e.getCause().getMessage()); } catch (InterruptedException e) { log.error("Interrupted Exception while deregistering {} @ /{}/{}/{}", componentType, tenant, namespace, componentName, e); throw new RestException(Status.REQUEST_TIMEOUT, e.getMessage()); } }
From source file:com.ikanow.aleph2.shared.crud.elasticsearch.services.TestElasticsearchCrudService.java
@Test public void test_CreateSingleObject() throws InterruptedException, ExecutionException { final ElasticsearchCrudService<TestBean> service = getTestService("testCreateSingleObject", TestBean.class); assertEquals(0, service.countObjects().get().intValue()); final TestBean test = new TestBean(); test._id = "_id_1"; test.test_string = "test_string_1"; // 1) Add a new object to an empty DB {// w w w. j a v a 2 s . co m final Future<Supplier<Object>> result = service.storeObject(test); final Supplier<Object> val = result.get(); assertEquals("_id_1", val.get()); assertEquals(1, service.countObjects().get().intValue()); final CompletableFuture<Optional<TestBean>> f_retval = service.getObjectById(val.get()); assertTrue("Need to find an object", f_retval.get().isPresent()); final TestBean retval = f_retval.get().get(); assertEquals(1, service.countObjects().get().intValue()); assertEquals("{\"_id\":\"_id_1\",\"test_string\":\"test_string_1\"}", BeanTemplateUtils.toJson(retval).toString()); } // 2) Add the _id again, should fail final TestBean test2 = BeanTemplateUtils.clone(test).with("test_string", "test_string_2").done(); { final Future<Supplier<Object>> result2 = service.storeObject(test2); Exception expected_ex = null; try { result2.get(); fail("Should have thrown exception on duplicate insert"); } catch (Exception e) { expected_ex = e; } if (null != expected_ex) assertThat(expected_ex.getCause(), instanceOf(RuntimeException.class)); assertEquals(1, service.countObjects().get().intValue()); final CompletableFuture<Optional<TestBean>> f_retval2 = service.getObjectById("_id_1"); assertTrue("Found an object", f_retval2.get().isPresent()); final TestBean retval2 = f_retval2.get().get(); assertEquals("{\"_id\":\"_id_1\",\"test_string\":\"test_string_1\"}", BeanTemplateUtils.toJson(retval2).toString()); } // 3) Add the same with override set { service.storeObject(test2, true).get(); assertEquals(1, service.countObjects().get().intValue()); final CompletableFuture<Optional<TestBean>> f_retval3 = service .getObjectBySpec(CrudUtils.allOf(TestBean.class)); //final CompletableFuture<Optional<TestBean>> f_retval3 = service.getObjectById("_id_1"); //^ note these 2 commands are equivalent because of the level of optimization configured for these tests final TestBean retval3 = f_retval3.get().get(); assertEquals("{\"_id\":\"_id_1\",\"test_string\":\"test_string_2\"}", BeanTemplateUtils.toJson(retval3).toString()); //4) add with no id final TestBean test4 = new TestBean(); test4.test_string = "test_string_4"; final Supplier<Object> result4 = service.storeObject(test4, true).get(); assertEquals(2, service.countObjects().get().intValue()); final String id = result4.get().toString(); final CompletableFuture<Optional<TestBean>> f_retval4 = service.getObjectById(id); final TestBean retval4 = f_retval4.get().get(); assertEquals("test_string_4", retval4.test_string); } }
From source file:com.ikanow.aleph2.shared.crud.elasticsearch.services.TestElasticsearchCrudService.java
@Test public void test_CreateSingleObject_Batch() throws InterruptedException, ExecutionException { DataSchemaBean.WriteSettings write_settings = new DataSchemaBean.WriteSettings(100, 1023L, 1, 3); final ElasticsearchCrudService<TestBean> service = getTestService("testCreateSingleObject", TestBean.class, true, Optional.of(write_settings)); assertEquals(write_settings, service._batch_write_settings.get()); @SuppressWarnings("unchecked") final ElasticsearchCrudService<TestBean>.ElasticsearchBatchSubsystem batch_service = service .getUnderlyingPlatformDriver(ElasticsearchBatchSubsystem.class, Optional.empty()).get(); @SuppressWarnings("unchecked") final ElasticsearchCrudService<JsonNode>.ElasticsearchBatchSubsystem batch_service_raw = service .getRawService().getUnderlyingPlatformDriver(ElasticsearchBatchSubsystem.class, Optional.empty()) .get();//from ww w . jav a 2s . com assertEquals(0, service.countObjects().get().intValue()); final TestBean test = new TestBean(); test._id = "_id_1"; test.test_string = "test_string_1"; // 1) Add a new object to an empty DB { batch_service.storeObject(test, false); Thread.sleep(3000L); assertEquals(1, service.countObjects().get().intValue()); final CompletableFuture<Optional<TestBean>> f_retval = service.getObjectById(test._id()); assertTrue("Need to find an object", f_retval.get().isPresent()); final TestBean retval = f_retval.get().get(); assertEquals(1, service.countObjects().get().intValue()); assertEquals("{\"_id\":\"_id_1\",\"test_string\":\"test_string_1\"}", BeanTemplateUtils.toJson(retval).toString()); } // 2) Add the _id again, should fail final TestBean test2 = BeanTemplateUtils.clone(test).with("test_string", "test_string_2").done(); { batch_service.storeObject(test2, false); Thread.sleep(3000L); assertEquals(1, service.countObjects().get().intValue()); final CompletableFuture<Optional<TestBean>> f_retval2 = service.getObjectById("_id_1"); assertTrue("Found an object", f_retval2.get().isPresent()); final TestBean retval2 = f_retval2.get().get(); assertEquals("{\"_id\":\"_id_1\",\"test_string\":\"test_string_1\"}", BeanTemplateUtils.toJson(retval2).toString()); } // 3) Add the same with override set { batch_service.storeObject(test2, true); Thread.sleep(3000L); assertEquals(1, service.countObjects().get().intValue()); final CompletableFuture<Optional<TestBean>> f_retval3 = service .getObjectBySpec(CrudUtils.allOf(TestBean.class)); //final CompletableFuture<Optional<TestBean>> f_retval3 = service.getObjectById("_id_1"); //^ note these 2 commands are equivalent because of the level of optimization configured for these tests final TestBean retval3 = f_retval3.get().get(); assertEquals("{\"_id\":\"_id_1\",\"test_string\":\"test_string_2\"}", BeanTemplateUtils.toJson(retval3).toString()); } //4) add with no id String other_id = null; { final TestBean test4 = new TestBean(); test4.test_string = "test_string_4"; batch_service.storeObject(test4, true); Thread.sleep(3000L); assertEquals(2, service.countObjects().get().intValue()); final CompletableFuture<Optional<TestBean>> f_retval4 = service .getObjectBySpec(CrudUtils.allOf(TestBean.class).when("test_string", "test_string_4")); final TestBean retval4 = f_retval4.get().get(); assertTrue("Was assigned _id", retval4._id != null); assertEquals("test_string_4", retval4.test_string); other_id = retval4._id; } // 5) delete test { final TestBean test_del = new TestBean(); test_del._id = "_id_1"; batch_service.storeObject(test_del, true); Thread.sleep(3000L); // Won't delete because it's not an ObjectNode, which is the only thing you can delete assertEquals(2, service.countObjects().get().intValue()); final JsonNode jn_test_del = BeanTemplateUtils.configureMapper(Optional.empty()).createObjectNode() .put("_id", test_del._id); batch_service_raw.storeObject(jn_test_del, true); Thread.sleep(3000L); assertEquals(1, service.countObjects().get().intValue()); final JsonNode jn_test_del2 = BeanTemplateUtils.configureMapper(Optional.empty()).createObjectNode() .put("_id", other_id).put("_index", "testCreateSingleObject").put("_type", "test"); batch_service_raw.storeObject(jn_test_del2, true); Thread.sleep(3000L); assertEquals(0, service.countObjects().get().intValue()); } }
From source file:org.apache.distributedlog.auditor.DLAuditor.java
private long calculateLedgerSpaceUsage(BookKeeperClient bkc, final ExecutorService executorService) throws IOException { final AtomicLong totalBytes = new AtomicLong(0); final AtomicLong totalEntries = new AtomicLong(0); final AtomicLong numLedgers = new AtomicLong(0); LedgerManager lm = BookKeeperAccessor.getLedgerManager(bkc.get()); final CompletableFuture<Void> doneFuture = FutureUtils.createFuture(); final BookKeeper bk = bkc.get(); BookkeeperInternalCallbacks.Processor<Long> collector = new BookkeeperInternalCallbacks.Processor<Long>() { @Override//from w ww. j av a 2s .com public void process(final Long lid, final AsyncCallback.VoidCallback cb) { numLedgers.incrementAndGet(); executorService.submit(new Runnable() { @Override public void run() { bk.asyncOpenLedgerNoRecovery(lid, BookKeeper.DigestType.CRC32, conf.getBKDigestPW().getBytes(UTF_8), new org.apache.bookkeeper.client.AsyncCallback.OpenCallback() { @Override public void openComplete(int rc, LedgerHandle lh, Object ctx) { final int cbRc; if (BKException.Code.OK == rc) { totalBytes.addAndGet(lh.getLength()); totalEntries.addAndGet(lh.getLastAddConfirmed() + 1); cbRc = rc; } else { cbRc = BKException.Code.ZKException; } executorService.submit(new Runnable() { @Override public void run() { cb.processResult(cbRc, null, null); } }); } }, null); } }); } }; AsyncCallback.VoidCallback finalCb = new AsyncCallback.VoidCallback() { @Override public void processResult(int rc, String path, Object ctx) { if (BKException.Code.OK == rc) { doneFuture.complete(null); } else { doneFuture.completeExceptionally(BKException.create(rc)); } } }; lm.asyncProcessLedgers(collector, finalCb, null, BKException.Code.OK, BKException.Code.ZKException); try { doneFuture.get(); logger.info("calculated {} ledgers\n\ttotal bytes = {}\n\ttotal entries = {}", new Object[] { numLedgers.get(), totalBytes.get(), totalEntries.get() }); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new DLInterruptedException("Interrupted on calculating ledger space : ", e); } catch (ExecutionException e) { if (e.getCause() instanceof IOException) { throw (IOException) (e.getCause()); } else { throw new IOException("Failed to calculate ledger space : ", e.getCause()); } } return totalBytes.get(); }
From source file:org.apache.pulsar.broker.admin.impl.PersistentTopicsBase.java
protected void internalDeletePartitionedTopic(boolean authoritative, boolean force) { validateAdminAccessForTenant(topicName.getTenant()); PartitionedTopicMetadata partitionMetadata = getPartitionedTopicMetadata(topicName, authoritative); int numPartitions = partitionMetadata.partitions; if (numPartitions > 0) { final CompletableFuture<Void> future = new CompletableFuture<>(); final AtomicInteger count = new AtomicInteger(numPartitions); try {//from ww w .j av a 2s . co m for (int i = 0; i < numPartitions; i++) { TopicName topicNamePartition = topicName.getPartition(i); pulsar().getAdminClient().persistentTopics().deleteAsync(topicNamePartition.toString(), force) .whenComplete((r, ex) -> { if (ex != null) { if (ex instanceof NotFoundException) { // if the sub-topic is not found, the client might not have called create // producer or it might have been deleted earlier, so we ignore the 404 error. // For all other exception, we fail the delete partition method even if a single // partition is failed to be deleted if (log.isDebugEnabled()) { log.debug("[{}] Partition not found: {}", clientAppId(), topicNamePartition); } } else { future.completeExceptionally(ex); log.error("[{}] Failed to delete partition {}", clientAppId(), topicNamePartition, ex); return; } } else { log.info("[{}] Deleted partition {}", clientAppId(), topicNamePartition); } if (count.decrementAndGet() == 0) { future.complete(null); } }); } future.get(); } catch (Exception e) { Throwable t = e.getCause(); if (t instanceof PreconditionFailedException) { throw new RestException(Status.PRECONDITION_FAILED, "Topic has active producers/subscriptions"); } else { throw new RestException(t); } } } // Only tries to delete the znode for partitioned topic when all its partitions are successfully deleted String path = path(PARTITIONED_TOPIC_PATH_ZNODE, namespaceName.toString(), domain(), topicName.getEncodedLocalName()); try { globalZk().delete(path, -1); globalZkCache().invalidate(path); // we wait for the data to be synced in all quorums and the observers Thread.sleep(PARTITIONED_TOPIC_WAIT_SYNC_TIME_MS); log.info("[{}] Deleted partitioned topic {}", clientAppId(), topicName); } catch (KeeperException.NoNodeException nne) { throw new RestException(Status.NOT_FOUND, "Partitioned topic does not exist"); } catch (KeeperException.BadVersionException e) { log.warn("[{}] Failed to delete partitioned topic {}: concurrent modification", clientAppId(), topicName); throw new RestException(Status.CONFLICT, "Concurrent modification"); } catch (Exception e) { log.error("[{}] Failed to delete partitioned topic {}", clientAppId(), topicName, e); throw new RestException(e); } }