Example usage for com.google.common.util.concurrent SettableFuture setException

List of usage examples for com.google.common.util.concurrent SettableFuture setException

Introduction

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

Prototype

@Override
    public boolean setException(Throwable throwable) 

Source Link

Usage

From source file:org.apache.omid.transaction.HBaseSyncPostCommitter.java

@Override
public ListenableFuture<Void> updateShadowCells(AbstractTransaction<? extends CellId> transaction) {

    SettableFuture<Void> updateSCFuture = SettableFuture.create();

    HBaseTransaction tx = HBaseTransactionManager.enforceHBaseTransactionAsParam(transaction);

    shadowCellsUpdateTimer.start();//  w  w  w.  j  a  v a 2s  .c o  m
    try {

        // Add shadow cells
        for (HBaseCellId cell : tx.getWriteSet()) {
            Put put = new Put(cell.getRow());
            put.add(cell.getFamily(),
                    CellUtils.addShadowCellSuffix(cell.getQualifier(), 0, cell.getQualifier().length),
                    tx.getStartTimestamp(), Bytes.toBytes(tx.getCommitTimestamp()));
            try {
                cell.getTable().put(put);
            } catch (IOException e) {
                LOG.warn("{}: Error inserting shadow cell {}", tx, cell, e);
                updateSCFuture.setException(
                        new TransactionManagerException(tx + ": Error inserting shadow cell " + cell, e));
            }
        }

        // Flush affected tables before returning to avoid loss of shadow cells updates when autoflush is disabled
        try {
            tx.flushTables();
            updateSCFuture.set(null);
        } catch (IOException e) {
            LOG.warn("{}: Error while flushing writes", tx, e);
            updateSCFuture
                    .setException(new TransactionManagerException(tx + ": Error while flushing writes", e));
        }

    } finally {
        shadowCellsUpdateTimer.stop();
    }

    return updateSCFuture;

}

From source file:com.yeetor.adb.AdbServer.java

private ListenableFuture<List<AdbForward>> executeGetForwardList() {
    final File adbFile = new File(AdbServer.server().adbPath);
    final SettableFuture future = SettableFuture.create();
    (new Thread(new Runnable() {
        public void run() {
            ProcessBuilder pb = new ProcessBuilder(new String[] { adbFile.getPath(), "forward", "--list" });
            pb.redirectErrorStream(true);
            Process p = null;// w w w  .  j ava2s  . c o m

            try {
                p = pb.start();
            } catch (IOException e) {
                future.setException(e);
                return;
            }

            StringBuilder sb = new StringBuilder();
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

            try {
                String line;
                try {
                    List<AdbForward> list = new ArrayList<AdbForward>();
                    while ((line = br.readLine()) != null) {
                        //64b2b4d9 tcp:555 localabstract:shit
                        AdbForward forward = new AdbForward(line);
                        if (forward.isForward()) {
                            list.add(forward);
                        }
                    }
                    future.set(list);
                    return;
                } catch (IOException ex) {
                    future.setException(ex);
                    return;
                }
            } finally {
                try {
                    br.close();
                } catch (IOException ex) {
                    future.setException(ex);
                }

            }
        }
    }, "Obtaining adb version")).start();
    return future;
}

From source file:org.opendaylight.netconf.topology.pipeline.tx.ProxyWriteOnlyTransaction.java

@Override
public CheckedFuture<Void, TransactionCommitFailedException> submit() {
    final Future<Void> submit = delegate.submit();
    final SettableFuture<Void> settableFuture = SettableFuture.create();
    final CheckedFuture<Void, TransactionCommitFailedException> checkedFuture = Futures
            .makeChecked(settableFuture, new Function<Exception, TransactionCommitFailedException>() {
                @Nullable/* ww w.j ava2 s  .com*/
                @Override
                public TransactionCommitFailedException apply(Exception input) {
                    return new TransactionCommitFailedException("Transaction commit failed", input);
                }
            });
    submit.onComplete(new OnComplete<Void>() {
        @Override
        public void onComplete(Throwable throwable, Void aVoid) throws Throwable {
            if (throwable == null) {
                settableFuture.set(aVoid);
            } else {
                settableFuture.setException(throwable);
            }
        }
    }, actorSystem.dispatcher());
    return checkedFuture;
}

