Example usage for com.google.common.util.concurrent Futures immediateFailedFuture

List of usage examples for com.google.common.util.concurrent Futures immediateFailedFuture

Introduction

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

Prototype

@CheckReturnValue
public static <V> ListenableFuture<V> immediateFailedFuture(Throwable throwable) 

Source Link

Document

Returns a ListenableFuture which has an exception set immediately upon construction.

Usage

From source file:org.jasig.portal.portlet.rendering.worker.PortletExecutionWorker.java

@Override
public final void submit() {
    if (this.submitted > 0) {
        throw new IllegalStateException(this.getClass().getSimpleName() + " for " + this.getPortletWindowId()
                + " has already been submitted.");
    }/*  w  w  w  . j a v a  2 s .co m*/

    this.submitted = System.currentTimeMillis();

    try {
        //Run pre-submit interceptors
        for (final IPortletExecutionInterceptor interceptor : this.interceptors) {
            interceptor.preSubmit(request, response, this);
        }

        final Callable<V> callable = new PortletExecutionCallable<V>(this,
                new ExecutionLifecycleCallable<V>(new Callable<V>() {
                    @Override
                    public V call() throws Exception {
                        return callInternal();
                    }
                }));

        this.future = this.executorService.submit(callable);
    } catch (final Exception e) {
        //All is not well do the basic portlet execution lifecycle and then, return a Future that simply rethrows the exception

        final Callable<Future<V>> callable = new ExecutionLifecycleCallable<Future<V>>(
                new Callable<Future<V>>() {
                    @Override
                    public Future<V> call() throws Exception {
                        return Futures.immediateFailedFuture(e);
                    }
                });

        try {
            this.future = callable.call();
        } catch (Exception e1) {
            //We know this will never throw
        }
    }
}

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();/* ww w . j av a 2  s.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:io.crate.operation.collect.HandlerSideDataCollectOperation.java

private ListenableFuture<Object[][]> handleWithService(CollectService collectService, CollectNode node,
        RamAccountingContext ramAccountingContext) {
    FlatProjectorChain projectorChain = new FlatProjectorChain(node.projections(), projectorVisitor,
            ramAccountingContext);// w ww.j  a  va  2  s.  c  o m
    CrateCollector collector = collectService.getCollector(node, projectorChain.firstProjector());
    projectorChain.startProjections();
    try {
        collector.doCollect(ramAccountingContext);
    } catch (CollectionAbortedException ex) {
        // ignore
    } catch (Exception e) {
        return Futures.immediateFailedFuture(e);
    }
    return projectorChain.result();
}

From source file:fr.duminy.components.swing.listpanel.SimpleItemManager.java

@Override
public final ListenableFuture<B> createItem() {
    B item;/*from   w ww .j av a  2 s .  c  o m*/

    try {
        item = itemClass.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        return Futures.immediateFailedFuture(e);
    }

    initItem(item);
    return type.displayForm(this, item, CREATE);
}

From source file:com.orangerhymelabs.helenus.cassandra.table.ViewRepository.java

@Override
public ListenableFuture<Boolean> delete(Identifier id) {
    if (dropDocumentSchema(id)) {
        // TODO: what about rollback?
        return super.delete(id);
    } else {/*w  w w. ja v  a 2 s .  c o  m*/
        return Futures.immediateFailedFuture(
                new StorageException("Failed to drop document schema for: " + id.toDbName()));
    }
}

From source file:com.vmware.photon.controller.rootscheduler.service.ManagedScheduler.java

public ListenableFuture<PlaceResponse> place(PlaceRequest request, long timeout) {
    // Clone the request and set the scheduler id
    request = new PlaceRequest(request);
    request.setScheduler_id(id);//w w  w .  jav  a2  s.  c  om

    try {
        SettableFuture<PlaceResponse> promise = SettableFuture.create();
        client.setTimeout(timeout);
        client.place(request, new PlaceCallback(promise));
        return promise;
    } catch (TException e) {
        return Futures.immediateFailedFuture(e);
    }
}

From source file:co.cask.cdap.internal.app.deploy.InMemoryAdapterConfigurator.java

/**
 * Executes the <code>ApplicationTemplate.configureAdapter</code> within the same JVM.
 * <p>//from   w ww .  j  ava 2  s. co m
 * This method could be dangerous and should be used only in standalone mode.
 * </p>
 *
 * @return A instance of {@link ListenableFuture}.
 */
