Example usage for java.lang InterruptedException InterruptedException

List of usage examples for java.lang InterruptedException InterruptedException

Introduction

In this page you can find the example usage for java.lang InterruptedException InterruptedException.

Prototype

public InterruptedException() 

Source Link

Document

Constructs an InterruptedException with no detail message.

Usage

From source file:org.zenoss.app.consumer.metric.impl.OpenTsdbWriter.java

void runUntilCanceled() throws InterruptedException {
    ExponentialBackOff backoffTracker = null;
    while (!isCanceled()) {
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }/*  ww  w  .j  a  va 2s  . c o m*/
        Collection<Metric> metrics = metricsQueue.poll(batchSize, maxIdleTime);
        log.debug("Back from polling metricsQueue. metrics.size = {}",
                null == metrics ? "null" : metrics.size());
        // Check to see if we should down this writer entirely.
        log.debug("Checking for shutdown. lastWorkTime = {}; maxIdleTime = {}; sum = {}; currentTime ={}",
                lastWorkTime, maxIdleTime, lastWorkTime + maxIdleTime, System.currentTimeMillis());
        if (isNullOrEmpty(metrics) && // No records could be read from the metrics queue
                lastWorkTime > 0 && // This thread has done work at least once
                maxIdleTime > 0 && // The max idle time is set to something meaningful
                System.currentTimeMillis() > lastWorkTime + maxIdleTime) // The max idle time has expired
        {
            log.info("Shutting down writer due to dearth of work");
            break;
        }

        /*
         * If all the conditions were not met for shutting this writer down,
         * we still might want to just abort this run if we didn't get any
         * data from the metrics queue
         */
        if (isNullOrEmpty(metrics)) {
            log.debug("No work to do, so checking again.");
            continue;
        }

        // We have some work to do, some process what we got from the metrics queue
        if (backoffTracker == null) {
            backoffTracker = createExponentialBackOff();
        }
        try {
            processBatch(metrics);
            backoffTracker.reset();
        } catch (NoSuchElementException e) {
            long backOff = this.minBackOff;
            try {
                backOff = backoffTracker.nextBackOffMillis();
            } catch (IOException e1) {
                // shouldn't happen but if it does we'll use the default backOff
                log.debug("caught IOException backing off tracker - should go to default backOff.");
            }
            if (ExponentialBackOff.STOP == backOff) {
                // We've reached the max amount of time to backoff, use max backoff
                backOff = backoffTracker.getMaxIntervalMillis();
                log.warn("Error getting OpenTsdbClient after {} ms: {}", backoffTracker.getElapsedTimeMillis(),
                        e.getMessage());
            }
            log.debug("Connection back off, sleeping {} ms", backOff);
            Thread.sleep(backOff);
        }
    }
    log.debug("work canceled.");
}

From source file:tap.formatter.JSONFormat.java

@Override
public void writeResult(TableIterator result, OutputStream output, TAPExecutionReport execReport, Thread thread)
        throws TAPException, IOException, InterruptedException {
    try {//from   www  . j a  v  a2s  . c o  m

        // Prepare the output stream for JSON:
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
        JSONWriter out = new JSONWriter(writer);

        // {
        out.object();

        // "metadata": [...]
        out.key("metadata");

        // Write metadata part:
        DBColumn[] columns = writeMetadata(result, out, execReport, thread);

        writer.flush();

        if (thread.isInterrupted())
            throw new InterruptedException();

        // "data": [...]
        out.key("data");

        // Write the data part:
        writeData(result, columns, out, execReport, thread);

        // }
        out.endObject();
        writer.flush();

    } catch (JSONException je) {
        throw new TAPException(je.getMessage(), je);
    }
}

From source file:net.technicpack.utilslib.ZipUtils.java

