Example usage for java.util.concurrent FutureTask cancel

List of usage examples for java.util.concurrent FutureTask cancel

Introduction

In this page you can find the example usage for java.util.concurrent FutureTask cancel.

Prototype

public boolean cancel(boolean mayInterruptIfRunning) 

Source Link

Usage

From source file:ubic.gemma.loader.util.fetcher.FtpArchiveFetcher.java

@Override
protected Collection<LocalFile> doTask(FutureTask<Boolean> future, long expectedSize, String seekFileName,
        String outputFileName) {/* w w  w .  ja v  a  2  s.co  m*/
    Executors.newSingleThreadExecutor().execute(future);
    try {
        File outputFile = new File(outputFileName);
        boolean ok = waitForDownload(future, expectedSize, outputFile);

        if (!ok) {
            // probably cancelled.
            return null;
        } else if (future.get().booleanValue()) {
            log.info("Unpacking " + outputFile);
            unPack(outputFile);
            cleanUp(outputFile);
            if (outputFile.isDirectory())
                return listFiles(seekFileName, outputFile, null);

            return listFiles(seekFileName, outputFile.getParentFile(), null);
        }
    } catch (ExecutionException e) {
        future.cancel(true);
        throw new RuntimeException(
                "Couldn't fetch " + seekFileName + " from " + this.getNetDataSourceUtil().getHost(), e);
    } catch (InterruptedException e) {
        future.cancel(true);
        throw new RuntimeException("Interrupted: Couldn't fetch " + seekFileName + " from "
                + this.getNetDataSourceUtil().getHost(), e);
    } catch (IOException e) {
        future.cancel(true);
        throw new RuntimeException("IOException: Couldn't fetch " + seekFileName + " from "
                + this.getNetDataSourceUtil().getHost(), e);
    }
    future.cancel(true);
    throw new RuntimeException(
            "Couldn't fetch " + seekFileName + " from " + this.getNetDataSourceUtil().getHost());
}

From source file:ubic.gemma.core.loader.util.fetcher.FtpArchiveFetcher.java

@Override
protected Collection<LocalFile> doTask(FutureTask<Boolean> future, long expectedSize, String seekFileName,
        String outputFileName) {/*  w  ww.  j av  a2 s.c o  m*/
    Executors.newSingleThreadExecutor().execute(future);
    try {
        File outputFile = new File(outputFileName);
        boolean ok = this.waitForDownload(future, expectedSize, outputFile);

        if (!ok) {
            // probably cancelled.
            return null;
        } else if (future.get()) {
            AbstractFetcher.log.info("Unpacking " + outputFile);
            this.unPack(outputFile);
            this.cleanUp(outputFile);
            if (outputFile.isDirectory())
                return this.listFiles(seekFileName, outputFile, null);

            return this.listFiles(seekFileName, outputFile.getParentFile(), null);
        }
    } catch (ExecutionException e) {
        future.cancel(true);
        throw new RuntimeException(
                "Couldn't fetch " + seekFileName + " from " + this.getNetDataSourceUtil().getHost(), e);
    } catch (InterruptedException e) {
        future.cancel(true);
        throw new RuntimeException("Interrupted: Couldn't fetch " + seekFileName + " from "
                + this.getNetDataSourceUtil().getHost(), e);
    } catch (IOException e) {
        future.cancel(true);
        throw new RuntimeException("IOException: Couldn't fetch " + seekFileName + " from "
                + this.getNetDataSourceUtil().getHost(), e);
    }
    future.cancel(true);
    throw new RuntimeException(
            "Couldn't fetch " + seekFileName + " from " + this.getNetDataSourceUtil().getHost());
}

From source file:com.skymobi.monitor.action.LogsAction.java

