Example usage for com.google.common.util.concurrent ListenableFutureTask create

List of usage examples for com.google.common.util.concurrent ListenableFutureTask create

Introduction

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

Prototype

public static <V> ListenableFutureTask<V> create(Callable<V> callable) 

Source Link

Document

Creates a ListenableFutureTask that will upon running, execute the given Callable .

Usage

From source file:com.vmware.photon.controller.deployer.dcp.task.UploadVibTaskService.java

private void processUploadVib(State currentState, HostService.State hostState) {
    File sourceDirectory = new File(HostUtils.getDeployerContext(this).getVibDirectory());
    if (!sourceDirectory.exists()) {
        throw new IllegalStateException(
                "VIB directory " + sourceDirectory.getAbsolutePath() + " does not exist");
    } else if (!sourceDirectory.isDirectory()) {
        throw new IllegalStateException(
                "VIB directory " + sourceDirectory.getAbsolutePath() + " is not a directory");
    }//  w w w  . j a va 2  s.  c  o  m

    File[] sourceFiles = sourceDirectory.listFiles((file) -> file.getName().toUpperCase().endsWith(".VIB"));
    if (sourceFiles.length == 0) {
        throw new IllegalStateException("No VIB files were found in " + sourceDirectory.getAbsolutePath());
    }

    for (File sourceFile : sourceFiles) {

        //
        // If this file has already been uploaded, then skip to the next file.
        //

        if (currentState.vibPaths != null && currentState.vibPaths.containsKey(sourceFile.getName())) {
            continue;
        }

        HttpFileServiceClient httpFileServiceClient = HostUtils.getHttpFileServiceClientFactory(this)
                .create(hostState.hostAddress, hostState.userName, hostState.password);
        String uploadPath = "/tmp/photon-controller-vibs/"
                + ServiceUtils.getIDFromDocumentSelfLink(currentState.deploymentServiceLink) + "/"
                + sourceFile.getName();
        ListenableFutureTask<Integer> task = ListenableFutureTask
                .create(httpFileServiceClient.uploadFile(sourceFile.getAbsolutePath(), uploadPath, false));
        HostUtils.getListeningExecutorService(this).submit(task);
        Futures.addCallback(task, new FutureCallback<Integer>() {
            @Override
            public void onSuccess(@Nullable Integer result) {
                try {
                    if (result != HttpsURLConnection.HTTP_OK && result != HttpsURLConnection.HTTP_CREATED) {
                        throw new IllegalStateException("Unexpected HTTP result " + result + " when uploading "
                                + sourceFile.getAbsolutePath());
                    }

                    Map<String, String> vibPaths = new HashMap<>(sourceFiles.length);
                    if (currentState.vibPaths != null) {
                        vibPaths.putAll(currentState.vibPaths);
                    }

                    vibPaths.put(sourceFile.getName(), uploadPath);

                    State patchState = buildPatch(currentState.taskState.stage, null);
                    patchState.vibPaths = vibPaths;
                    TaskUtils.sendSelfPatch(UploadVibTaskService.this, patchState);
                } catch (Throwable t) {
                    failTask(t);
                }
            }

            @Override
            public void onFailure(Throwable throwable) {
                failTask(throwable);
            }
        });

        return;
    }

    sendStageProgressPatch(TaskState.TaskStage.FINISHED);
}

From source file:org.trinity.foundation.render.qt.impl.painter.PainterImpl.java

@Override
public ListenableFuture<Void> resize(final int width, final int height) {
    final QWidget view = this.viewDiscovery.lookupView(this.model);
    final Callable<Void> callable = new Callable<Void>() {
        @Override//  w  w  w . j a  v a  2  s  .c o  m
        public Void call() {
            LOG.debug("[view={}] resize width={}, height={}.", view, width, height);
            view.resize(width, height);
            return null;
        }
    };

    final ListenableFutureTask<Void> futureTask = ListenableFutureTask.create(callable);
    QApplication.invokeLater(futureTask);
    return futureTask;
}

From source file:org.waveprotocol.box.server.waveserver.LucenePerUserWaveViewHandlerImpl.java

@Override
public ListenableFuture<Void> onWaveInit(final WaveletName waveletName) {
    Preconditions.checkNotNull(waveletName);

    ListenableFutureTask<Void> task = ListenableFutureTask.create(new Callable<Void>() {

        @Override//w  w  w .  ja va2s .c o  m
        public Void call() throws Exception {
            ReadableWaveletData waveletData;
            try {
                waveletData = waveletProvider.getReadableWaveletData(waveletName);
                updateIndex(waveletData);
            } catch (WaveServerException e) {
                LOG.log(Level.SEVERE, "Failed to initialize index for " + waveletName, e);
                throw e;
            }
            return null;
        }
    });
    executor.execute(task);
    return task;
}

