Example usage for com.google.common.util.concurrent ListenableFuture get

List of usage examples for com.google.common.util.concurrent ListenableFuture get

Introduction

In this page you can find the example usage for com.google.common.util.concurrent ListenableFuture get.

Prototype

V get() throws InterruptedException, ExecutionException;

Source Link

Document

Waits if necessary for the computation to complete, and then retrieves its result.

Usage

From source file:de.dfki.kiara.impl.ServiceMethodExecutorImpl.java

@Override
public ListenableFuture<Message> performLocalCall(InvocationEnvironment env, final Message requestMessage)
        throws IOException, IllegalAccessException, IllegalArgumentException, ExecutionException,
        InterruptedException {/*  www .  j  av  a2  s  . co m*/
    if (requestMessage.getMessageKind() != Message.Kind.REQUEST) {
        throw new IllegalArgumentException("message is not a request");
    }
    final String methodName = requestMessage.getMethodName();
    final Protocol protocol = requestMessage.getProtocol();
    final ServiceMethodBinder serviceMethodBinder = getServiceMethodBinder(methodName);

    Object result;
    boolean isException = false;

    if (serviceMethodBinder == null) {
        isException = true;
        result = new GenericRemoteException("unbound method '" + methodName + "'",
                GenericRemoteException.METHOD_NOT_FOUND);

        Message responseMessage = protocol.createResponseMessage(requestMessage,
                new Message.ResponseObject(result, isException));
        return Futures.immediateFuture(responseMessage);
    } else {
        final MethodEntry methodEntry = serviceMethodBinder.getMethodEntry();

        final List<Object> args = requestMessage.getRequestObject(methodEntry.serializationParamTypes).args;

        //methodEntry.hasFutureParams
        final int numArgs = args.size();
        for (int i = 0; i < numArgs; ++i) {
            if (methodEntry.isFutureParam.get(i)) {
                final Function<Object, Object> f = ((Function<Object, Object>) methodEntry.serializationToParamConverters[i]);
                args.set(i, f.apply(args.get(i)));
            } else if (methodEntry.specialParamTypes[i] != null && env != null) {
                final TypeToken<?> ptype = methodEntry.specialParamTypes[i];
                if (ptype.isAssignableFrom(de.dfki.kiara.ServerConnection.class)) {
                    args.set(i, env.getServiceConnection());
                }
            }
        }

        AsyncFunction<List<Object>, Message> ff = new AsyncFunction<List<Object>, Message>() {

            @Override
            public ListenableFuture<Message> apply(final List<Object> input) throws Exception {
                return Global.executor.submit(new Callable<Message>() {
                    @Override
                    public Message call() throws Exception {
                        Object result;
                        boolean isException = false;

                        try {
                            result = serviceMethodBinder.getBoundMethod()
                                    .invoke(serviceMethodBinder.getImplementedClass(), args.toArray());

                            if (methodEntry.futureParamOfReturnType != null) {
                                ListenableFuture<?> futureResult = (ListenableFuture<?>) (methodEntry.returnTypeConverter != null
                                        ? ((Function<Object, Object>) (methodEntry.returnTypeConverter))
                                                .apply(result)
                                        : result);
                                result = futureResult.get();
                            }

                        } catch (InvocationTargetException ex) {
                            isException = true;
                            result = ex.getTargetException();
                        }

                        Message responseMessage = protocol.createResponseMessage(requestMessage,
                                new Message.ResponseObject(result, isException));
                        return responseMessage;
                    }
                });
            }
        };
        return Futures.transform(Futures.immediateFuture(args), ff);
    }
}

From source file:org.apache.twill.internal.zookeeper.ReentrantDistributedLock.java

/**
 * Deletes the given node if the given future failed.
 *//*from  w ww .  j a  v  a2  s. com*/
private void deleteNodeOnFailure(final ListenableFuture<?> future, final String node) {
    future.addListener(new Runnable() {
        @Override
        public void run() {
            try {
                future.get();
            } catch (Exception e) {
                zkClient.delete(node);
            }
        }
    }, Threads.SAME_THREAD_EXECUTOR);
}

From source file:org.jenkinsci.plugins.workflow.support.concurrent.ListFuture.java