@RequestMapping(value = "/projects/{projectName}/logs/more", method = RequestMethod.GET)
public void console(final HttpServletResponse response, ModelMap map, @PathVariable String projectName,
        LogQuery logQuery) throws IOException, ParseException {
    Project project = projectService.findProject(projectName);
    map.put("project", project);
    final MongoConverter converter = project.fetchMongoTemplate().getConverter();
    final DBCursor cursor = logsService.findLogs(projectName, logQuery);
    final StringBuffer buf = new StringBuffer();
    @SuppressWarnings("unchecked")
    FutureTask<String> task = new FutureTask(new Callable<String>() {
        @Override/* ww  w .  j a  v a2  s  .  c om*/
        public String call() throws Exception {
            long startTime = System.currentTimeMillis();
            //???20
            logger.debug("result:");
            while (cursor.hasNext()) {
                Log log = converter.read(Log.class, cursor.next());

                buf.insert(0, log.toString() + "\n");
                long current = System.currentTimeMillis();
                if ((current - startTime) / 1000 >= mongWaitSeconds)
                    break;
            }
            return buf.toString();
        }
    });
    executor.execute(task);
    try {
        task.get(mongWaitSeconds + 5, TimeUnit.SECONDS);
        cursor.close();
    } catch (Exception e) {
        logger.error("time out ", e);
        task.cancel(true);
    }

    response.setContentType("text/html;charset=UTF-8");
    response.getWriter().write(buf.toString());
    response.getWriter().flush();

}

From source file:org.nuxeo.ecm.core.event.impl.PostCommitEventExecutor.java

public void run(List<EventListenerDescriptor> listeners, EventBundle bundle, long timeoutMillis, boolean bulk) {
    // check that there's at list one listener interested
    boolean some = false;
    for (EventListenerDescriptor listener : listeners) {
        if (listener.acceptBundle(bundle)) {
            some = true;//from   ww  w.j av a  2 s .  co  m
            break;
        }
    }
    if (!some) {
        if (log.isDebugEnabled()) {
            log.debug("Events postcommit execution has nothing to do");
        }
        return;
    }

    if (log.isDebugEnabled()) {
        log.debug(String.format("Events postcommit execution starting with timeout %sms%s",
                Long.valueOf(timeoutMillis), bulk ? " in bulk mode" : ""));
    }

    Callable<Boolean> callable = !bulk ? new EventBundleRunner(listeners, bundle)
            : new EventBundleBulkRunner(listeners, bundle);
    FutureTask<Boolean> futureTask = new FutureTask<Boolean>(callable);
    try {
        executor.execute(futureTask);
    } catch (RejectedExecutionException e) {
        log.error("Events postcommit execution rejected", e);
        return;
    }
    try {
        // wait for runner to be finished, with timeout
        Boolean ok = futureTask.get(timeoutMillis, TimeUnit.MILLISECONDS);
        if (Boolean.FALSE.equals(ok)) {
            log.error("Events postcommit bulk execution aborted due to previous error");
        }
    } catch (InterruptedException e) {
        // restore interrupted status
        Thread.currentThread().interrupt();
        // interrupt thread
        futureTask.cancel(true); // mayInterruptIfRunning=true
    } catch (TimeoutException e) {
        if (!bulk) {
            log.warn(String.format(
                    "Events postcommit execution exceeded timeout of %sms, leaving thread running",
                    Long.valueOf(timeoutMillis)));
            // don't cancel task, let it run
        } else {
            log.error(String.format(
                    "Events postcommit bulk execution exceeded timeout of %sms, interrupting thread",
                    Long.valueOf(timeoutMillis)));
            futureTask.cancel(true); // mayInterruptIfRunning=true
        }
    } catch (ExecutionException e) {
        log.error("Events postcommit execution encountered unexpected exception", e.getCause());
    }

    if (log.isDebugEnabled()) {
        log.debug("Events postcommit execution finished");
    }
}

From source file:com.eclectide.intellij.whatthecommit.WhatTheCommitAction.java