public static void unzipFile(File zip, File output, IZipFileFilter fileFilter, DownloadListener listener)
        throws IOException, InterruptedException {
    if (!zip.exists()) {
        Utils.getLogger().log(Level.SEVERE, "File to unzip does not exist: " + zip.getAbsolutePath());
        return;/*  w w w.  j  a  v  a2 s  . c  o m*/
    }
    if (!output.exists()) {
        output.mkdirs();
    }

    ZipFile zipFile = new ZipFile(zip);
    int size = zipFile.size() + 1;
    int progress = 1;
    try {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            if (Thread.interrupted())
                throw new InterruptedException();

            ZipEntry entry = null;

            try {
                entry = entries.nextElement();
            } catch (IllegalArgumentException ex) {
                //We must catch & rethrow as a zip exception because some crappy code in the zip lib will
                //throw illegal argument exceptions for malformed zips.
                throw new ZipException("IllegalArgumentException while parsing next element.");
            }

            if (!entry.getName().contains("../")
                    && (fileFilter == null || fileFilter.shouldExtract(entry.getName()))) {
                File outputFile = new File(output, entry.getName());

                if (outputFile.getParentFile() != null) {
                    outputFile.getParentFile().mkdirs();
                }

                if (!entry.isDirectory()) {
                    unzipEntry(zipFile, entry, outputFile);
                }
            }

            if (listener != null) {
                float totalProgress = (float) progress / (float) size;
                listener.stateChanged("Extracting " + entry.getName() + "...", totalProgress * 100.0f);
            }
            progress++;
        }
    } finally {
        zipFile.close();
    }
}

From source file:com.appunite.socketio.SocketIOBase.java

private ConnectionResult connect(String url)
        throws WrongHttpResponseCode, IOException, WrongSocketIOResponse, InterruptedException {
    Uri uri = Uri.parse(url);/*from w  w  w.j av a2s  .  co  m*/

    synchronized (mInterruptionLock) {
        if (mInterrupted) {
            throw new InterruptedException();
        }
        mRequest = new HttpGet(url);
    }
    HTTPUtils.setupDefaultHeaders(mRequest);

    HttpResponse response = getClient().execute(mRequest);
    synchronized (mInterruptionLock) {
        if (mRequest.isAborted() || mInterrupted) {
            mRequest = null;
            throw new InterruptedException();
        }
        mRequest = null;
    }
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new WrongHttpResponseCode(response);
    }

    String responseStr = HTTPUtils.getStringFromResponse(response);
    StringTokenizer responseSplit = new StringTokenizer(responseStr, ":");

    ConnectionResult result = new ConnectionResult();
    try {
        result.sessionId = responseSplit.nextToken();
        if (TextUtils.isEmpty(result.sessionId)) {
            throw new WrongSocketIOResponse("Empty socket io session id");
        }

        result.timeout = getIntOrAbsetFromString(responseSplit.nextToken());
        result.heartbeat = getIntOrAbsetFromString(responseSplit.nextToken());

        ImmutableSet<String> types = getTypesFromString(responseSplit.nextToken());
        if (!types.contains("websocket")) {
            throw new WrongSocketIOResponse("Websocket not found in server response");
        }
    } catch (NoSuchElementException e) {
        throw new WrongSocketIOResponse("Not enough color separated values in response", e);
    }
    result.socketUri = new Uri.Builder().scheme("ws").encodedAuthority(uri.getEncodedAuthority())
            .path(uri.getPath()).appendPath("websocket").appendPath(result.sessionId).build();
    return result;
}

From source file:org.ut.biolab.medsavant.client.util.ExportVCF.java

public static File exportTDF(File destFile, MedSavantWorker worker, Condition[][] conditions) throws Exception {
    System.out.println("Requesting table export from server...");
    int fileID = MedSavantClient.VariantManager.exportVariants(LoginController.getSessionID(),
            ProjectController.getInstance().getCurrentProjectID(),
            ReferenceController.getInstance().getCurrentReferenceID(), conditions, false, true);

    if (worker != null) {
        if (worker.isCancelled()) {
            throw new InterruptedException();
        }//from w  w w .j  a v  a  2 s. co  m
        worker.showProgress(0.5);
    }

    System.out.println("Transferring export from server to " + destFile.getAbsolutePath() + " ...");
    ClientNetworkUtils.moveFileFromServer(fileID, destFile);
    System.out.println("Table transferred");

    File resultingFile;

    if (IOUtils.isZipped(destFile)) {
        resultingFile = IOUtils.unzipFile(destFile, destFile.getParentFile().getAbsolutePath()).get(0);
        destFile.delete();
    } else {
        resultingFile = destFile;
    }

    if (worker != null) {
        worker.showProgress(1);
    }

    return resultingFile;
}

