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.opendaylight.controller.cluster.datastore.ThreePhaseCommitCohortProxy.java

private ListenableFuture<Void> voidOperation(final String operationName, final MessageSupplier messageSupplier,
        final Class<?> expectedResponseClass, final boolean propagateException,
        final OperationCallback callback) {
    LOG.debug("Tx {} {}", transactionId, operationName);

    final SettableFuture<Void> returnFuture = SettableFuture.create();

    // The cohort actor list should already be built at this point by the canCommit phase but,
    // if not for some reason, we'll try to build it here.

    ListenableFuture<Void> future = resolveCohorts();
    if (successfulFuture(future)) {
        finishVoidOperation(operationName, messageSupplier, expectedResponseClass, propagateException,
                returnFuture, callback);
    } else {/*from  ww  w .  j  a  va 2  s  .co  m*/
        Futures.addCallback(future, new FutureCallback<Void>() {
            @Override
            public void onSuccess(Void notUsed) {
                finishVoidOperation(operationName, messageSupplier, expectedResponseClass, propagateException,
                        returnFuture, callback);
            }

            @Override
            public void onFailure(Throwable failure) {
                LOG.debug("Tx {}: a {} cohort path Future failed: {}", transactionId, operationName, failure);

                if (propagateException) {
                    returnFuture.setException(failure);
                } else {
                    returnFuture.set(null);
                }
            }
        });
    }

    return returnFuture;
}

From source file:org.opendaylight.netconf.topology.util.BaseTopologyManager.java

@Override
public ListenableFuture<Node> onNodeUpdated(final NodeId nodeId, final Node node) {
    LOG.debug("TopologyManager({}) onNodeUpdated received, nodeid: {}", id, nodeId.getValue());

    // Master needs to trigger onNodeUpdated on peers and combine results
    if (isMaster) {
        // first cleanup old node
        final ListenableFuture<Void> deleteFuture = onNodeDeleted(nodeId);
        final SettableFuture<Node> createFuture = SettableFuture.create();
        final TopologyManager selfProxy = TypedActor.self();
        final ActorContext context = TypedActor.context();
        Futures.addCallback(deleteFuture, new FutureCallback<Void>() {
            @Override/*from  w  w w  . j av  a 2s  .c  o  m*/
            public void onSuccess(Void result) {
                LOG.warn("Delete part of update succesfull, triggering create");
                // trigger create on all nodes
                Futures.addCallback(selfProxy.onNodeCreated(nodeId, node), new FutureCallback<Node>() {
                    @Override
                    public void onSuccess(Node result) {
                        createFuture.set(result);
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        createFuture.setException(t);
                    }
                }, context.dispatcher());
            }

            @Override
            public void onFailure(Throwable t) {
                LOG.warn("Delete part of update failed, {}", t);
            }
        }, context.dispatcher());
        return createFuture;
    }

    // Trigger update on this slave
    return delegateTopologyHandler.onNodeUpdated(nodeId, node);
}

From source file:com.android.camera.one.v2.initialization.CaptureSessionCreator.java

/**
 * Asynchronously creates a capture session, returning a future to it.
 *
 * @param surfaces The set of output surfaces for the camera capture
 *            session.//www  .j  av  a  2  s.  c o  m
 * @return A Future for the camera capture session.
 */
public ListenableFuture<CameraCaptureSessionProxy> createCaptureSession(List<Surface> surfaces) {
    final SettableFuture<CameraCaptureSessionProxy> sessionFuture = SettableFuture.create();
    try {
        mDevice.createCaptureSession(surfaces, new CameraCaptureSessionProxy.StateCallback() {
            @Override
            public void onActive(CameraCaptureSessionProxy session) {
                // Ignore.
            }

            @Override
            public void onConfigureFailed(CameraCaptureSessionProxy session) {
                sessionFuture.cancel(true);
                session.close();
            }

            @Override
            public void onConfigured(CameraCaptureSessionProxy session) {
                boolean valueSet = sessionFuture.set(session);
                if (!valueSet) {
                    // If the future was already marked with cancellation or
                    // an exception, close the session.
                    session.close();
                }
            }

            @Override
            public void onReady(CameraCaptureSessionProxy session) {
                // Ignore.
            }

            @Override
            public void onClosed(CameraCaptureSessionProxy session) {
                sessionFuture.cancel(true);
                session.close();
            }
        }, mCameraHandler);
    } catch (CameraAccessException e) {
        sessionFuture.setException(e);
    }
    return sessionFuture;
}