From source file:org.trinity.foundation.render.qt.impl.painter.PainterImpl.java

@Override
public ListenableFuture<Void> hide() {
    final QWidget view = this.viewDiscovery.lookupView(this.model);
    final Callable<Void> callable = new Callable<Void>() {
        @Override/*from   w  w w. j  a va 2 s.c  o m*/
        public Void call() {
            LOG.debug("[view={}] hide.", view);
            view.hide();
            return null;
        }
    };

    final ListenableFutureTask<Void> futureTask = ListenableFutureTask.create(callable);
    QApplication.invokeLater(futureTask);
    return futureTask;
}

From source file:org.waveprotocol.box.server.waveserver.SolrWaveIndexerImpl.java

@Override
public void waveletCommitted(final WaveletName waveletName, final HashedVersion version) {

    Preconditions.checkNotNull(waveletName);

    ListenableFutureTask<Void> task = ListenableFutureTask.create(new Callable<Void>() {

        @Override// w ww  .  j  av a2  s.c  o  m
        public Void call() throws Exception {
            ReadableWaveletData waveletData;
            try {
                waveletData = waveletDataProvider.getReadableWaveletData(waveletName);
                LOG.fine("commit " + version + " " + waveletData.getVersion());
                if (waveletData.getVersion() == version.getVersion()) {
                    updateIndex(waveletData);
                }
            } catch (WaveServerException e) {
                LOG.log(Level.SEVERE, "Failed to update index for " + waveletName, e);
                throw e;
            }
            return null;
        }
    });
    executor.execute(task);
}

From source file:com.vmware.photon.controller.deployer.dcp.task.DeployAgentTaskService.java

