Example usage for java.util.concurrent Future get

List of usage examples for java.util.concurrent Future get

Introduction

In this page you can find the example usage for java.util.concurrent Future get.

Prototype

V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;

Source Link

Document

Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.

Usage

From source file:mase.conillon.ConillonMasterProblem.java

public static <T> T runWithTimeout(Callable<T> callable, long timeout, TimeUnit timeUnit) throws Exception {
    final ExecutorService executor = Executors.newSingleThreadExecutor();
    final Future<T> future = executor.submit(callable);
    executor.shutdown(); // This does not cancel the already-scheduled task.
    try {//from  w w  w.  j  a  v  a  2s .  c o m
        return future.get(timeout, timeUnit);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        future.cancel(true);
        throw e;
    }
}

From source file:org.springside.samples.quickservice.functional.TaskRestServiceTest.java

@BeforeClass
public static void start() throws Exception {
    Future<ConfigurableApplicationContext> future = Executors.newSingleThreadExecutor()
            .submit(new Callable<ConfigurableApplicationContext>() {
                @Override// w w w  .ja  va2s .c  o m
                public ConfigurableApplicationContext call() throws Exception {
                    return SpringApplication.run(QuickServiceApplication.class);
                }
            });
    context = future.get(60, TimeUnit.SECONDS);
}

From source file:com.silica.Silica.java

