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:net.sf.jasperreports.engine.export.JRXhtmlExporter.java

/**
 *
 *//*from w  w  w.  ja va  2  s  .c  o  m*/
protected void exportReportToWriter() throws JRException, IOException {
    HtmlExporterConfiguration configuration = getCurrentConfiguration();
    String htmlHeader = configuration.getHtmlHeader();
    String betweenPagesHtml = configuration.getBetweenPagesHtml();
    String htmlFooter = configuration.getHtmlFooter();

    if (htmlHeader == null) {
        String encoding = ((WriterExporterOutput) getExporterOutput()).getEncoding();

        writer.write(
                "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n");
        writer.write("<html>\n");
        writer.write("<head>\n");
        writer.write("  <title></title>\n");
        writer.write("  <meta http-equiv=\"Content-Type\" content=\"text/html; charset=" + encoding + "\"/>\n");
        writer.write("  <style type=\"text/css\">\n");
        writer.write("    a {text-decoration: none}\n");
        writer.write("  </style>\n");
        writer.write("</head>\n");
        writer.write("<body text=\"#000000\" link=\"#000000\" alink=\"#000000\" vlink=\"#000000\">\n");
        writer.write("<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n");
        writer.write("<tr><td width=\"50%\">&nbsp;</td><td align=\"center\">\n");
        writer.write("\n");
    } else {
        writer.write(htmlHeader);
    }

    List<ExporterInputItem> items = exporterInput.getItems();

    for (reportIndex = 0; reportIndex < items.size(); reportIndex++) {
        ExporterInputItem item = items.get(reportIndex);

        setCurrentExporterInputItem(item);

        List<JRPrintPage> pages = jasperPrint.getPages();
        if (pages != null && pages.size() > 0) {
            PageRange pageRange = getPageRange();
            int startPageIndex = (pageRange == null || pageRange.getStartPageIndex() == null) ? 0
                    : pageRange.getStartPageIndex();
            int endPageIndex = (pageRange == null || pageRange.getEndPageIndex() == null) ? (pages.size() - 1)
                    : pageRange.getEndPageIndex();

            JRPrintPage page = null;
            for (pageIndex = startPageIndex; pageIndex <= endPageIndex; pageIndex++) {
                if (Thread.interrupted()) {
                    throw new JRException("Current thread interrupted.");
                }

                page = pages.get(pageIndex);

                writer.write("<a name=\"" + JR_PAGE_ANCHOR_PREFIX + reportIndex + "_" + (pageIndex + 1)
                        + "\"></a>\n");

                /*   */
                exportPage(page);

                if (reportIndex < items.size() - 1 || pageIndex < endPageIndex) {
                    if (betweenPagesHtml == null) {
                        writer.write("<br/>\n<br/>\n");
                    } else {
                        writer.write(betweenPagesHtml);
                    }
                }

                writer.write("\n");
            }
        }
    }

    if (fontsToProcess != null && fontsToProcess.size() > 0)// when no fontHandler and/or resourceHandler, fonts are not processed 
    {
        HtmlResourceHandler fontHandler = getExporterOutput().getFontHandler() == null ? getFontHandler()
                : getExporterOutput().getFontHandler();
        for (HtmlFont htmlFont : fontsToProcess.values()) {
            writer.write("<link class=\"jrWebFont\" rel=\"stylesheet\" href=\""
                    + fontHandler.getResourcePath(htmlFont.getId()) + "\">\n");
        }
    }

    //      if (!isOutputResourcesToDir)
    {
        writer.write("<![if IE]>\n");
        writer.write("<script>\n");
        writer.write("var links = document.querySelectorAll('link.jrWebFont');\n");
        writer.write(
                "setTimeout(function(){ if (links) { for (var i = 0; i < links.length; i++) { links.item(i).href = links.item(i).href; } } }, 0);\n");
        writer.write("</script>\n");
        writer.write("<![endif]>\n");
    }

    if (htmlFooter == null) {
        writer.write("</td><td width=\"50%\">&nbsp;</td></tr>\n");
        writer.write("</table>\n");
        writer.write("</body>\n");
        writer.write("</html>\n");
    } else {
        writer.write(htmlFooter);
    }

    writer.flush();//FIXMEEXPORT other exporters always perform flush
}

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

