Example usage for java.lang Thread interrupted

List of usage examples for java.lang Thread interrupted

Introduction

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

Prototype

public static boolean interrupted() 

Source Link

Document

Tests whether the current thread has been interrupted.

Usage

From source file:org.axonframework.migration.eventstore.JpaEventStoreMigrator.java

public boolean run() throws Exception {
    final AtomicInteger updateCount = new AtomicInteger();
    final AtomicInteger skipCount = new AtomicInteger();
    final AtomicLong lastId = new AtomicLong(
            Long.parseLong(configuration.getProperty("lastProcessedId", "-1")));
    try {/*from ww w .  ja v a 2  s . c  o  m*/
        TransactionTemplate template = new TransactionTemplate(txManager);
        template.setReadOnly(true);
        System.out.println("Starting conversion. Fetching batches of " + QUERY_BATCH_SIZE + " items.");
        while (template.execute(new TransactionCallback<Boolean>() {
            @Override
            public Boolean doInTransaction(TransactionStatus status) {
                final Session hibernate = entityManager.unwrap(Session.class);
                Iterator<Object[]> results = hibernate.createQuery(
                        "SELECT e.aggregateIdentifier, e.sequenceNumber, e.type, e.id FROM DomainEventEntry e "
                                + "WHERE e.id > :lastIdentifier ORDER BY e.id ASC")
                        .setFetchSize(1000).setMaxResults(QUERY_BATCH_SIZE).setReadOnly(true)
                        .setParameter("lastIdentifier", lastId.get()).iterate();
                if (!results.hasNext()) {
                    System.out.println("Empty batch. Assuming we're done.");
                    return false;
                } else if (Thread.interrupted()) {
                    System.out.println("Received an interrupt. Stopping...");
                    return false;
                }
                while (results.hasNext()) {
                    List<ConversionItem> conversionBatch = new ArrayList<ConversionItem>();
                    while (conversionBatch.size() < CONVERSION_BATCH_SIZE && results.hasNext()) {
                        Object[] item = results.next();
                        String aggregateIdentifier = (String) item[0];
                        long sequenceNumber = (Long) item[1];
                        String type = (String) item[2];
                        Long entryId = (Long) item[3];
                        lastId.set(entryId);
                        conversionBatch
                                .add(new ConversionItem(sequenceNumber, aggregateIdentifier, type, entryId));
                    }
                    if (!conversionBatch.isEmpty()) {
                        executor.submit(new TransformationTask(conversionBatch, skipCount));
                    }
                }
                return true;
            }
        })) {
            System.out.println("Reading next batch, starting at ID " + lastId.get() + ".");
            System.out.println(
                    "Estimated backlog size is currently: " + (workQueue.size() * CONVERSION_BATCH_SIZE));
        }
    } finally {
        executor.shutdown();
        executor.awaitTermination(5, TimeUnit.MINUTES);
        if (lastId.get() >= 0) {
            System.out.println(
                    "Processed events from old event store up to (and including) id = " + lastId.get());
        }
    }
    System.out.println("In total " + updateCount.get() + " items have been converted.");
    return skipCount.get() == 0;
}

From source file:at.bitfire.davdroid.syncadapter.TasksSyncManager.java