From source file:org.mule.modules.cookbook.CookbookConnector.java

/**
 * Description for getRecentlyAddedSource
 *
 * {@sample.xml ../../../doc/cook-book-connector.xml.sample cook-book:getRecentlyAddedSource}
 *
 * @param callback/*from  w  w w. j av  a 2 s.c o m*/
 *            The callback that will hook the result into mule event.
 * @throws Exception
 *             When the source fails.
 */
@OAuthProtected
@Source(sourceStrategy = SourceStrategy.POLLING, pollingPeriod = 10000)
public void getRecentlyAddedSource(final SourceCallback callback) throws Exception {

    if (this.getConfig().getClient() != null) {
        // Every 5 seconds our callback will be executed
        this.getConfig().getClient().getRecentlyAdded(new ICookbookCallback() {

            @Override
            public void execute(List<Recipe> recipes) throws Exception {
                callback.process(recipes);
            }
        });

        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
    }
}

From source file:org.globus.ftp.vanilla.TransferMonitor.java

public void run() {

    try {/*from  w  ww .jav a 2 s.  c om*/
        // if the other thread had already terminated
        // with an error, behave as if it happened just now.
        if (transferState.hasError()) {
            logger.debug("the other thread terminated before this one started.");
            throw new InterruptedException();
        }

        logger.debug("waiting for 1st reply;  maxWait = " + maxWait + ", ioDelay = " + ioDelay);
        this.controlChannel.waitFor(aborted, ioDelay, maxWait);

        logger.debug("reading first reply");
        Reply firstReply = controlChannel.read();

        // 150 Opening BINARY mode data connection.
        // or
        // 125 Data connection already open; transfer starting
        if (Reply.isPositivePreliminary(firstReply)) {
            transferState.transferStarted();
            logger.debug("first reply OK: " + firstReply.toString());

            for (;;) {

                logger.debug("reading next reply");
                this.controlChannel.waitFor(aborted, ioDelay, maxWait);
                logger.debug("got next reply");
                Reply nextReply = controlChannel.read();

                //perf marker
                if (nextReply.getCode() == 112) {
                    logger.debug("marker arrived: " + nextReply.toString());
                    if (mListener != null) {
                        mListener.markerArrived(new PerfMarker(nextReply.getMessage()));
                    }
                    continue;
                }

                //restart marker
                if (nextReply.getCode() == 111) {
                    logger.debug("marker arrived: " + nextReply.toString());
                    if (mListener != null) {
                        mListener.markerArrived(new GridFTPRestartMarker(nextReply.getMessage()));
                    }
                    continue;
                }

                //226 Transfer complete
                if (nextReply.getCode() == 226) {
                    abortable = false;
                    logger.debug("transfer complete: " + nextReply.toString());
                    break;
                }

                // any other reply
                logger.debug("unexpected reply: " + nextReply.toString());
                logger.debug("exiting the transfer thread");
                ServerException e = ServerException.embedUnexpectedReplyCodeException(
                        new UnexpectedReplyCodeException(nextReply), "Server reported transfer failure");

                transferState.transferError(e);
                other.abort();
                break;
            }

        } else { //first reply negative
            logger.debug("first reply bad: " + firstReply.toString());
            logger.debug("category: " + firstReply.getCategory());
            abortable = false;
            ServerException e = ServerException
                    .embedUnexpectedReplyCodeException(new UnexpectedReplyCodeException(firstReply));

            transferState.transferError(e);
            other.abort();
        }

        logger.debug("thread dying naturally");

    } catch (InterruptedException td) {
        //other transfer thread called abort()
        logger.debug("thread dying of InterruptedException.");
        transferState.transferError(td);
    } catch (InterruptedIOException td) {
        //other transfer thread called abort() which occurred
        //while this thread was performing IO
        logger.debug("thread dying of InterruptedIOException.");
        transferState.transferError(td);
    } catch (IOException e) {
        logger.debug("thread dying of IOException");
        transferState.transferError(e);
        other.abort();

    } catch (FTPReplyParseException rpe) {
        logger.debug("thread dying of FTPReplyParseException");
        ServerException se = ServerException.embedFTPReplyParseException(rpe);
        transferState.transferError(se);
        other.abort();
    } catch (ServerException e) {
        logger.debug("thread dying of timeout");
        transferState.transferError(e);
        other.abort();
    } finally {
        done();
        transferState.transferDone();
    }
}