private static <T extends Serializable> T getResult(Future<T> future, long jobTimeoutMsec,
        String jobDescription) throws ServiceException {
    Exception exception = null;//from  w  ww. ja  v a 2 s.  co m
    try {
        return future.get(jobTimeoutMsec, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        LOG.info(jobDescription, e);
        exception = e;
    } catch (ExecutionException e) {
        LOG.error(jobDescription, e);
        exception = e;
    } catch (TimeoutException e) {
        LOG.warn(jobDescription, e);
        exception = e;
    }
    throw new ServiceException(jobDescription, exception);
}

From source file:UnitTest4.java

public static void execute()
        throws ClientProtocolException, IOException, InterruptedException, ExecutionException {
    /*/*from   w  w  w . j a v a 2  s  . c om*/
      CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
      try {
    httpclient.start();
    HttpGet request = new HttpGet("http://www.apache.org/");
    Future<HttpResponse> future = httpclient.execute(request, null);
    HttpResponse response = future.get();
    System.out.println("Response: " + response.getStatusLine());
    System.out.println("Shutting down");
      } finally {
    httpclient.close();
      }
      System.out.println("Done");
    */

    /*
    try (CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault()) {
        httpclient.start();
        HttpPost request = new HttpPost(addr);
        StringEntity entity = new StringEntity(event, ContentType.create("application/json", Consts.UTF_8));
        request.setEntity(entity);
        httpclient.execute(request, null);
    } catch (Exception e) {
        LOG.error("Failed to sending event", e);
    }
    */
    //Asserts a;
    CloseableHttpAsyncClient m_httpClient = HttpAsyncClients.createDefault();

    m_httpClient.start();

    HttpHost m_target = new HttpHost("localhost", 5000, "http");
    //HttpPost postRequest = new HttpPost("http://localhost:5000/hello");
    HttpPost postRequest = new HttpPost("/");

    StringEntity params = new StringEntity("");

    postRequest.addHeader("content-type", "application/json");
    postRequest.setEntity(params);

    log.debug("execute() executing request to " + m_target);

    //HttpAsyncRequestConsumer<HttpRequest> gh;

    // works HttpResponse httpResponse = httpClient.execute(target, getRequest);
    Future<HttpResponse> future = m_httpClient.execute(m_target, postRequest, null);
    //Future<HttpResponse> future = m_httpClient.execute(postRequest, null);
    //HttpResponse httpResponse = future.get();
    while (future.isDone() == false) {
        log.debug("Inside while");
    }
    HttpResponse httpResponse = null;
    try {
        httpResponse = future.get(100, TimeUnit.NANOSECONDS);
    } catch (TimeoutException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    HttpEntity entity = httpResponse.getEntity();

    log.debug("execute()----------------------------------------");
    log.debug("execute() {}", httpResponse.getStatusLine());
    Header[] headers = httpResponse.getAllHeaders();
    for (int i = 0; i < headers.length; i++) {
        log.debug("execute() {}", headers[i]);
    }
    log.debug("execute()----------------------------------------");

    String jsonString = null;
    if (entity != null) {
        jsonString = EntityUtils.toString(entity);
        log.debug("execute() {}", jsonString);
    }

}

From source file:com.mxhero.plugin.cloudstorage.onedrive.api.OneDrive.java

/**
 * Redeem daemon.//from ww  w  .j a v a  2  s  .com
 *
 * @param redeemDaemonRequest the redeem daemon request
 * @return the Access Token redeemed it
 * @throws AuthenticationException the authentication exception
 */
public static String redeemDaemon(RedeemDaemonRequest redeemDaemonRequest) throws AuthenticationException {
    ExecutorService service = Executors.newCachedThreadPool();
    AuthenticationResult authenticationResult = null;
    String authority = String.format(ApiEnviroment.tokenDaemonBaseUrl.getValue(),
            redeemDaemonRequest.getTenantId());
    logger.debug("Trying to get App Only token for {}", redeemDaemonRequest);
    try {
        AuthenticationContext authenticationContext = new AuthenticationContext(authority, false, service);
        String filePkcs12 = ApiEnviroment.fileUrlPkcs12Certificate.getValue();
        if (StringUtils.isNotEmpty(redeemDaemonRequest.getFileUrlPkcs12Certificate())) {
            filePkcs12 = redeemDaemonRequest.getFileUrlPkcs12Certificate();
        }

        String filePkcs12Secret = ApiEnviroment.pkcs12CertificateSecret.getValue();
        if (StringUtils.isNotEmpty(redeemDaemonRequest.getCertificateSecret())) {
            filePkcs12Secret = redeemDaemonRequest.getCertificateSecret();
        }

        Validate.notEmpty(filePkcs12,
                "Pkcs12 Key file path must be provided or configured. You can set it on environment var 'ONEDRIVE_DAEMON_PKCS12_FILE_URL' or through Java System Property 'onedrive.daemon.pkcs12.file.url'");
        Validate.notEmpty(filePkcs12Secret,
                "Pkcs12 Secret Key file must be provided or configured. You can set it on environment var 'ONEDRIVE_DAEMON_PKCS12_FILE_SECRET' or through Java System Property 'onedrive.daemon.pkcs12.file.secret'");

        InputStream pkcs12Certificate = new FileInputStream(filePkcs12);
        AsymmetricKeyCredential credential = AsymmetricKeyCredential.create(redeemDaemonRequest.getClientId(),
                pkcs12Certificate, filePkcs12Secret);

        Future<AuthenticationResult> future = authenticationContext
                .acquireToken(redeemDaemonRequest.getResourceSharepointId(), credential, null);
        authenticationResult = future.get(10, TimeUnit.SECONDS);
        logger.debug("Token retrieved {}",
                ToStringBuilder.reflectionToString(authenticationResult, ToStringStyle.SHORT_PREFIX_STYLE));
        return authenticationResult.getAccessToken();
    } catch (Exception e) {
        logger.error("Error trying to get new App Only Token", e);
        throw new AuthenticationException(
                String.format("Error trying to get new App Only Token for tenantId %s and sharepointUri %s",
                        redeemDaemonRequest.getTenantId(), redeemDaemonRequest.getResourceSharepointId()));
    } finally {
        service.shutdown();
    }

}

From source file:com.eucalyptus.storage.TGTWrapper.java

/**
 * executeTGTs the specified tgt command in a separate process. 
 * A {@link DirectStorageInfo#timeoutInMillis timeout} is enforced on 
 * the process using {@link java.util.concurrent.ExecutorService ExecutorService} 
 * framework. If the process does not complete with in the timeout, it is cancelled.
 * //from   w ww.  ja  v  a  2  s . c o m
 * @param command
 * @param timeout
 * @return CommandOutput
 * @throws EucalyptusCloudException
 */
private static CommandOutput execute(@NotNull String[] command, @NotNull Long timeout)
        throws EucalyptusCloudException, CallTimeoutException {
    try {
        Integer returnValue = -999999;
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(command);
        StreamConsumer error = new StreamConsumer(process.getErrorStream());
        StreamConsumer output = new StreamConsumer(process.getInputStream());
        error.start();
        output.start();
        Callable<Integer> processMonitor = new ProcessMonitor(process);
        Future<Integer> processController = service.submit(processMonitor);
        try {
            returnValue = processController.get(timeout, TimeUnit.MILLISECONDS);
        } catch (TimeoutException tex) {
            String commandStr = buildCommand(command);
            LOG.error(commandStr + " timed out. Cancelling the process, logging a fault and exceptioning out");
            processController.cancel(true);
            Faults.forComponent(Storage.class).havingId(TGT_HOSED).withVar("component", "Storage Controller")
                    .withVar("timeout", Long.toString(timeout)).log();
            throw new CallTimeoutException("No response from the command " + commandStr
                    + ". Process timed out after waiting for " + timeout + " milliseconds");
        }
        output.join();
        error.join();
        LOG.debug("TGTWrapper executed: " + JOINER.join(command) + "\n return=" + returnValue + "\n stdout="
                + output.getReturnValue() + "\n stderr=" + error.getReturnValue());
        return new CommandOutput(returnValue, output.getReturnValue(), error.getReturnValue());
    } catch (CallTimeoutException e) {
        throw e;
    } catch (Exception ex) {
        throw new EucalyptusCloudException(ex);
    }
}

From source file:com.eucalyptus.blockstorage.TGTWrapper.java

/**
 * executeTGTs the specified tgt command in a separate process. 
 * A {@link DirectStorageInfo#timeoutInMillis timeout} is enforced on 
 * the process using {@link java.util.concurrent.ExecutorService ExecutorService} 
 * framework. If the process does not complete with in the timeout, it is cancelled.
 * /*from   w ww  .j a v  a2  s  . com*/
 * @param command
 * @param timeout
 * @return CommandOutput
 * @throws EucalyptusCloudException
 */
private static CommandOutput execute(@Nonnull String[] command, @Nonnull Long timeout)
        throws EucalyptusCloudException, CallTimeoutException {
    try {
        Integer returnValue = -999999;
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(command);
        StreamConsumer error = new StreamConsumer(process.getErrorStream());
        StreamConsumer output = new StreamConsumer(process.getInputStream());
        error.start();
        output.start();
        Callable<Integer> processMonitor = new ProcessMonitor(process);
        Future<Integer> processController = getExecutorWithInit().submit(processMonitor);
        try {
            returnValue = processController.get(timeout, TimeUnit.MILLISECONDS);
        } catch (TimeoutException tex) {
            String commandStr = buildCommand(command);
            LOG.error(commandStr + " timed out. Cancelling the process, logging a fault and exceptioning out");
            processController.cancel(true);
            Faults.forComponent(Storage.class).havingId(TGT_HOSED).withVar("component", "Storage Controller")
                    .withVar("timeout", Long.toString(timeout)).log();
            throw new CallTimeoutException("No response from the command " + commandStr
                    + ". Process timed out after waiting for " + timeout + " milliseconds");
        }
        output.join();
        error.join();
        LOG.debug("TGTWrapper executed: " + JOINER.join(command) + "\n return=" + returnValue + "\n stdout="
                + output.getReturnValue() + "\n stderr=" + error.getReturnValue());
        return new CommandOutput(returnValue, output.getReturnValue(), error.getReturnValue());
    } catch (CallTimeoutException e) {
        throw e;
    } catch (Exception ex) {
        throw new EucalyptusCloudException(ex);
    }
}

From source file:com.magnet.plugin.helpers.URLHelper.java

public static InputStream loadUrl(final String url) throws Exception {
    final InputStream[] inputStreams = new InputStream[] { null };
    final Exception[] exception = new Exception[] { null };
    Future<?> downloadThreadFuture = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
        public void run() {
            try {
                HttpURLConnection connection;
                if (ApplicationManager.getApplication() != null) {
                    connection = HttpConfigurable.getInstance().openHttpConnection(url);
                } else {
                    connection = (HttpURLConnection) new URL(url).openConnection();
                    connection.setReadTimeout(Rest2MobileConstants.CONNECTION_TIMEOUT);
                    connection.setConnectTimeout(Rest2MobileConstants.CONNECTION_TIMEOUT);
                }//from ww w . ja  va  2 s  .co  m
                connection.connect();

                inputStreams[0] = connection.getInputStream();
            } catch (IOException e) {
                exception[0] = e;
            }
        }
    });

    try {
        downloadThreadFuture.get(5, TimeUnit.SECONDS);
    } catch (TimeoutException ignored) {
    }

    if (!downloadThreadFuture.isDone()) {
        downloadThreadFuture.cancel(true);
        throw new ConnectionException(IdeBundle.message("updates.timeout.error"));
    }

    if (exception[0] != null)
        throw exception[0];
    return inputStreams[0];
}

