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.archive.crawler.extractor.ExtractorHTML.java

/**
 * Run extractor. This method is package visible to ease testing.
 * //from w ww  .j a  v  a  2  s.  c o m
 * @param curi
 *            CrawlURI we're processing.
 * @param cs
 *            Sequence from underlying ReplayCharSequence. This is TRANSIENT
 *            data. Make a copy if you want the data to live outside of this
 *            extractors' lifetime.
 */
void extract(CrawlURI curi, CharSequence cs) {
    Matcher tags = TextUtils.getMatcher(RELEVANT_TAG_EXTRACTOR, cs);

    while (tags.find()) {
        if (Thread.interrupted()) {
            break;
        }
        if (tags.start(8) > 0) {
            // comment match
            // for now do nothing
        } else if (tags.start(7) > 0) {
            // <meta> match
            int start = tags.start(5);
            int end = tags.end(5);
            assert start >= 0 : "Start is: " + start + ", " + curi;
            assert end >= 0 : "End is :" + end + ", " + curi;
            if (processMeta(curi, cs.subSequence(start, end))) {

                // meta tag included NOFOLLOW; abort processing
                break;
            }
        } else if (tags.start(5) > 0) {
            // generic <whatever> match
            int start5 = tags.start(5);
            int end5 = tags.end(5);
            assert start5 >= 0 : "Start is: " + start5 + ", " + curi;
            assert end5 >= 0 : "End is :" + end5 + ", " + curi;
            int start6 = tags.start(6);
            int end6 = tags.end(6);
            assert start6 >= 0 : "Start is: " + start6 + ", " + curi;
            assert end6 >= 0 : "End is :" + end6 + ", " + curi;
            processGeneralTag(curi, cs.subSequence(start6, end6), cs.subSequence(start5, end5));

        } else if (tags.start(1) > 0) {
            // <script> match
            int start = tags.start(1);
            int end = tags.end(1);
            assert start >= 0 : "Start is: " + start + ", " + curi;
            assert end >= 0 : "End is :" + end + ", " + curi;
            assert tags.end(2) >= 0 : "Tags.end(2) illegal " + tags.end(2) + ", " + curi;
            processScript(curi, cs.subSequence(start, end), tags.end(2) - start);

        } else if (tags.start(3) > 0) {
            // <style... match
            int start = tags.start(3);
            int end = tags.end(3);
            assert start >= 0 : "Start is: " + start + ", " + curi;
            assert end >= 0 : "End is :" + end + ", " + curi;
            assert tags.end(4) >= 0 : "Tags.end(4) illegal " + tags.end(4) + ", " + curi;
            processStyle(curi, cs.subSequence(start, end), tags.end(4) - start);
        }
    }
    TextUtils.recycleMatcher(tags);
}

From source file:edu.mit.mobile.android.locast.sync.SyncEngine.java

/**
 * Uploads any unpublished casts./*  w w w . j a v  a2s.  c o  m*/
 *
 * This is the method that does all the hard work.
 *
 * @param toSync
 * @param provider
 * @param syncMap
 * @param syncResult
 * @return the number of casts uploaded.
 * @throws JSONException
 * @throws NetworkProtocolException
 * @throws IOException
 * @throws NoPublicPath
 * @throws RemoteException
 * @throws OperationApplicationException
 * @throws SyncException
 * @throws InterruptedException
 */
