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:com.xylocore.cassandra.query.TableScanQuery.java

public static void main(String[] args) {
    Cluster myCluster = null;/* ww  w  .j a va  2s  .co m*/

    try {
        myCluster = Cluster.builder().addContactPoint("127.0.0.1").withPort(9042).build();

        Session mySession = myCluster.connect("cirdan");

        List<Entity> myAllEntities = new ArrayList<Entity>();

        BiConsumer<Row, Entity> myEntityExtractor = (myRow, myEntity) -> {
            myEntity.setA(myRow.getInt("a"));
            myEntity.setB(myRow.getInt("b"));
            myEntity.setC(myRow.getInt("c"));
            myEntity.setD(myRow.getInt("d"));
        };

        Consumer<List<Entity>> myEntityProcessor = (myEntities) -> {
            myEntities.forEach(e -> {
                logger.debug("entity: {}", e);
            });

            myAllEntities.addAll(myEntities);
        };

        TableScanQueryExecutionContext<Entity> myExecutionContext = TableScanQueryExecutionContextBuilder
                .builder(Entity.class).entityCreator(() -> {
                    return new Entity();
                }).reuseEntity(false).entityExtractor(myEntityExtractor).entityProcessor(myEntityProcessor)
                .build();

        TableScanQuery<Entity> myQuery = TableScanQueryBuilder.<Entity>builder().session(mySession)
                .keyspace("cirdan").tableName("b").columns("a", "b", "c", "d")
                //                                         .column   ( "a"       )
                //                                         .column   ( "b"       )
                //                                         .column   ( "c"       )
                //                                         .column   ( "d"       )
                .build();

        CompletableFuture<Void> myFuture = myQuery.execute(myExecutionContext);
        myFuture.get();

        myAllEntities.forEach((e) -> System.err.println(e.toString()));
    } catch (Exception myException) {
        myException.printStackTrace();
    } finally {
        if (myCluster != null) {
            myCluster.close();
        }
    }
}

From source file:com.connio.sdk.example.ConnioAsyncClientExample.java

