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.xenon.task.UploadVibTaskService.java

private void processUploadVibSubStage(VibService.State vibState, HostService.State hostState) {

    File sourceDirectory = new File(HostUtils.getDeployerContext(this).getVibDirectory());
    if (!sourceDirectory.exists() || !sourceDirectory.isDirectory()) {
        throw new IllegalStateException("Invalid VIB source directory " + sourceDirectory);
    }//  w ww .j  av a  2s  .  co m

    File sourceFile = new File(sourceDirectory, vibState.vibName);
    if (!sourceFile.exists() || !sourceFile.isFile()) {
        throw new IllegalStateException("Invalid VIB source file " + sourceFile);
    }

    HttpFileServiceClient httpFileServiceClient = HostUtils.getHttpFileServiceClientFactory(this)
            .create(hostState.hostAddress, hostState.userName, hostState.password);
    String uploadPath = UriUtils.buildUriPath("tmp", "photon-controller-vibs",
            ServiceUtils.getIDFromDocumentSelfLink(vibState.documentSelfLink), sourceFile.getName());
    ListenableFutureTask<Integer> futureTask = ListenableFutureTask
            .create(httpFileServiceClient.uploadFile(sourceFile.getAbsolutePath(), uploadPath, false));
    HostUtils.getListeningExecutorService(this).submit(futureTask);

    Futures.addCallback(futureTask, new FutureCallback<Integer>() {
        @Override
        public void onSuccess(@javax.validation.constraints.NotNull Integer result) {
            try {
                switch (result) {
                case HttpsURLConnection.HTTP_OK:
                case HttpsURLConnection.HTTP_CREATED:
                    setUploadPath(vibState.documentSelfLink, uploadPath);
                    break;
                default:
                    throw new IllegalStateException(
                            "Unexpected HTTP result " + result + " when uploading VIB file " + vibState.vibName
                                    + " to host " + hostState.hostAddress);
                }
            } catch (Throwable t) {
                failTask(t);
            }
        }

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

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

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

    List<String> command = new ArrayList<>();
    command.add("./" + SCRIPT_NAME);
    command.add(hostState.hostAddress);//from w  w w  . java  2  s .c  o  m
    command.add(hostState.userName);
    command.add(hostState.password);
    command.add(currentState.vibPath);

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

    DeployerContext deployerContext = HostUtils.getDeployerContext(this);

    File scriptLogFile = new File(deployerContext.getScriptLogDirectory(),
            SCRIPT_NAME + "-" + hostState.hostAddress + "-"
                    + ServiceUtils.getIDFromDocumentSelfLink(currentState.documentSelfLink) + ".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);
    Futures.addCallback(futureTask, new FutureCallback<Integer>() {
        @Override
        public void onSuccess(@Nullable Integer result) {
            if (result == null) {
                failTask(new NullPointerException(SCRIPT_NAME + " returned null"));
            } else if (result != 0) {
                logScriptErrorAndFail(hostState, result, scriptLogFile);
            } else {
                sendStageProgressPatch(currentState, TaskState.TaskStage.STARTED,
                        TaskState.SubStage.WAIT_FOR_INSTALLATION);
            }
        }

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

From source file:org.apache.fluo.core.oracle.OracleClient.java

public ListenableFuture<Stamp> getStampAsync() {
    checkClosed();//from  w w  w.j  av  a2  s.co m

    TimeRequest tr = new TimeRequest();
    ListenableFutureTask<Stamp> lf = ListenableFutureTask.create(tr);
    tr.lf = lf;
    try {
        queue.put(tr);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    return lf;
}

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

/**
 * This method verifies host credentials.
 *
 * @param state Supplies state.//w w  w . ja v  a  2s. c  o m
 * @throws Throwable
 */
private void validateHostCredentials(State state) throws Throwable {

    HttpFileServiceClient httpFileServiceClient = HostUtils.getHttpFileServiceClientFactory(this)
            .create(state.hostAddress, state.userName, state.password);
    ListenableFutureTask<Integer> futureTask = ListenableFutureTask
            .create(httpFileServiceClient.getDirectoryListingOfDatastores());
    HostUtils.getListeningExecutorService(this).submit(futureTask);

    FutureCallback<Integer> futureCallback = new FutureCallback<Integer>() {
        @Override
        public void onSuccess(@Nullable Integer result) {
            try {
                if (hasManagementVmAddress(state)) {
                    validateManagementVmAddress(state);
                } else {
                    sendStageProgressPatch(TaskState.TaskStage.FINISHED);
                }
            } catch (Throwable t) {
                failTask(t);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            if (t instanceof InvalidLoginException) {
                failTask(t, TaskState.ResultCode.InvalidLogin);
            } else {
                failTask(t);
            }
        }
    };

    Futures.addCallback(futureTask, futureCallback);
}

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

private void processUploadImageSubStage(State currentState) {

    FileBody fileBody = new FileBody(new File(currentState.imageFile));
    fileBody.setStreamListener((delta) -> {
        ImageUploadProgressNotification notification = new ImageUploadProgressNotification();
        notification.kind = ImageUploadProgressNotification.Kind.ADD_UPLOAD_PROGRESS;
        notification.delta = delta;//from   ww w. j a  va  2  s.  co m
        sendRequest(Operation.createPatch(this, getSelfLink()).setBody(notification));
    });

    //
    // N.B. Image upload is not performed asynchronously (and can't be), so this operation is
    // performed on a separate thread.
    //

    ListenableFutureTask<Task> futureTask = ListenableFutureTask.create(() -> HostUtils.getApiClient(this)
            .getImagesApi().uploadImage(fileBody, ImageReplicationType.ON_DEMAND.name()));

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

    Futures.addCallback(futureTask, new FutureCallback<Task>() {
        @Override
        public void onSuccess(@javax.validation.constraints.NotNull Task task) {
            try {
                processUploadImageTaskResult(task);
            } catch (Throwable t) {
                failTask(t);
            }
        }

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

From source file:org.apache.hadoop.hive.ql.exec.tez.TezSessionPool.java

private ListenableFuture<?> resizeUpInternal(int delta) {
    // 1) Cancel the kills if any, to avoid killing the returned sessions.
    //    Also sets the count for the async initialization.
    int oldVal;/*from w  w  w.ja  va  2  s .  c o  m*/
    do {
        oldVal = deltaRemaining.get();
    } while (!deltaRemaining.compareAndSet(oldVal, oldVal + delta));
    int toStart = oldVal + delta;
    if (toStart <= 0)
        return createDummyFuture();
    LOG.info("Resizing the pool; adding " + toStart + " sessions");

    // 2) If we need to create some extra sessions, we'd do it just like startup does.
    int threadCount = Math.max(1, Math.min(toStart,
            HiveConf.getIntVar(initConf, ConfVars.HIVE_SERVER2_TEZ_SESSION_MAX_INIT_THREADS)));
    List<ListenableFutureTask<Boolean>> threadTasks = new ArrayList<>(threadCount);
    // This is an async method, so always launch threads, even for a single task.
    for (int i = 0; i < threadCount; ++i) {
        ListenableFutureTask<Boolean> task = ListenableFutureTask
                .create(new CreateSessionsRunnable(deltaRemaining));
        new Thread(task, "Tez pool resize " + i).start();
        threadTasks.add(task);
    }
    return Futures.allAsList(threadTasks);
}

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

/**
 * Register a client to Lotus, and then produce the URL to access it.
 *
 * @param currentState          Current State.
 * @param deploymentState       State of deployment.
 * @param lbIpAddress           IP address of the load balancer.
 *//*ww  w .  ja  v a  2s.  c om*/
private void registerAuthClient(final State currentState, final DeploymentService.State deploymentState,
        final String lbIpAddress) throws Throwable {
    AuthHelperFactory authHelperFactory = ((AuthHelperFactoryProvider) getHost()).getAuthHelperFactory();
    final AuthHelper authHelper = authHelperFactory.create();

    ServiceUtils.logInfo(this, "Starting a thread to register client %s at %s:%s using user %s on tenant %s.",
            lbIpAddress, deploymentState.oAuthServerAddress, deploymentState.oAuthServerPort,
            deploymentState.oAuthUserName, deploymentState.oAuthTenantName);

    //
    // Lightwave requires login name to be in format "domain/user"
    //
    ListenableFutureTask futureTask = ListenableFutureTask.create(new Callable() {
        @Override
        public Object call() throws Exception {
            return authHelper.getResourceLoginUri(deploymentState.oAuthTenantName,
                    deploymentState.oAuthTenantName + "\\" + deploymentState.oAuthUserName,
                    deploymentState.oAuthPassword, deploymentState.oAuthServerAddress,
                    deploymentState.oAuthServerPort,
                    String.format(currentState.loginRedirectUrlTemplate, lbIpAddress),
                    String.format(currentState.logoutRedirectUrlTemplate, lbIpAddress));
        }
    });

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

    FutureCallback<AuthClientHandler.ImplicitClient> futureCallback = new FutureCallback<AuthClientHandler.ImplicitClient>() {
        @Override
        public void onSuccess(AuthClientHandler.ImplicitClient result) {
            State patchState = buildPatch(TaskState.TaskStage.FINISHED, null);
            patchState.loginUrl = result.loginURI;
            patchState.logoutUrl = result.logoutURI;
            TaskUtils.sendSelfPatch(RegisterAuthClientTaskService.this, patchState);
        }

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

    Futures.addCallback(futureTask, futureCallback);
}

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

/**
 * Register a client to Lotus, and then produce the URL to access it.
 *
 * @param currentState          Current State.
 * @param deploymentState       State of deployment.
 * @param lbIpAddress           IP address of the load balancer.
 *///ww w  .  j a  va2 s .c  o  m
private void registerAuthClient(final State currentState, final DeploymentService.State deploymentState,
        final String lbIpAddress) throws Throwable {
    DeployerServiceGroup deployerServiceGroup = (DeployerServiceGroup) ((PhotonControllerXenonHost) getHost())
            .getDeployer();
    AuthHelperFactory authHelperFactory = deployerServiceGroup.getAuthHelperFactory();
    final AuthHelper authHelper = authHelperFactory.create();

    ServiceUtils.logInfo(this, "Starting a thread to register client %s at %s:%s using user %s on tenant %s.",
            lbIpAddress, deploymentState.oAuthServerAddress, deploymentState.oAuthServerPort,
            deploymentState.oAuthUserName, deploymentState.oAuthTenantName);

    //
    // Lightwave requires login name to be in format "domain/user"
    //
    ListenableFutureTask futureTask = ListenableFutureTask.create(new Callable() {
        @Override
        public Object call() throws Exception {
            return authHelper.getResourceLoginUri(deploymentState.oAuthTenantName,
                    deploymentState.oAuthTenantName + "\\" + deploymentState.oAuthUserName,
                    deploymentState.oAuthPassword, deploymentState.oAuthServerAddress,
                    deploymentState.oAuthServerPort,
                    String.format(currentState.loginRedirectUrlTemplate, lbIpAddress),
                    String.format(currentState.logoutRedirectUrlTemplate, lbIpAddress));
        }
    });

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

    FutureCallback<AuthClientHandler.ImplicitClient> futureCallback = new FutureCallback<AuthClientHandler.ImplicitClient>() {
        @Override
        public void onSuccess(AuthClientHandler.ImplicitClient result) {
            State patchState = buildPatch(TaskState.TaskStage.FINISHED, null);
            patchState.loginUrl = result.loginURI;
            patchState.logoutUrl = result.logoutURI;
            TaskUtils.sendSelfPatch(RegisterAuthClientTaskService.this, patchState);
        }

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

    Futures.addCallback(futureTask, futureCallback);
}

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

/**
 * This method verifies host's address.//ww w . ja  va  2  s.  c  o m
 *
 * @param state Supplies state.
 * @throws Throwable
 */
private void validateManagementVmAddress(State state) throws Throwable {

    HostManagementVmAddressValidator hostManagementVmAddressValidator = HostUtils
            .getHostManagementVmAddressValidatorFactory(this)
            .create(state.metadata.get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_IP));
    ListenableFutureTask<Boolean> futureTask = ListenableFutureTask.create(hostManagementVmAddressValidator);
    HostUtils.getListeningExecutorService(this).submit(futureTask);

    FutureCallback<Boolean> futureCallback = new FutureCallback<Boolean>() {
        @Override
        public void onSuccess(@Nullable Boolean result) {
            sendStageProgressPatch(TaskState.TaskStage.FINISHED);
        }

        @Override
        public void onFailure(Throwable t) {
            if (t instanceof ManagementVmAddressAlreadyInUseException) {
                failTask(t, TaskState.ResultCode.ManagementVmAddressAlreadyInUse);
            } else {
                failTask(t);
            }
        }
    };

    Futures.addCallback(futureTask, futureCallback);
}

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

private void createIsoFile(final State currentState, String configDirectoryName) throws Throwable {

    final File isoFile = new File("/tmp", CONFIG_FILENAME + "-" + currentState.vmId + ".iso");
    DeployerContext deployerContext = HostUtils.getDeployerContext(this);
    final File userDataConfigFile = new File(deployerContext.getScriptDirectory(),
            CONFIG_FILENAME + "-user-data-" + currentState.vmId + ".yml");
    final File metaDataConfigFile = new File(deployerContext.getScriptDirectory(),
            CONFIG_FILENAME + "-meta-data-" + currentState.vmId + ".yml");
    File scriptLogFile = new File(deployerContext.getScriptDirectory(),
            SCRIPT_NAME + "-" + currentState.vmId + ".log");

    String userDataConfigFilename = createFile(currentState.userDataTemplate, userDataConfigFile);
    String metaDataConfigFilename = createFile(currentState.metaDataTemplate, metaDataConfigFile);

    List<String> command = new ArrayList<>();
    command.add("./" + SCRIPT_NAME);
    command.add(isoFile.getAbsolutePath());
    command.add(userDataConfigFilename);
    command.add(metaDataConfigFilename);
    if (configDirectoryName != null) {
        command.add(configDirectoryName);
    }/*  ww w.  j  a v  a2  s.co  m*/

    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) {
                failTask(new Exception(SCRIPT_NAME + " returned " + result.toString()));
            } else {
                try {
                    Files.deleteIfExists(userDataConfigFile.toPath());
                    Files.deleteIfExists(metaDataConfigFile.toPath());
                    if (configDirectoryName != null) {
                        FileUtils.deleteDirectory(new File(configDirectoryName));
                    }
                    attachAndUploadIso(currentState, isoFile.getAbsolutePath());
                } catch (IOException e) {
                    failTask(e);
                }
            }
        }

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

    Futures.addCallback(futureTask, futureCallback);
}