private int uploadUnpublished(Uri toSync, Account account, ContentProviderClient provider, SyncMap syncMap,
        HashMap<String, SyncEngine.SyncStatus> syncStatuses, SyncResult syncResult)
        throws JSONException, NetworkProtocolException, IOException, NoPublicPath, RemoteException,
        OperationApplicationException, SyncException, InterruptedException {
    int count = 0;

    final String type = provider.getType(toSync);
    final boolean isDir = type.startsWith(CONTENT_TYPE_PREFIX_DIR);

    final Cursor uploadMe = provider.query(toSync, null, SELECTION_UNPUBLISHED, null, null);

    if (uploadMe == null) {
        throw new SyncException("could not query " + toSync);
    }

    final int idCol = uploadMe.getColumnIndex(JsonSyncableItem._ID);

    try {
        for (uploadMe.moveToFirst(); !uploadMe.isAfterLast(); uploadMe.moveToNext()) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }

            final long id = uploadMe.getLong(idCol);

            final Uri localUri = isDir ? ContentUris.withAppendedId(toSync, id) : toSync;
            final String postUri = MediaProvider.getPostPath(mContext, localUri);

            Intent intent = new Intent(SYNC_STATUS_CHANGED);
            intent.putExtra(EXTRA_SYNC_STATUS, "castBegin");
            intent.putExtra(EXTRA_SYNC_ID, id);
            mContext.sendStickyBroadcast(intent);

            try {
                final JSONObject jo = JsonSyncableItem.toJSON(mContext, localUri, uploadMe, syncMap);

                if (DEBUG) {
                    Log.d(TAG, "uploading " + localUri + " to " + postUri);
                }

                // Upload! Any non-successful responses are handled by
                // exceptions.
                final HttpResponse res = mNetworkClient.post(postUri, jo.toString());

                long serverTime;
                try {
                    serverTime = getServerTime(res);
                    // We should never get a corrupted date from the server,
                    // but if it does happen,
                    // using the local time is a sane fallback.
                } catch (final DateParseException e) {
                    serverTime = System.currentTimeMillis();
                }

                // newly-created items return the JSON serialization of the
                // object as the server
                // knows it, so the local database needs to be updated to
                // reflect that.
                final JSONObject newJo = NetworkClient.toJsonObject(res);
                try {
                    final SyncStatus ss = loadItemFromJsonObject(newJo, syncMap, serverTime);

                    // update immediately, so that any cancellation or
                    // interruption of the sync
                    // keeps the local state in sync with what's on the
                    // server
                    final int updates = provider.update(localUri, ss.remoteCVs, null, null);

                    final String locUriString = localUri.toString();

                    if (updates == 1) {
                        ss.state = SyncState.NOW_UP_TO_DATE;
                        ss.local = localUri;

                        // ensure that it's findable by local URI too
                        syncStatuses.put(locUriString, ss);

                        syncMap.onPostSyncItem(mContext, account, ss.local, ss.remoteJson, true);

                        count++;
                        syncResult.stats.numUpdates++;

                    } else {
                        Log.e(TAG, "error updating " + locUriString);

                        syncResult.stats.numSkippedEntries++;
                    }

                    syncResult.stats.numEntries++;

                } catch (final JSONException e) {
                    if (DEBUG) {
                        Log.e(TAG, "result was " + newJo.toString());
                    }
                    throw e;
                }
            } finally {
                intent = new Intent(SYNC_STATUS_CHANGED);
                intent.putExtra(EXTRA_SYNC_STATUS, "castEnd");
                intent.putExtra(EXTRA_SYNC_ID, id);
                mContext.sendStickyBroadcast(intent);
            }
        }
    } finally {
        uploadMe.close();
    }

    return count;
}

From source file:com.addthis.hydra.task.output.tree.TreeMapper.java

@Override
public QueryHandle query(final Query query, final DataChannelOutput consumer) throws QueryException {
    if (Thread.interrupted()) {
        log.warn("[query] caught/reset thread in a previously interrupted state :: " + Thread.currentThread());
    }/*from  w ww .  j  a  va2s. c o  m*/
    return new QueryThread(query, consumer);
}

From source file:org.micromanager.plugins.magellan.imagedisplay.DisplayOverlayer.java