From source file:com.magnet.plugin.common.helpers.URLHelper.java

public static InputStream loadUrl(final String url) throws Exception {
    final InputStream[] inputStreams = new InputStream[] { null };
    final Exception[] exception = new Exception[] { null };
    Future<?> downloadThreadFuture = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
        public void run() {
            try {
                HttpURLConnection connection;
                if (ApplicationManager.getApplication() != null) {
                    connection = HttpConfigurable.getInstance().openHttpConnection(url);
                } else {
                    connection = (HttpURLConnection) new URL(url).openConnection();
                    connection.setReadTimeout(CONNECTION_TIMEOUT);
                    connection.setConnectTimeout(CONNECTION_TIMEOUT);
                }//  ww  w  .  j  av  a2 s  . c o  m
                connection.connect();

                inputStreams[0] = connection.getInputStream();
            } catch (IOException e) {
                exception[0] = e;
            }
        }
    });

    try {
        downloadThreadFuture.get(5, TimeUnit.SECONDS);
    } catch (TimeoutException ignored) {
    }

    if (!downloadThreadFuture.isDone()) {
        downloadThreadFuture.cancel(true);
        throw new Exception(IdeBundle.message("updates.timeout.error"));
    }

    if (exception[0] != null)
        throw exception[0];
    return inputStreams[0];
}