private void processDeployAgent(State currentState, DeploymentService.State deploymentState,
        HostService.State hostState) {

    List<String> command = new ArrayList<>();
    command.add("./" + SCRIPT_NAME);
    command.add(hostState.hostAddress);//  w  w  w.ja v a 2 s.c o m
    command.add(hostState.userName);
    command.add(hostState.password);

    String vibPath = VMFS_VOLUMES + "/"
            + StringUtils.strip(deploymentState.imageDataStoreNames.iterator().next(), "/") + "/"
            + StringUtils.strip(currentState.vibPath, "/");

    command.add(vibPath);

    if (null != deploymentState.syslogEndpoint) {
        command.add("-l");
        command.add(deploymentState.syslogEndpoint);
    }

    DeployerContext deployerContext = HostUtils.getDeployerContext(this);

    File scriptLogFile = new File(deployerContext.getScriptLogDirectory(),
            SCRIPT_NAME + "-" + currentState.uniqueId + ".log");

    ScriptRunner scriptRunner = new ScriptRunner.Builder(command, deployerContext.getScriptTimeoutSec())
            .directory(deployerContext.getScriptDirectory())
            .redirectOutput(ProcessBuilder.Redirect.to(scriptLogFile)).build();

    ListenableFutureTask<Integer> futureTask = ListenableFutureTask.create(scriptRunner);
    HostUtils.getListeningExecutorService(this).submit(futureTask);

    FutureCallback<Integer> futureCallback = new FutureCallback<Integer>() {
        @Override
        public void onSuccess(@Nullable Integer result) {
            if (null == result) {
                failTask(new IllegalStateException(SCRIPT_NAME + " returned null"));
            } else if (0 != result) {
                logScriptErrorAndFail(hostState, result, scriptLogFile);
            } else {
                sendStageProgressPatch(TaskState.TaskStage.FINISHED);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            failTask(t);
        }
    };

    Futures.addCallback(futureTask, futureCallback);
}

From source file:com.vmware.photon.controller.deployer.dcp.task.DeleteAgentTaskService.java

/**
 * This method creates a script runner object and submits it to the executor
 * service for the DCP host. On successful completion, the service is
 * transitioned to the FINISHED state.//  w  w  w .  ja v a  2  s.c om
 *
 * @param currentState
 * @param hostState
 */
private void processStartedState(final State currentState, final HostService.State hostState) {
    DeployerContext deployerContext = HostUtils.getDeployerContext(this);
    List<String> command = new ArrayList<>();
    command.add("./" + SCRIPT_NAME);
    command.add(hostState.hostAddress);
    command.add(hostState.userName);
    command.add(hostState.password);

    File scriptLogFile = new File(deployerContext.getScriptLogDirectory(),
            SCRIPT_NAME + "-" + currentState.uniqueID + ".log");

    ScriptRunner scriptRunner = new ScriptRunner.Builder(command, deployerContext.getScriptTimeoutSec())
            .directory(deployerContext.getScriptDirectory())
            .redirectOutput(ProcessBuilder.Redirect.to(scriptLogFile)).build();

    ListenableFutureTask<Integer> futureTask = ListenableFutureTask.create(scriptRunner);
    HostUtils.getListeningExecutorService(this).submit(futureTask);

    FutureCallback<Integer> futureCallback = new FutureCallback<Integer>() {
        @Override
        public void onSuccess(@Nullable Integer result) {
            if (null == result) {
                failTask(new NullPointerException(SCRIPT_NAME + " returned null"));
            } else if (0 != result) {
                logScriptErrorAndFail(hostState, result, scriptLogFile);
            } else {
                sendStageProgressPatch(TaskState.TaskStage.FINISHED);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            failTask(t);
        }
    };

    Futures.addCallback(futureTask, futureCallback);
}

From source file:com.vmware.photon.controller.deployer.xenon.task.DeleteAgentTaskService.java

/**
 * This method creates a script runner object and submits it to the executor
 * service for the Xenon host. On successful completion, the service is
 * transitioned to the FINISHED state.//from  w  w  w.j  ava  2 s .c om
 *
 * @param currentState
 * @param hostState
 */
private void processStartedState(final State currentState, final HostService.State hostState) {
    DeployerContext deployerContext = HostUtils.getDeployerContext(this);
    List<String> command = new ArrayList<>();
    command.add("./" + SCRIPT_NAME);
    command.add(hostState.hostAddress);
    command.add(hostState.userName);
    command.add(hostState.password);
    command.add("photon-controller-agent");

    File scriptLogFile = new File(deployerContext.getScriptLogDirectory(),
            SCRIPT_NAME + "-" + currentState.uniqueID + ".log");

    ScriptRunner scriptRunner = new ScriptRunner.Builder(command, deployerContext.getScriptTimeoutSec())
            .directory(deployerContext.getScriptDirectory())
            .redirectOutput(ProcessBuilder.Redirect.to(scriptLogFile)).build();

    ListenableFutureTask<Integer> futureTask = ListenableFutureTask.create(scriptRunner);
    HostUtils.getListeningExecutorService(this).submit(futureTask);

    FutureCallback<Integer> futureCallback = new FutureCallback<Integer>() {
        @Override
        public void onSuccess(@Nullable Integer result) {
            if (null == result) {
                failTask(new NullPointerException(SCRIPT_NAME + " returned null"));
            } else if (0 != result) {
                logScriptErrorAndFail(hostState, result, scriptLogFile);
            } else {
                sendStageProgressPatch(TaskState.TaskStage.FINISHED);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            failTask(t);
        }
    };

    Futures.addCallback(futureTask, futureCallback);
}

From source file:com.vmware.photon.controller.deployer.dcp.task.DeleteContainerTaskService.java

/**
 * This method deletes a docker container by submitting a future task to
 * the executor service for the DCP host. On successful completion, the
 * service is transitioned to the FINISHED state.
 *
 * @param currentState Supplies the updated state of the current service
 *                     instance./*from  w  ww  .j a  va  2s.  c om*/
 */
private void processDeleteContainer(final State currentState, final String vmIpAddress,
        final String containerId) {
    final Service service = this;
    ListenableFutureTask<String> futureTask = ListenableFutureTask.create(new Callable<String>() {
        @Override
        public String call() {
            DockerProvisioner dockerProvisioner = HostUtils.getDockerProvisionerFactory(service)
                    .create(vmIpAddress);
            return dockerProvisioner.deleteContainer(containerId, currentState.removeVolumes,
                    currentState.force);
        }
    });

    HostUtils.getListeningExecutorService(this).submit(futureTask);

    FutureCallback<String> futureCallback = new FutureCallback<String>() {
        @Override
        public void onSuccess(@Nullable String result) {
            try {
                if (null == result) {
                    failTask(new IllegalStateException("Delete container returned null"));
                    return;
                }

                State patchState = buildPatch(TaskState.TaskStage.FINISHED, null);
                TaskUtils.sendSelfPatch(service, patchState);
            } catch (Throwable e) {
                failTask(e);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            failTask(t);
        }
    };

    Futures.addCallback(futureTask, futureCallback);
}

From source file:org.trinity.foundation.render.qt.impl.painter.PainterImpl.java

@Override
public ListenableFuture<DisplaySurface> getDislaySurface() {

    final QWidget view = this.viewDiscovery.lookupView(this.model);
    final Callable<DisplaySurface> callable = new Callable<DisplaySurface>() {
        @Override/*from w  w  w  . j av a2s. c o m*/
        public DisplaySurface call() {
            final DisplaySurfaceHandle displaySurfaceHandle = new RenderDisplaySurfaceHandle(view);
            return PainterImpl.this.displaySurfaceFactory.createDisplaySurface(displaySurfaceHandle);
        }
    };

    final ListenableFutureTask<DisplaySurface> futureTask = ListenableFutureTask.create(callable);
    QApplication.invokeLater(futureTask);
    return futureTask;
}