From source file:com.microsoft.tooling.msservices.helpers.auth.AADManagerImpl.java

private <V> void requestWithAuthenticationResult(@NotNull UserInfo userInfo, @NotNull String resource,
        @NotNull RequestCallback<ListenableFuture<V>> requestCallback,
        @NotNull final SettableFuture<V> wrappedFuture) {
    try {/*from   ww  w.j  a  va 2s  .  c o m*/
        AuthenticationResult authResult = getAuthenticationResult(userInfo, resource);

        requestWithAuthenticationResult(requestCallback, wrappedFuture, authResult);
    } catch (AzureCmdException e) {
        wrappedFuture.setException(e);
    }
}

From source file:com.continuuity.weave.internal.kafka.client.SimpleKafkaClient.java

@Override
public PreparePublish preparePublish(final String topic, final Compression compression) {
    final Map<Integer, MessageSetEncoder> encoders = Maps.newHashMap();

    return new PreparePublish() {
        @Override//  w ww  .j a v a2 s. com
        public PreparePublish add(byte[] payload, Object partitionKey) {
            return add(ByteBuffer.wrap(payload), partitionKey);
        }

        @Override
        public PreparePublish add(ByteBuffer payload, Object partitionKey) {
            // TODO: Partition
            int partition = 0;

            MessageSetEncoder encoder = encoders.get(partition);
            if (encoder == null) {
                encoder = getEncoder(compression);
                encoders.put(partition, encoder);
            }
            encoder.add(ChannelBuffers.wrappedBuffer(payload));

            return this;
        }

        @Override
        public ListenableFuture<?> publish() {
            List<ListenableFuture<?>> futures = Lists.newArrayListWithCapacity(encoders.size());
            for (Map.Entry<Integer, MessageSetEncoder> entry : encoders.entrySet()) {
                futures.add(doPublish(topic, entry.getKey(), entry.getValue().finish()));
            }
            encoders.clear();
            return Futures.allAsList(futures);
        }

        private ListenableFuture<?> doPublish(String topic, int partition, ChannelBuffer messageSet) {
            final KafkaRequest request = KafkaRequest.createProduce(topic, partition, messageSet);
            final SettableFuture<?> result = SettableFuture.create();
            final ConnectionPool.ConnectResult connection = connectionPool
                    .connect(getTopicBroker(topic, partition).getAddress());

            connection.getChannelFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    try {
                        future.getChannel().write(request)
                                .addListener(getPublishChannelFutureListener(result, null, connection));
                    } catch (Exception e) {
                        result.setException(e);
                    }
                }
            });

            return result;
        }
    };
}

From source file:com.google.devtools.build.lib.remote.AbstractRemoteActionCache.java

/**
 * Download a file (that is not a directory). If the {@code content} is not given, the content is
 * fetched from the digest.//from ww w  .  j a  v a  2 s  .c  om
 */
