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:org.opendaylight.laas.impl.CentinelLaasStreamImpl.java

/**
 * @param change/*from   w  w  w. j ava2  s  .  c om*/
 * @param tx
 *            removes data from operational data store.
 */
private void removeFromOperational(AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> change,
        final ReadWriteTransaction tx) {
    DataObject deletedDataObjectFromConfig = null;
    Entry<InstanceIdentifier<?>, DataObject> configRemovedEntrySet = null;

    Set<InstanceIdentifier<?>> configRemovedPath = change.getRemovedPaths();

    for (Entry<InstanceIdentifier<?>, DataObject> dataObject : change.getOriginalData().entrySet()) {
        if (configRemovedPath.contains(dataObject.getKey())) {
            configRemovedEntrySet = dataObject;
        }
    }

    deletedDataObjectFromConfig = configRemovedEntrySet.getValue();
    if (deletedDataObjectFromConfig instanceof StreamList && configRemovedEntrySet != null) {
        StreamList streamConfigObj = (StreamList) deletedDataObjectFromConfig;

        // Read operational data store
        ListenableFuture<Optional<StreamRecord>> readFutureFromOperational = tx
                .read(LogicalDatastoreType.OPERATIONAL, streamRecordId);

        try {
            Optional<StreamRecord> streamRecord = readFutureFromOperational.get();
            List<StreamList> streamList = new ArrayList<StreamList>();

            if (streamRecord.isPresent()) {
                streamList = streamRecord.get().getStreamList();
            }
            java.util.Iterator<StreamList> streamListIterator = streamList.iterator();

            while (streamListIterator.hasNext()) {
                StreamList streamOperationalObj = streamListIterator.next();
                if (streamOperationalObj.getConfigID().equals(streamConfigObj.getConfigID())) {
                    if (restService.deleteFromOperationalStream(streamOperationalObj)) {
                        LOG.info("Deleted succesfully from Graylog");
                        tx.delete(LogicalDatastoreType.OPERATIONAL,
                                streamRecordId.child(StreamList.class, streamOperationalObj.getKey()));
                        tx.submit();
                    }
                }
            }
        }

        catch (Exception e) {
            LOG.error("Exception occured while getting record from operational data store", e);
        }
    }
}

From source file:co.cask.cdap.docgen.client.GenerateClientUsageExample.java

public void queryClient() throws Exception {
    // Construct the client used to interact with CDAP
    QueryClient queryClient = new QueryClient(clientConfig);

    // Perform an ad-hoc query using the Purchase example
    ListenableFuture<ExploreExecutionResult> resultFuture = queryClient.execute(Id.Namespace.DEFAULT,
            "SELECT * FROM dataset_history WHERE customer IN ('Alice','Bob')");
    ExploreExecutionResult results = resultFuture.get();

    // Fetch schema
    List<ColumnDesc> schema = results.getResultSchema();
    String[] header = new String[schema.size()];
    for (int i = 0; i < header.length; i++) {
        ColumnDesc column = schema.get(i);
        // Hive columns start at 1
        int index = column.getPosition() - 1;
        header[index] = column.getName() + ": " + column.getType();
    }/*  w w w .j  av a  2 s . c  om*/
}

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

private void checkItemDoesNotExists(final DOMDataReadWriteTransaction rWTransaction,
        final LogicalDatastoreType store, final YangInstanceIdentifier path) {
    final ListenableFuture<Boolean> futureDatastoreData = rWTransaction.exists(store, path);
    try {/*  w  w w  . j a  v  a2  s.  c  om*/
        if (futureDatastoreData.get()) {
            final String errMsg = "Post Configuration via Restconf was not executed because data already exists";
            LOG.trace("{}:{}", errMsg, path);
            rWTransaction.cancel();
            throw new RestconfDocumentedException("Data already exists for path: " + path, ErrorType.PROTOCOL,
                    ErrorTag.DATA_EXISTS);
        }
    } catch (InterruptedException | ExecutionException e) {
        LOG.warn("It wasn't possible to get data loaded from datastore at path {}", path, e);
    }

}

From source file:de.ii.xtraplatform.ogc.api.gml.parser.GMLParser.java

