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.muckebox.android.net.DownloadRunnable.java

public boolean downloadFile() throws IOException {
    MuckeboxHttpClient httpClient = new MuckeboxHttpClient();
    HttpGet httpGet = null;/*from ww  w. jav  a2  s.c o m*/

    try {
        httpGet = new HttpGet(getDownloadUrl());
        httpGet.addHeader("Range", String.format("bytes=%d-", mBytesTotal));

        HttpResponse httpResponse = httpClient.execute(httpGet);
        StatusLine statusLine = httpResponse.getStatusLine();

        if (statusLine.getStatusCode() != 200) {
            Log.e(LOG_TAG, "HTTP request failed, response: '" + statusLine.getReasonPhrase() + "'");

            return false;
        }

        HttpEntity httpEntity = httpResponse.getEntity();

        String mimeType = httpEntity.getContentType().getValue();
        InputStream is = httpEntity.getContent();

        Log.i(LOG_TAG, "Downloading from " + httpGet.getURI() + " (offset " + mBytesTotal + ")");

        ensureOutputStream(mimeType);

        while (true) {
            ByteBuffer buf = ByteBuffer.allocate(BUFFER_SIZE);
            boolean eosReached = BufferUtils.readIntoBuffer(is, buf);

            handleReceivedData(buf);

            if (eosReached) {
                Log.v(LOG_TAG, "Download finished!");

                Result res = makeResult(mimeType, mBytesTotal);

                if (mHandler != null)
                    mHandler.sendMessage(
                            mHandler.obtainMessage(MESSAGE_DOWNLOAD_FINISHED, (int) mTrackId, 0, res));

                return true;
            }

            if (Thread.interrupted()) {
                throw new ClosedByInterruptException();
            }
        }
    } finally {
        if (httpGet != null)
            httpGet.abort();

        if (httpClient != null)
            httpClient.destroy();
    }
}