/**
 * Calls the get method of all dependency futures to work around a bug in
 * some ListenableFutures where the listeners aren't called until get() is
 * called./*from ww w  . jav a 2 s. co m*/
 */
private void callAllGets() throws InterruptedException {
    List<? extends ListenableFuture<? extends V>> oldFutures = futures;
    if (oldFutures != null && !isDone()) {
        for (ListenableFuture<? extends V> future : oldFutures) {
            // We wait for a little while for the future, but if it's not done,
            // we check that no other futures caused a cancellation or failure.
            // This can introduce a delay of up to 10ms in reporting an exception.
            while (!future.isDone()) {
                try {
                    future.get();
                } catch (Error e) {
                    throw e;
                } catch (InterruptedException e) {
                    throw e;
                } catch (Throwable e) {
                    // ExecutionException / CancellationException / RuntimeException
                    if (allMustSucceed) {
                        return;
                    } else {
                        continue;
                    }
                }
            }
        }
    }
}

From source file:com.facebook.buck.rules.modern.builders.RemoteExecutionStrategy.java

private ListenableFuture<Optional<BuildResult>> sendFailedEventOnException(
        ListenableFuture<Optional<BuildResult>> futureToBeWrapped, BuildTarget buildTarget,
        Digest actionDigest) {//from www.j  av a 2 s  .  c o m
    futureToBeWrapped.addListener(() -> {
        Optional<Throwable> exception = Optional.empty();
        try {
            futureToBeWrapped.get();
        } catch (InterruptedException e) {
            exception = Optional.of(e);
        } catch (ExecutionException e) {
            exception = Optional.of(e.getCause());
        }

        if (exception.isPresent()) {
            RemoteExecutionActionEvent.sendTerminalEvent(eventBus,
                    exception.get() instanceof InterruptedException ? State.ACTION_CANCELLED
                            : State.ACTION_FAILED,
                    buildTarget, Optional.of(actionDigest));
        }
    }, MoreExecutors.directExecutor());

    return futureToBeWrapped;
}

From source file:org.apache.usergrid.tools.WarehouseExport.java

private void copyToS3(String fileName) {

    String bucketName = (String) properties.get(BUCKET_PROPNAME);
    String accessId = (String) properties.get(ACCESS_ID_PROPNAME);
    String secretKey = (String) properties.get(SECRET_KEY_PROPNAME);

    Properties overrides = new Properties();
    overrides.setProperty("s3" + ".identity", accessId);
    overrides.setProperty("s3" + ".credential", secretKey);

    final Iterable<? extends Module> MODULES = ImmutableSet.of(new JavaUrlHttpCommandExecutorServiceModule(),
            new Log4JLoggingModule(), new NettyPayloadModule());

    BlobStoreContext context = ContextBuilder.newBuilder("s3").credentials(accessId, secretKey).modules(MODULES)
            .overrides(overrides).buildView(BlobStoreContext.class);

    // Create Container (the bucket in s3)
    try {//from   ww w  .  j  a  va2 s.c  o m
        AsyncBlobStore blobStore = context.getAsyncBlobStore(); // it can be changed to sync
        // BlobStore (returns false if it already exists)
        ListenableFuture<Boolean> container = blobStore.createContainerInLocation(null, bucketName);
        if (container.get()) {
            LOG.info("Created bucket " + bucketName);
        }
    } catch (Exception ex) {
        logger.error("Could not start binary service: {}", ex.getMessage());
        throw new RuntimeException(ex);
    }

    try {
        File file = new File(fileName);
        AsyncBlobStore blobStore = context.getAsyncBlobStore();
        BlobBuilder blobBuilder = blobStore.blobBuilder(file.getName()).payload(file).calculateMD5()
                .contentType("text/plain").contentLength(file.length());

        Blob blob = blobBuilder.build();

        ListenableFuture<String> futureETag = blobStore.putBlob(bucketName, blob,
                PutOptions.Builder.multipart());

        LOG.info("Uploaded file etag=" + futureETag.get());
    } catch (Exception e) {
        LOG.error("Error uploading to blob store", e);
    }
}

