Example usage for java.lang Thread isInterrupted

List of usage examples for java.lang Thread isInterrupted

Introduction

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

Prototype

public boolean isInterrupted() 

Source Link

Document

Tests whether this thread has been interrupted.

Usage

From source file:com.termmed.utils.FileHelper.java

/**
 * Gets the file type by header./*  w w  w .j a v a 2  s .co m*/
 *
 * @param inputFile the input file
 * @param isReduced the is reduced
 * @return the file type by header
 * @throws Exception the exception
 */
public static String getFileTypeByHeader(File inputFile, boolean isReduced) throws Exception {
    String namePattern = null;
    try {
        Thread currThread = Thread.currentThread();
        if (currThread.isInterrupted()) {
            return null;
        }

        String patternFile;
        if (isReduced) {
            patternFile = "validation-rules_reduced.xml";
        } else {
            patternFile = "validation-rules.xml";
        }
        XMLConfiguration xmlConfig = new XMLConfiguration(
                FileHelper.class.getResource("/org/ihtsdo/utils/" + patternFile));
        if (xmlConfig == null) {
            String error = "Pattern file '" + patternFile + "' doesn't exist.";
            log.error(error);
            throw new Exception(error);
        }
        List<String> namePatterns = new ArrayList<String>();

        Object prop = xmlConfig.getProperty("files.file.fileType");
        if (prop instanceof Collection) {
            namePatterns.addAll((Collection) prop);
        }
        //         System.out.println("");
        boolean toCheck = false;
        String headerRule = null;
        FileInputStream fis = new FileInputStream(inputFile);
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        String header = br.readLine();
        if (header != null) {
            for (int i = 0; i < namePatterns.size(); i++) {
                if (currThread.isInterrupted()) {
                    return null;
                }
                headerRule = xmlConfig.getString("files.file(" + i + ").headerRule.regex");
                namePattern = namePatterns.get(i);
                //            log.info("===================================");
                //            log.info("For file : " + inputFile.getAbsolutePath());
                //            log.info("namePattern:" + namePattern);
                //            log.info("headerRule:" + headerRule);
                if (header.matches(headerRule)) {

                    //               log.info("Match");
                    if ((inputFile.getName().toLowerCase().contains("textdefinition")
                            && namePattern.equals("rf2-descriptions"))
                            || (inputFile.getName().toLowerCase().contains("description")
                                    && namePattern.equals("rf2-textDefinition"))) {
                        continue;
                    }
                    toCheck = true;
                    break;
                }
            }
        }
        if (!toCheck) {
            log.info("Header for null pattern:" + header);
            namePattern = null;
            //System.out.println( "Cannot found header matcher for : " + inputFile.getName());
        }
        br.close();
    } catch (FileNotFoundException e) {
        System.out.println("FileAnalizer: " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        System.out.println("FileAnalizer: " + e.getMessage());
    } catch (IOException e) {
        System.out.println("FileAnalizer: " + e.getMessage());
    } catch (ConfigurationException e) {
        System.out.println("FileAnalizer: " + e.getMessage());
    }
    return namePattern;
}

From source file:org.apache.ftpserver.DataConnectionConfig.java

/**
 * Get passive data port. Data port number zero (0) means that 
 * any available port will be used./*from  w  ww . java  2s. c om*/
 */
public synchronized int getPassivePort() {
    int dataPort = -1;
    int loopTimes = 2;
    Thread currThread = Thread.currentThread();

    while ((dataPort == -1) && (--loopTimes >= 0) && (!currThread.isInterrupted())) {

        // search for a free port            
        for (int i = 0; i < m_pasvPort.length; i++) {
            if (m_pasvPort[i][1] == 0) {
                if (m_pasvPort[i][0] != 0) {
                    m_pasvPort[i][1] = 1;
                }
                dataPort = m_pasvPort[i][0];
                break;
            }
        }

        // no available free port - wait for the release notification
        if (dataPort == -1) {
            try {
                wait();
            } catch (InterruptedException ex) {
            }
        }

    }
    return dataPort;
}

From source file:com.espertech.esper.dataflow.core.EPDataFlowInstanceImpl.java

public void cancel() {
    if (state == EPDataFlowState.COMPLETE || state == EPDataFlowState.CANCELLED) {
        return;//from   w ww  . ja  v  a  2 s  . c  o  m
    }
    if (state == EPDataFlowState.INSTANTIATED) {
        setState(EPDataFlowState.CANCELLED);
        sourceRunnables.clear();
        callOperatorClose();
        return;
    }

    // handle async start
    if (threads != null) {
        for (GraphSourceRunnable runnable : sourceRunnables) {
            runnable.shutdown();
        }
        for (Thread thread : threads) {
            if (thread.isAlive() && !thread.isInterrupted()) {
                thread.interrupt();
            }
        }
    }
    // handle run
    else {
        if (runCurrentThread != null) {
            runCurrentThread.interrupt();
        }
        runCurrentThread = null;
    }

    callOperatorClose();

    setState(EPDataFlowState.CANCELLED);
    sourceRunnables.clear();
}

From source file:ThreadViewer.java

private void createPendingCellData() {
    Thread[] thread = findAllThreads();
    Object[][] cell = new Object[thread.length][columnCount];

    for (int i = 0; i < thread.length; i++) {
        Thread t = thread[i];
        Object[] rowCell = cell[i];

        rowCell[0] = new Integer(t.getPriority());
        rowCell[1] = new Boolean(t.isAlive());
        rowCell[2] = new Boolean(t.isDaemon());
        rowCell[3] = new Boolean(t.isInterrupted());
        rowCell[4] = t.getThreadGroup().getName();
        rowCell[5] = t.getName();/* ww w . j  a  v  a 2 s.c  o  m*/
    }

    synchronized (dataLock) {
        pendingCellData = cell;
    }
}

From source file:com.legalsoft.generic.gtc.controller.TimerBooleanController.java

/**
 * Mtodo para ejecutar este controller./*from   w  w  w. ja v a 2 s  .  co m*/
 */
@Override
public void run() {
    // Cambiar el nombre del thread.
    Thread thread = Thread.currentThread();
    thread.setName("TIMER");
    logger.info("Ejecutando el hilo del Timer @{}", Main.get_TS());
    // ejecutar en un bloque controlado.
    try {
        while (!thread.isInterrupted()) {
            // obtener el delay... en un bloque sincronizado.
            long cicleDelay;
            synchronized (delay) {
                cicleDelay = delay[0];
            }
            // ahora, una espera con este delay.
            Thread.sleep(cicleDelay);
            // Luego, llamar a los listeners.
            // el clculo del resultado es sincronizado.
            boolean result = calculateResult();
            fireTimerEvent(result);
        }
    } catch (InterruptedException exception) {
        logger.error("Ejecucin interrumpida: {}", exception);
        // terminando....
        thread.interrupt();
    }
    logger.info("Terminada la ejecucion del Timer @{}", Main.get_TS());
}

From source file:com.baidu.asynchttpclient.AsyncHttpResponseHandler.java

protected void sendMessage(Message msg) {
    if (handler != null) {
        Thread thread = handler.getLooper().getThread();
        if (thread.isAlive() && !thread.isInterrupted()) {
            handler.sendMessage(msg);/*from   www  .  j a  v a  2  s.  c  o m*/
        }
    } else {
        handleMessage(msg);
    }
}

From source file:org.shareok.data.kernel.api.services.job.TaskManagerImpl.java

/**
 * //from   w w  w.  j av a  2  s .  c om
 * @param uid : user ID
 * @param handler : handler of job execution
 * @param localFile : uploaded file from local computer
 * @param remoteFilePath : remote resource of the file
 * @return : path to the report file
 */
@Override
public RedisJob execute(long uid, JobHandler handler, MultipartFile localFile, String remoteFilePath) {
    try {

        RedisJob newJob = redisJobService.createJob(uid, handler.getJobType(),
                handler.outputJobDataByJobType());
        long jobId = newJob.getJobId();

        String jobFilePath = DataHandlersUtil.getJobReportPath(DataUtil.JOB_TYPES[handler.getJobType()], jobId);

        DataService ds = ServiceUtil.getDataService(handler.getJobType());

        String filePath = "";
        String reportFilePath = jobFilePath + File.separator + String.valueOf(jobId) + "-report.txt";

        if (null != localFile && !localFile.isEmpty()) {
            filePath = ServiceUtil.saveUploadedFile(localFile, jobFilePath);
        } else if (null != remoteFilePath && !"".equals(remoteFilePath)) {
            filePath = processRemoteFileByJobType(handler.getJobType(), redisJobService, jobFilePath,
                    remoteFilePath);
        }

        handler.setFilePath(filePath);
        handler.setReportFilePath(reportFilePath);
        ds.setUserId(uid);
        ds.setHandler(handler);

        redisJobService.updateJob(jobId, "status", "0");
        redisJobService.updateJob(jobId, "filePath", filePath);

        //Handle the job queue stuff:
        String queueName = RedisUtil.getJobQueueName(uid, DataUtil.JOB_TYPES[handler.getJobType()],
                handler.getServerName());
        Thread thread = ServiceUtil.getThreadByName(queueName);
        if (jobQueueService.isJobQueueEmpty(queueName)) {
            if (null != thread && !thread.isInterrupted()) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                    logger.debug("Current thread is interrupted while sleeping", ex);
                }
                if (!thread.isInterrupted()) {
                    jobQueueService.addJobIntoQueue(jobId, queueName);
                    redisJobService.updateJob(jobId, "status", "7");
                } else {
                    //                        try {
                    //                            thread.join();
                    //                        } catch (InterruptedException ex) {
                    //                            logger.debug("Current thread is interrupted while sleeping", ex);
                    //                        }
                    jobQueueService.addJobIntoQueue(jobId, queueName);
                    redisJobService.updateJob(jobId, "status", "7");
                    Thread newThread = new Thread(ds, queueName);
                    newThread.start();
                }
            } else {
                //                    if(null != thread && thread.isInterrupted()){
                //                        while(thread.isAlive()){
                //                            try {
                //                                Thread.sleep(50L);
                //                            } catch (InterruptedException ex) {
                //                                Logger.getLogger(TaskManagerImpl.class.getName()).log(Level.SEVERE, null, ex);
                //                            }
                //                        }
                //
                //                    }
                jobQueueService.addJobIntoQueue(jobId, queueName);
                redisJobService.updateJob(jobId, "status", "7");
                Thread newThread = new Thread(ds, queueName);
                newThread.start();
            }
        } else {
            jobQueueService.addJobIntoQueue(jobId, queueName);
            redisJobService.updateJob(jobId, "status", "7");
            if (null == thread) {
                Thread newThread = new Thread(ds, queueName);
                newThread.start();
            }
        }

        return redisJobService.findJobByJobId(jobId);
    } catch (BeansException | NumberFormatException | EmptyUploadedPackagePathOfSshUploadJobException ex) {
        //            logger.error("Cannot exectue the job with type "+DataUtil.JOB_TYPES[handler.get]+" for repository "+DataUtil.REPO_TYPES[repoType], ex);
        logger.error("Cannot exectue the job with type.", ex);
    }
    return null;
}