private void databaseColumnsForTables(DatabaseHost databaseHost, List<AutoCompleteListItem> tables) {

    trace("Retrieving column names for tables for host [ " + databaseHost.getName() + " ]");

    ResultSet rs = null;// w ww. j  av  a  2 s  .  com
    List<ColumnInformation> columns = new ArrayList<ColumnInformation>();
    List<AutoCompleteListItem> list = new ArrayList<AutoCompleteListItem>();

    String catalog = databaseHost.getCatalogNameForQueries(defaultCatalogForHost(databaseHost));
    String schema = databaseHost.getSchemaNameForQueries(defaultSchemaForHost(databaseHost));
    DatabaseMetaData dmd = databaseHost.getDatabaseMetaData();

    for (int i = 0, n = tables.size(); i < n; i++) {

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

                return;
            }
        } catch (SQLException e) {
        }

        AutoCompleteListItem table = tables.get(i);
        if (table == null) {

            continue;
        }

        trace("Retrieving column names for table [ " + table.getValue() + " ]");

        try {

            rs = dmd.getColumns(catalog, schema, table.getValue(), null);
            while (rs.next()) {

                String name = rs.getString(4);
                columns.add(
                        columnInformationFactory.build(table.getValue(), name, rs.getString(6), rs.getInt(5),
                                rs.getInt(7), rs.getInt(9), rs.getInt(11) == DatabaseMetaData.columnNoNulls));
            }

            for (ColumnInformation column : columns) {

                list.add(new AutoCompleteListItem(column.getName(), table.getValue(), column.getDescription(),
                        DATABASE_COLUMN_DESCRIPTION, AutoCompleteListItemType.DATABASE_TABLE_COLUMN));
            }

            provider.addListItems(list);
            releaseResources(rs);
            columns.clear();
            list.clear();

        } catch (Throwable e) {

            // don't want to break the editor here so just log and bail...

            error("Error retrieving column data for table " + table.getDisplayValue() + " - driver returned: "
                    + e.getMessage());

        } finally {

            releaseResources(rs);
        }

    }

    trace("Finished retrieving column names for tables for host [ " + databaseHost.getName() + " ]");
}

From source file:com.splout.db.dnode.Fetcher.java

/**
 * In case of interrupted, written file is not deleted.
 *///from   ww  w.ja  v a  2  s.  c om
private void copyFile(File sourceFile, File destFile, Reporter reporter)
        throws IOException, InterruptedException {
    if (!destFile.exists()) {
        destFile.createNewFile();
    }
    FileChannel source = null;
    FileChannel destination = null;

    Throttler throttler = new Throttler((double) bytesPerSecThrottle);

    FileInputStream iS = null;
    FileOutputStream oS = null;

    try {
        iS = new FileInputStream(sourceFile);
        oS = new FileOutputStream(destFile);
        source = iS.getChannel();
        destination = oS.getChannel();
        long bytesSoFar = 0;
        long reportingBytesSoFar = 0;
        long size = source.size();

        int transferred = 0;

        while (bytesSoFar < size) {
            // Needed to being able to be interrupted at any moment.
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }

            // Casting to int here is safe since we will transfer at most "downloadBufferSize" bytes.
            // This is done on purpose for being able to implement Throttling.
            transferred = (int) destination.transferFrom(source, bytesSoFar, downloadBufferSize);
            bytesSoFar += transferred;
            reportingBytesSoFar += transferred;
            throttler.incrementAndThrottle(transferred);
            if (reportingBytesSoFar >= bytesToReportProgress) {
                reporter.progress(reportingBytesSoFar);
                reportingBytesSoFar = 0l;
            }
        }

        if (reporter != null) {
            reporter.progress(reportingBytesSoFar);
        }

    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        if (iS != null) {
            iS.close();
        }
        if (oS != null) {
            oS.close();
        }
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
}

From source file:jp.terasoluna.fw.web.thin.LimitedLock.java