private void addSurfaceInterpolation(Overlay overlay, SingleResolutionInterpolation interp,
        int displayPixPerInterpTile) throws InterruptedException {
    int width = display_.getImagePlus().getWidth();
    int height = display_.getImagePlus().getHeight();
    ZoomableVirtualStack zStack = (ZoomableVirtualStack) display_.virtualStack_;
    double sliceZ = zStack.getZCoordinateOfDisplayedSlice(display_.getVisibleSliceIndex());
    double zStep = acq_.getZStep();

    //Make numTestPoints a factor of image size for clean display of surface
    int numTestPointsX = width / displayPixPerInterpTile;
    int numTestPointsY = height / displayPixPerInterpTile;
    double roiWidth = width / (double) numTestPointsX;
    double roiHeight = height / (double) numTestPointsY;

    for (int x = 0; x < numTestPointsX; x++) {
        for (int y = 0; y < numTestPointsY; y++) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }/*w w w .  j a  v a2  s.  c o  m*/
            Point2D.Double stageCoord = display_.stageCoordFromImageCoords((int) ((x + 0.5) * roiWidth),
                    (int) ((y + 0.5) * roiHeight));
            if (!interp.isInterpDefined(stageCoord.x, stageCoord.y)) {
                continue;
            }
            float interpZ = interp.getInterpolatedValue(stageCoord.x, stageCoord.y);

            if (Math.abs(sliceZ - interpZ) < zStep / 2) {
                double roiX = roiWidth * x;
                double roiY = roiHeight * y;
                //calculate distance from last ROI for uninterrupted coverage of image
                int displayWidth = (int) (roiWidth * (x + 1)) - (int) (roiX);
                int displayHeight = (int) (roiHeight * (y + 1)) - (int) (roiY);
                Roi rect = new Roi(roiX, roiY, displayWidth, displayHeight); //make ROI
                int[] lutRed = VIRIDIS_RED;
                int[] lutBlue = VIRIDIS_BLUE;
                int[] lutGreen = VIRIDIS_GREEN;
                double colorScale = ((sliceZ - interpZ) / (zStep / 2) + 1) / 2; //between 0 and 1
                rect.setFillColor(new Color(lutRed[(int) (colorScale * lutRed.length)],
                        lutGreen[(int) (colorScale * lutGreen.length)],
                        lutBlue[(int) (colorScale * lutBlue.length)], 175));
                overlay.add(rect);
            }
        }
    }
}

From source file:com.cloudbees.jenkins.plugins.bitbucket.client.BitbucketCloudApiClient.java

private CloseableHttpResponse executeMethod(HttpRequestBase httpMethod)
        throws InterruptedException, IOException {

    if (authenticator != null) {
        authenticator.configureRequest(httpMethod);
    }//  ww w.  j  a  va2 s. c  o  m

    RequestConfig.Builder requestConfig = RequestConfig.custom();
    requestConfig.setConnectTimeout(10 * 1000);
    requestConfig.setConnectionRequestTimeout(60 * 1000);
    requestConfig.setSocketTimeout(60 * 1000);
    httpMethod.setConfig(requestConfig.build());

    CloseableHttpResponse response = client.execute(API_HOST, httpMethod, context);
    while (response.getStatusLine().getStatusCode() == API_RATE_LIMIT_CODE) {
        release(httpMethod);
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
        /*
        TODO: When bitbucket starts supporting rate limit expiration time, remove 5 sec wait and put code
              to wait till expiration time is over. It should also fix the wait for ever loop.
         */
        LOGGER.fine("Bitbucket Cloud API rate limit reached, sleeping for 5 sec then retry...");
        Thread.sleep(5000);
        response = client.execute(API_HOST, httpMethod, context);
    }
    return response;
}

From source file:com.mycompany.trafficimportfileconverter2.Main2Controller.java