From source file:org.opendaylight.controller.sal.restconf.impl.BrokerFacade.java

private NormalizedNode<?, ?> readDataViaTransaction(final DOMDataReadTransaction transaction,
        final LogicalDatastoreType datastore, final YangInstanceIdentifier path) {
    LOG.trace("Read " + datastore.name() + " via Restconf: {}", path);
    final ListenableFuture<Optional<NormalizedNode<?, ?>>> listenableFuture = transaction.read(datastore, path);
    if (listenableFuture != null) {
        Optional<NormalizedNode<?, ?>> optional;
        try {//from   w  ww  .j  a va  2  s .c o m
            LOG.debug("Reading result data from transaction.");
            optional = listenableFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            LOG.warn("Exception by reading " + datastore.name() + " via Restconf: {}", path, e);
            throw new RestconfDocumentedException("Problem to get data from transaction.", e.getCause());

        }
        if (optional != null) {
            if (optional.isPresent()) {
                return optional.get();
            }
        }
    }
    return null;
}

From source file:com.facebook.buck.core.build.engine.impl.CachingBuildEngine.java

@Nullable
@Override//from   ww w.j a  va 2  s  .c  o m
public BuildResult getBuildRuleResult(BuildTarget buildTarget) throws ExecutionException, InterruptedException {
    ListenableFuture<BuildResult> result = results.get(buildTarget);
    if (result == null) {
        return null;
    }
    return result.get();
}

From source file:org.opendaylight.yangtools.restconf.client.RestListenableEventStreamContext.java

private ClientResponse extractWebSocketUriFromRpc(final String methodName)
        throws ExecutionException, InterruptedException, UnsupportedEncodingException {
    ListenableFuture<ClientResponse> clientFuture = restconfClient.get(
            ResourceUri.STREAM.getPath() + "/" + encodeUri(this.streamInfo.getIdentifier()),
            MediaType.APPLICATION_XML, new Function<ClientResponse, ClientResponse>() {

                @Override//from  w  w w.  j a v  a 2  s . c om
                public ClientResponse apply(final ClientResponse clientResponse) {
                    return clientResponse;
                }
            });

    return clientFuture.get();
}

From source file:org.voltdb.DefaultSnapshotDataTarget.java