From source file:de.hybris.platform.cronjob.jalo.TriggerableJobTest.java

private void waitToFinish(final CronJob cronJob) {
    final Thread thread = Thread.currentThread();
    final long maxWaitTime = System.currentTimeMillis() + (triggerPerformWaitSeconds * 1000);
    while (!cronJob.isFinished() && !thread.isInterrupted() && System.currentTimeMillis() < maxWaitTime) {
        try {//w  w w.  ja  va 2 s. c  o  m
            Thread.sleep(500);
        } catch (final InterruptedException e) {
            thread.interrupt();
        }
    }
}

From source file:org.talend.updates.runtime.ui.feature.form.FeaturesSearchForm.java

private void doSearch(SearchOption searchOption) {
    final FeatureProgress progress = showProgress();
    execute(new Runnable() {

        @Override//www. jav  a 2  s.  c o m
        public void run() {
            final Thread thread = Thread.currentThread();
            try {
                if (thread.isInterrupted()) {
                    return;
                }
                ModalContext.run(new IRunnableWithProgress() {

                    @Override
                    public void run(IProgressMonitor monitor)
                            throws InvocationTargetException, InterruptedException {
                        doSearch(monitor, searchOption);
                    }
                }, true, progress.getProgressMonitor(), getDisplay());
            } catch (Exception e1) {
                ExceptionHandler.process(e1);
            }
        }
    });
}

