Example usage for java.util.concurrent CancellationException CancellationException

List of usage examples for java.util.concurrent CancellationException CancellationException

Introduction

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

Prototype

public CancellationException(String message) 

Source Link

Document

Constructs a CancellationException with the specified detail message.

Usage

From source file:com.amazonaws.mobileconnectors.s3.transfermanager.internal.UploadCallable.java

/**
 * Uploads all parts in the request in serial in this thread, then completes
 * the upload and returns the result.//from  w ww  .j a va 2 s.c  o m
 */
private UploadResult uploadPartsInSeries(UploadPartRequestFactory requestFactory) {

    final List<PartETag> partETags = new ArrayList<PartETag>();

    while (requestFactory.hasMoreRequests()) {
        if (threadPool.isShutdown())
            throw new CancellationException("TransferManager has been shutdown");
        UploadPartRequest uploadPartRequest = requestFactory.getNextUploadPartRequest();
        // Mark the stream in case we need to reset it
        InputStream inputStream = uploadPartRequest.getInputStream();
        if (inputStream != null && inputStream.markSupported()) {
            if (uploadPartRequest.getPartSize() >= Integer.MAX_VALUE) {
                inputStream.mark(Integer.MAX_VALUE);
            } else {
                inputStream.mark((int) uploadPartRequest.getPartSize());
            }
        }
        partETags.add(s3.uploadPart(uploadPartRequest).getPartETag());
    }

    CompleteMultipartUploadResult completeMultipartUploadResult = s3
            .completeMultipartUpload(new CompleteMultipartUploadRequest(putObjectRequest.getBucketName(),
                    putObjectRequest.getKey(), multipartUploadId, partETags));

    UploadResult uploadResult = new UploadResult();
    uploadResult.setBucketName(completeMultipartUploadResult.getBucketName());
    uploadResult.setKey(completeMultipartUploadResult.getKey());
    uploadResult.setETag(completeMultipartUploadResult.getETag());
    uploadResult.setVersionId(completeMultipartUploadResult.getVersionId());
    return uploadResult;
}

From source file:org.apache.hadoop.hbase.master.snapshot.RestoreSnapshotHandler.java

@Override
public void cancel(String why) {
    if (this.stopped)
        return;/*from w ww.j a  v  a2  s.  c  o m*/
    this.stopped = true;
    String msg = "Stopping restore snapshot=" + ClientSnapshotDescriptionUtils.toString(snapshot) + " because: "
            + why;
    LOG.info(msg);
    CancellationException ce = new CancellationException(why);
    this.monitor.receive(new ForeignException(masterServices.getServerName().toString(), ce));
}

From source file:com.microsoft.azuretools.utils.WebAppUtils.java

public static void deployCustomJdk(WebApp webApp, String jdkDownloadUrl, WebContainer webContainer,
        IProgressIndicator indicator) throws IOException, InterruptedException, WebAppException {
    FTPClient ftp = null;/*from  w  w  w .j  a v  a 2s  .c  om*/
    String customJdkFolderName = null;
    try {

        PublishingProfile pp = webApp.getPublishingProfile();
        ftp = getFtpConnection(pp);

        // stop and restart web app
        //            if (indicator != null) indicator.setText("Stopping the service...");
        //            webApp.stop();

        if (indicator != null)
            indicator.setText("Deleting custom jdk artifacts, if any (takes a while)...");
        removeCustomJdkArtifacts(ftp, indicator);

        if (indicator != null)
            indicator.setText("Uploading scripts...");
        uploadJdkDownloadScript(ftp, jdkDownloadUrl);

        //            if (indicator != null) indicator.setText("Starting the service...");
        //            webApp.start();

        final String siteUrl = "https://" + webApp.defaultHostName();

        // send get to activate the script
        sendGet(siteUrl);

        // Polling report.txt...
        if (indicator != null)
            indicator.setText("Checking the JDK gets downloaded and unpacked...");
        //int step = 0;
        while (!doesRemoteFileExist(ftp, ftpRootPath, reportFilename)) {
            if (indicator != null && indicator.isCanceled())
                throw new CancellationException("Canceled by user.");
            //if (step++ > 3) checkFreeSpaceAvailability(ftp);
            Thread.sleep(5000);
            sendGet(siteUrl);
        }

        if (indicator != null)
            indicator.setText("Checking status...");
        OutputStream reportFileStream = new ByteArrayOutputStream();
        ftp.retrieveFile("report.txt", reportFileStream);
        String reportFileString = reportFileStream.toString();
        if (reportFileString.startsWith("FAIL")) {
            String err = reportFileString.substring(reportFileString.indexOf(":" + 1));
            throw new WebAppException(err);
        }

        // get top level jdk folder name (under jdk folder)
        FTPFile[] ftpDirs = ftp.listDirectories(ftpJdkPath);
        if (ftpDirs.length != 1) {
            String err = "Bad JDK archive. Please make sure the JDK archive contains a single JDK folder. For example, 'my-jdk1.7.0_79.zip' archive should contain 'jdk1.7.0_79' folder only";
            throw new WebAppException(err);
        }

        customJdkFolderName = ftpDirs[0].getName();

        uploadWebConfigForCustomJdk(ftp, webApp, customJdkFolderName, webContainer, indicator);
    } catch (IOException | WebAppException | InterruptedException ex) {
        if (doesRemoteFolderExist(ftp, ftpRootPath, jdkFolderName)) {
            indicator.setText("Error happened. Cleaning up...");
            removeFtpDirectory(ftp, ftpJdkPath, indicator);
        }
        throw ex;
    } finally {
        indicator.setText("Removing working data from server...");
        cleanupWorkerData(ftp);
        if (ftp != null && ftp.isConnected()) {
            ftp.disconnect();
        }
    }
}