public DefaultSnapshotDataTarget(final File file, final int hostId, final String clusterName,
        final String databaseName, final String tableName, final int numPartitions, final boolean isReplicated,
        final List<Integer> partitionIds, final VoltTable schemaTable, final long txnId, int version[])
        throws IOException {
    String hostname = CoreUtils.getHostnameOrAddress();
    m_file = file;//from   www. j  a  v  a2s  .  c om
    m_tableName = tableName;
    m_fos = new FileOutputStream(file);
    m_channel = m_fos.getChannel();
    final FastSerializer fs = new FastSerializer();
    fs.writeInt(0);//CRC
    fs.writeInt(0);//Header length placeholder
    fs.writeByte(1);//Indicate the snapshot was not completed, set to true for the CRC calculation, false later
    for (int ii = 0; ii < 4; ii++) {
        fs.writeInt(version[ii]);//version
    }
    JSONStringer stringer = new JSONStringer();
    byte jsonBytes[] = null;
    try {
        stringer.object();
        stringer.key("txnId").value(txnId);
        stringer.key("hostId").value(hostId);
        stringer.key("hostname").value(hostname);
        stringer.key("clusterName").value(clusterName);
        stringer.key("databaseName").value(databaseName);
        stringer.key("tableName").value(tableName.toUpperCase());
        stringer.key("isReplicated").value(isReplicated);
        stringer.key("isCompressed").value(true);
        if (!isReplicated) {
            stringer.key("partitionIds").array();
            for (int partitionId : partitionIds) {
                stringer.value(partitionId);
            }
            stringer.endArray();

            stringer.key("numPartitions").value(numPartitions);
        }
        stringer.endObject();
        String jsonString = stringer.toString();
        JSONObject jsonObj = new JSONObject(jsonString);
        jsonString = jsonObj.toString(4);
        jsonBytes = jsonString.getBytes("UTF-8");
    } catch (Exception e) {
        throw new IOException(e);
    }
    fs.writeInt(jsonBytes.length);
    fs.write(jsonBytes);

    final BBContainer container = fs.getBBContainer();
    container.b.position(4);
    container.b.putInt(container.b.remaining() - 4);
    container.b.position(0);

    final byte schemaBytes[] = schemaTable.getSchemaBytes();

    final CRC32 crc = new CRC32();
    ByteBuffer aggregateBuffer = ByteBuffer.allocate(container.b.remaining() + schemaBytes.length);
    aggregateBuffer.put(container.b);
    aggregateBuffer.put(schemaBytes);
    aggregateBuffer.flip();
    crc.update(aggregateBuffer.array(), 4, aggregateBuffer.capacity() - 4);

    final int crcValue = (int) crc.getValue();
    aggregateBuffer.putInt(crcValue).position(8);
    aggregateBuffer.put((byte) 0).position(0);//Haven't actually finished writing file

    if (m_simulateFullDiskWritingHeader) {
        m_writeException = new IOException("Disk full");
        m_writeFailed = true;
        m_fos.close();
        throw m_writeException;
    }

    /*
     * Be completely sure the write succeeded. If it didn't
     * the disk is probably full or the path is bunk etc.
     */
    m_acceptOneWrite = true;
    ListenableFuture<?> writeFuture = write(Callables.returning((BBContainer) DBBPool.wrapBB(aggregateBuffer)),
            false);
    try {
        writeFuture.get();
    } catch (InterruptedException e) {
        m_fos.close();
        throw new java.io.InterruptedIOException();
    } catch (ExecutionException e) {
        m_fos.close();
        throw m_writeException;
    }
    if (m_writeFailed) {
        m_fos.close();
        throw m_writeException;
    }

    ScheduledFuture<?> syncTask = null;
    syncTask = m_syncService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            int bytesSinceLastSync = 0;
            while ((bytesSinceLastSync = m_bytesWrittenSinceLastSync.getAndSet(0)) > 0) {
                try {
                    m_channel.force(false);
                } catch (IOException e) {
                    hostLog.error("Error syncing snapshot", e);
                }
                m_bytesAllowedBeforeSync.release(bytesSinceLastSync);
            }
        }
    }, 1, 1, TimeUnit.SECONDS);
    m_syncTask = syncTask;
}

From source file:org.apache.druid.server.coordinator.CostBalancerStrategy.java

/**
 * For assignment, we want to move to the lowest cost server that isn't already serving the segment.
 *
 * @param proposalSegment A DataSegment that we are proposing to move.
 * @param serverHolders   An iterable of ServerHolders for a particular tier.
 *
 * @return A ServerHolder with the new home for a segment.
 *//*from w  w  w  . j  a va2  s.co  m*/

protected Pair<Double, ServerHolder> chooseBestServer(final DataSegment proposalSegment,
        final Iterable<ServerHolder> serverHolders, final boolean includeCurrentServer) {
    Pair<Double, ServerHolder> bestServer = Pair.of(Double.POSITIVE_INFINITY, null);

    List<ListenableFuture<Pair<Double, ServerHolder>>> futures = Lists.newArrayList();

    for (final ServerHolder server : serverHolders) {
        futures.add(
                exec.submit(() -> Pair.of(computeCost(proposalSegment, server, includeCurrentServer), server)));
    }

    final ListenableFuture<List<Pair<Double, ServerHolder>>> resultsFuture = Futures.allAsList(futures);
    final List<Pair<Double, ServerHolder>> bestServers = new ArrayList<>();
    bestServers.add(bestServer);
    try {
        for (Pair<Double, ServerHolder> server : resultsFuture.get()) {
            if (server.lhs <= bestServers.get(0).lhs) {
                if (server.lhs < bestServers.get(0).lhs) {
                    bestServers.clear();
                }
                bestServers.add(server);
            }
        }

        // Randomly choose a server from the best servers
        bestServer = bestServers.get(ThreadLocalRandom.current().nextInt(bestServers.size()));
    } catch (Exception e) {
        log.makeAlert(e, "Cost Balancer Multithread strategy wasn't able to complete cost computation.").emit();
    }
    return bestServer;
}