public ListenableFuture<Void> downloadFile(Path path, Digest digest, @Nullable ByteString content)
        throws IOException {
    Preconditions.checkNotNull(path.getParentDirectory()).createDirectoryAndParents();
    if (digest.getSizeBytes() == 0) {
        // Handle empty file locally.
        FileSystemUtils.writeContent(path, new byte[0]);
        return COMPLETED_SUCCESS;
    }

    if (content != null && !content.isEmpty()) {
        try (OutputStream stream = path.getOutputStream()) {
            content.writeTo(stream);
        }
        return COMPLETED_SUCCESS;
    }

    OutputStream out = new LazyFileOutputStream(path);
    SettableFuture<Void> outerF = SettableFuture.create();
    ListenableFuture<Void> f = downloadBlob(digest, out);
    Futures.addCallback(f, new FutureCallback<Void>() {
        @Override
        public void onSuccess(Void result) {
            try {
                out.close();
                outerF.set(null);
            } catch (IOException e) {
                outerF.setException(e);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            outerF.setException(t);
            try {
                out.close();
            } catch (IOException e) {
                // Intentionally left empty. The download already failed, so we can ignore
                // the error on close().
            }
        }
    }, MoreExecutors.directExecutor());
    return outerF;
}

From source file:com.android.tools.idea.avdmanager.AvdManagerConnection.java

/**
 * Handle the {@link AccelerationErrorCode} found when attempting to start an AVD.
 * @param project/*w w  w .ja v a 2 s  .  c  o  m*/
 * @param error
 * @return a future with a device that was launched delayed, or null if startAvd should proceed to start the AVD.
 */
@Nullable
private ListenableFuture<IDevice> handleAccelerationError(@Nullable final Project project,
        @NotNull final AvdInfo info, @NotNull AccelerationErrorCode error) {
    switch (error) {
    case ALREADY_INSTALLED:
        return null;
    case TOOLS_UPDATE_REQUIRED:
    case PLATFORM_TOOLS_UPDATE_ADVISED:
    case SYSTEM_IMAGE_UPDATE_ADVISED:
        // Do not block emulator from running if we need updates (run with degradated performance):
        return null;
    case NO_EMULATOR_INSTALLED:
        // report this error below
        break;
    default:
        Abi abi = Abi.getEnum(info.getAbiType());
        boolean isAvdIntel = abi == Abi.X86 || abi == Abi.X86_64;
        if (!isAvdIntel) {
            // Do not block Arm and Mips emulators from running without an accelerator:
            return null;
        }
        // report all other errors
        break;
    }
    String accelerator = SystemInfo.isLinux ? "KVM" : "Intel HAXM";
    int result = Messages.showOkCancelDialog(project,
            String.format("%1$s is required to run this AVD.\n%2$s\n\n%3$s\n", accelerator, error.getProblem(),
                    error.getSolutionMessage()),
            error.getSolution().getDescription(), AllIcons.General.WarningDialog);
    if (result != Messages.OK || error.getSolution() == AccelerationErrorSolution.SolutionCode.NONE) {
        return Futures.immediateFailedFuture(new RuntimeException("Could not start AVD"));
    }
    final SettableFuture<ListenableFuture<IDevice>> future = SettableFuture.create();
    Runnable retry = () -> future.set(startAvd(project, info));
    Runnable cancel = () -> future.setException(new RuntimeException("Retry after fixing problem by hand"));
    Runnable action = AccelerationErrorSolution.getActionForFix(error, project, retry, cancel);
    ApplicationManager.getApplication().invokeLater(action);
    return Futures.dereference(future);
}

From source file:com.twitter.heron.statemgr.zookeeper.curator.CuratorStateManager.java

protected <M extends Message> ListenableFuture<M> getNodeData(WatchCallback watcher, String path,
        final Message.Builder builder) {
    final SettableFuture<M> future = SettableFuture.create();

    Watcher wc = ZkWatcherCallback.makeZkWatcher(watcher);

    BackgroundCallback cb = new BackgroundCallback() {
        @Override// ww w. ja v a 2  s .c o  m
        @SuppressWarnings("unchecked") // we don't know what M is until runtime
        public void processResult(CuratorFramework aClient, CuratorEvent event) throws Exception {
            byte[] data;
            if (event != null & (data = event.getData()) != null) {
                builder.mergeFrom(data);
                future.set((M) builder.build());
            } else {
                future.setException(new RuntimeException("Failed to fetch data from path: " + event.getPath()));
            }
        }
    };

    try {
        client.getData().usingWatcher(wc).inBackground(cb).forPath(path);

        // Suppress it since forPath() throws Exception
        // SUPPRESS CHECKSTYLE IllegalCatch
    } catch (Exception e) {
        future.setException(new RuntimeException("Could not getData", e));
    }

    return future;
}

From source file:org.opendaylight.netconf.topology.singleton.impl.ProxyDOMRpcService.java

@Nonnull
@Override/*  www .  j  a va 2 s  .  c om*/
public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type,
        @Nullable final NormalizedNode<?, ?> input) {
    LOG.trace("{}: Rpc operation invoked with schema type: {} and node: {}.", id, type, input);

    final NormalizedNodeMessage normalizedNodeMessage = new NormalizedNodeMessage(YangInstanceIdentifier.EMPTY,
            input);
    final Future<Object> scalaFuture = Patterns.ask(masterActorRef,
            new InvokeRpcMessage(new SchemaPathMessage(type), normalizedNodeMessage), actorResponseWaitTime);

    final SettableFuture<DOMRpcResult> settableFuture = SettableFuture.create();

    final CheckedFuture<DOMRpcResult, DOMRpcException> checkedFuture = Futures.makeChecked(settableFuture,
            new Function<Exception, DOMRpcException>() {

                @Nullable
                @Override
                public DOMRpcException apply(@Nullable final Exception exception) {
                    return new ClusteringRpcException(id + ": Exception during remote rpc invocation.",
                            exception);
                }
            });

    scalaFuture.onComplete(new OnComplete<Object>() {
        @Override
        public void onComplete(final Throwable failure, final Object success) throws Throwable {
            if (failure != null) {
                settableFuture.setException(failure);
                return;
            }
            if (success instanceof Throwable) {
                settableFuture.setException((Throwable) success);
                return;
            }
            if (success instanceof EmptyResultResponse || success == null) {
                settableFuture.set(null);
                return;
            }
            final Collection<RpcError> errors = ((InvokeRpcMessageReply) success).getRpcErrors();
            final NormalizedNodeMessage normalizedNodeMessageResult = ((InvokeRpcMessageReply) success)
                    .getNormalizedNodeMessage();
            final DOMRpcResult result;
            if (normalizedNodeMessageResult == null) {
                result = new DefaultDOMRpcResult(errors);
            } else {
                if (errors == null) {
                    result = new DefaultDOMRpcResult(normalizedNodeMessageResult.getNode());
                } else {
                    result = new DefaultDOMRpcResult(normalizedNodeMessageResult.getNode(), errors);
                }
            }
            settableFuture.set(result);
        }
    }, actorSystem.dispatcher());

    return checkedFuture;

}