public static void main(String[] args) {
    try {/*www .j  ava  2  s.  c om*/

        // Initialises the context with api key credentials
        Connio.init("_key_671901158138828071", "31acec81b2414b03acf3d8c37ebdf305");

        // Create device profile
        final CompletableFuture<DeviceProfile> deviceProfile = DeviceProfile.create("device_profile_sdk")
                .executeAsync();

        // On device profile creation we compose property creation using it
        final CompletableFuture<Property> property = deviceProfile.thenCompose((dp) -> {
            return dp.addProperty("numericProperty1", Property.Type.Number).setAccess(Property.Access.Public)
                    .executeAsync();
        });

        // On device profile and property creation we compose method creation using them
        final CompletableFuture<Method> method = deviceProfile
                .thenCombine(property, (dp, p) -> new ImmutablePair<>(dp, p))
                .thenCompose((deviceProfileAndProperty) -> {
                    final DeviceProfile dp = deviceProfileAndProperty.getLeft();
                    final Property prop = deviceProfileAndProperty.getRight();

                    final MethodImpl implementation = new MethodImpl.Builder("return value;",
                            MethodImpl.ExecType.Javascript).build();
                    return dp.addMethod("getter", Method.Access.Public, implementation).setInputId(prop.getId())
                            .executeAsync();
                });

        // On device profile and method creation we will create the device
        final CompletableFuture<Device> device = deviceProfile.thenCombine(method, (dp, m) -> dp)
                .thenCompose((dp) -> dp.addDevice().setStatus(Device.Status.Debug).executeAsync());

        // Write three data points
        device.thenCombine(property,
                (d, p) -> d.writeData(p, new DataFeed(new DataPoint.Builder(16.0).build())).executeAsync());
        device.thenCombine(property,
                (d, p) -> d.writeData(p, new DataFeed(new DataPoint.Builder(17.0).build())).executeAsync());
        device.thenCombine(property,
                (d, p) -> d.writeData(p, new DataFeed(new DataPoint.Builder(18.0).build())).executeAsync());

        // Retrieve getter method value
        CompletableFuture<Object> methodValue = device.thenCombine(method, (d, m) -> new ImmutablePair<>(d, m))
                .thenCompose((deviceAndMethod) -> {
                    final Device d = deviceAndMethod.getLeft();
                    final Method m = deviceAndMethod.getRight();

                    return d.readMethod(m).executeAsync();
                });

        // Get device state
        CompletableFuture<Optional<DeviceState>> deviceState = device.thenCompose(d -> d.state().fetchAsync());

        // Until this point there's no blocking whatsoever. Now we block until we get futures values to print
        // some information
        System.out.println("Device profile id: " + deviceProfile.get().getId());
        System.out.println("Property id: " + property.get().getId());
        System.out.println("Method id: " + method.get().getId());
        System.out.println("Device id: " + device.get().getId());
        System.out.println("Getter method value: " + methodValue.get());
        System.out.println("Device state: " + deviceState.get().get());

        Connio.terminate();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.apache.servicecomb.foundation.vertx.VertxUtils.java

public static void blockCloseVertxByName(String name) {
    CompletableFuture<Void> future = closeVertxByName(name);
    try {//  w  ww.  j  av a 2s  . c  o m
        future.get();
    } catch (Throwable e) {
        LOGGER.error("Failed to close vertx {}.", name, e);
    }
}

From source file:org.apache.bookkeeper.stream.server.StorageServer.java

static int doMain(String[] args) {
    // register thread uncaught exception handler
    Thread.setDefaultUncaughtExceptionHandler((thread, exception) -> log
            .error("Uncaught exception in thread {}: {}", thread.getName(), exception.getMessage()));

    // parse the commandline
    ServerArguments arguments = new ServerArguments();
    JCommander jCommander = new JCommander(arguments);
    jCommander.setProgramName("StorageServer");
    jCommander.parse(args);//  ww  w .j a va 2  s .c om

    if (arguments.help) {
        jCommander.usage();
        return ExitCode.INVALID_CONF.code();
    }

    CompositeConfiguration conf = new CompositeConfiguration();
    if (null != arguments.serverConfigFile) {
        loadConfFile(conf, arguments.serverConfigFile);
    }

    int grpcPort = arguments.port;

    LifecycleComponent storageServer;
    try {
        storageServer = buildStorageServer(conf, grpcPort);
    } catch (ConfigurationException e) {
        log.error("Invalid storage configuration", e);
        return ExitCode.INVALID_CONF.code();
    } catch (UnknownHostException e) {
        log.error("Unknonw host name", e);
        return ExitCode.UNKNOWN_HOSTNAME.code();
    }

    CompletableFuture<Void> liveFuture = ComponentStarter.startComponent(storageServer);
    try {
        liveFuture.get();
    } catch (InterruptedException e) {
        // the server is interrupted.
        Thread.currentThread().interrupt();
        log.info("Storage server is interrupted. Exiting ...");
    } catch (ExecutionException e) {
        log.info("Storage server is exiting ...");
    }
    return ExitCode.OK.code();
}

From source file:msuresh.raftdistdb.RaftCluster.java

private static JSONArray CreatePartitionCluster(int numReplicas)
        throws ExecutionException, InterruptedException {
    JSONArray arr = new JSONArray();
    JSONObject[] lis = new JSONObject[numReplicas];
    List<Address> members = new ArrayList<>();
    SetupServerAddress(numReplicas, lis, members, arr);
    CompletableFuture<Integer> future = new CompletableFuture<>();
    List<CopycatServer> atomixList = new ArrayList<>();
    for (Address a : members) {
        ServerSetup s = new ServerSetup(members, a, atomixList, future);
        s.start();/*from  ww w .  j  a  v  a 2s .  c  om*/
    }
    future.get();
    return arr;
}

From source file:msuresh.raftdistdb.TestAtomix.java

public static void createCluster(String test, int nodesInCluster)
        throws InterruptedException, ExecutionException {
    InitPortNumber();//from   w  ww. ja  v a 2  s  . c o m
    try {
        List<Address> members = new ArrayList<>();
        for (int i = 0; i < nodesInCluster; i++) {
            Address addr = new Address("localhost", portId++);
            members.add(addr);
        }
        CompletableFuture<Integer> future = new CompletableFuture<>();
        Map atomixList;
        atomixList = new HashMap();
        for (Address a : members) {
            ServerSetup s = new ServerSetup(members, a, atomixList, future);
            s.start();
        }
        future.get();
        UpdatePortNumber();

        if (test.compareTo("leaderFailure") == 0) {
            for (Object s : atomixList.keySet()) {
                LeaderReelection l = new LeaderReelection((Address) s, (CopycatServer) atomixList.get(s), true);
                l.start();
            }
            Thread.sleep(20000);
            //                for(Object s : atomixList.keySet()){
            //                    CopycatServer cs = (CopycatServer)atomixList.get(s);
            //                    while(cs.isOpen())
            //                        Thread.sleep(1000);
            //                    System.out.println("printing" + cs.toString());
            //                }
            System.out.println(
                    "Leader Reelection test is done. Program might not close properly due to a bug in Atomix. Follow manual instructions to close the process and sockets.");
        } else if (test.compareTo("replicationTest") == 0) {
            CopycatClient client = CopycatClient.builder(members).withTransport(new NettyTransport()).build();
            client.open().join();
            System.out.println("Adding a testkey with testval to the cluster ..");
            client.submit(new PutCommand("testkey1", "testval")).get();
            List<LeaderReelection> reelectionList = new ArrayList<>();
            System.out.println("Crashing leader to trigger a reelection .. ");
            for (Object s : atomixList.keySet()) {

                LeaderReelection l = new LeaderReelection((Address) s, (CopycatServer) atomixList.get(s),
                        false);
                l.start();
                reelectionList.add(l);
            }

            //                for(LeaderReelection l : reelectionList){
            //                    l.future.get();
            //                    
            //                }
            //                client = CopycatClient.builder(members)
            //                        .withTransport(new NettyTransport())
            //                        .build();
            //                client.open().join();
            System.out.println(" Polling the cluster for testkey ..");
            Object str = client.submit(new GetQuery("testkey1")).get();
            System.out.println("The cluster returned (which should be 'testval'):" + (String) str);
            System.out.println("closing open servers..");
            for (Object s : atomixList.keySet()) {
                CopycatServer cs = (CopycatServer) atomixList.get(s);

                if (cs.isOpen())
                    cs.close();

            }
        }
    } catch (Exception ex) {
        System.out.println(ex.toString());
    }

}

From source file:eu.interedition.collatex.tools.CollationServer.java

private static String detectDotPath() {
    for (String detectionCommand : new String[] { "which dot", "where dot.exe" }) {
        try {/*from   w ww.j a v a2s  . c o  m*/

            final Process process = Runtime.getRuntime().exec(detectionCommand);
            try (BufferedReader processReader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), Charset.defaultCharset()))) {
                final CompletableFuture<Optional<String>> path = CompletableFuture
                        .supplyAsync(() -> processReader.lines().map(String::trim)
                                .filter(l -> l.toLowerCase().contains("dot")).findFirst());
                process.waitFor();
                final String dotPath = path.get().get();
                LOG.info(() -> "Detected GraphViz' dot at '" + dotPath + "'");
                return dotPath;
            }
        } catch (Throwable t) {
            LOG.log(Level.FINE, detectionCommand, t);
        }
    }
    return null;
}