From source file:com.tasktop.c2c.server.scm.web.GitHandler.java

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final boolean containerSupportsChunkedIO = computeContainerSupportsChunkedIO();

    String pathInfo = request.getPathInfo();
    log.info("Git request: " + request.getMethod() + " " + request.getRequestURI() + " " + pathInfo);

    Repository repository = null;//from  www .  ja  v a  2  s. c om
    try {
        // only work on Git requests
        Matcher matcher = pathInfo == null ? null : GIT_COMMAND_PATTERN.matcher(pathInfo);
        if (matcher == null || !matcher.matches()) {
            log.info("Unexpected path: " + pathInfo);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        String requestCommand = matcher.group(1);
        String requestPath = matcher.group(2);

        // sanity check on path, disallow path separator components
        if (requestPath == null || requestPath.contains("/") || requestPath.contains("..")) {
            badPathResponse();
        }

        repository = repositoryResolver.open(request, requestPath);

        InputStream requestInput = request.getInputStream();
        if (!containerSupportsChunkedIO) {
            requestInput = new ChunkedInputStream(requestInput);
        }

        MultiplexingOutputStream mox = createMultiplexingOutputStream(response, containerSupportsChunkedIO);
        // indicate that we're ok to handle the request
        // note that following this there will be a two-way communication with the process
        // that might still encounter errors. That's ok.
        startOkResponse(response, containerSupportsChunkedIO);

        // identify the git command
        GitCommand command = GitCommand.fromCommandName(requestCommand);
        if (command != null) {
            // permissions check
            if (!Security.hasOneOfRoles(command.getRoles())) {
                log.info("Access denied to " + Security.getCurrentUser() + " for " + command.getCommandName()
                        + " on " + TenancyUtil.getCurrentTenantProjectIdentifer() + " " + requestPath);
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
            switch (command) {
            case RECEIVE_PACK:
                ReceivePack rp = new ReceivePack(repository);
                rp.setPostReceiveHook(postReceiveHook);
                rp.receive(requestInput, mox.stream(PacketType.STDOUT), mox.stream(PacketType.STDERR));
                break;
            case UPLOAD_PACK:
                UploadPack up = new UploadPack(repository);
                up.upload(requestInput, mox.stream(PacketType.STDOUT), mox.stream(PacketType.STDERR));
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
        }

        // at this stage we're done with IO
        // send the exit value and closing chunk
        try {
            int exitValue = 0;

            if (exitValue != 0) {
                log.info("Exit value: " + exitValue);
            }
            mox.writeExitCode(exitValue);
            mox.close();
        } catch (IOException e) {
            // ignore
            log.debug("Cannot complete writing exit state", e);
        }

        // clear interrupt status
        Thread.interrupted();

    } catch (ErrorResponseException e) {
        createGitErrorResponse(response, containerSupportsChunkedIO, e.getMessage());
    } catch (ServiceNotAuthorizedException e) {
        createGitErrorResponse(response, containerSupportsChunkedIO, e.getMessage());
    } catch (ServiceNotEnabledException e) {
        createGitErrorResponse(response, containerSupportsChunkedIO, e.getMessage());
    } finally {
        log.info("Git request complete");
        if (repository != null) {
            repository.close();
        }
    }
}

From source file:net.sourceforge.vulcan.core.support.ProjectBuilderTest.java

@Override
protected void tearDown() throws Exception {
    super.tearDown();
    Thread.interrupted();
}

From source file:org.apache.tomee.jul.handler.rotating.ArchivingTest.java

@SuppressWarnings("unchecked")
@Test/*from ww w.ja  va  2 s  .co m*/
public void logAndRotateAndPurge() throws Exception {
    clean("target/ArchivingTestPurge-" + format + "/logs");

    final AtomicReference<String> today = new AtomicReference<>();
    final Map<String, String> config = new HashMap<>();

    // initial config
    today.set("2015-09-01");
    config.put("filenamePattern", "target/ArchivingTestPurge-" + format + "/logs/test.%s.%d.log");
    config.put("archiveDirectory", "target/ArchivingTestPurge-" + format + "/logs/archives");
    config.put("archiveFormat", format);
    config.put("archiveOlderThan", "1 s");
    config.put("purgeOlderThan", "2 s");
    config.put("limit", "10 kilobytes");
    config.put("level", "INFO");
    config.put("dateCheckInterval", "1 second");

    final LocalFileHandler handler = new LocalFileHandler() {
        @Override
        protected String currentDate() {
            return today.get();
        }

        @Override
        protected String getProperty(final String name, final String defaultValue) {
            final String s = config.get(name.substring(name.lastIndexOf('.') + 1));
            return s != null ? s : defaultValue;
        }
    };

    final String string10chars = "abcdefghij";
    final int iterations = 950;
    for (int i = 0; i < iterations; i++) {
        handler.publish(new LogRecord(Level.INFO, string10chars));
    }

    today.set("2015-09-02");
    try {
        Thread.sleep(2000);
    } catch (final InterruptedException e) {
        Thread.interrupted();
    }

    final File logArchive = new File(
            "target/ArchivingTestPurge-" + format + "/logs/archives/test.2015-09-01.0.log." + format);
    final File parentFile = logArchive.getParentFile();
    if (!parentFile.exists() && !parentFile.mkdirs()) {
        Assert.fail("Unable to create: " + parentFile);
    }
    final Path dir = parentFile.toPath();
    final WatchService watcher = FileSystems.getDefault().newWatchService();
    final WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_MODIFY);

    latch.set(new CountDownLatch(1));
    watch(key);

    handler.publish(new LogRecord(Level.INFO, string10chars)); // will trigger the archiving

    assertTrue("Failed to get archived log", latch.get().await(20, TimeUnit.SECONDS));
    final WatchEvent<?> watchEvent = lastEvent.get();

    assertTrue(StandardWatchEventKinds.ENTRY_CREATE.equals(watchEvent.kind())
            || StandardWatchEventKinds.ENTRY_MODIFY.equals(watchEvent.kind()));

    final WatchEvent<Path> ev = (WatchEvent<Path>) watchEvent;

    final String io = ev.context().toString();
    assertTrue(io.startsWith("test.2015-09-01.") && io.endsWith(format));

    today.set("2015-09-03");
    try {
        Thread.sleep(2500);
    } catch (final InterruptedException e) {
        Thread.interrupted();
    }

    handler.publish(new LogRecord(Level.INFO, string10chars)); // will trigger the purging
    handler.close();
    withRetry(10, 2, new Runnable() {
        @Override
        public void run() {
            assertFalse(logArchive.getAbsolutePath() + " was purged", logArchive.exists());
        }
    });
}

From source file:com.brienwheeler.lib.test.stepper.SteppableThreadTest.java

private void interruptInWait(SteppableThread stepper, TestMode mode) throws InterruptedException {
    final Thread testThread = Thread.currentThread();
    Thread interruptThread = new Thread() {
        @Override/* w w  w  . jav  a  2  s.c  om*/
        public void run() {
            try {
                Thread.sleep(10L);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }

            testThread.interrupt();
        }
    };
    interruptThread.start();

    try {
        if (mode == TestMode.RELEASE)
            stepper.release();
        else if (mode == TestMode.WAITDONE)
            stepper.waitDone();
        else if (mode == TestMode.JOIN)
            stepper.releaseAndJoin();
        Assert.fail();
    } catch (RuntimeException e) {
        Assert.assertTrue(Thread.interrupted()); // test and clear
        Assert.assertEquals(InterruptedException.class, e.getCause().getClass());
    }

    interruptThread.join();
}

From source file:cc.arduino.utils.network.FileDownloader.java

private void downloadFile(boolean noResume) throws InterruptedException {
    RandomAccessFile file = null;

    try {/*from   w  ww  .ja va2s. c om*/
        // Open file and seek to the end of it
        file = new RandomAccessFile(outputFile, "rw");
        initialSize = file.length();

        if (noResume && initialSize > 0) {
            // delete file and restart downloading
            Files.delete(outputFile.toPath());
            initialSize = 0;
        }

        file.seek(initialSize);

        setStatus(Status.CONNECTING);

        Proxy proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(downloadUrl.toURI());
        if ("true".equals(System.getProperty("DEBUG"))) {
            System.err.println("Using proxy " + proxy);
        }

        HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection(proxy);
        connection.setRequestProperty("User-agent", userAgent);
        if (downloadUrl.getUserInfo() != null) {
            String auth = "Basic " + new String(new Base64().encode(downloadUrl.getUserInfo().getBytes()));
            connection.setRequestProperty("Authorization", auth);
        }

        connection.setRequestProperty("Range", "bytes=" + initialSize + "-");
        connection.setConnectTimeout(5000);
        setDownloaded(0);

        // Connect
        connection.connect();
        int resp = connection.getResponseCode();

        if (resp == HttpURLConnection.HTTP_MOVED_PERM || resp == HttpURLConnection.HTTP_MOVED_TEMP) {
            URL newUrl = new URL(connection.getHeaderField("Location"));

            proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(newUrl.toURI());

            // open the new connnection again
            connection = (HttpURLConnection) newUrl.openConnection(proxy);
            connection.setRequestProperty("User-agent", userAgent);
            if (downloadUrl.getUserInfo() != null) {
                String auth = "Basic " + new String(new Base64().encode(downloadUrl.getUserInfo().getBytes()));
                connection.setRequestProperty("Authorization", auth);
            }

            connection.setRequestProperty("Range", "bytes=" + initialSize + "-");
            connection.setConnectTimeout(5000);

            connection.connect();
            resp = connection.getResponseCode();
        }

        if (resp < 200 || resp >= 300) {
            throw new IOException("Received invalid http status code from server: " + resp);
        }

        // Check for valid content length.
        long len = connection.getContentLength();
        if (len >= 0) {
            setDownloadSize(len);
        }
        setStatus(Status.DOWNLOADING);

        synchronized (this) {
            stream = connection.getInputStream();
        }
        byte buffer[] = new byte[10240];
        while (status == Status.DOWNLOADING) {
            int read = stream.read(buffer);
            if (read == -1)
                break;

            file.write(buffer, 0, read);
            setDownloaded(getDownloaded() + read);

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

        if (getDownloadSize() != null) {
            if (getDownloaded() < getDownloadSize())
                throw new Exception("Incomplete download");
        }
        setStatus(Status.COMPLETE);
    } catch (InterruptedException e) {
        setStatus(Status.CANCELLED);
        // lets InterruptedException go up to the caller
        throw e;

    } catch (SocketTimeoutException e) {
        setStatus(Status.CONNECTION_TIMEOUT_ERROR);
        setError(e);

    } catch (Exception e) {
        setStatus(Status.ERROR);
        setError(e);

    } finally {
        IOUtils.closeQuietly(file);

        synchronized (this) {
            IOUtils.closeQuietly(stream);
        }
    }
}

From source file:org.apache.tomcat.util.threads.ThreadPoolExecutor.java

/**
 * Executes the given command at some time in the future.  The command
 * may execute in a new thread, in a pooled thread, or in the calling
 * thread, at the discretion of the <tt>Executor</tt> implementation.
 * If no threads are available, it will be added to the work queue.
 * If the work queue is full, the system will wait for the specified
 * time and it throw a RejectedExecutionException if the queue is still
 * full after that./*from  w w  w .j  a  v a2s  .  c  o m*/
 *
 * @param command the runnable task
 * @throws RejectedExecutionException if this task cannot be
 * accepted for execution - the queue is full
 * @throws NullPointerException if command or unit is null
 */
public void execute(Runnable command, long timeout, TimeUnit unit) {
    submittedCount.incrementAndGet();
    try {
        super.execute(command);
    } catch (RejectedExecutionException rx) {
        if (super.getQueue() instanceof TaskQueue) {
            final TaskQueue queue = (TaskQueue) super.getQueue();
            try {
                if (!queue.force(command, timeout, unit)) {
                    submittedCount.decrementAndGet();
                    throw new RejectedExecutionException("Queue capacity is full.");
                }
            } catch (InterruptedException x) {
                submittedCount.decrementAndGet();
                Thread.interrupted();
                throw new RejectedExecutionException(x);
            }
        } else {
            submittedCount.decrementAndGet();
            throw rx;
        }

    }
}

From source file:info.novatec.inspectit.rcp.storage.util.DataRetriever.java

/**
 * Retrieves the wanted data described in the {@link StorageDescriptor} from the desired
 * {@link CmrRepositoryDefinition}. This method will try to invoke as less as possible HTTP
 * requests for all descriptors./*from   w w  w  .  java  2 s  .  c o m*/
 * <p>
 * The method will execute the HTTP requests sequentially.
 * <p>
 * It is not guaranteed that amount of returned objects in the list is same as the amount of
 * provided descriptors. If some of the descriptors are pointing to the wrong files or files
 * positions, it can happen that this influences the rest of the descriptor that point to the
 * same file. Thus, a special care needs to be taken that the data in descriptors is correct.
 * 
 * @param <E>
 *            Type of the objects are wanted.
 * @param cmrRepositoryDefinition
 *            {@link CmrRepositoryDefinition}.
 * @param storageData
 *            {@link StorageData} that points to the wanted storage.
 * @param descriptors
 *            Descriptors.
 * @return List of objects in the supplied generic type. Note that if the data described in the
 *         descriptor is not of a supplied generic type, there will be a casting exception
 *         thrown.
 * @throws SerializationException
 *             If {@link SerializationException} occurs.
 * @throws IOException
 *             If {@link IOException} occurs.
 */
@SuppressWarnings("unchecked")
public <E extends DefaultData> List<E> getDataViaHttp(CmrRepositoryDefinition cmrRepositoryDefinition,
        IStorageData storageData, List<IStorageDescriptor> descriptors)
        throws IOException, SerializationException {
    Map<Integer, List<IStorageDescriptor>> separateFilesGroup = createFilesGroup(descriptors);
    List<E> receivedData = new ArrayList<E>();
    String serverUri = getServerUri(cmrRepositoryDefinition);

    HttpClient httpClient = new DefaultHttpClient();
    for (Map.Entry<Integer, List<IStorageDescriptor>> entry : separateFilesGroup.entrySet()) {
        HttpGet httpGet = new HttpGet(
                serverUri + storageManager.getHttpFileLocation(storageData, entry.getKey()));
        StringBuilder rangeHeader = new StringBuilder("bytes=");

        RangeDescriptor rangeDescriptor = null;
        for (IStorageDescriptor descriptor : entry.getValue()) {
            if (null == rangeDescriptor) {
                rangeDescriptor = new RangeDescriptor(descriptor);
            } else {
                if (rangeDescriptor.getEnd() + 1 == descriptor.getPosition()) {
                    rangeDescriptor.setEnd(descriptor.getPosition() + descriptor.getSize() - 1);
                } else {
                    rangeHeader.append(rangeDescriptor.toString());
                    rangeHeader.append(',');
                    rangeDescriptor = new RangeDescriptor(descriptor);
                }
            }
        }
        rangeHeader.append(rangeDescriptor);

        httpGet.addHeader("Range", rangeHeader.toString());
        ISerializer serializer = null;
        try {
            serializer = serializerQueue.take();
        } catch (InterruptedException e) {
            Thread.interrupted();
        }
        InputStream inputStream = null;
        Input input = null;
        try {
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (MultipartEntityUtil.isMultipart(entity)) {
                inputStream = entity.getContent();
                @SuppressWarnings("deprecation")
                // all non-deprecated constructors have default modifier
                MultipartStream multipartStream = new MultipartStream(inputStream,
                        MultipartEntityUtil.getBoundary(entity).getBytes());
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                boolean nextPart = multipartStream.skipPreamble();
                while (nextPart) {
                    multipartStream.readHeaders();
                    multipartStream.readBodyData(byteArrayOutputStream);
                    input = new Input(byteArrayOutputStream.toByteArray());
                    while (KryoUtil.hasMoreBytes(input)) {
                        Object object = serializer.deserialize(input);
                        E element = (E) object;
                        receivedData.add(element);
                    }
                    nextPart = multipartStream.readBoundary();
                }
            } else {
                // when kryo changes the visibility of optional() method, we can really stream
                input = new Input(EntityUtils.toByteArray(entity));
                while (KryoUtil.hasMoreBytes(input)) {
                    Object object = serializer.deserialize(input);
                    E element = (E) object;
                    receivedData.add(element);
                }
            }
        } finally {
            if (null != inputStream) {
                inputStream.close();
            }
            if (null != input) {
                input.close();
            }
            serializerQueue.add(serializer);
        }
    }
    return receivedData;
}

From source file:org.executequery.gui.editor.autocomplete.AutoCompleteSelectionsFactory.java

private void databaseObjectsForHost(DatabaseHost databaseHost, String type, String databaseObjectDescription,
        AutoCompleteListItemType autocompleteType) {

    trace("Building autocomplete object list using [ " + databaseHost.getName() + " ] for type - " + type);

    ResultSet rs = null;//from   www .ja  v a  2  s. c  om
    DatabaseMetaData databaseMetaData = databaseHost.getDatabaseMetaData();
    try {
        String catalog = databaseHost.getCatalogNameForQueries(defaultCatalogForHost(databaseHost));
        String schema = databaseHost.getSchemaNameForQueries(defaultSchemaForHost(databaseHost));

        String typeName = null;
        List<String> tableNames = new ArrayList<String>();
        List<AutoCompleteListItem> list = new ArrayList<AutoCompleteListItem>();
        String[] types = new String[] { type };

        int count = 0;

        rs = databaseMetaData.getTables(catalog, schema, null, types);
        while (rs.next()) {

            try {
                if (Thread.interrupted() || databaseMetaData.getConnection().isClosed()) {

                    return;
                }
            } catch (SQLException e) {
            }

            typeName = rs.getString(4);

            // only include if the returned reported type matches
            if (type != null && type.equalsIgnoreCase(typeName)) {

                tableNames.add(rs.getString(3));
                count++;
            }

            if (count >= INCREMENT) {

                addTablesToProvider(databaseObjectDescription, autocompleteType, tableNames, list);
                count = 0;
                list.clear();
                tableNames.clear();
            }

        }

        addTablesToProvider(databaseObjectDescription, autocompleteType, tableNames, list);

    } catch (SQLException e) {

        error("Tables not available for type " + type + " - driver returned: " + e.getMessage());

    } finally {

        releaseResources(rs);
        trace("Finished autocomplete object list using [ " + databaseHost.getName() + " ] for type - " + type);
    }

}