From source file:tap.formatter.JSONFormat.java

/**
 * Write the whole data part of the JSON file.
 * //from w  ww  .j a v a  2s. c om
 * @param result         Result to write.   
 * @param selectedColumns   All columns' metadata.
 * @param out            Output stream in which the data must be written.
 * @param execReport      Execution report (which contains the maximum allowed number of records to output).
 * @param thread         Thread which has asked for this formatting (it must be used in order to test the {@link Thread#isInterrupted()} flag and so interrupt everything if need).
 * 
 * @throws IOException            If there is an error while writing something in the output stream.
 * @throws InterruptedException      If the thread has been interrupted.
 * @throws JSONException         If there is an error while formatting something in JSON.
 * @throws TAPException            If any other error occurs.
 */
protected void writeData(TableIterator result, DBColumn[] selectedColumns, JSONWriter out,
        TAPExecutionReport execReport, Thread thread)
        throws IOException, TAPException, InterruptedException, JSONException {
    // [
    out.array();

    execReport.nbRows = 0;
    while (result.nextRow()) {
        // Stop right now the formatting if the job has been aborted/canceled/interrupted:
        if (thread.isInterrupted())
            throw new InterruptedException();

        // Deal with OVERFLOW, if needed:
        if (execReport.parameters.getMaxRec() > 0 && execReport.nbRows >= execReport.parameters.getMaxRec())
            break;

        // [
        out.array();
        int indCol = 0;
        while (result.hasNextCol())
            // ...
            writeFieldValue(result.nextCol(), selectedColumns[indCol++], out);
        // ]
        out.endArray();
        execReport.nbRows++;
    }

    // ]
    out.endArray();
}