private void watchForConsumption() throws IOException {
    WatchService watcher = FileSystems.getDefault().newWatchService();

    try {//from w w  w. j a  v a 2s .com
        Path dir = getOutputDir().toPath();
        WatchKey key = dir.register(watcher, ENTRY_DELETE);

        for (;;) {

            if (Thread.interrupted()) {
                key.cancel();
                return;
            }
            try {
                key = watcher.take();
            } catch (InterruptedException x) {
                return;
            }

            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();

                // This key is registered only
                // for ENTRY_CREATE events,
                // but an OVERFLOW event can
                // occur regardless if events
                // are lost or discarded.
                if (kind == OVERFLOW) {
                    continue;
                }

                //                        // The filename is the
                //                        // context of the event.
                WatchEvent<Path> ev = (WatchEvent<Path>) event;
                Path filepath = ev.context();
                String filename = filepath.toString();
                System.out.println("the filename was: " + filename);
                System.out.println(kind);
                Optional<String> res = findFile(filename);
                if (res.isPresent()) {
                    System.out.println("BEFORE REMOVAL: " + myfiles.toString());
                    System.out.println("removing: " + res.get());
                    removeFromFiles(res.get());
                    System.out.println("Removed. Now: " + myfiles.toString());
                    int dpi = findThisDP(res.get());
                    if (-1 != dpi) {
                        UI(() -> {
                            datePickers[dpi].setStyle("-fx-background-color: lightgreen");
                            dayLabels[dpi].setStyle("-fx-background-color: lightgreen");
                        });
                    }
                    log("Wide Orbit CONSUMED: " + filename);

                } else {
                    System.out.println("is present was false for: " + filename);
                    System.out.println(myfiles.toString());
                }
                // Reset the key -- this step is critical if you want to
                // receive further watch events.  If the key is no longer valid,
                // the directory is inaccessible so exit the loop.
                boolean valid = key.reset();
                if (!valid) {
                    return;
                }
                if (myfiles.isEmpty()) {
                    key.cancel();
                    log("ALL WRITTEN FILES CONSUMED.");
                    System.out.println("\n\n\n");

                    return;
                }
            } //end of events
        } //end of infinite loop

    } catch (IOException x) {
        System.err.println(x);
    } finally {
        Thread.currentThread().interrupt();
    }

}

From source file:org.freelectron.leobel.testlwa.models.AVSAudioPlayer.java

/**
 * Play the alarm sound/* w ww  .  j a  va  2s.co  m*/
 */
public void startAlert() {
    if (!isAlarming()) {
        interruptContent();
        if (isSpeaking()) {
            // alerts are in the background when Alexa is speaking
            alertState = AlertState.INTERRUPTED;
        } else {
            alertState = AlertState.PLAYING;

            alarmThread = new Thread() {
                @Override
                public void run() {
                    while (isAlarming() && !isSpeaking()) {
                        if (Thread.interrupted()) {
                            break;
                        }
                        InputStream inpStream = resLoader.getResourceAsStream("/sdcard/alarm.mp3");
                        synchronized (playLock) {
                            try {
                                play(inpStream, false);
                                while (inpStream.available() > 0) {
                                    playLock.wait(TIMEOUT_IN_MS);
                                }
                            } catch (InterruptedException | IOException e) {
                            }
                        }
                    }
                }
            };
            alarmThread.start();
        }
    }
}

From source file:org.micromanager.plugins.magellan.surfacesandregions.SurfaceInterpolator.java

private synchronized void updateConvexHullAndInterpolate() {
    //duplicate points for use on caluclation thread
    final LinkedList<Point3d> points = new LinkedList<Point3d>(points_);
    if (currentInterpolationTask_ != null && !currentInterpolationTask_.isDone()) {
        //cancel current interpolation because interpolation points have changed, call does not block
        currentInterpolationTask_.cancel(true);
    }/*  w  w  w.  j  a v  a 2  s.  co  m*/
    //don't want one of the get methods returning a null object thinking it has a value
    synchronized (convexHullLock_) {
        convexHullVertices_ = null;
        convexHullRegion_ = null;
    }
    synchronized (interpolationLock_) {
        currentInterpolation_ = null;
    }
    synchronized (xyPositionLock_) {
        xyPositions_ = null;
    }
    numRows_ = 0;
    numCols_ = 0;

    currentInterpolationTask_ = executor_.submit(new Runnable() {
        @Override
        public void run() {
            if (points.size() > 2) {
                try {
                    //convert xyPoints to a vector2d for convex hull calculation
                    LinkedList<Vector2D> xyPoints = new LinkedList<Vector2D>();
                    for (Point3d p : points) {
                        xyPoints.add(new Vector2D(p.x, p.y));
                    }
                    ConvexHull2D hull = null;
                    hull = mChain_.generate(xyPoints);
                    if (Thread.interrupted()) {
                        throw new InterruptedException();
                    }
                    synchronized (convexHullLock_) {
                        convexHullVertices_ = hull.getVertices();
                        convexHullLock_.notifyAll();
                    }
                    if (Thread.interrupted()) {
                        throw new InterruptedException();
                    }
                    convexHullRegion_ = hull.createRegion();
                    if (Thread.interrupted()) {
                        throw new InterruptedException();
                    }
                    calculateConvexHullBounds();
                    if (Thread.interrupted()) {
                        throw new InterruptedException();
                    }
                    //use the most recently set overlap value for display purposes. When it comes time to calc the real thing, 
                    //get it from the acquisition settings
                    fitXYPositionsToConvexHull(FixedAreaAcquisitionSettings.getStoredTileOverlapPercentage());
                    //Interpolate surface as specified by the subclass method
                    interpolateSurface(points);
                    //let manager handle event firing to acquisitions using surface
                    manager_.surfaceUpdated(SurfaceInterpolator.this);
                } catch (InterruptedException e) {
                    return;
                }
            }
        }
    });
}

