Example usage for java.util.concurrent Future cancel

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

Introduction

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

Prototype

boolean cancel(boolean mayInterruptIfRunning);

Source Link

Document

Attempts to cancel execution of this task.

Usage

From source file:org.apache.nifi.controller.StandardProcessorNode.java

/**
 * Will invoke lifecycle operation (OnScheduled or OnUnscheduled)
 * asynchronously to ensure that it could be interrupted if stop action was
 * initiated on the processor that may be infinitely blocking in such
 * operation. While this approach paves the way for further enhancements
 * related to managing processor'slife-cycle operation at the moment the
 * interrupt will not happen automatically. This is primarily to preserve
 * the existing behavior of the NiFi where stop operation can only be
 * invoked once the processor is started. Unfortunately that could mean that
 * the processor may be blocking indefinitely in lifecycle operation
 * (OnScheduled or OnUnscheduled). To deal with that a new NiFi property has
 * been introduced <i>nifi.processor.scheduling.timeout</i> which allows one
 * to set the time (in milliseconds) of how long to wait before canceling
 * such lifecycle operation (OnScheduled or OnUnscheduled) allowing
 * processor's stop sequence to proceed. The default value for this property
 * is {@link Long#MAX_VALUE}.//  ww w . j  av  a  2 s . c  o m
 * <p>
 * NOTE: Canceling the task does not guarantee that the task will actually
 * completes (successfully or otherwise), since cancellation of the task
 * will issue a simple Thread.interrupt(). However code inside of lifecycle
 * operation (OnScheduled or OnUnscheduled) is written purely and will
 * ignore thread interrupts you may end up with runaway thread which may
 * eventually require NiFi reboot. In any event, the above explanation will
 * be logged (WARN) informing a user so further actions could be taken.
 * </p>
 */
private <T> void invokeTaskAsCancelableFuture(final SchedulingAgentCallback callback, final Callable<T> task) {
    final String timeoutString = nifiProperties.getProperty(NiFiProperties.PROCESSOR_SCHEDULING_TIMEOUT);
    final long onScheduleTimeout = timeoutString == null ? 60000
            : FormatUtils.getTimeDuration(timeoutString.trim(), TimeUnit.MILLISECONDS);
    final Future<?> taskFuture = callback.invokeMonitoringTask(task);
    try {
        taskFuture.get(onScheduleTimeout, TimeUnit.MILLISECONDS);
    } catch (final InterruptedException e) {
        LOG.warn("Thread was interrupted while waiting for processor '"
                + this.processor.getClass().getSimpleName() + "' lifecycle OnScheduled operation to finish.");
        Thread.currentThread().interrupt();
        throw new RuntimeException("Interrupted while executing one of processor's OnScheduled tasks.", e);
    } catch (final TimeoutException e) {
        taskFuture.cancel(true);
        LOG.warn("Timed out while waiting for OnScheduled of '" + this.processor.getClass().getSimpleName()
                + "' processor to finish. An attempt is made to cancel the task via Thread.interrupt(). However it does not "
                + "guarantee that the task will be canceled since the code inside current OnScheduled operation may "
                + "have been written to ignore interrupts which may result in a runaway thread. This could lead to more issues, "
                + "eventually requiring NiFi to be restarted. This is usually a bug in the target Processor '"
                + this.processor + "' that needs to be documented, reported and eventually fixed.");
        throw new RuntimeException("Timed out while executing one of processor's OnScheduled task.", e);
    } catch (final ExecutionException e) {
        throw new RuntimeException("Failed while executing one of processor's OnScheduled task.", e);
    } finally {
        callback.postMonitor();
    }
}

From source file:pl.nask.hsn2.service.urlfollower.WebClientWorker.java

private ProcessedPage getInsecurePagesChain(final ProcessedPage processedPage)
        throws IOException, BreakingChainException, ExecutionException, TimeoutException {
    final WebRequest req = insecurePagesChaingInitialization(processedPage);
    ExecutorService ex = Executors.newSingleThreadExecutor();
    Future<Page> f = ex.submit(new Callable<Page>() {
        @Override/*from w w w.  ja  v a 2s  .c  o m*/
        public Page call() throws IOException {
            return wc.getPage(processedPage.getPage().getEnclosingWindow(), req);
        }
    });
    Page p = null;
    try {
        if (!interruptProcessing) {
            if (taskParams.getPageTimeoutMillis() <= 0) {
                p = f.get();
            } else {
                p = f.get(taskParams.getPageTimeoutMillis(), TimeUnit.MILLISECONDS);
            }
        }
    } catch (InterruptedException e) {
        LOGGER.warn("Gathering {} interrupted", req.getUrl());
        Thread.currentThread().interrupt();
    } catch (java.util.concurrent.TimeoutException e) {
        throw new TimeoutException("Timeout when gathering:" + req.getUrl(), e);
    } finally {
        if (f != null) {
            f.cancel(true);
        }
        closeExecutorWithJSDisabled(ex);
    }
    return insecurePagesChainPostprocessing(processedPage, p);
}