From source file:org.apache.bookkeeper.mledger.offload.OffloaderUtils.java

/**
 * Extract the Pulsar offloader class from a offloader archive.
 *
 * @param narPath nar package path/*from w  w  w.  j a  v a  2  s. c  o m*/
 * @return the offloader class name
 * @throws IOException when fail to retrieve the pulsar offloader class
 */
static Pair<NarClassLoader, LedgerOffloaderFactory> getOffloaderFactory(String narPath) throws IOException {
    NarClassLoader ncl = NarClassLoader.getFromArchive(new File(narPath), Collections.emptySet());
    String configStr = ncl.getServiceDefinition(PULSAR_OFFLOADER_SERVICE_NAME);

    OffloaderDefinition conf = ObjectMapperFactory.getThreadLocalYaml().readValue(configStr,
            OffloaderDefinition.class);
    if (StringUtils.isEmpty(conf.getOffloaderFactoryClass())) {
        throw new IOException(String.format(
                "The '%s' offloader does not provide an offloader factory implementation", conf.getName()));
    }

    try {
        // Try to load offloader factory class and check it implements Offloader interface
        Class factoryClass = ncl.loadClass(conf.getOffloaderFactoryClass());
        CompletableFuture<LedgerOffloaderFactory> loadFuture = new CompletableFuture<>();
        Thread loadingThread = new Thread(() -> {
            Thread.currentThread().setContextClassLoader(ncl);

            log.info("Loading offloader factory {} using class loader {}", factoryClass, ncl);
            try {
                Object offloader = factoryClass.newInstance();
                if (!(offloader instanceof LedgerOffloaderFactory)) {
                    throw new IOException("Class " + conf.getOffloaderFactoryClass()
                            + " does not implement interface " + LedgerOffloaderFactory.class.getName());
                }
                loadFuture.complete((LedgerOffloaderFactory) offloader);
            } catch (Throwable t) {
                loadFuture.completeExceptionally(t);
            }
        }, "load-factory-" + factoryClass);
        try {
            loadingThread.start();
            return Pair.of(ncl, loadFuture.get());
        } finally {
            loadingThread.join();
        }
    } catch (Throwable t) {
        rethrowIOException(t);
    }
    return null;
}

From source file:org.eclipse.winery.accountability.AccountabilityManagerImplIntegrationTest.java

@Test
void getHistory() throws Exception {
    String processId = "{http://plain.winery.opentosca.org/servicetemplates}ServiceTemplateWithAllReqCapVariants";

    CompletableFuture<List<ModelProvenanceElement>> history = this.provenance.getHistory(processId);
    List<ModelProvenanceElement> historyElements = history.get();

    assertTrue(historyElements.size() == 2);// we manually added 2

    historyElements/*  w  ww.j ava  2s.com*/
            .forEach(historyElement -> assertTrue(StringUtils.isNotEmpty(historyElement.getAuthorAddress())));
}

From source file:org.eclipse.winery.accountability.AccountabilityManagerImplIntegrationTest.java

@Test
void getHistoryWithoutAuthenticationData() throws Exception {
    String processId = "SomeProcessIdForIvalidTestingPurposeOnly";
    String fileId = "not needed in this test";

    CompletableFuture<List<FileProvenanceElement>> history = this.provenance.getHistory(processId, fileId);
    List<FileProvenanceElement> historyElements = history.get();
    FileProvenanceElement element = historyElements.get(0);

    assertFalse(element.isAuthorized());
    assertEquals("no authorization data stored in the blockchain", element.getAuthorAddress());
}