@Override
protected void downloadRemote() throws IOException, HttpException, DavException, CalendarStorageException {
    App.log.info("Downloading " + toDownload.size() + " tasks (" + MAX_MULTIGET + " at once)");

    // download new/updated iCalendars from server
    for (DavResource[] bunch : ArrayUtils.partition(toDownload.toArray(new DavResource[toDownload.size()]),
            MAX_MULTIGET)) {//from w  ww  . jav  a 2s . c  o m
        if (Thread.interrupted())
            return;

        App.log.info("Downloading " + StringUtils.join(bunch, ", "));

        if (bunch.length == 1) {
            // only one contact, use GET
            DavResource remote = bunch[0];

            ResponseBody body = remote.get("text/calendar");

            // CalDAV servers MUST return ETag on GET [https://tools.ietf.org/html/rfc4791#section-5.3.4]
            GetETag eTag = (GetETag) remote.properties.get(GetETag.NAME);
            if (eTag == null || StringUtils.isEmpty(eTag.eTag))
                throw new DavException("Received CalDAV GET response without ETag for " + remote.location);

            Charset charset = Charsets.UTF_8;
            MediaType contentType = body.contentType();
            if (contentType != null)
                charset = contentType.charset(Charsets.UTF_8);

            @Cleanup
            InputStream stream = body.byteStream();
            processVTodo(remote.fileName(), eTag.eTag, stream, charset);

        } else {
            // multiple contacts, use multi-get
            List<HttpUrl> urls = new LinkedList<>();
            for (DavResource remote : bunch)
                urls.add(remote.location);
            davCalendar().multiget(urls.toArray(new HttpUrl[urls.size()]));

            // process multiget results
            for (DavResource remote : davCollection.members) {
                String eTag;
                GetETag getETag = (GetETag) remote.properties.get(GetETag.NAME);
                if (getETag != null)
                    eTag = getETag.eTag;
                else
                    throw new DavException("Received multi-get response without ETag");

                Charset charset = Charsets.UTF_8;
                GetContentType getContentType = (GetContentType) remote.properties.get(GetContentType.NAME);
                if (getContentType != null && getContentType.type != null) {
                    MediaType type = MediaType.parse(getContentType.type);
                    if (type != null)
                        charset = type.charset(Charsets.UTF_8);
                }

                CalendarData calendarData = (CalendarData) remote.properties.get(CalendarData.NAME);
                if (calendarData == null || calendarData.iCalendar == null)
                    throw new DavException("Received multi-get response without address data");

                @Cleanup
                InputStream stream = new ByteArrayInputStream(calendarData.iCalendar.getBytes());
                processVTodo(remote.fileName(), eTag, stream, charset);
            }
        }
    }
}

From source file:org.alfresco.extension.bulkfilesystemimport.impl.SingleThreadedBulkFilesystemImporter.java

/**
 * Method that does the work of recursively importing a directory.  The only reason this method exists is to ensure subclasses can
 * cleanly override bulkImportImpl without messing up the mechanics of the recursion.
 * //  w  w  w . ja  va2 s .  com
 * @param target          The target space to ingest the content into <i>(must not be null and must be a valid, writable space in the repository)</i>.
 * @param sourceRoot      The original directory from which this import was initiated <i>(must not be null)</i>.
 * @param source          The source directory on the local filesystem to read content from <i>(must not be null and must be a valid, readable directory on the local filesystem)</i>.
 * @param replaceExisting A flag indicating whether to replace (true) or skip (false) files that are already in the repository.
 * @param inPlaceImport   A flag indicating whether this is an "in place" import (i.e. the source directory is already located inside the configured content store).
 */
protected final void bulkImportRecursively(final NodeRef target, final String sourceRoot, final File source,
        final boolean replaceExisting, final boolean inPlaceImport) throws InterruptedException {
    List<Pair<NodeRef, File>> subDirectories = importDirectory(target, sourceRoot, source, replaceExisting,
            inPlaceImport);

    // Recursively import sub directories
    for (final Pair<NodeRef, File> subDirectory : subDirectories) {
        if (Thread.interrupted())
            break; // Exit ASAP if the thread has been interrupted

        if (subDirectory != null) {
            bulkImportRecursively(subDirectory.getFirst(), sourceRoot, subDirectory.getSecond(),
                    replaceExisting, inPlaceImport);
        }
    }
}

From source file:eu.stratosphere.nephele.io.channels.bytebuffered.AbstractByteBufferedOutputChannel.java

/**
 * Requests a new write buffer from the framework. This method blocks until the requested buffer is available.
 * //w w  w . j a  v  a2  s  .c  om
 * @throws InterruptedException
 *         thrown if the thread is interrupted while waiting for the buffer
 * @throws IOException
 *         thrown if an I/O error occurs while waiting for the buffer
 */
private void requestWriteBufferFromBroker() throws InterruptedException, IOException {
    if (Thread.interrupted()) {
        throw new InterruptedException();
    }
    this.dataBuffer = this.outputChannelBroker.requestEmptyWriteBuffer();
}

From source file:org.geowebcache.seed.GWCTask.java

protected void checkInterrupted() throws InterruptedException {
    if (Thread.interrupted()) {
        this.state = STATE.DEAD;
        throw new InterruptedException();
    }//from w  ww  .  ja v a 2 s . c  o m
}

From source file:io.smartspaces.tasks.SimpleAcceptingPriorityTaskQueue.java

/**
 * Process tasks until the event processing thread is interrupted.
 *//*from  w  ww . j  a v  a 2s .com*/