From source file:learn.jersey.services.BufferedMutatorExample.java

@Override
public int run(String[] args) throws InterruptedException, ExecutionException, TimeoutException {

    /** a callback invoked when an asynchronous write fails. */
    final BufferedMutator.ExceptionListener listener = new BufferedMutator.ExceptionListener() {
        @Override//from w  ww . j  a va 2  s  . c o  m
        public void onException(RetriesExhaustedWithDetailsException e, BufferedMutator mutator) {
            for (int i = 0; i < e.getNumExceptions(); i++) {
                LOG.info("Failed to sent put " + e.getRow(i) + ".");
            }
        }
    };
    BufferedMutatorParams params = new BufferedMutatorParams(TABLE).listener(listener);

    //
    // step 1: create a single Connection and a BufferedMutator, shared by
    // all worker threads.
    //
    try (final Connection conn = ConnectionFactory.createConnection(getConf());
            final BufferedMutator mutator = conn.getBufferedMutator(params)) {

        /** worker pool that operates on BufferedTable instances */
        final ExecutorService workerPool = Executors.newFixedThreadPool(POOL_SIZE);
        List<Future<Void>> futures = new ArrayList<>(TASK_COUNT);

        for (int i = 0; i < TASK_COUNT; i++) {
            futures.add(workerPool.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    //
                    // step 2: each worker sends edits to the shared
                    // BufferedMutator instance. They all use
                    // the same backing buffer, call-back "listener", and
                    // RPC executor pool.
                    //
                    Put p = new Put(Bytes.toBytes("someRow"));
                    p.addColumn(FAMILY, Bytes.toBytes("someQualifier"), Bytes.toBytes("some value"));
                    mutator.mutate(p);
                    // do work... maybe you want to call mutator.flush()
                    // after many edits to ensure any of
                    // this worker's edits are sent before exiting the
                    // Callable
                    return null;
                }
            }));
        }

        //
        // step 3: clean up the worker pool, shut down.
        //
        for (Future<Void> f : futures) {
            f.get(5, TimeUnit.MINUTES);
        }
        workerPool.shutdown();
    } catch (IOException e) {
        // exception while creating/destroying Connection or BufferedMutator
        LOG.info("exception while creating/destroying Connection or BufferedMutator", e);
    } // BufferedMutator.close() ensures all work is flushed. Could be the
      // custom listener is
      // invoked from here.
    return 0;
}