From source file:org.apache.axis2.jaxws.client.async.AsyncResponse.java

public Object get() throws InterruptedException, ExecutionException {
    if (cancelled) {
        throw new CancellationException(Messages.getMessage("getErr"));
    }/*www . j a  va  2 s. c  o m*/

    // Wait for the response to come back
    if (log.isDebugEnabled()) {
        log.debug("Waiting for async response delivery.");
    }

    // If latch count > 0, it means we have not yet received
    // and processed the async response, and must block the
    // thread.
    latch.await();

    if (savedException != null) {
        throw savedException;
    }

    return responseObject;
}

From source file:com.amazonaws.services.s3.transfer.internal.UploadCallable.java

/**
 * Submits a callable for each part to upload to our thread pool and records its corresponding Future.
 *///  w  ww.j  ava2 s .c o  m
private void uploadPartsInParallel(UploadPartRequestFactory requestFactory, String uploadId) {

    Map<Integer, PartSummary> partNumbers = identifyExistingPartsForResume(uploadId);

    while (requestFactory.hasMoreRequests()) {
        if (threadPool.isShutdown())
            throw new CancellationException("TransferManager has been shutdown");
        UploadPartRequest request = requestFactory.getNextUploadPartRequest();
        if (partNumbers.containsKey(request.getPartNumber())) {
            PartSummary summary = partNumbers.get(request.getPartNumber());
            eTagsToSkip.add(new PartETag(request.getPartNumber(), summary.getETag()));
            continue;
        }
        futures.add(threadPool.submit(new UploadPartCallable(s3, request)));
    }
}

From source file:com.amazonaws.mobileconnectors.s3.transfermanager.internal.UploadCallable.java

/**
 * Submits a callable for each part to upload to our thread pool and records
 * its corresponding Future./*from w w  w  .  j ava2 s . com*/
 */
private void uploadPartsInParallel(UploadPartRequestFactory requestFactory, String uploadId) {

    Map<Integer, PartSummary> partNumbers = identifyExistingPartsForResume(uploadId);

    while (requestFactory.hasMoreRequests()) {
        if (threadPool.isShutdown())
            throw new CancellationException("TransferManager has been shutdown");
        UploadPartRequest request = requestFactory.getNextUploadPartRequest();
        if (partNumbers.containsKey(request.getPartNumber())) {
            PartSummary summary = partNumbers.get(request.getPartNumber());
            eTagsToSkip.add(new PartETag(request.getPartNumber(), summary.getETag()));
            transferProgress.updateProgress(summary.getSize());
            continue;
        }
        futures.add(threadPool.submit(new UploadPartCallable(s3, request)));
    }
}

From source file:org.apache.axis2.jaxws.client.async.AsyncResponse.java