private void processTasks() {
    try {
        while (!Thread.interrupted()) {
            processNextTask();
        }
    } catch (InterruptedException e) {
        // Don't care
    }
}

From source file:com.nextgis.mobile.map.Layer.java

public boolean isDrawCanceled() {
    return mInterrupted || Thread.interrupted();
}

From source file:io.subutai.plugin.usergrid.rest.RestServiceImpl.java

private OperationState waitUntilOperationFinish(UUID uuid) {
    // OperationState state = OperationState.RUNNING;
    OperationState state = null;//  w ww .  j av  a2 s. c  om
    long start = System.currentTimeMillis();
    while (!Thread.interrupted()) {
        TrackerOperationView po = tracker.getTrackerOperation(UsergridConfig.PRODUCT_KEY, uuid);

        if (po != null) {

            if (po.getState() != OperationState.RUNNING) {
                state = po.getState();
                break;
            }

        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            break;
        }
        if (System.currentTimeMillis() - start > (6000 * 1000)) {
            break;
        }
    }

    return state;
}

From source file:net.technicpack.launchercore.mirror.MirrorStore.java

public Download downloadFile(String url, String name, String output, File cache, IFileVerifier verifier,
        DownloadListener listener) throws IOException, InterruptedException {
    int tries = DOWNLOAD_RETRIES;
    File outputFile = null;/*  w ww . j a v  a2 s. c  o  m*/
    Download download = null;
    while (tries > 0) {
        Utils.getLogger().info("Starting download of " + url + ", with " + tries + " tries remaining");
        tries--;
        download = new Download(getFullUrl(url), name, output);
        download.setListener(listener);
        download.run();
        if (download.getResult() != Download.Result.SUCCESS) {
            if (download.getOutFile() != null) {
                download.getOutFile().delete();
            }

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

            System.err.println("Download of " + url + " Failed!");
            if (listener != null) {
                listener.stateChanged("Download failed, retries remaining: " + tries, 0F);
            }
        } else {
            if (download.getOutFile().exists()
                    && (verifier == null || verifier.isFileValid(download.getOutFile()))) {
                outputFile = download.getOutFile();
                break;
            }
        }
    }
    if (outputFile == null) {
        throw new DownloadException("Failed to download " + url,
                download != null ? download.getException() : null);
    }
    if (cache != null) {
        FileUtils.copyFile(outputFile, cache);
    }
    return download;
}

From source file:com.jeremyhaberman.playgrounds.WebPlaygroundDAO.java

@Override
public Collection<Playground> getAll(Context context) {
    // synchronized (Swingset.initPlaygroundLock) {
    playgrounds = new ArrayList<Playground>();
    String result = swingset.getResources().getString(R.string.error);
    HttpURLConnection httpConnection = null;
    Log.d(TAG, "getPlaygrounds()");

    try {//w ww  .j a  v  a 2 s  .  c o m
        // Check if task has been interrupted
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }

        // Build query
        URL url = new URL("http://swingsetweb.appspot.com/playground");
        httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setConnectTimeout(15000);
        httpConnection.setReadTimeout(15000);
        StringBuilder response = new StringBuilder();

        if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // Read results from the query
            BufferedReader input = new BufferedReader(
                    new InputStreamReader(httpConnection.getInputStream(), "UTF-8"));
            String strLine = null;
            while ((strLine = input.readLine()) != null) {
                response.append(strLine);
            }
            input.close();

        }

        // Parse to get translated text
        JSONArray jsonPlaygrounds = new JSONArray(response.toString());
        int numOfPlaygrounds = jsonPlaygrounds.length();

        JSONObject jsonPlayground = null;

        for (int i = 0; i < numOfPlaygrounds; i++) {
            jsonPlayground = jsonPlaygrounds.getJSONObject(i);
            playgrounds.add(toPlayground(jsonPlayground));
        }

    } catch (Exception e) {
        Log.e(TAG, "Exception", e);
        Intent errorIntent = new Intent(context, Playgrounds.class);
        errorIntent.putExtra("Exception", e.getLocalizedMessage());
        errorIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(errorIntent);
    } finally {
        if (httpConnection != null) {
            httpConnection.disconnect();
        }
    }

    // all done
    Log.d(TAG, "   -> returned " + result);
    return playgrounds;
    // }
}