From source file:com.navercorp.redis.cluster.connection.RedisConnectionAsync.java

/**
 * Send command./*from   www .java 2 s . com*/
 *
 * @param cmd  the cmd
 * @param args the args
 * @return the redis connection
 */
public void sendCommand(final Command cmd, final byte[]... args) {
    log.trace("[RedisConnection] Command={} {}", cmd.name(), toStringArgs(args));
    RedisProtocol.sendCommand(outputStream, cmd, args);
    try {
        outputStream.flush();
    } catch (IOException e) {
        throw new JedisConnectionException(e);
    }

    final SettableFuture<byte[]> future = SettableFuture.create();

    byte[] cmdBytes = new byte[outputBuf.readableBytes()];
    outputBuf.readBytes(cmdBytes);
    outputBuf.discardSomeReadBytes();

    vc.request(cmdBytes, activeTimeout, new RequestCallback() {
        @Override
        public void onResponse(byte[] response, StatusCode statusCode) {
            switch (statusCode) {
            case OK:
                future.set(response);
                break;

            case CONNECTION_ERROR:
                future.setException(new GatewayException("Connection error"));
                break;
            case INTERNAL_ERROR:
                future.setException(new GatewayException("Internal error"));
                break;
            case NO_AVAILABLE_CONNECTION:
                future.setException(new GatewayException("no available connection"));
                break;
            case SHUTDOWN:
                future.setException(new GatewayException("already closed"));
                break;
            case TIMEOUT:
                future.setException(new GatewayException("Timeout"));
                break;
            }
        }
    });

    pipelinedFutures.add(future);
}

From source file:com.microsoft.office365.snippetapp.helpers.AuthenticationController.java

/**
 * Description: Calls AuthenticationContext.acquireToken(...) once to initialize with
 * user's credentials and avoid interactive prompt on later calls.
 * If all tokens expire, app must call initialize() again to prompt user interactively and
 * set up authentication context./* ww  w .  ja va 2 s .  c  o m*/
 *
 * @return A signal to wait on before continuing execution.
 */
public SettableFuture<AuthenticationResult> initialize() {

    final SettableFuture<AuthenticationResult> result = SettableFuture.create();

    if (verifyAuthenticationContext()) {
        AuthenticationContext authContext = getAuthenticationContext();
        if (authContext != null)
            authContext.acquireToken(this.contextActivity, this.resourceId, Constants.CLIENT_ID,
                    Constants.REDIRECT_URI, PromptBehavior.Auto,
                    new AuthenticationCallback<AuthenticationResult>() {

                        @Override
                        public void onSuccess(final AuthenticationResult authenticationResult) {

                            if (authenticationResult != null
                                    && authenticationResult.getStatus() == AuthenticationStatus.Succeeded) {
                                dependencyResolver = new ADALDependencyResolver(getAuthenticationContext(),
                                        resourceId, Constants.CLIENT_ID);
                                O365ServicesManager.initialize(authenticationResult.getTenantId());
                                result.set(authenticationResult);
                            }
                        }

                        @Override
                        public void onError(Exception t) {
                            result.setException(t);
                        }
                    });
        else
            result.setException(
                    new Throwable("Auth context verification failed. Did you set a context activity?"));
    } else {
        result.setException(new Throwable("Auth context verification failed. Did you set a context activity?"));
    }
    return result;
}

From source file:io.datakernel.service.ServiceGraph.java

private ListenableFuture<LongestPath> combineDependenciesFutures(List<ListenableFuture<LongestPath>> futures,
        Executor executor) {/*from   ww w.  j a  va2  s .  c o m*/
    if (futures.size() == 0) {
        return Futures.immediateFuture(null);
    }
    if (futures.size() == 1) {
        return futures.get(0);
    }

    final SettableFuture<LongestPath> settableFuture = SettableFuture.create();
    final AtomicInteger atomicInteger = new AtomicInteger(futures.size());
    final AtomicReference<LongestPath> bestPath = new AtomicReference<>();
    final AtomicReference<Throwable> exception = new AtomicReference<>();
    for (final ListenableFuture<LongestPath> future : futures) {
        future.addListener(new Runnable() {
            @Override
            public void run() {
                try {
                    LongestPath path = future.get();
                    if (bestPath.get() == null || (path != null && path.totalTime > bestPath.get().totalTime)) {
                        bestPath.set(path);
                    }
                } catch (InterruptedException | ExecutionException e) {
                    if (exception.get() == null) {
                        exception.set(getRootCause(e));
                    }
                }
                if (atomicInteger.decrementAndGet() == 0) {
                    if (exception.get() != null) {
                        settableFuture.setException(exception.get());
                    } else {
                        settableFuture.set(bestPath.get());
                    }
                }
            }
        }, executor);
    }
    return settableFuture;
}