From source file:com.microsoft.windowsazure.mobileservices.table.sync.MobileServiceSyncTable.java

/**
 * Insert an item into the local table and enqueue the operation to be
 * synchronized on context push.//  w  ww .j  a v a  2  s  .c o m
 *
 * @param item the item to be inserted
 * @return A ListenableFuture that is done when the item has been inserted,
 * returning a copy of the inserted item including id.
 */
public ListenableFuture<E> insert(E item) {
    final SettableFuture<E> future = SettableFuture.create();

    final JsonObject json = mClient.getGsonBuilder().create().toJsonTree(item).getAsJsonObject();

    JsonElement idJsonObject = json.get("id");

    if (idJsonObject != null && !idJsonObject.isJsonNull()) {
        String itemId = idJsonObject.getAsString();

        ListenableFuture<JsonObject> lookUpInternalFuture = mInternalTable.lookUp(itemId);

        Futures.addCallback(lookUpInternalFuture, new FutureCallback<JsonObject>() {
            @Override
            public void onFailure(Throwable throwable) {
                future.setException(throwable);
            }

            @Override
            public void onSuccess(JsonObject result) {

                if (result != null) {
                    future.set(parseResults(result).get(0));
                    return;
                }

                insertInternal(json, future);
            }
        });
    } else {
        insertInternal(json, future);
    }

    return future;
}