public String loadCommitMessage(final String url) {
    final FutureTask<String> downloadTask = new FutureTask<String>(new Callable<String>() {
        public String call() {
            final HttpClient client = new HttpClient();
            final GetMethod getMethod = new GetMethod(url);
            try {
                final int statusCode = client.executeMethod(getMethod);
                if (statusCode != HttpStatus.SC_OK)
                    throw new RuntimeException("Connection error (HTTP status = " + statusCode + ")");
                return getMethod.getResponseBodyAsString();
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            }/*from   w w  w .  j  ava 2 s . co  m*/
        }
    });

    ApplicationManager.getApplication().executeOnPooledThread(downloadTask);

    try {
        return downloadTask.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        // ignore
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    if (!downloadTask.isDone()) {
        downloadTask.cancel(true);
        throw new RuntimeException("Connection timed out");
    }

    return "";
}

From source file:org.springframework.batch.core.step.tasklet.SystemCommandTasklet.java

/**
 * Execute system command and map its exit code to {@link ExitStatus} using
 * {@link SystemProcessExitCodeMapper}.//from   www  .  j a va  2 s .com
 */
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {

    FutureTask<Integer> systemCommandTask = new FutureTask<Integer>(new Callable<Integer>() {

        @Override
        public Integer call() throws Exception {
            Process process = Runtime.getRuntime().exec(command, environmentParams, workingDirectory);
            return process.waitFor();
        }

    });

    long t0 = System.currentTimeMillis();

    taskExecutor.execute(systemCommandTask);

    while (true) {
        Thread.sleep(checkInterval);//moved to the end of the logic

        if (stoppable) {
            JobExecution jobExecution = jobExplorer
                    .getJobExecution(chunkContext.getStepContext().getStepExecution().getJobExecutionId());

            if (jobExecution.isStopping()) {
                stopped = true;
            }
        }

        if (systemCommandTask.isDone()) {
            contribution.setExitStatus(systemProcessExitCodeMapper.getExitStatus(systemCommandTask.get()));
            return RepeatStatus.FINISHED;
        } else if (System.currentTimeMillis() - t0 > timeout) {
            systemCommandTask.cancel(interruptOnCancel);
            throw new SystemCommandException("Execution of system command did not finish within the timeout");
        } else if (execution.isTerminateOnly()) {
            systemCommandTask.cancel(interruptOnCancel);
            throw new JobInterruptedException(
                    "Job interrupted while executing system command '" + command + "'");
        } else if (stopped) {
            systemCommandTask.cancel(interruptOnCancel);
            contribution.setExitStatus(ExitStatus.STOPPED);
            return RepeatStatus.FINISHED;
        }
    }
}

From source file:org.apache.ambari.server.KdcServerConnectionVerification.java

/**
 * Attempt to communicate with KDC server over UDP.
 * @param server KDC hostname or IP address
 * @param port   KDC server port/* ww w  .j  a  v  a  2  s  .c  o  m*/
 * @return  true if communication is successful; false otherwise
 */
public boolean isKdcReachableViaUDP(final String server, final int port) {
    int timeoutMillis = udpTimeout * 1000;
    final KdcConfig config = KdcConfig.getDefaultConfig();
    config.setHostName(server);
    config.setKdcPort(port);
    config.setUseUdp(true);
    config.setTimeout(timeoutMillis);

    final KdcConnection connection = getKdcUdpConnection(config);
    FutureTask<Boolean> future = new FutureTask<Boolean>(new Callable<Boolean>() {
        @Override
        public Boolean call() {
            try {
                // we are only testing whether we can communicate with server and not
                // validating credentials
                connection.getTgt("noUser@noRealm", "noPassword");
            } catch (KerberosException e) {
                // unfortunately, need to look at msg as error 60 is a generic error code
                return !(e.getErrorCode() == ErrorType.KRB_ERR_GENERIC.getValue()
                        && e.getMessage().contains("TimeOut"));
                //todo: evaluate other error codes to provide better information
                //todo: as there may be other error codes where we should return false
            } catch (Exception e) {
                // some bad unexpected thing occurred
                throw new RuntimeException(e);
            }
            return true;
        }
    });

    new Thread(future, "ambari-kdc-verify").start();
    Boolean result;
    try {
        // timeout after specified timeout
        result = future.get(timeoutMillis, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        LOG.error("Interrupted while trying to communicate with KDC server over UDP");
        result = false;
        future.cancel(true);
    } catch (ExecutionException e) {
        LOG.error(
                "An unexpected exception occurred while attempting to communicate with the KDC server over UDP",
                e);
        result = false;
    } catch (TimeoutException e) {
        LOG.error("Timeout occurred while attempting to to communicate with KDC server over UDP");
        result = false;
        future.cancel(true);
    }

    return result;
}

From source file:com.google.android.dialer.provider.DialerProvider.java

private <T> T execute(Callable<T> callable, String name, long time, TimeUnit timeUnit) {
    FutureCallable<T> futureCallable = new FutureCallable<T>(callable);
    FutureTask<T> future = new FutureTask<T>(futureCallable);
    futureCallable.setFuture(future);//from ww w . j  av  a 2  s .  c o m

    synchronized (mActiveTasks) {
        mActiveTasks.addLast(future);
        if (Log.isLoggable("DialerProvider", Log.VERBOSE)) {
            Log.v("DialerProvider", "Currently running tasks: " + mActiveTasks.size());
        }
        while (mActiveTasks.size() > 8) {
            Log.w("DialerProvider", "Too many tasks, canceling one");
            mActiveTasks.removeFirst().cancel(true);
        }
    }

    if (Log.isLoggable("DialerProvider", Log.VERBOSE)) {
        Log.v("DialerProvider", "Starting task " + name);
    }

    new Thread(future, name).start();
    try {
        if (Log.isLoggable("DialerProvider", Log.VERBOSE)) {
            Log.v("DialerProvider", "Getting future " + name);
        }
        return future.get(time, timeUnit);
    } catch (InterruptedException e) {
        Log.w("DialerProvider", "Task was interrupted: " + name);
        Thread.currentThread().interrupt();
    } catch (ExecutionException e) {
        Log.w("DialerProvider", "Task threw an exception: " + name, e);
    } catch (TimeoutException e) {
        Log.w("DialerProvider", "Task timed out: " + name);
        future.cancel(true);
    } catch (CancellationException e) {
        Log.w("DialerProvider", "Task was cancelled: " + name);
    }

    // TODO: Is this appropriate?
    return null;
}

From source file:net.yacy.cora.protocol.http.HTTPClient.java

private void execute(final HttpUriRequest httpUriRequest, final boolean concurrent) throws IOException {
    final HttpClientContext context = HttpClientContext.create();
    context.setRequestConfig(reqConfBuilder.build());
    if (this.host != null)
        context.setTargetHost(new HttpHost(this.host));

    setHeaders(httpUriRequest);//from   w  w  w  .j  a  v a2s.  co m
    // statistics
    storeConnectionInfo(httpUriRequest);
    // execute the method; some asserts confirm that that the request can be send with Content-Length and is therefore not terminated by EOF
    if (httpUriRequest instanceof HttpEntityEnclosingRequest) {
        final HttpEntityEnclosingRequest hrequest = (HttpEntityEnclosingRequest) httpUriRequest;
        final HttpEntity entity = hrequest.getEntity();
        assert entity != null;
        //assert !entity.isChunked();
        //assert entity.getContentLength() >= 0;
        assert !hrequest.expectContinue();
    }

    final String initialThreadName = Thread.currentThread().getName();
    Thread.currentThread().setName("HTTPClient-" + httpUriRequest.getURI());
    final long time = System.currentTimeMillis();
    try {

        if (concurrent) {
            FutureTask<CloseableHttpResponse> t = new FutureTask<CloseableHttpResponse>(
                    new Callable<CloseableHttpResponse>() {
                        @Override
                        public CloseableHttpResponse call() throws ClientProtocolException, IOException {
                            final CloseableHttpClient client = clientBuilder.build();
                            CloseableHttpResponse response = client.execute(httpUriRequest, context);
                            return response;
                        }
                    });
            executor.execute(t);
            try {
                this.httpResponse = t.get(this.timeout, TimeUnit.MILLISECONDS);
            } catch (ExecutionException e) {
                throw e.getCause();
            } catch (Throwable e) {
            }
            try {
                t.cancel(true);
            } catch (Throwable e) {
            }
            if (this.httpResponse == null)
                throw new IOException("timout to client after " + this.timeout + "ms" + " for url "
                        + httpUriRequest.getURI().toString());
        } else {
            final CloseableHttpClient client = clientBuilder.build();
            this.httpResponse = client.execute(httpUriRequest, context);
        }
        this.httpResponse.setHeader(HeaderFramework.RESPONSE_TIME_MILLIS,
                Long.toString(System.currentTimeMillis() - time));
    } catch (final Throwable e) {
        ConnectionInfo.removeConnection(httpUriRequest.hashCode());
        httpUriRequest.abort();
        if (this.httpResponse != null)
            this.httpResponse.close();
        //e.printStackTrace();
        throw new IOException(
                "Client can't execute: " + (e.getCause() == null ? e.getMessage() : e.getCause().getMessage())
                        + " duration=" + Long.toString(System.currentTimeMillis() - time) + " for url "
                        + httpUriRequest.getURI().toString());
    } finally {
        /* Restore the thread initial name */
        Thread.currentThread().setName(initialThreadName);
    }
}

From source file:org.alfresco.repo.rendition.executer.AbstractTransformationRenderingEngine.java

@Override
protected void render(RenderingContext context) {
    ContentReader contentReader = context.makeContentReader();
    // There will have been an exception if there is no content data so contentReader is not null.
    String sourceUrl = contentReader.getContentUrl();
    String sourceMimeType = contentReader.getMimetype();
    String targetMimeType = getTargetMimeType(context);

    // The child NodeRef gets created here
    TransformationOptions options = getTransformOptions(context);

    // Log the following getTransform() as trace so we can see the wood for the trees
    ContentTransformer transformer;/*from   w ww  . ja v a2s .  com*/
    boolean orig = TransformerDebug.setDebugOutput(false);
    try {
        transformer = this.contentService.getTransformer(sourceUrl, sourceMimeType, contentReader.getSize(),
                targetMimeType, options);
    } finally {
        TransformerDebug.setDebugOutput(orig);
    }

    if (null == transformer) {
        // There's no transformer available for the requested rendition!
        throw new RenditionServiceException(
                String.format(TRANSFORMER_NOT_EXISTS_MESSAGE_PATTERN, sourceMimeType, targetMimeType));
    }

    if (!transformer.isTransformable(sourceMimeType, contentReader.getSize(), targetMimeType, options)) {
        throw new RenditionServiceException(
                String.format(NOT_TRANSFORMABLE_MESSAGE_PATTERN, sourceMimeType, targetMimeType));
    }

    long startTime = new Date().getTime();
    boolean actionCancelled = false;
    boolean actionCompleted = false;

    // Cache the execution summary to get details later
    ExecutionSummary executionSummary = null;
    try {
        executionSummary = getExecutionSummary(context);
    } catch (ActionServiceException e) {
        if (logger.isInfoEnabled()) {
            logger.info("Cancelling of multiple concurrent action instances "
                    + "currently unsupported, this action can't be cancelled");
        }
    }

    // Call the transform in a different thread so we can move on if cancelled
    FutureTask<ContentWriter> transformTask = new FutureTask<ContentWriter>(new TransformationCallable(
            contentReader, targetMimeType, options, context, AuthenticationUtil.getFullyAuthenticatedUser()));
    getExecutorService().execute(transformTask);

    // Start checking for cancellation or timeout
    while (true) {
        try {
            Thread.sleep(CANCELLED_ACTION_POLLING_INTERVAL);
            if (transformTask.isDone()) {
                actionCompleted = true;
                break;
            }
            // Check timeout in case transformer doesn't obey it
            if (options.getTimeoutMs() > 0 && new Date().getTime()
                    - startTime > (options.getTimeoutMs() + CANCELLED_ACTION_POLLING_INTERVAL)) {
                // We hit a timeout, let the transform thread continue but results will be ignored
                if (logger.isDebugEnabled()) {
                    logger.debug(
                            "Transformation did not obey timeout limit, " + "rendition action is moving on");
                }
                break;
            }
            if (executionSummary != null) {
                ExecutionDetails executionDetails = actionTrackingService.getExecutionDetails(executionSummary);
                if (executionDetails != null) {
                    actionCancelled = executionDetails.isCancelRequested();
                    if (actionCancelled) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Cancelling transformation");
                        }
                        transformTask.cancel(true);
                        break;
                    }
                }
            }
        } catch (InterruptedException e) {
            // entire thread was asked to stop
            actionCancelled = true;
            transformTask.cancel(true);
            break;
        }
    }

    if (actionCancelled) {
        throw new RenditionCancelledException("Rendition action cancelled");
    }

    if (!actionCompleted && !actionCancelled) {
        throw new RenditionServiceException("Transformation failed to obey timeout limit");
    }

    if (actionCompleted) {
        // Copy content from temp writer to real writer
        ContentWriter writer = context.makeContentWriter();
        try {
            // We should not need another timeout here, things should be ready for us
            ContentWriter tempTarget = transformTask.get();
            if (tempTarget == null) {
                // We should never be in this state, but just in case
                throw new RenditionServiceException("Target of transformation not present");
            }
            writer.putContent(tempTarget.getReader().getContentInputStream());
        } catch (ExecutionException e) {
            // Unwrap our cause and throw that
            Throwable transformException = e.getCause();
            if (transformException instanceof RuntimeException) {
                throw (RuntimeException) e.getCause();
            }
            throw new RenditionServiceException(TRANSFORMING_ERROR_MESSAGE + e.getCause().getMessage(),
                    e.getCause());
        } catch (InterruptedException e) {
            // We were asked to stop
            transformTask.cancel(true);
        }
    }
}