From source file:ch.vorburger.osgi.builder.internal.SourceInstallServiceImpl.java

@Override
public ListenableFuture<Bundle> installSourceBundle(File projectDirectoryOrBundleJAR) {
    SettableFuture<Bundle> installFuture = SettableFuture.create();
    BuildServiceSingleFileOutputListener listener = singleProducedFile -> {
        try (InputStream inputStream = new FileInputStream(singleProducedFile)) {
            String location = getBundleLocation(projectDirectoryOrBundleJAR);
            Bundle bundle = bundleContext.getBundle(location);
            if (bundle == null) {
                LOG.info("Installing Bundle from {}", location);
                bundle = bundleContext.installBundle(location, inputStream);
                bundle.start();//  w w w. j  ava2s . c o m
            } else {
                LOG.info("Updating Bundle from {}", location);
                bundle.update(inputStream);
                // We (possibly "re")-start here, because it's possible that
                // an initial (or previous) start() failed due to some bug in the bundle
                // and that could have meanwhile be fixed, but OSGi won't re-try starting
                // a bundle an update if we don't tell it to...
                bundle.start();
            }
            installFuture.set(bundle);
        } catch (BundleException | IOException e) {
            LOG.error("Problem reading/installing bundle JAR: {}", singleProducedFile, e);
            installFuture.setException(e);
        }
    };

    ListenableFuture<Void> buildFuture;
    if (new File(projectDirectoryOrBundleJAR, "pom.xml").exists()) {
        LOG.info("Found a POM in directory, will continously build with Maven: {}",
                projectDirectoryOrBundleJAR);
        buildFuture = mavenBuildService.buildContinously(projectDirectoryOrBundleJAR, "install", listener);
    } else if (projectDirectoryOrBundleJAR.isDirectory()) {
        LOG.info("Found directory (but no POM), will continously build with Gradle: {}",
                projectDirectoryOrBundleJAR);
        buildFuture = gradleBuildService.buildContinously(projectDirectoryOrBundleJAR, "build", listener);
    } else if (projectDirectoryOrBundleJAR.isFile() && projectDirectoryOrBundleJAR.getName().endsWith(".jar")) {
        LOG.info("Found JAR, will install and update on update: {}", projectDirectoryOrBundleJAR);
        // The JAR is already ready now, and can be started by caller:
        try {
            // NB: The default quietPeriod of 100ms is often not enough while Gradle updates the JAR and leads to ZipException, so 500ms:
            bundleFileWatcher = new FileWatcherBuilder().path(projectDirectoryOrBundleJAR).quietPeriodInMS(500)
                    .listener((path, changeKind) -> {
                        switch (changeKind) {
                        case MODIFIED:
                            // NB: FileWatcherBuilder invoked the listener once on start, and then on subsequent changes
                            listener.buildSucceeded(projectDirectoryOrBundleJAR);
                            break;

                        case DELETED:
                            String location = getBundleLocation(projectDirectoryOrBundleJAR);
                            LOG.info("Uninstalling Bundle from {}", location);
                            bundleContext.getBundle(location).uninstall();
                            break;

                        default:
                            LOG.error("Unsupported file watcher change kind, ignored: {}", changeKind);
                            break;
                        }

                        System.out.println(changeKind.name() + " " + path.toString());
                    }).build();
            buildFuture = Futures.immediateFuture(null);
        } catch (IOException e) {
            buildFuture = Futures.immediateFailedFuture(e);
        }
        // But we make sure than upon changes it gets reloaded:
        // TODO!!!!
    } else {
        buildFuture = Futures.immediateFailedFuture(
                new IllegalArgumentException("Neither a directory (with or w.o. pom.xml) nor a JAR, "
                        + "how I am supposed to (build and) install this as an OSGi bundle: "
                        + projectDirectoryOrBundleJAR));
    }

    Futures.addCallback(buildFuture, new FutureCallback<Void>() {

        @Override
        public void onFailure(Throwable throwable) {
            // If this happens, then the listener above will never get invoked
            // because the (first, as it's continous) build failed before, so:
            installFuture.setException(throwable);
        }

        @Override
        public void onSuccess(Void nothing) {
        }
    });
    return installFuture;
}