private void parseRoot(ListenableFuture<SMInputCursor> rootFuture, String ns, String ft)
        throws ExecutionException {

    QName featureType = new QName(ns, ft);

    SMInputCursor root = null;//from w w w . ja  v a 2s  .com
    try {

        analyzer.analyzeStart(rootFuture);

        root = rootFuture.get();
        if (root == null) {
            return;
        }

        LOGGER.debug("Parsing GetFeature response for '{}'", ft);

        // parse for exceptions
        if (root.getLocalName().equals(WFS.getWord(WFS.VOCABULARY.EXCEPTION_REPORT))) {
            parseException(root);
        }

        if (root.hasName(featureType)) {
            parseFeature(root);
        } else {
            SMInputCursor body = root.descendantElementCursor().advance();
            while (body.readerAccessible()) {
                if (body.hasName(featureType)) {
                    parseFeature(body);
                } else if (body.hasLocalName(ft)) {
                    if (analyzer.analyzeNamespaceRewrite(ns, body.getNsUri(), ft)) {
                        parseFeature(body);
                    }
                }
                body = body.advance();
            }
        }

        analyzer.analyzeEnd();
    } catch (GMLAnalyzeFailed ex) {
        LOGGER.debug("GMLParser recieved 'stop parsing' {}", ex.getMessage());
    } catch (XMLStreamException ex) {
        LOGGER.debug("Error parsing WFS GetFeature (IOException) {}", ex.getMessage());
    } catch (Exception ex) {
        LOGGER.debug("Error parsing WFS GetFeature (IOException) {}", ex.getMessage());
        ex.printStackTrace();
    } finally {
        if (root != null) {
            try {
                root.getStreamReader().closeCompletely();
            } catch (XMLStreamException ex) {
            }
        }
    }
}

From source file:org.springframework.cassandra.core.session.DefaultBridgedReactiveSession.java

@Override
public Mono<PreparedStatement> prepare(RegularStatement statement) {

    Assert.notNull(statement, "Statement must not be null");

    return Mono.defer(() -> {
        try {// w  w w . ja va 2  s .c  o  m
            if (logger.isDebugEnabled()) {
                logger.debug("Preparing Statement [{}]", statement);
            }

            CompletableFuture<PreparedStatement> future = new CompletableFuture<>();
            ListenableFuture<PreparedStatement> resultSetFuture = session.prepareAsync(statement);

            resultSetFuture.addListener(() -> {

                if (resultSetFuture.isDone()) {
                    try {
                        future.complete(resultSetFuture.get());
                    } catch (Exception e) {
                        future.completeExceptionally(e);
                    }
                }
            }, Runnable::run);

            return Mono.fromFuture(future);
        } catch (Exception e) {
            return Mono.error(e);
        }

    }).subscribeOn(scheduler);
}

From source file:com.google.idea.blaze.android.run.binary.instantrun.BlazeApkBuildStepInstantRun.java

private String getExecutionRoot(BlazeContext context, WorkspaceRoot workspaceRoot) {
    ListenableFuture<String> execRootFuture = BlazeInfo.getInstance().runBlazeInfo(context,
            Blaze.getBuildSystem(project), workspaceRoot, buildFlags, BlazeInfo.EXECUTION_ROOT_KEY);
    try {// w ww  . ja v a2s .  co  m
        return execRootFuture.get();
    } catch (InterruptedException e) {
        context.setCancelled();
    } catch (ExecutionException e) {
        LOG.error(e);
        context.setHasError();
    }
    return null;
}

From source file:com.microsoftopentechnologies.intellij.wizards.activityConfiguration.SummaryStep.java

private void updateO365Permission() {
    try {/*from  w w  w  .j ava2s.co m*/
        // update graph api
        final Office365Manager manager = Office365RestAPIManager.getManager();
        ListenableFuture<Application> future = manager.setO365PermissionsForApp(model.getOfficeApp(),
                model.getOfficePermissions());
        future.get();
    } catch (ExecutionException ex) {
        String message = "";

        if (ex.getCause() instanceof ODataException) {
            message = parseODataException((ODataException) ex.getCause());
        }

        if (!message.isEmpty()) {
            UIHelper.showException(
                    "An error occurred while trying to associate the Office 365 application - " + message,
                    ex.getCause(), "Error associating Office 365 application", false, false);
        } else {
            UIHelper.showException("An error occurred while trying to associate the Office 365 application",
                    ex.getCause(), "Error associating Office 365 application");
        }
    } catch (Throwable ex) {
        UIHelper.showException("An error occurred while trying to associate the Office 365 application", ex,
                "Error associating Office 365 application");
    }
}

From source file:com.google.caliper.runner.ExperimentingCaliperRun.java