/**
 * ?bN?B/*from w  w w  .  j  a v  a 2s.c  o m*/
 * <p>
 * ?Xbh?bN?AXbh?Xbh??s?A?Xbh@?B<br>
 * ?Xbh?bN???A?\bhA?B<br>
 * Xbh?Xbh??s???AInterruptedExceptionX??[?A?Xbh?Xe?[^XNA?B<br>
 * (?ANXO????A?Xe?[^Xs?B)
 * </p>
 * <p>
 * ?L?AX?[p?[NX?Bg|Cg?B<br>
 * <ul>
 * <li>?bNXbh?l??\bh?s?A?bNO?AlXbh?A?bNXbhf?B<br>
 * ?bNXbh?\bh?s(??bN)?A?bNXbh??AXbhf?s?B</li>
 * </ul>
 * </p>
 * @throws InterruptedException ?Xbh????(NX@\?A?bNf??)
 * @see java.util.concurrent.locks.ReentrantLock#lockInterruptibly()
 */
@Override
public void lockInterruptibly() throws InterruptedException {
    boolean successToLock = false;
    // ?bNXbh????A
    // ?VXbh?bNv??A
    // ?bNXbh??B
    // (?bN?Xbh?AI?bN(??bN)|???A
    // ?bNXbh??B)
    if (getOwner() != Thread.currentThread()) {
        synchronized (lock) {
            // u?bN???Asuper.unlock();?s?A?bNXbh?bN?B
            // Xbh?bN???A
            // ?bNXbh?bN?A
            // Xbh?A?J?A?bN?oR?bN??A
            // ?bN?\bhXbh?A??Xbh?B
            // ?AXbh?bN??A
            // ?Au?bN?Asuper.lockInterruptibly();?sOXbh????A
            // Xbh?Au?bN???A??????
            // (?bNXbh???AXbh?A??)?A
            // Xbh?bN??A?bNv?Xbh?l??A
            // ??@?Ax??B
            int queueLength = getQueueLength();
            if (queueLength > threshold) {
                HashSet<Thread> oldWaitingThreadSet = null;
                synchronized (waitingThreadList) {
                    List<Thread> oldWaitingThreadList = waitingThreadList.subList(0, queueLength - threshold);
                    oldWaitingThreadSet = new HashSet<Thread>(oldWaitingThreadList);
                }
                // waitingThreadListXbh?A
                // ??bNXbh?A
                // ??bNXbhXg?A
                // oldWaitingThreadListoldWaitingThreadSet?AgetQueuedThreads()?B
                for (Thread queuedThread : getQueuedThreads()) {
                    if (oldWaitingThreadSet.contains(queuedThread)) {
                        if (log.isDebugEnabled()) {
                            log.debug("interrupt thread '" + queuedThread + "'.");
                        }
                        synchronized (waitingThreadList) {
                            // ?waitingThreadList.remove?A?XbhfinallyO?A?s?
                            // ?XbhremoveO?AXbh?f?s\??A
                            // f??Xbh??A
                            // remove?B
                            waitingThreadList.remove(queuedThread);
                            queuedThread.interrupt();

                            // ??A
                            // Xbh?bNL?[?o^CO?A
                            // Xbh?A???getQueueLength()?s?A
                            // getQueueLength()?AwaitingThreadList??A
                            // waitingThreadList.subLists(ListsubLists)?A
                            // (synchronized (lock))?AXbh?bNL?[?o?B
                            while (getQueuedThreads().contains(queuedThread)) {
                                Thread.yield();
                            }
                        }
                    }
                }
            }
        }
    }

    try {
        synchronized (waitingThreadList) {
            waitingThreadList.add(Thread.currentThread());
        }
        super.lockInterruptibly();
        successToLock = true;
    } finally {
        // O??A
        // NX?(?s)???s??
        // NX?(/?s)???I
        // ???sKv?A
        // locktB?[h?bN?B
        synchronized (lock) {
            synchronized (waitingThreadList) {
                waitingThreadList.remove(Thread.currentThread()); // O?remove?Aremove
                if (!successToLock) {
                    // O?NX????A
                    // ?Xe?[^Xc?A
                    // ?Xe?[^XNA?B
                    // ?bN??AreturnO????A
                    // ?Xe?[^XNAreturn?B
                    Thread.interrupted();
                }
            }
        }
    }
}

From source file:com.lukakama.serviio.watchservice.watcher.WatcherRunnable.java

private void checkInterrupted() throws InterruptedException {
    if (Thread.interrupted()) {
        throw new InterruptedException();
    }//from www . jav a  2 s  . co  m
}

From source file:com.zia.freshdocs.widget.CMISAdapter.java

/**
 * Download the content for the given NodeRef
 * @param ref// w w w .j a va2s.c  o m
 * @param handler
 */
protected void downloadContent(final NodeRef ref, final Handler handler) {
    startProgressDlg(false);
    _progressDlg.setMax(Long.valueOf(ref.getContentLength()).intValue());

    _dlThread = new ChildDownloadThread(handler, new Downloadable() {
        public Object execute() {
            File f = null;

            try {
                CMISApplication app = (CMISApplication) getContext().getApplicationContext();
                URL url = new URL(ref.getContent());
                String name = ref.getName();
                long fileSize = ref.getContentLength();
                f = app.getFile(name, fileSize);

                if (f != null && f.length() != fileSize) {
                    Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

                    FileOutputStream fos = new FileOutputStream(f);
                    InputStream is = _cmis.get(url.getPath());

                    byte[] buffer = new byte[BUF_SIZE];
                    int len = is.read(buffer);
                    int total = len;
                    Message msg = null;
                    Bundle b = null;

                    while (len != -1) {
                        msg = handler.obtainMessage();
                        b = new Bundle();
                        b.putInt("progress", total);
                        msg.setData(b);
                        handler.sendMessage(msg);

                        fos.write(buffer, 0, len);
                        len = is.read(buffer);
                        total += len;

                        if (Thread.interrupted()) {
                            fos.close();
                            f = null;
                            throw new InterruptedException();
                        }
                    }

                    fos.flush();
                    fos.close();
                }
            } catch (Exception e) {
                Log.e(CMISAdapter.class.getSimpleName(), "", e);
            }

            return f;
        }
    });
    _dlThread.start();
}

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

/**
 * Uploads dirty records to the server, using a PUT request for each record.
 * Checks Thread.interrupted() before each request to allow quick sync cancellation.
 *//*w ww  .ja v a 2  s. c  o  m*/
protected void uploadDirty()
        throws IOException, HttpException, CalendarStorageException, ContactsStorageException {
    // upload dirty contacts
    for (LocalResource local : localCollection.getDirty()) {
        if (Thread.interrupted())
            return;

        final String fileName = local.getFileName();

        DavResource remote = new DavResource(httpClient,
                collectionURL.newBuilder().addPathSegment(fileName).build());

        // generate entity to upload (VCard, iCal, whatever)
        RequestBody body = prepareUpload(local);

        try {
            if (local.getETag() == null) {
                App.log.info("Uploading new record " + fileName);
                remote.put(body, null, true);
            } else {
                App.log.info("Uploading locally modified record " + fileName);
                remote.put(body, local.getETag(), false);
            }
        } catch (ConflictException | PreconditionFailedException e) {
            // we can't interact with the user to resolve the conflict, so we treat 409 like 412
            App.log.log(Level.INFO, "Resource has been modified on the server before upload, ignoring", e);
        }

        String eTag = null;
        GetETag newETag = (GetETag) remote.properties.get(GetETag.NAME);
        if (newETag != null) {
            eTag = newETag.eTag;
            App.log.fine("Received new ETag=" + eTag + " after uploading");
        } else
            App.log.fine("Didn't receive new ETag after uploading, setting to null");

        local.clearDirty(eTag);
    }
}

From source file:com.techcavern.pircbotz.PircBotZ.java

protected void startLineProcessing() {
    while (true) {
        //Get line from the server
        String line;/*from  www .j  a  v a  2  s.  c  o m*/
        try {
            line = inputReader.readLine();
        } catch (InterruptedIOException iioe) {
            // This will happen if we haven't received anything from the server for a while.
            // So we shall send it a ping to check that we are still connected.
            sendRaw().rawLine("PING " + (System.currentTimeMillis() / 1000));
            // Now we go back to listening for stuff from the server...
            continue;
        } catch (Exception e) {
            if (e instanceof SocketException && getState() == State.DISCONNECTED) {
                log.info("Shutdown has been called, closing InputParser");
                return;
            } else {
                disconnectException = e;
                //Something is wrong. Assume its bad and begin disconnect
                log.error("Exception encountered when reading next line from server", e);
                line = null;
            }
        }

        //End the loop if the line is null
        if (line == null)
            break;

        //Start acting the line
        try {
            inputParser.handleLine(line);
        } catch (Exception e) {
            //Exception in client code. Just log and continue
            log.error("Exception encountered when parsing line", e);
        }

        //Do nothing if this thread is being interrupted (meaning shutdown() was run)
        if (Thread.interrupted())
            return;
    }

    //Now that the socket is definatly closed call event, log, and kill the OutputThread
    shutdown();
}

From source file:com.ibm.stocator.fs.common.Utils.java

public static boolean shouldAbort() {
    return Thread.interrupted();
}

From source file:com.aquatest.dbinterface.tools.DatabaseUpdater.java

/**
 * Invoke web service to retrieve data, and then build and execute queries
 * to update local database//  w w  w .  ja  v a  2 s  . c o  m
 * 
 * @param type
 *            of rows to fetch (TYPE_ADDED, TYPE_UPDATED, TYPE_DELETED)
 * @param table
 *            table to request rows for
 * @return <code>true</code> if the method succeeds, <code>false</code> if
 *         the method fails
 * @throws ClientProtocolException
 * @throws JSONException
 *             if the data returned is not what was expected
 * @throws IOException
 */
private boolean fetchAndExecuteQueries(int type, String table)
        throws ClientProtocolException, JSONException, IOException {
    // Log.v("START", "fetchAndExecuteQueries(" + type + ", " + table +
    // ")");
    try {

        int count = 0;
        int totalCount = 1;
        int offset = 0;
        String status = "";
        JSONArray dataArray = null;
        boolean run = true;

        // determine JSON method to contact with our web service call
        String wsMethodName = "";
        switch (type) {
        case TYPE_ADDED:
            wsMethodName = AquaTestWebService.ADDED_ROWS;
            break;

        case TYPE_UPDATED:
            wsMethodName = AquaTestWebService.UPDATED_ROWS;
            break;

        case TYPE_DELETED:
            wsMethodName = AquaTestWebService.DELETED_ROWS;
            break;

        // TODO a default case should be added with error handling
        } // switch

        // this loop allows for paging of the data from the web service -
        // server returns max 1000 records at a time
        // TODO return fewer records at a time to save memory on the device?
        // e.g sample return string is almost 800,000 characters long
        while (((count + offset) < totalCount) && run) {
            // fetch data from web service
            // Log.v("DatabaseUpdater", "invoking web service [" +
            // wsMethodName + "] on table [" + table + "]");

            // java compiler optimises this "if" statement away based on
            // value of MOCK_WEB_SERVICES i.e. similar to C compiler #ifdef
            // blocks
            JSONObject jsonResponse;
            if (DebugConstants.MOCK_WEB_SERVICES) {
                // mock web services
                jsonResponse = MockAquaTestWebService.retrieveDataChanges(wsMethodName, table, lastUpdateTime,
                        (offset + count));
            } else {
                // use real production server
                jsonResponse = AquaTestWebService.retrieveDataChanges(wsMethodName, table, lastUpdateTime,
                        (offset + count));
            }

            // // Log.v("JSON_REQUEST", wsMethodName + " : " + table);

            // cancel update if so result was returned
            if (jsonResponse == null)
                return false;

            // interpret the JSON results
            //try {
            status = jsonResponse.getString(STATUS_KEY);
            //} catch (JSONException e) {

            //}

            if (status.compareTo(STATUS_SUCCESS) == 0) {
                // these fields allow for paging of the responses
                count = jsonResponse.getInt(COUNT_KEY);
                totalCount = jsonResponse.getInt(TOTAL_COUNT_KEY);
                offset = jsonResponse.getInt(OFFSET_KEY);

                // process the returned data
                if (count > 0 && jsonResponse.has(DATA_KEY)) {
                    // get the data array
                    dataArray = jsonResponse.getJSONArray(DATA_KEY);

                    // create the prepared sql statement
                    // FIXME this currently assumes that the first object
                    // contains all the field names needed
                    JSONArray dataFieldNames = dataArray.getJSONObject(0).names();
                    SQLiteStatement preparedStatement = generateQueryString(type, table, dataFieldNames);

                    try {
                        // do this to optimise the Android code
                        int dataLength = dataArray.length();

                        // loop over the returned data array
                        for (int i = 0; i < dataLength; i++) {
                            // check if thread has been cancelled
                            if (Thread.interrupted())
                                return false;

                            // get the current data record
                            JSONObject row = dataArray.getJSONObject(i);

                            // add parameters to the prepared statement
                            bindQueryParameters(preparedStatement, type, dataFieldNames, row);

                            // Log.v("SQL", "executing statement for data: "
                            // + row);

                            // execute the prepared statement
                            preparedStatement.execute();
                        } // for
                    } finally {
                        // release resources
                        preparedStatement.close();
                    }
                }
                // else exit
                else {
                    // Log.v("JSON", "empty or no data key: " + table + ", "
                    // + wsMethodName + "(" + offset + "," + count + ")");
                    run = false;
                } // else
            }
            // else the call failed, so do not continue
            else {
                // Log.v("DatabaseUpdater",
                // "web service call failed with status [" + status + "]");
                run = false;
            } // else

        } // while

        return true;
    } finally {
        // Log.v("END", "fetchAndExecuteQueries(" + type + ", " + table +
        // ")");
    }
}