public Object get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
    if (cancelled) {
        throw new CancellationException(Messages.getMessage("getErr"));
    }/*from   w  ww.  jav  a 2s .c  o m*/

    // Wait for the response to come back
    if (log.isDebugEnabled()) {
        log.debug("Waiting for async response delivery with time out.");
        log.debug("timeout = " + timeout);
        log.debug("units   = " + unit);
    }

    // latch.await will only block if its count is > 0
    latch.await(timeout, unit);

    if (savedException != null) {
        throw savedException;
    }

    // If the response still hasn't been returned, then we've timed out
    // and must throw a TimeoutException
    if (latch.getCount() > 0) {
        throw new TimeoutException(Messages.getMessage("getErr1"));
    }

    return responseObject;
}

From source file:org.apache.hadoop.hbase.master.snapshot.TakeSnapshotHandler.java

@Override
public void cancel(String why) {
    if (finished)
        return;/*from   w w w.  ja v a 2s  .  c om*/

    this.finished = true;
    LOG.info("Stop taking snapshot=" + ClientSnapshotDescriptionUtils.toString(snapshot) + " because: " + why);
    CancellationException ce = new CancellationException(why);
    monitor.receive(new ForeignException(master.getServerName().toString(), ce));
}

From source file:org.onosproject.store.consistent.impl.DistributedLeadershipManager.java

private void doWithdraw(String path, CompletableFuture<Void> future) {
    if (activeTopics.contains(path)) {
        future.completeExceptionally(/*ww w  .j av  a 2 s  .c  o  m*/
                new CancellationException(String.format("%s is now a active topic", path)));
    }
    try {
        leaderMap.computeIf(path, localNodeId::equals, (topic, leader) -> null);
        candidateMap.computeIf(path, candidates -> candidates != null && candidates.contains(localNodeId),
                (topic, candidates) -> candidates.stream().filter(nodeId -> !localNodeId.equals(nodeId))
                        .collect(Collectors.toList()));
        future.complete(null);
    } catch (Exception e) {
        log.debug("Failed to verify (and clear) any lock this node might be holding for {}", path, e);
        retryWithdraw(path, future);
    }
}

From source file:org.csploit.android.services.UpdateService.java

/**
 * check if an archive is valid by reading it.
 * @throws RuntimeException if trying to run this with no archive
 *//* w  w w. j  a v a 2s  .c o m*/
private void verifyArchiveIntegrity() throws RuntimeException, KeyException {
    File f;
    long total;
    short old_percentage, percentage;
    CountingInputStream counter;
    ArchiveInputStream is;
    byte[] buffer;
    String rootDirectory;

    Logger.info("verifying archive integrity");

    if (mCurrentTask == null || mCurrentTask.path == null)
        throw new RuntimeException("no archive to test");

    mBuilder.setContentTitle(getString(R.string.checking)).setSmallIcon(android.R.drawable.ic_popup_sync)
            .setContentText("").setContentInfo("").setProgress(100, 0, true);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

    f = new File(mCurrentTask.path);
    try {
        counter = new CountingInputStream(new FileInputStream(f));
    } catch (FileNotFoundException e) {
        throw new RuntimeException(String.format("archive '%s' does not exists", mCurrentTask.path));
    }

    try {
        is = openArchiveStream(counter);
        ArchiveEntry entry;
        buffer = new byte[2048];
        total = f.length();
        old_percentage = -1;
        rootDirectory = null;

        // consume the archive
        while (mRunning && (entry = is.getNextEntry()) != null) {
            if (!mCurrentTask.skipRoot)
                continue;

            String name = entry.getName();

            if (rootDirectory == null) {
                if (name.contains("/")) {
                    rootDirectory = name.substring(0, name.indexOf('/'));
                } else if (entry.isDirectory()) {
                    rootDirectory = name;
                } else {
                    throw new IOException(
                            String.format("archive '%s' contains files under it's root", mCurrentTask.path));
                }
            } else {
                if (!name.startsWith(rootDirectory)) {
                    throw new IOException("multiple directories found in the archive root");
                }
            }
        }

        while (mRunning && is.read(buffer) > 0) {
            percentage = (short) (((double) counter.getBytesRead() / total) * 100);
            if (percentage != old_percentage) {
                mBuilder.setProgress(100, percentage, false).setContentInfo(percentage + "%");
                mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
                old_percentage = percentage;
            }
        }
    } catch (IOException e) {
        throw new KeyException("corrupted archive: " + e.getMessage());
    } finally {
        try {
            counter.close();
        } catch (IOException ignore) {
        }
    }

    if (!mRunning)
        throw new CancellationException("archive integrity check cancelled");

    if (mCurrentTask.skipRoot && rootDirectory == null)
        throw new KeyException(String.format("archive '%s' is empty", mCurrentTask.path));
}