From source file:com.yahoo.yqlplus.engine.internal.java.runtime.TimeoutHandler.java

public <T> ListenableFuture<T> withTimeoutAsync(final Callable<ListenableFuture<T>> callable,
        final Timeout tracker, ListeningExecutorService executor) {
    final SettableFuture<T> result = SettableFuture.create();
    final long remaining = tracker.remainingTicks();
    final TimeUnit units = tracker.getTickUnits();
    final ListenableFuture<ListenableFuture<T>> source = executor.submit(callable);
    final ScheduledFuture<?> scheduledFuture = timers.schedule(new IntermediateTask<>(result, remaining, units),
            remaining, units);// w  ww  .  ja v  a  2s  .com
    Futures.addCallback(source, scoper.continueScope(new FutureCallback<ListenableFuture<T>>() {
        @Override
        public void onSuccess(ListenableFuture<T> next) {
            scheduledFuture.cancel(false);
            try {
                long remaining = tracker.verify();
                final ScheduledFuture<?> remainingFuture = timers
                        .schedule(new TimeoutTask<>(next, result, remaining, units), remaining, units);
                Futures.addCallback(next, scoper.continueScope(new FutureCallback<T>() {
                    @Override
                    public void onSuccess(T out) {
                        remainingFuture.cancel(false);
                        result.set(out);
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        remainingFuture.cancel(false);
                        result.setException(t);
                    }
                }));
            } catch (TimeoutException e) {
                next.cancel(true);
                result.setException(e);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            scheduledFuture.cancel(false);
            result.setException(t);
        }
    }));
    return scoper.scopeCallbacks(result);
}

From source file:utils.teamcity.wallt.controller.api.ApiController.java

@Override
public ListenableFuture<Void> loadProjectList() {
    if (!getApiVersion().isSupported(ApiFeature.PROJECT_STATUS, ApiFeature.BUILD_TYPE_STATUS))
        return Futures.immediateFuture(null);

    final SettableFuture<Void> ackFuture = SettableFuture.create();

    runInWorkerThread(() -> {/*w  w  w . java2  s  .  c  o m*/
        final ListenableFuture<ProjectList> projectListFuture = _apiRequestController
                .sendRequest(getApiVersion(), "projects", ProjectList.class);
        addCallback(projectListFuture, new FutureCallback<ProjectList>() {
            @Override
            public void onSuccess(final ProjectList result) {
                final List<ProjectData> projects = result.getProjects().stream()
                        .map((project) -> _projectProvider.get(getApiVersion()).apply(project))
                        .collect(Collectors.toList());
                _projectManager.registerProjects(projects);
                _eventBus.post(_projectManager);
                ackFuture.set(null);

                for (final ProjectData project : _projectManager.getProjects()) {
                    LOGGER.info("Discovering project " + project.getId() + " (" + project.getName() + ")");
                }
            }

            @Override
            public void onFailure(final Throwable t) {
                LOGGER.error("Error during loading project list:", t);
                ackFuture.setException(t);
            }
        });
    });

    return ackFuture;
}

From source file:org.anhonesteffort.p25.chnlzr.ChnlzrConnectionFactory.java

public ListenableFuture<ChnlzrConnectionHandler> create(HostId chnlzrHost) {
    SettableFuture<ChnlzrConnectionHandler> future = SettableFuture.create();
    ChnlzrConnectionHandler connection = new ChnlzrConnectionHandler(future);
    Bootstrap bootstrap = new Bootstrap();

    bootstrap.group(workerGroup).channel(channel).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.connectionTimeoutMs())
            .option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, config.bufferHighWaterMark())
            .option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, config.bufferLowWaterMark())
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*  w  w  w. j a  v a  2  s  .c om*/
                public void initChannel(SocketChannel ch) {
                    ch.pipeline().addLast("idle state",
                            new IdleStateHandler(0, 0, config.idleStateThresholdMs(), TimeUnit.MILLISECONDS));
                    ch.pipeline().addLast("heartbeat", IdleStateHeartbeatWriter.INSTANCE);
                    ch.pipeline().addLast("encoder", BaseMessageEncoder.INSTANCE);
                    ch.pipeline().addLast("decoder", new BaseMessageDecoder());
                    ch.pipeline().addLast("connector", connection);
                }
            });

    bootstrap.connect(chnlzrHost.getHostname(), chnlzrHost.getPort()).addListener(connect -> {
        if (!connect.isSuccess())
            future.setException(new ConnectException("failed to connect to chnlzr"));
    });

    return future;
}