@Override
public void run() throws InvalidBenchmarkException {
    ImmutableSet<Experiment> allExperiments = selector.selectExperiments();
    // TODO(lukes): move this standard-out handling into the ConsoleOutput class?
    stdout.println("Experiment selection: ");
    stdout.println("  Benchmark Methods:   "
            + FluentIterable.from(allExperiments).transform(new Function<Experiment, String>() {
                @Override/*from  w ww  . j a v a 2 s  .  c o  m*/
                public String apply(Experiment experiment) {
                    return experiment.instrumentation().benchmarkMethod().getName();
                }
            }).toSet());
    stdout.println("  Instruments:   "
            + FluentIterable.from(selector.instruments()).transform(new Function<Instrument, String>() {
                @Override
                public String apply(Instrument instrument) {
                    return instrument.name();
                }
            }));
    stdout.println("  User parameters:   " + selector.userParameters());
    stdout.println("  Virtual machines:  "
            + FluentIterable.from(selector.vms()).transform(new Function<VirtualMachine, String>() {
                @Override
                public String apply(VirtualMachine vm) {
                    return vm.name;
                }
            }));
    stdout.println("  Selection type:    " + selector.selectionType());
    stdout.println();

    if (allExperiments.isEmpty()) {
        throw new InvalidBenchmarkException(
                "There were no experiments to be performed for the class %s using the instruments %s",
                benchmarkClass.benchmarkClass().getSimpleName(), instruments);
    }

    stdout.format("This selection yields %s experiments.%n", allExperiments.size());
    stdout.flush();

    // always dry run first.
    ImmutableSet<Experiment> experimentsToRun = dryRun(allExperiments);
    if (experimentsToRun.size() != allExperiments.size()) {
        stdout.format("%d experiments were skipped.%n", allExperiments.size() - experimentsToRun.size());
    }

    if (experimentsToRun.isEmpty()) {
        throw new InvalidBenchmarkException("All experiments were skipped.");
    }

    if (options.dryRun()) {
        return;
    }

    stdout.flush();

    int totalTrials = experimentsToRun.size() * options.trialsPerScenario();
    Stopwatch stopwatch = Stopwatch.createStarted();
    List<ScheduledTrial> trials = createScheduledTrials(experimentsToRun, totalTrials);

    final ListeningExecutorService executor = executorProvider.get();
    List<ListenableFuture<TrialResult>> pendingTrials = scheduleTrials(trials, executor);
    ConsoleOutput output = new ConsoleOutput(stdout, totalTrials, stopwatch);
    try {
        // Process results as they complete.
        for (ListenableFuture<TrialResult> trialFuture : inCompletionOrder(pendingTrials)) {
            try {
                TrialResult result = trialFuture.get();
                output.processTrial(result);
                for (ResultProcessor resultProcessor : resultProcessors) {
                    resultProcessor.processTrial(result.getTrial());
                }
            } catch (ExecutionException e) {
                if (e.getCause() instanceof TrialFailureException) {
                    output.processFailedTrial((TrialFailureException) e.getCause());
                } else {
                    for (ListenableFuture<?> toCancel : pendingTrials) {
                        toCancel.cancel(true);
                    }
                    throw Throwables.propagate(e.getCause());
                }
            } catch (InterruptedException e) {
                // be responsive to interruption, cancel outstanding work and exit
                for (ListenableFuture<?> toCancel : pendingTrials) {
                    // N.B. TrialRunLoop is responsive to interruption.
                    toCancel.cancel(true);
                }
                throw new RuntimeException(e);
            }
        }
    } finally {
        executor.shutdown();
        output.close();
    }

    for (ResultProcessor resultProcessor : resultProcessors) {
        try {
            resultProcessor.close();
        } catch (IOException e) {
            logger.log(WARNING, "Could not close a result processor: " + resultProcessor, e);
        }
    }
}

From source file:com.google.devtools.build.remote.WatcherServer.java