From source file:org.apache.hadoop.hdfs.DFSInputStream.java

private void cancelAll(List<Future<ByteBuffer>> futures) {
    for (Future<ByteBuffer> future : futures) {
        // Unfortunately, hdfs reads do not take kindly to interruption.
        // Threads return a variety of interrupted-type exceptions but
        // also complaints about invalid pbs -- likely because read
        // is interrupted before gets whole pb.  Also verbose WARN
        // logging.  So, for now, do not interrupt running read.
        future.cancel(false);
    }//  w w w. jav  a2s . co m
}

From source file:com.mellanox.r4h.DFSInputStream.java

private void cancelAll(List<Future<ByteBuffer>> futures) {
    for (Future<ByteBuffer> future : futures) {
        // Unfortunately, hdfs reads do not take kindly to interruption.
        // Threads return a variety of interrupted-type exceptions but
        // also complaints about invalid pbs -- likely because read
        // is interrupted before gets whole pb. Also verbose WARN
        // logging. So, for now, do not interrupt running read.
        future.cancel(false);
    }/*  w w w  .j  a  v  a2  s  .  c  o m*/
}

From source file:pl.nask.hsn2.service.urlfollower.WebClientWorker.java

public final Page getInsecurePage(String url) throws IOException, ExecutionException, TimeoutException {
    final WebRequest req = insecurePageInitialization(url);
    long processingTime = System.currentTimeMillis();
    ExecutorService ex = Executors.newSingleThreadExecutor();
    Future<Page> f = ex.submit(new Callable<Page>() {
        @Override//  w  w w.j  a va2 s.  c  o m
        public Page call() throws IOException {
            ctx.addTimeAttribute("download_time_start", System.currentTimeMillis());
            Page page = wc.getPage(req);
            ctx.addTimeAttribute("download_time_end", System.currentTimeMillis());
            return page;
        }
    });
    Page page = null;
    try {
        if (!interruptProcessing) {
            if (taskParams.getPageTimeoutMillis() <= 0) {
                page = f.get();
            } else {
                page = f.get(taskParams.getPageTimeoutMillis(), TimeUnit.MILLISECONDS);
            }
        }
    } catch (InterruptedException e) {
        LOGGER.warn("Gathering {} interrupted", url);
        Thread.currentThread().interrupt();
    } catch (java.util.concurrent.TimeoutException e) {
        throw new TimeoutException(
                "Timeout when gathering (" + taskParams.getPageTimeoutMillis() + " ms):" + url, e);
    } finally {
        if (f != null) {
            f.cancel(true);
        }
        closeExecutorWithJSDisabled(ex);
    }
    processingTime = System.currentTimeMillis() - processingTime;
    insecurePagePostprocessing(url, processingTime, page);
    return page;
}

From source file:com.seafile.seadroid2.provider.SeafileProvider.java

@Override
public ParcelFileDescriptor openDocument(final String documentId, final String mode,
        final CancellationSignal signal) throws FileNotFoundException {

    if (!Utils.isNetworkOn())
        throw new FileNotFoundException();

    // open the file. this might involve talking to the seafile server. this will hang until
    // it is done.
    final Future<ParcelFileDescriptor> future = ConcurrentAsyncTask
            .submit(new Callable<ParcelFileDescriptor>() {

                @Override/*w ww .j a v  a 2  s  . c  o  m*/
                public ParcelFileDescriptor call() throws Exception {

                    String path = docIdParser.getPathFromId(documentId);
                    DataManager dm = createDataManager(documentId);
                    String repoId = DocumentIdParser.getRepoIdFromId(documentId);

                    // we can assume that the repo is cached because the client has already seen it
                    SeafRepo repo = dm.getCachedRepoByID(repoId);
                    if (repo == null)
                        throw new FileNotFoundException();

                    File f = getFile(signal, dm, repo, path);

                    // return the file to the client.
                    String parentPath = Utils.getParentPath(path);
                    return makeParcelFileDescriptor(dm, repo.getName(), repoId, parentPath, f, mode);
                }
            });

    if (signal != null) {
        signal.setOnCancelListener(new CancellationSignal.OnCancelListener() {
            @Override
            public void onCancel() {
                Log.d(DEBUG_TAG, "openDocument cancelling download");
                future.cancel(true);
            }
        });
    }

    try {
        return future.get();
    } catch (InterruptedException e) {
        Log.d(DEBUG_TAG, "openDocument cancelled download");
        throw new FileNotFoundException();
    } catch (CancellationException e) {
        Log.d(DEBUG_TAG, "openDocumentThumbnail cancelled download");
        throw new FileNotFoundException();
    } catch (ExecutionException e) {
        Log.d(DEBUG_TAG, "could not open file", e);
        throw new FileNotFoundException();
    }
}