public ListenableFuture<ConfigResponse> config() {
    SettableFuture<ConfigResponse> result = SettableFuture.create();

    try {
        // Load the JAR using the JAR class load and load the manifest file.
        Manifest manifest = BundleJarUtil.getManifest(archive);
        Preconditions.checkArgument(manifest != null, "Failed to load manifest from %s", archive.toURI());
        String mainClassName = manifest.getMainAttributes().getValue(ManifestFields.MAIN_CLASS);
        Preconditions.checkArgument(mainClassName != null && !mainClassName.isEmpty(),
                "Main class attribute cannot be empty");

        File unpackedJarDir = Files.createTempDir();
        try (Archive archive = new Archive(BundleJarUtil.unpackProgramJar(this.archive, unpackedJarDir),
                mainClassName)) {
            Object appMain = archive.getMainClass().newInstance();
            if (!(appMain instanceof ApplicationTemplate)) {
                throw new IllegalStateException(String.format("Application main class is of invalid type: %s",
                        appMain.getClass().getName()));
            }

            ApplicationTemplate template = (ApplicationTemplate) appMain;
            try (PluginInstantiator pluginInstantiator = new PluginInstantiator(cConf,
                    adapterConfig.getTemplate(), template.getClass().getClassLoader())) {
                DefaultAdapterConfigurer configurer = new DefaultAdapterConfigurer(namespaceId, adapterName,
                        adapterConfig, templateSpec, pluginRepository, pluginInstantiator);
                TypeToken typeToken = TypeToken.of(template.getClass());
                TypeToken<?> resultToken = typeToken
                        .resolveType(ApplicationTemplate.class.getTypeParameters()[0]);
                Type configType;
                // if the user parameterized their template, like 'xyz extends ApplicationTemplate<T>',
                // we can deserialize the config into that object. Otherwise it'll just be an Object
                if (resultToken.getType() instanceof Class) {
                    configType = resultToken.getType();
                } else {
                    configType = Object.class;
                }

                template.configureAdapter(adapterName, decodeConfig(adapterConfig, configType), configurer);
                AdapterDefinition spec = configurer.createSpecification();
                result.set(new DefaultConfigResponse(0, CharStreams.newReaderSupplier(GSON.toJson(spec))));
            }
        } finally {
            removeDir(unpackedJarDir);
        }

        return result;
    } catch (Throwable t) {
        LOG.error(t.getMessage(), t);
        return Futures.immediateFailedFuture(t);
    }
}

From source file:io.crate.executor.transport.executionphases.ExecutionPhasesTask.java

@Override
public ListenableFuture<List<Long>> executeBulk() {
    FluentIterable<NodeOperation> nodeOperations = FluentIterable.from(nodeOperationTrees)
            .transformAndConcat(new Function<NodeOperationTree, Iterable<? extends NodeOperation>>() {
                @Nullable/*  w ww  .ja  v  a2 s.  c o  m*/
                @Override
                public Iterable<? extends NodeOperation> apply(NodeOperationTree input) {
                    return input.nodeOperations();
                }
            });
    Map<String, Collection<NodeOperation>> operationByServer = NodeOperationGrouper
            .groupByServer(nodeOperations);
    InitializationTracker initializationTracker = new InitializationTracker(operationByServer.size());

    List<Tuple<ExecutionPhase, RowReceiver>> handlerPhases = new ArrayList<>(nodeOperationTrees.size());
    List<SettableFuture<Long>> results = new ArrayList<>(nodeOperationTrees.size());
    for (NodeOperationTree nodeOperationTree : nodeOperationTrees) {
        SettableFuture<Long> result = SettableFuture.create();
        results.add(result);
        RowReceiver receiver = new InterceptingRowReceiver(jobId(), new RowCountResultRowDownstream(result),
                initializationTracker, transportKillJobsNodeAction);
        handlerPhases.add(new Tuple<>(nodeOperationTree.leaf(), receiver));
    }

    try {
        setupContext(operationByServer, handlerPhases, initializationTracker);
    } catch (Throwable throwable) {
        return Futures.immediateFailedFuture(throwable);
    }
    return Futures.successfulAsList(results);
}

From source file:com.microsoft.azure.keyvault.cryptography.RsaKey.java

@Override
public ListenableFuture<Pair<byte[], String>> wrapKeyAsync(final byte[] key, final String algorithm)
        throws NoSuchAlgorithmException {

    if (key == null) {
        throw new IllegalArgumentException("key");
    }//  www  . j  av  a  2  s  . c  om

    // Interpret the requested algorithm
    String algorithmName = (Strings.isNullOrWhiteSpace(algorithm) ? getDefaultKeyWrapAlgorithm() : algorithm);
    Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithmName);

    if (baseAlgorithm == null || !(baseAlgorithm instanceof AsymmetricEncryptionAlgorithm)) {
        throw new NoSuchAlgorithmException(algorithmName);
    }

    AsymmetricEncryptionAlgorithm algo = (AsymmetricEncryptionAlgorithm) baseAlgorithm;

    ICryptoTransform transform;
    ListenableFuture<Pair<byte[], String>> result;

    try {
        transform = algo.CreateEncryptor(_keyPair, _provider);
        result = Futures.immediateFuture(Pair.of(transform.doFinal(key), algorithmName));
    } catch (Exception e) {
        result = Futures.immediateFailedFuture(e);
    }

    return result;
}

From source file:io.crate.executor.transport.task.elasticsearch.ESDeleteTask.java

@Override
public final ListenableFuture<List<Long>> executeBulk() {
    try {/*from w  w  w. ja v a 2 s .c om*/
        startContext();
    } catch (Throwable throwable) {
        return Futures.immediateFailedFuture(throwable);
    }
    return Futures.successfulAsList(results);
}