From source file:com.serphacker.serposcope.scraper.google.scraper.GoogleScraper.java

public GoogleScrapResult scrap(GoogleScrapSearch search) throws InterruptedException {
    lastSerpHtml = null;/*from   www  .  ja v  a  2s. c  o m*/
    captchas = 0;
    List<String> urls = new ArrayList<>();
    prepareHttpClient(search);
    long resultsNumber = 0;

    String referrer = "https://" + buildHost(search) + "/";
    for (int page = 0; page < search.getPages(); page++) {

        if (Thread.interrupted()) {
            throw new InterruptedException();
        }

        String url = buildRequestUrl(search, page);

        Status status = null;
        for (int retry = 0; retry < MAX_RETRY; retry++) {

            LOG.debug("GET {} via {} try {}", url,
                    http.getProxy() == null ? new DirectNoProxy() : http.getProxy(), retry + 1);

            status = downloadSerp(url, referrer, search);
            if (status == Status.OK) {
                status = parseSerp(urls);
                if (status == Status.OK) {
                    break;
                }
            }

            if (!isRetryableStatus(status)) {
                break;
            }
        }

        if (status != Status.OK) {
            return new GoogleScrapResult(status, urls, captchas);
        }

        if (page == 0) {
            resultsNumber = parseResultsNumberOnFirstPage();
        }

        if (!hasNextPage()) {
            break;
        }

        long pause = search.getRandomPagePauseMS();
        if (pause > 0) {
            try {
                LOG.trace("sleeping {} milliseconds", pause);
                Thread.sleep(pause);
            } catch (InterruptedException ex) {
                throw ex;
            }
        }
    }
    return new GoogleScrapResult(Status.OK, urls, captchas, resultsNumber);
}

From source file:savant.data.sources.BigWigDataSource.java

@Override
public List<GenericContinuousRecord> getRecords(String ref, RangeAdapter range, Resolution resolution,
        RecordFilterAdapter filt) throws IOException, InterruptedException {
    List<GenericContinuousRecord> result = new ArrayList<GenericContinuousRecord>();
    try {//from  w  ww  . ja v a 2 s  .  c o m
        BigWigIterator wigIterator = bbReader.getBigWigIterator(ref, range.getFrom(), ref, range.getTo(),
                false);
        int nextPos = range.getFrom();
        int rangeEnd = range.getTo();
        while (wigIterator.hasNext()) {
            WigItem wig = wigIterator.next();

            int datumStart = wig.getStartBase();
            int datumEnd = wig.getEndBase();
            float value = wig.getWigValue();

            while (nextPos < datumStart && nextPos <= rangeEnd) {
                result.add(GenericContinuousRecord.valueOf(ref, nextPos, Float.NaN));
                nextPos++;
            }
            while (nextPos < datumEnd && nextPos <= rangeEnd) {
                result.add(GenericContinuousRecord.valueOf(ref, nextPos, value));
                nextPos++;
            }
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }
        }
    } catch (RuntimeException ignored) {
        // If BigWig reader has no data in the given range, it throws a RuntimeException.  Really?  Who does that?
    }
    return result;
}

From source file:net.wimpi.telnetd.util.Mutex.java

public void acquire() throws InterruptedException {
    //log.debug("acquire()::" + Thread.currentThread().toString());
    if (Thread.interrupted())
        throw new InterruptedException();
    synchronized (this) {
        try {//from   w  w  w. j  a  v a 2 s . c o m
            while (inuse_)
                wait();
            inuse_ = true;
        } catch (InterruptedException ex) {
            notify();
            throw ex;
        }
    }
}