From source file:org.apache.stratos.integration.common.TopologyHandler.java

/**
 * Assert application Inactive status//  ww  w  .ja  v  a 2  s  .co  m
 *
 * @param applicationId
 * @param timeout
 */
public void assertApplicationInActiveStatus(final String applicationId, final int timeout)
        throws InterruptedException {
    log.info(String.format(
            "Asserting application status INACTIVE for [application-id] %s within [timeout] %d ms...",
            applicationId, timeout));
    final long startTime = System.currentTimeMillis();
    final Object synObject = new Object();
    ApplicationInstanceInactivatedEventListener inactivatedEventListener = new ApplicationInstanceInactivatedEventListener() {
        @Override
        protected void onEvent(Event event) {
            Application application = ApplicationManager.getApplications().getApplication(applicationId);
            if (application == null || application.getStatus() == ApplicationStatus.Inactive) {
                synchronized (synObject) {
                    synObject.notify();
                }
            }
        }
    };
    applicationsEventReceiver.addEventListener(inactivatedEventListener);

    Future future = executorService.submit(new Runnable() {
        @Override
        public void run() {
            Application application = ApplicationManager.getApplications().getApplication(applicationId);
            while (!((application != null) && (application.getStatus() == ApplicationStatus.Inactive))) {
                if ((System.currentTimeMillis() - startTime) > timeout) {
                    log.error(String.format(
                            "Application [application-id] %s did not become inactive within [timeout] %d",
                            applicationId, timeout));
                    break;
                }
                ApplicationStatus currentStatus = (application != null) ? application.getStatus() : null;
                log.info(String.format(
                        "Waiting for [application-id] %s [current-status] %s to become [status] %s...",
                        applicationId, currentStatus, ApplicationStatus.Inactive));
                sleep(10000);
                application = ApplicationManager.getApplications().getApplication(applicationId);
            }
            synchronized (synObject) {
                synObject.notify();
            }
        }
    });

    synchronized (synObject) {
        synObject.wait();
        future.cancel(true);
        applicationsEventReceiver.removeEventListener(inactivatedEventListener);
    }
    Application application = ApplicationManager.getApplications().getApplication(applicationId);
    ApplicationStatus currentStatus = (application != null) ? application.getStatus() : null;
    log.info(String.format(
            "Assert application inactive status for [application-id] %s [current-status] %s took %d ms",
            applicationId, currentStatus, System.currentTimeMillis() - startTime));
    assertNotNull(String.format("Application is not found: [application-id] %s", applicationId), application);
    assertEquals(
            String.format("Application status did not change to %s: [application-id] %s",
                    ApplicationStatus.Inactive, applicationId),
            ApplicationStatus.Inactive, application.getStatus());
}

From source file:org.apache.stratos.integration.common.TopologyHandler.java

/**
 * Assert application Active status//from   www  .  j a  v a2 s  .  com
 *
 * @param applicationId
 */
