Example usage for java.util.concurrent CompletableFuture get

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

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public T get() throws InterruptedException, ExecutionException 

Source Link

Document

Waits if necessary for this future to complete, and then returns its result.

Usage

From source file:org.apache.tinkerpop.gremlin.server.GremlinServerSessionIntegrateTest.java

@Test
public void shouldEnsureSessionBindingsAreThreadSafe() throws Exception {
    final Cluster cluster = Cluster.open();
    final Client client = cluster.connect(name.getMethodName());

    client.submitAsync("a=100;b=1000;c=10000;null");
    final int requests = 1000;
    final List<CompletableFuture<ResultSet>> futures = new ArrayList<>(requests);
    IntStream.range(0, requests).forEach(i -> {
        try {//from   w  ww .ja  v a  2 s.co  m
            futures.add(client.submitAsync("a+b+c"));
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    });

    assertEquals(requests, futures.size());

    for (CompletableFuture<ResultSet> f : futures) {
        final Result r = f.get().one();
        assertEquals(11100, r.getInt());
    }

    client.close();
    cluster.close();
}

From source file:org.apache.pulsar.broker.web.PulsarWebResource.java

protected static void validateAdminAccessForTenant(PulsarService pulsar, String clientAppId,
        String originalPrincipal, String tenant) throws RestException, Exception {
    if (log.isDebugEnabled()) {
        log.debug("check admin access on tenant: {} - Authenticated: {} -- role: {}", tenant,
                (isClientAuthenticated(clientAppId)), clientAppId);
    }/*  ww w . j a v a  2s .  c om*/

    TenantInfo tenantInfo;

    try {
        tenantInfo = pulsar.getConfigurationCache().propertiesCache().get(path(POLICIES, tenant))
                .orElseThrow(() -> new RestException(Status.NOT_FOUND, "Tenant does not exist"));
    } catch (KeeperException.NoNodeException e) {
        log.warn("Failed to get tenant info data for non existing tenant {}", tenant);
        throw new RestException(Status.NOT_FOUND, "Tenant does not exist");
    }

    if (pulsar.getConfiguration().isAuthenticationEnabled()
            && pulsar.getConfiguration().isAuthorizationEnabled()) {
        if (!isClientAuthenticated(clientAppId)) {
            throw new RestException(Status.FORBIDDEN, "Need to authenticate to perform the request");
        }

        validateOriginalPrincipal(pulsar.getConfiguration().getProxyRoles(), clientAppId, originalPrincipal);

        if (pulsar.getConfiguration().getProxyRoles().contains(clientAppId)) {

            CompletableFuture<Boolean> isProxySuperUserFuture;
            CompletableFuture<Boolean> isOriginalPrincipalSuperUserFuture;
            try {
                isProxySuperUserFuture = pulsar.getBrokerService().getAuthorizationService()
                        .isSuperUser(clientAppId);

                isOriginalPrincipalSuperUserFuture = pulsar.getBrokerService().getAuthorizationService()
                        .isSuperUser(originalPrincipal);

                Set<String> adminRoles = tenantInfo.getAdminRoles();
                boolean proxyAuthorized = isProxySuperUserFuture.get() || adminRoles.contains(clientAppId);
                boolean originalPrincipalAuthorized = isOriginalPrincipalSuperUserFuture.get()
                        || adminRoles.contains(originalPrincipal);
                if (!proxyAuthorized || !originalPrincipalAuthorized) {
                    throw new RestException(Status.UNAUTHORIZED,
                            String.format("Proxy not authorized to access resource (proxy:%s,original:%s)",
                                    clientAppId, originalPrincipal));
                }
            } catch (InterruptedException | ExecutionException e) {
                throw new RestException(Status.INTERNAL_SERVER_ERROR, e.getMessage());
            }
            log.debug("Successfully authorized {} (proxied by {}) on tenant {}", originalPrincipal, clientAppId,
                    tenant);
        } else if (pulsar.getConfiguration().getSuperUserRoles().contains(clientAppId)) {
            // Super-user has access to configure all the policies
            log.debug("granting access to super-user {} on tenant {}", clientAppId, tenant);
        } else {

            if (!tenantInfo.getAdminRoles().contains(clientAppId)) {
                throw new RestException(Status.UNAUTHORIZED,
                        "Don't have permission to administrate resources on this tenant");
            }

            log.debug("Successfully authorized {} on tenant {}", clientAppId, tenant);
        }
    }
}

From source file:org.ulyssis.ipp.control.CommandDispatcher.java

public Result send(Command command) {
    final CompletableFuture<Result> future = new CompletableFuture<>();
    sendAsync(command, (c, r) -> {/*from ww w . ja  v a 2 s .c o m*/
        assert (c == command);
        future.complete(r);
    });
    try {
        return future.get();
    } catch (InterruptedException e) {
        return Result.TIMEOUT;
    } catch (ExecutionException e) {
        LOG.error("We got an ExecutionException. This should not happen.", e.getCause());
        return Result.ERROR;
    }
}

From source file:com.ikanow.aleph2.analytics.storm.utils.TestStormControllerUtil_Cache.java

@Test
public void testCache() throws IOException, InterruptedException, ExecutionException {
    final String jar_location = System.getProperty("java.io.tmpdir");
    File file1 = createFakeZipFile(null);//File.createTempFile("recent_date_test_", null);
    Thread.sleep(1500);//from   w ww .  j  av  a 2 s  . c o  m
    File file2 = createFakeZipFile(null);//File.createTempFile("recent_date_test_", null);
    Thread.sleep(1500);
    File file3 = createFakeZipFile(null);//File.createTempFile("recent_date_test_", null);      
    List<String> files1 = Arrays.asList(file1.getCanonicalPath(), file2.getCanonicalPath(),
            file3.getCanonicalPath());
    String input_jar_location = JarBuilderUtil.getHashedJarName(files1, jar_location);
    File input_jar = new File(input_jar_location);
    input_jar.delete();
    assertFalse(input_jar.exists());

    //first time it should create
    final CompletableFuture<String> jar_future1 = StormControllerUtil
            .buildOrReturnCachedStormTopologyJar(files1, jar_location);
    jar_future1.get();
    assertTrue(input_jar.exists());

    //second time it should cache
    long file_mod_time = getFileModifiedTime(input_jar);
    final CompletableFuture<String> jar_future2 = StormControllerUtil
            .buildOrReturnCachedStormTopologyJar(files1, jar_location);
    jar_future2.get();
    assertEquals(file_mod_time, getFileModifiedTime(input_jar));

    //third time modify a file, it should no longer cache
    Thread.sleep(1500); //sleep a ms so the modified time updates
    file1.delete();
    file1 = createFakeZipFile(file2.getCanonicalPath());
    final CompletableFuture<String> jar_future3 = StormControllerUtil
            .buildOrReturnCachedStormTopologyJar(files1, jar_location);
    jar_future3.get();
    assertNotEquals(file_mod_time, getFileModifiedTime(input_jar)); //original jar creation time should not match its current modified time (it should have been remade)

    //cleanup
    file1.delete();
    file2.delete();
    file3.delete();
    new File(input_jar_location).delete();
}

From source file:org.eclipse.jdt.ls.core.internal.handlers.InitHandlerTest.java

private InitializeResult initialize(boolean dynamicRegistration)
        throws InterruptedException, ExecutionException {
    InitializeParams params = new InitializeParams();
    ClientCapabilities capabilities = new ClientCapabilities();
    WorkspaceClientCapabilities workspaceCapabilities = new WorkspaceClientCapabilities();
    workspaceCapabilities// w  w w. j  a v a  2s .c o m
            .setDidChangeConfiguration(new DidChangeConfigurationCapabilities(dynamicRegistration));
    ExecuteCommandCapabilities executeCommand = new ExecuteCommandCapabilities(dynamicRegistration);
    workspaceCapabilities.setExecuteCommand(executeCommand);
    capabilities.setWorkspace(workspaceCapabilities);
    TextDocumentClientCapabilities textDocument = new TextDocumentClientCapabilities();
    SynchronizationCapabilities synchronizationCapabilities = new SynchronizationCapabilities();
    synchronizationCapabilities.setWillSave(Boolean.TRUE);
    synchronizationCapabilities.setWillSaveWaitUntil(Boolean.TRUE);
    capabilities.setTextDocument(textDocument);
    params.setCapabilities(capabilities);
    CompletableFuture<InitializeResult> result = server.initialize(params);
    return result.get();
}

From source file:com.yahoo.pulsar.broker.namespace.NamespaceServiceTest.java

@Test
public void testSplitMapWithRefreshedStatMap() throws Exception {

    OwnershipCache MockOwnershipCache = spy(pulsar.getNamespaceService().getOwnershipCache());

    ManagedLedger ledger = mock(ManagedLedger.class);
    when(ledger.getCursors()).thenReturn(Lists.newArrayList());

    doNothing().when(MockOwnershipCache).disableOwnership(any(NamespaceBundle.class));
    Field ownership = NamespaceService.class.getDeclaredField("ownershipCache");
    ownership.setAccessible(true);/*from  ww w . j  av a 2s  .c om*/
    ownership.set(pulsar.getNamespaceService(), MockOwnershipCache);

    NamespaceService namespaceService = pulsar.getNamespaceService();
    NamespaceName nsname = new NamespaceName("pulsar/global/ns1");
    DestinationName dn = DestinationName.get("persistent://pulsar/global/ns1/topic-1");
    NamespaceBundles bundles = namespaceService.getNamespaceBundleFactory().getBundles(nsname);
    NamespaceBundle originalBundle = bundles.findBundle(dn);

    PersistentTopic topic = new PersistentTopic(dn.toString(), ledger, pulsar.getBrokerService());
    Method method = pulsar.getBrokerService().getClass().getDeclaredMethod("addTopicToStatsMaps",
            DestinationName.class, PersistentTopic.class);
    method.setAccessible(true);
    method.invoke(pulsar.getBrokerService(), dn, topic);
    String nspace = originalBundle.getNamespaceObject().toString();
    List<PersistentTopic> list = this.pulsar.getBrokerService().getAllTopicsFromNamespaceBundle(nspace,
            originalBundle.toString());
    assertNotNull(list);

    // Split bundle and take ownership of split bundles
    CompletableFuture<Void> result = namespaceService.splitAndOwnBundle(originalBundle);
    try {
        result.get();
    } catch (Exception e) {
        // make sure: no failure
        fail("split bundle faild", e);
    }

    try {
        // old bundle should be removed from status-map
        list = this.pulsar.getBrokerService().getAllTopicsFromNamespaceBundle(nspace,
                originalBundle.toString());
        fail();
    } catch (NullPointerException ne) {
        // OK
    }

    // status-map should be updated with new split bundles
    NamespaceBundle splitBundle = pulsar.getNamespaceService().getBundle(dn);
    assertTrue(!CollectionUtils.isEmpty(
            this.pulsar.getBrokerService().getAllTopicsFromNamespaceBundle(nspace, splitBundle.toString())));

}

From source file:org.eclipse.winery.repository.export.CsarExporterTest.java

@Test
@EnabledIf("(new java.io.File(\"C:/Ethereum/keystore/UTC--2018-03-05T15-33-22.456000000Z--e4b51a3d4e77d2ce2a9d9ce107ec8ec7cff5571d.json\")).exists()")
public void testPutCsarInBlockchainAndImmutableStorage() throws Exception {
    setRevisionTo("origin/plain");
    CsarExporter exporter = new CsarExporter();
    DefinitionsChildId id = new ServiceTemplateId("http://plain.winery.opentosca.org/servicetemplates",
            "ServiceTemplateWithAllReqCapVariants", false);
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    CompletableFuture<String> future = exporter
            .writeCsarAndSaveManifestInProvenanceLayer(RepositoryFactory.getRepository(), id, os);
    String transactionHash = future.get();

    assertNotNull(transactionHash);/*from   w ww . j av a2s.  com*/

    try (InputStream inputStream = new ByteArrayInputStream(os.toByteArray());
            ZipInputStream zis = new ZipInputStream(inputStream)) {
        ManifestContents manifestContents = parseManifest(zis);

        assertNotNull(manifestContents);

        for (String section : manifestContents.getSectionNames()) {
            assertNotNull(manifestContents.getAttributesForSection(section)
                    .get(TOSCAMetaFileAttributes.IMMUTABLE_ADDRESS));
        }
    }
}

From source file:com.yahoo.pulsar.broker.namespace.NamespaceServiceTest.java

@Test
public void testSplitAndOwnBundles() throws Exception {

    OwnershipCache MockOwnershipCache = spy(pulsar.getNamespaceService().getOwnershipCache());
    doNothing().when(MockOwnershipCache).disableOwnership(any(NamespaceBundle.class));
    Field ownership = NamespaceService.class.getDeclaredField("ownershipCache");
    ownership.setAccessible(true);/*www  . j av  a  2  s .com*/
    ownership.set(pulsar.getNamespaceService(), MockOwnershipCache);
    NamespaceService namespaceService = pulsar.getNamespaceService();
    NamespaceName nsname = new NamespaceName("pulsar/global/ns1");
    DestinationName dn = DestinationName.get("persistent://pulsar/global/ns1/topic-1");
    NamespaceBundles bundles = namespaceService.getNamespaceBundleFactory().getBundles(nsname);
    NamespaceBundle originalBundle = bundles.findBundle(dn);

    // Split bundle and take ownership of split bundles
    CompletableFuture<Void> result = namespaceService.splitAndOwnBundle(originalBundle);

    try {
        result.get();
    } catch (Exception e) {
        // make sure: no failure
        fail("split bundle faild", e);
    }
    NamespaceBundleFactory bundleFactory = this.pulsar.getNamespaceService().getNamespaceBundleFactory();
    NamespaceBundles updatedNsBundles = bundleFactory.getBundles(nsname);

    // new updated bundles shouldn't be null
    assertNotNull(updatedNsBundles);
    List<NamespaceBundle> bundleList = updatedNsBundles.getBundles();
    assertNotNull(bundles);

    NamespaceBundleFactory utilityFactory = NamespaceBundleFactory.createFactory(Hashing.crc32());

    // (1) validate bundleFactory-cache has newly split bundles and removed old parent bundle
    Pair<NamespaceBundles, List<NamespaceBundle>> splitBundles = splitBundles(utilityFactory, nsname, bundles,
            originalBundle);
    assertNotNull(splitBundles);
    Set<NamespaceBundle> splitBundleSet = new HashSet<>(splitBundles.getRight());
    splitBundleSet.removeAll(bundleList);
    assertTrue(splitBundleSet.isEmpty());

    // (2) validate LocalZookeeper policies updated with newly created split
    // bundles
    String path = joinPath(LOCAL_POLICIES_ROOT, nsname.toString());
    byte[] content = this.pulsar.getLocalZkCache().getZooKeeper().getData(path, null, new Stat());
    Policies policies = ObjectMapperFactory.getThreadLocal().readValue(content, Policies.class);
    NamespaceBundles localZkBundles = bundleFactory.getBundles(nsname, policies.bundles);
    assertTrue(updatedNsBundles.equals(localZkBundles));
    System.out.println(policies);

    // (3) validate ownership of new split bundles by local owner
    bundleList.stream().forEach(b -> {
        try {
            byte[] data = this.pulsar.getLocalZkCache().getZooKeeper().getData(ServiceUnitZkUtils.path(b), null,
                    new Stat());
            NamespaceEphemeralData node = ObjectMapperFactory.getThreadLocal().readValue(data,
                    NamespaceEphemeralData.class);
            Assert.assertEquals(node.getNativeUrl(), this.pulsar.getBrokerServiceUrl());
        } catch (Exception e) {
            fail("failed to setup ownership", e);
        }
    });

}

From source file:org.apache.bookkeeper.tests.integration.utils.DockerUtils.java

public static void dumpContainerLogToTarget(DockerClient docker, String containerId) {
    File output = new File(getTargetDirectory(containerId), "docker.log");
    try (FileOutputStream os = new FileOutputStream(output)) {
        CompletableFuture<Boolean> future = new CompletableFuture<>();
        docker.logContainerCmd(containerId).withStdOut(true).withStdErr(true).withTimestamps(true)
                .exec(new ResultCallback<Frame>() {
                    @Override//from  www  . j  ava  2  s .  c om
                    public void close() {
                    }

                    @Override
                    public void onStart(Closeable closeable) {
                    }

                    @Override
                    public void onNext(Frame object) {
                        try {
                            os.write(object.getPayload());
                        } catch (IOException e) {
                            onError(e);
                        }
                    }

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

                    @Override
                    public void onComplete() {
                        future.complete(true);
                    }
                });
        future.get();
    } catch (RuntimeException | ExecutionException | IOException e) {
        LOG.error("Error dumping log for {}", containerId, e);
    } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
        LOG.info("Interrupted dumping log from container {}", containerId, ie);
    }
}

From source file:de.urszeidler.ethereum.licencemanager1.deployer.ContractsDeployer.java

/**
 * Deploys a 'LicenseManager' on the blockchain and wrapps the contract proxy.
 *  /*from ww  w  .j a v  a  2 s . c o  m*/
 * @param sender the sender address
 * @param _paymentAddress 
 * @param _name 
 * @return the contract interface
 */
public DeployDuo<LicenseManager> createLicenseManager(EthAccount sender,
        org.adridadou.ethereum.propeller.values.EthAddress _paymentAddress, String _name)
        throws IOException, InterruptedException, ExecutionException {
    CompletableFuture<EthAddress> address = deployLicenseManager(sender, _paymentAddress, _name);
    return new EthereumInstance.DeployDuo<LicenseManager>(address.get(),
            createLicenseManagerProxy(sender, address.get()));
}