From source file:org.archive.modules.extractor.ExtractorHTML.java

/**
 * Run extractor./*from  w  ww.  j  a  v  a 2  s . c  om*/
 * This method is package visible to ease testing.
 * @param curi CrawlURI we're processing.
 * @param cs Sequence from underlying ReplayCharSequence. This
 * is TRANSIENT data. Make a copy if you want the data to live outside
 * of this extractors' lifetime.
 */
protected void extract(CrawlURI curi, CharSequence cs) {
    Matcher tags = TextUtils.getMatcher(relevantTagPattern, cs);
    while (tags.find()) {
        if (Thread.interrupted()) {
            break;
        }
        if (tags.start(8) > 0) {
            // comment match
            // for now do nothing
        } else if (tags.start(7) > 0) {
            // <meta> match
            int start = tags.start(5);
            int end = tags.end(5);
            assert start >= 0 : "Start is: " + start + ", " + curi;
            assert end >= 0 : "End is :" + end + ", " + curi;
            if (processMeta(curi, cs.subSequence(start, end))) {

                // meta tag included NOFOLLOW; abort processing
                break;
            }
        } else if (tags.start(5) > 0) {
            // generic <whatever> match
            int start5 = tags.start(5);
            int end5 = tags.end(5);
            assert start5 >= 0 : "Start is: " + start5 + ", " + curi;
            assert end5 >= 0 : "End is :" + end5 + ", " + curi;
            int start6 = tags.start(6);
            int end6 = tags.end(6);
            assert start6 >= 0 : "Start is: " + start6 + ", " + curi;
            assert end6 >= 0 : "End is :" + end6 + ", " + curi;
            String element = cs.subSequence(start6, end6).toString();
            CharSequence attributes = cs.subSequence(start5, end5);
            processGeneralTag(curi, element, attributes);
            // remember FORM to help later extra processing
            if ("form".equalsIgnoreCase(element)) {
                curi.getDataList(A_FORM_OFFSETS).add((Integer) (start6 - 1));
            }

        } else if (tags.start(1) > 0) {
            // <script> match
            int start = tags.start(1);
            int end = tags.end(1);
            assert start >= 0 : "Start is: " + start + ", " + curi;
            assert end >= 0 : "End is :" + end + ", " + curi;
            assert tags.end(2) >= 0 : "Tags.end(2) illegal " + tags.end(2) + ", " + curi;
            processScript(curi, cs.subSequence(start, end), tags.end(2) - start);

        } else if (tags.start(3) > 0) {
            // <style... match
            int start = tags.start(3);
            int end = tags.end(3);
            assert start >= 0 : "Start is: " + start + ", " + curi;
            assert end >= 0 : "End is :" + end + ", " + curi;
            assert tags.end(4) >= 0 : "Tags.end(4) illegal " + tags.end(4) + ", " + curi;
            processStyle(curi, cs.subSequence(start, end), tags.end(4) - start);
        }
    }
    TextUtils.recycleMatcher(tags);
}