public void assertApplicationActiveStatus(final String applicationId) throws InterruptedException {
    log.info(String.format("Asserting application status ACTIVE for [application-id] %s...", applicationId));
    final long startTime = System.currentTimeMillis();
    final Object synObject = new Object();
    ApplicationInstanceActivatedEventListener activatedEventListener = new ApplicationInstanceActivatedEventListener() {
        @Override
        protected void onEvent(Event event) {
            ApplicationInstanceActivatedEvent activatedEvent = (ApplicationInstanceActivatedEvent) event;
            Application application = ApplicationManager.getApplications().getApplication(applicationId);
            if (application == null) {
                log.warn(String.format("Application is null: [application-id] %s, [instance-id] %s",
                        applicationId, activatedEvent.getInstanceId()));
            }
            if (application != null && application.getStatus() == ApplicationStatus.Active) {
                synchronized (synObject) {
                    synObject.notify();
                }
            }
        }
    };
    applicationsEventReceiver.addEventListener(activatedEventListener);

    Future future = executorService.submit(new Runnable() {
        @Override
        public void run() {
            Application application = ApplicationManager.getApplications().getApplication(applicationId);
            while (!((application != null) && (application.getStatus() == ApplicationStatus.Active))) {
                if ((System.currentTimeMillis() - startTime) > APPLICATION_ACTIVATION_TIMEOUT) {
                    log.error(String.format(
                            "Application [application-id] %s did not activate within [timeout] %d",
                            applicationId, APPLICATION_ACTIVATION_TIMEOUT));
                    break;
                }
                ApplicationStatus currentStatus = (application != null) ? application.getStatus() : null;
                log.info(String.format(
                        "Waiting for [application-id] %s [current-status] %s to become [status] %s...",
                        applicationId, currentStatus, ApplicationStatus.Active));
                sleep(10000);
                application = ApplicationManager.getApplications().getApplication(applicationId);
            }
            synchronized (synObject) {
                synObject.notify();
            }
        }
    });

    synchronized (synObject) {
        synObject.wait();
        future.cancel(true);
        applicationsEventReceiver.removeEventListener(activatedEventListener);
    }

    Application application = ApplicationManager.getApplications().getApplication(applicationId);
    ApplicationStatus currentStatus = (application != null) ? application.getStatus() : null;
    log.info(String.format(
            "Assert application active status for [application-id] %s [current-status] %s took %d ms",
            applicationId, currentStatus, System.currentTimeMillis() - startTime));
    assertNotNull(String.format("Application is not found: [application-id] %s", applicationId), application);
    assertEquals(
            String.format("Application status did not change to %s: [application-id] %s",
                    ApplicationStatus.Active, applicationId),
            ApplicationStatus.Active, application.getStatus());
}

From source file:com.utdallas.s3lab.smvhunter.monkey.MonkeyMe.java

@Override
public void run() {
    if (logDebug)
        logger.debug("starting thread");
    while (!apkQueue.isEmpty()) {
        File apkFile = apkQueue.poll();
        String apkName = apkFile.getName();

        //check if the apk has been tested already
        if (completedApps.contains(apkName) || seenApks.contains(apkName)) {
            logger.info(String.format("app %s already tested. Skipping ============", apkName));
            continue;
        }//from   w w w. j  a  v a 2 s . co  m

        //add it to the seen apks
        seenApks.add(apkName);

        IDevice device = null;
        try {

            //get the package name from the apk name
            String[] nameArr = apkName.split("-");
            String packageName = nameArr[0];

            List<StaticResultBean> staticResultBeans = resultFromStaticAnalysis.get(apkName);

            //install only if interested 
            if (staticResultBeans != null && !staticResultBeans.isEmpty()) {
                //get a device from pool
                device = DevicePool.getinstance().getDeviceFromPool();

                if (logDebug)
                    logger.debug(String.format("%s installing apk %s", device.getSerialNumber(), apkFile));
                //install the apk
                installApk(apkName, device, packageName, 0);
            } else { //not interested
                continue;
            }

            logger.info("No of screens to traverse " + staticResultBeans.size());

            //start the app and attach strace
            //strace will run for the whole lifetime of the app
            //e.g. start the app  adb shell am start -n ao.bai.https
            execCommand(String.format("%s shell am start -n %s", getDeviceString(device),
                    apkName.replace("-", "/").replace(".apk", "")));
            Future<?> networkFuture = executors.submit(new NetworkMonitor(device, packageName));

            //for each vulnerable entry point from static analysis
            for (StaticResultBean resBean : staticResultBeans) {
                String seed = resBean.getSeedName();
                String seedType = resBean.getSeedType();

                //reset the window before proceeding
                //press enter two times
                execCommand(String.format("%s %s", getDeviceString(device), "shell input keyevent 66"));
                execCommand(String.format("%s %s", getDeviceString(device), "shell input keyevent 66"));

                //seed type can be either activity or service
                //dont process if it is not of the type activity
                if (StringUtils.equalsIgnoreCase(seedType, "activity")) {
                    //start activity
                    //format adb shell am start -n com.ifs.banking.fiid1027/com.banking.activities.ContactUsActivity
                    String result = execCommand(String.format("%s %s %s/%s", getDeviceString(device),
                            " shell am start -n ", packageName, seed));
                    logger.info("Activity started with result : " + result);
                    Thread.sleep(5000);

                    //get smart input for this method
                    List<SmartInputBean> smart = resultFromSmartInputGeneration.get(seed);

                    //perform UI automation
                    enumerateCurrentWindow(device, apkName, smart);

                } else if (StringUtils.equalsIgnoreCase(seedType, "service")) {
                    //ignore
                } else {
                    logger.debug(String.format("Did not process seed %s for apk %s ", seed, seedType, apkFile));
                }
            }

            //interrupt the network monitor
            networkFuture.cancel(true);

            //completed 
            writeCompleted(apkName);

            //uninstall the apk
            uninstallApk(packageName, device);

        } catch (Exception e) {
            logger.error("exception occured " + apkName, e);
            //            apkQueue.add(apkFile);
        } finally {
            //return the device to pool
            if (device != null) {
                DevicePool.getinstance().returnDeviceToPool(device);
            }
        }
    }

    //release the latch
    cdl.countDown();
}