@Override
public void watch(Request wr, StreamObserver<ChangeBatch> responseObserver) {
    final String opName = wr.getTarget();
    ListenableFuture<ActionResult> future = operationsCache.get(opName);
    if (future == null) {
        responseObserver.onError(StatusProto.toStatusRuntimeException(Status.newBuilder()
                .setCode(Code.NOT_FOUND.getNumber()).setMessage("Operation not found: " + opName).build()));
        return;/*from w  w  w. ja v a 2 s . c  o  m*/
    }

    future.addListener(() -> {
        try {
            try {
                ActionResult result = future.get();
                responseObserver.onNext(packExists(Operation.newBuilder().setName(opName).setDone(true)
                        .setResponse(Any.pack(ExecuteResponse.newBuilder().setResult(result).build()))));
                responseObserver.onCompleted();
            } catch (ExecutionException e) {
                Throwables.throwIfUnchecked(e.getCause());
                throw (Exception) e.getCause();
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Work failed: " + opName, e);
            responseObserver
                    .onNext(ChangeBatch.newBuilder()
                            .addChanges(Change.newBuilder().setState(Change.State.EXISTS)
                                    .setData(Any.pack(Operation.newBuilder().setName(opName)
                                            .setError(StatusUtils.internalErrorStatus(e)).build()))
                                    .build())
                            .build());
            responseObserver.onCompleted();
            if (e instanceof InterruptedException) {
                Thread.currentThread().interrupt();
            }
        } finally {
            operationsCache.remove(opName);
        }
    }, MoreExecutors.directExecutor());
}

From source file:org.apache.usergrid.services.assets.data.S3BinaryStore.java

@Override
public void write(final UUID appId, final Entity entity, InputStream inputStream) throws IOException {

    String uploadFileName = AssetUtils.buildAssetKey(appId, entity);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    long written = IOUtils.copyLarge(inputStream, baos, 0, FIVE_MB);
    byte[] data = baos.toByteArray();

    final Map<String, Object> fileMetadata = AssetUtils.getFileMetadata(entity);
    fileMetadata.put(AssetUtils.LAST_MODIFIED, System.currentTimeMillis());

    String mimeType = AssetMimeHandler.get().getMimeType(entity, data);

    if (written < FIVE_MB) { // total smaller than 5mb

        BlobStore blobStore = getContext().getBlobStore();
        BlobBuilder.PayloadBlobBuilder bb = blobStore.blobBuilder(uploadFileName).payload(data).calculateMD5()
                .contentType(mimeType);//from   w  ww .j  a v  a2  s  . c  om

        fileMetadata.put(AssetUtils.CONTENT_LENGTH, written);
        if (fileMetadata.get(AssetUtils.CONTENT_DISPOSITION) != null) {
            bb.contentDisposition(fileMetadata.get(AssetUtils.CONTENT_DISPOSITION).toString());
        }
        final Blob blob = bb.build();

        String md5sum = Hex.encodeHexString(blob.getMetadata().getContentMetadata().getContentMD5());
        fileMetadata.put(AssetUtils.CHECKSUM, md5sum);

        String eTag = blobStore.putBlob(bucketName, blob);
        fileMetadata.put(AssetUtils.E_TAG, eTag);
    } else { // bigger than 5mb... dump 5 mb tmp files and upload from them

        // todo: yes, AsyncBlobStore is deprecated, but there appears to be no replacement yet
        final AsyncBlobStore blobStore = getContext().getAsyncBlobStore();

        File tempFile = File.createTempFile(entity.getUuid().toString(), "tmp");
        tempFile.deleteOnExit();
        OutputStream os = null;
        try {
            os = new BufferedOutputStream(new FileOutputStream(tempFile.getAbsolutePath()));
            os.write(data);
            written += IOUtils.copyLarge(inputStream, os, 0, (FileUtils.ONE_GB * 5));
        } finally {
            IOUtils.closeQuietly(os);
        }

        BlobBuilder.PayloadBlobBuilder bb = blobStore.blobBuilder(uploadFileName).payload(tempFile)
                .calculateMD5().contentType(mimeType);

        fileMetadata.put(AssetUtils.CONTENT_LENGTH, written);
        if (fileMetadata.get(AssetUtils.CONTENT_DISPOSITION) != null) {
            bb.contentDisposition(fileMetadata.get(AssetUtils.CONTENT_DISPOSITION).toString());
        }
        final Blob blob = bb.build();

        final File finalTempFile = tempFile;
        final ListenableFuture<String> future = blobStore.putBlob(bucketName, blob,
                PutOptions.Builder.multipart());

        Runnable listener = new Runnable() {
            @Override
            public void run() {
                try {
                    String eTag = future.get();
                    fileMetadata.put(AssetUtils.E_TAG, eTag);
                    EntityManager em = emf.getEntityManager(appId);
                    em.update(entity);
                    finalTempFile.delete();
                } catch (Exception e) {
                    LOG.error("error uploading", e);
                }
                if (finalTempFile != null && finalTempFile.exists()) {
                    finalTempFile.delete();
                }
            }
        };
        future.addListener(listener, executor);
    }
}