From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java

private BasicOCSPResp generateBasicOcspResp(Extensions exts, List<OCSPResponseItem> responses, String sigAlg,
        X509Certificate signerCert, OcspSigningCacheEntry ocspSigningCacheEntry, Date producedAt)
        throws OCSPException, NoSuchProviderException, CryptoTokenOfflineException {
    final PrivateKey signerKey = ocspSigningCacheEntry.getPrivateKey();
    final String provider = ocspSigningCacheEntry.getSignatureProviderName();
    BasicOCSPResp returnval = null;//from  w  w  w  . j  av a  2 s.c o m
    BasicOCSPRespBuilder basicRes = new BasicOCSPRespBuilder(ocspSigningCacheEntry.getRespId());
    if (responses != null) {
        for (OCSPResponseItem item : responses) {
            basicRes.addResponse(item.getCertID(), item.getCertStatus(), item.getThisUpdate(),
                    item.getNextUpdate(), item.getExtensions());
        }
    }
    if (exts != null) {
        @SuppressWarnings("rawtypes")
        Enumeration oids = exts.oids();
        if (oids.hasMoreElements()) {
            basicRes.setResponseExtensions(exts);
        }
    }
    final X509Certificate[] chain = ocspSigningCacheEntry.getResponseCertChain();
    if (log.isDebugEnabled()) {
        log.debug("The response certificate chain contains " + chain.length + " certificates");
    }
    /*
     * The below code breaks the EJB standard by creating its own thread pool and creating a single thread (of the HsmResponseThread 
     * type). The reason for this is that the HSM may deadlock when requesting an OCSP response, which we need to guard against. Since 
     * there is no way of performing this action within the EJB3.0 standard, we are consciously creating threads here. 
     * 
     * Note that this does in no way break the spirit of the EJB standard, which is to not interrupt EJB's transaction handling by 
     * competing with its own thread pool, since these operations have no database impact.
     */
    final Future<BasicOCSPResp> task = service
            .submit(new HsmResponseThread(basicRes, sigAlg, signerKey, chain, provider, producedAt));
    try {
        returnval = task.get(HsmResponseThread.HSM_TIMEOUT_SECONDS, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        task.cancel(true);
        throw new Error("OCSP response retrieval was interrupted while running. This should not happen", e);
    } catch (ExecutionException e) {
        task.cancel(true);
        throw new OcspFailureException("Failure encountered while retrieving OCSP response.", e);
    } catch (TimeoutException e) {
        task.cancel(true);
        throw new CryptoTokenOfflineException("HSM timed out while trying to get OCSP response", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Signing OCSP response with OCSP signer cert: " + signerCert.getSubjectDN().getName());
    }
    if (!returnval.getResponderId().equals(ocspSigningCacheEntry.getRespId())) {
        log.error("Response responderId does not match signer certificate responderId!");
        throw new OcspFailureException("Response responderId does not match signer certificate responderId!");
    }
    if (!ocspSigningCacheEntry.checkResponseSignatureVerified()) {
        // We only check the response signature the first time for each OcspSigningCacheEntry to detect a misbehaving HSM.
        // The client is still responsible for validating the signature, see RFC 6960 Section 3.2.2
        boolean verify;
        try {
            verify = returnval
                    .isSignatureValid(new JcaContentVerifierProviderBuilder().build(signerCert.getPublicKey()));
        } catch (OperatorCreationException e) {
            // Very fatal error
            throw new EJBException("Can not create Jca content signer: ", e);
        }
        if (verify) {
            if (log.isDebugEnabled()) {
                log.debug("The OCSP response is verifying.");
            }
        } else {
            log.error("The response is NOT verifying! Attempted to sign using "
                    + CertTools.getSubjectDN(signerCert) + " but signature was not valid.");
            throw new OcspFailureException("Attempted to sign using " + CertTools.getSubjectDN(signerCert)
                    + " but signature was not valid.");
        }
    }
    return returnval;
}