Example usage for java.lang Thread run

List of usage examples for java.lang Thread run

Introduction

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

Prototype

@Override
public void run() 

Source Link

Document

If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.

Usage

From source file:org.rifidi.designer.library.basemodels.gate.GateEntity.java

/**
 * Turns on the reader associated with the gate.
 *//*  w w w  . j  a v a 2 s  .  c o m*/
public void turnOn() {
    Thread thr = new Thread(new Runnable() {

        /*
         * (non-Javadoc)
         * 
         * @see java.lang.Runnable#run()
         */
        @Override
        public void run() {

            try {
                readerModuleManagerInterface.turnReaderOn();
                running = true;
                // attach antenna fields to the gate
                for (VisualEntity antenna : children) {
                    ((AntennaFieldEntity) antenna).turnOn();
                }
            } catch (Exception e) {
                logger.error("Problem turning on gate: " + e);
            }
        }

    });
    thr.run();
}

From source file:com.ge.research.semtk.edc.client.ResultsClient.java

/**
 * Store Table.  fullResult is csv.  sample is shorter csv.
 * @param contents//from   w  w  w  .  j a  v  a2s  .  com
 * @throws Exception
 */
@SuppressWarnings("unchecked")
public void execStoreTableResults(String jobId, Table table)
        throws ConnectException, EndpointNotFoundException, Exception {
    // chunk up the table by size and then send all the chunks. 
    // hopefully, this will avoid sending anything too large to the results service

    int tableRowsDone = 0;
    int totalRows = table.getNumRows();
    int segment = 0;

    long startTime = 0, endTime = 0;
    double prepSec = 0.0;
    double sendSec = 0.0;
    boolean timerFlag = false;

    Thread thread = null;

    if (totalRows == 0) {
        // just create and send the header row.
        StringBuilder resultsSoFar = new StringBuilder();

        for (int i1 = 0; i1 < table.getNumColumns(); i1 += 1) {
            resultsSoFar.append((table.getColumnNames())[i1]);
            if (i1 < table.getNumColumns() - 1) {
                resultsSoFar.append(",");
            }
        }

        resultsSoFar.append("\n");

        conf.setServiceEndpoint("results/storeIncrementalCsvResults");
        this.parametersJSON.put("contents", resultsSoFar.toString());
        this.parametersJSON.put("jobId", jobId);
        this.parametersJSON.put("segmentNumber", segment);

        thread = new Thread(this);
        thread.run();
    }

    else { // write out all the results, y'know?
        while (tableRowsDone < totalRows) {
            if (timerFlag) {
                startTime = System.nanoTime();
            }
            int tableRowsAtStart = tableRowsDone;
            // get the next few rows.
            StringBuilder resultsSoFar = new StringBuilder();
            //String lastResults  = "";

            // get the next allocation of rows. 
            for (int i = 0; i < this.ROWS_TO_PROCESS; i += 1) {
                try {

                    // Make sure we include a header row.
                    if (tableRowsDone == 0) { // first record...
                        for (int i1 = 0; i1 < table.getNumColumns(); i1 += 1) {
                            resultsSoFar.append((table.getColumnNames())[i1]);
                            if (i1 < table.getNumColumns() - 1) {
                                resultsSoFar.append(",");
                            }
                        }
                    }

                    // get the next row into a comma separated string.
                    String curr = new StringBuilder(table.getRow(tableRowsDone).toString()).toString(); // ArrayList.toString() is fast
                    // but if any element contained commas, then can't use ArrayList.toString()
                    if (StringUtils.countMatches(curr, ",") != (table.getNumColumns() - 1)) {
                        // escape double quotes (using "" for csv files), then enclose each element in double quotes 
                        curr = table
                                .getRow(tableRowsDone).stream().map(s -> (new StringBuilder()).append("\"")
                                        .append(s.replace("\"", "\"\"")).append("\"").toString())
                                .collect(Collectors.joining(","));
                    } else {
                        // ArrayList.toString() added surrounding brackets and spaces after each comma - remove these
                        curr = StringUtils.substring(curr, 1, curr.length() - 1);
                        curr = StringUtils.replace(curr, ", ", ",");
                    }

                    tableRowsDone += 1;

                    // add to the existing results we want to send.
                    //lastResults = resultsSoFar.toString(); // PEC changed  
                    resultsSoFar.append("\n");
                    resultsSoFar.append(curr); // TODO when this was using +=, it would have triggered the batch-too-big behavior, but now that it's a StringBuilder, not sure

                } catch (IndexOutOfBoundsException eek) {
                    // we have run out of rows. the remaining rows were fewer than the block size. just note this and move on.
                    i = this.ROWS_TO_PROCESS;
                }

                // TODO review with Justin.  Removing the "revert to slightly smaller batch size" for now because saving the lastBatch after every row
                // was slowing the performance.  We can reintroduce it in a better way later.  For now, let any exceptions flow up
                //            catch(Exception eee){
                //               // the send size would have been too large.
                //               tableRowsDone = tableRowsDone - 1;
                //               
                //               System.out.println("*** caught an exception trying to process a result: " +  tableRowsDone);
                //               System.out.println(eee.getMessage());
                //         
                //               i = this.ROWS_TO_PROCESS; // remove the one that broke things. this way, we reprocess it
                //               //resultsSoFar = new StringBuilder(lastResults); // reset the values.  
                //            }
            }

            // fail if tableRowsDone has not changed. this implies that even the first result was too large.
            if ((tableRowsDone == tableRowsAtStart) && (tableRowsDone < totalRows)) {
                throw new Exception(
                        "unable to write results. there is a row size which is too large. row number was "
                                + tableRowsDone + " of a total " + totalRows + ".");
            }

            if (timerFlag) {
                endTime = System.nanoTime();
                prepSec += ((endTime - startTime) / 1000000000.0);
                System.err.println(String.format("tot prep=%.2f sec", prepSec));
                startTime = endTime;
            }

            // take care of last run
            if (thread != null) {
                thread.join();
                ((SimpleResultSet) this.getRunRes()).throwExceptionIfUnsuccessful();
                if (this.getRunException() != null) {
                    throw this.getRunException();
                }
                segment += 1;
                conf.setServiceEndpoint(null);
                this.parametersJSON.remove("contents");
                this.parametersJSON.remove("jobId");
            }

            // send the current one:

            conf.setServiceEndpoint("results/storeIncrementalCsvResults");
            this.parametersJSON.put("contents", resultsSoFar.toString());
            this.parametersJSON.put("jobId", jobId);
            this.parametersJSON.put("segmentNumber", segment);

            thread = new Thread(this);
            thread.run();

            if (timerFlag) {
                endTime = System.nanoTime();
                sendSec += ((endTime - startTime) / 1000000000.0);
                System.err.println(String.format("tot send=%.2f sec", sendSec));
                startTime = endTime;
            }
        } // end of while loop.

    }

    // cleanup
    // take care of last run
    if (thread != null) {
        thread.join();
        ((SimpleResultSet) this.getRunRes()).throwExceptionIfUnsuccessful();
        if (this.getRunException() != null) {
            throw this.getRunException();
        }

    }

    if (timerFlag) {
        System.err.println(String.format("prep=%.2f sec   send=%.2f sec", prepSec, sendSec));
    }
    return;
}

From source file:org.cgiar.ccafs.marlo.action.TestSMTPAction.java

@Override
public String execute() throws Exception {

    Properties properties = System.getProperties();
    properties.put("mail.smtp.host", config.getEmailHost());
    properties.put("mail.smtp.port", config.getEmailPort());

    Session session = Session.getInstance(properties, new Authenticator() {

        @Override// w w w. ja va  2 s. c  o m
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(config.getEmailUsername(), config.getEmailPassword());
        }
    });

    // Create a new message
    MimeMessage msg = new MimeMessage(session) {

        @Override
        protected void updateMessageID() throws MessagingException {
            if (this.getHeader("Message-ID") == null) {
                super.updateMessageID();
            }
        }
    };

    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("h.jimenez@cgiar.org", false));
    msg.setSubject("Test email");
    msg.setSentDate(new Date());
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent("If you receive this email, it means that the server is working correctly.",
            "text; charset=utf-8");

    Thread thread = new Thread() {

        @Override
        public void run() {

            sent = false;
            int i = 0;
            while (!sent) {
                try {
                    Transport.send(sendMail);
                    LOG.info("Message sent TRIED#: " + i + " \n" + "Test email");
                    sent = true;

                } catch (MessagingException e) {
                    LOG.info("Message  DON'T sent: \n" + "Test email");

                    i++;
                    if (i == 10) {
                        break;

                    }
                    try {
                        Thread.sleep(1 * // minutes to sleep
                        60 * // seconds to a minute
                        1000);
                    } catch (InterruptedException e1) {

                        e1.printStackTrace();
                    }
                    e.printStackTrace();
                }

            }

        };
    };

    thread.run();

    if (sent) {
        return SUCCESS;
    } else {
        return INPUT;
    }
}

From source file:com.vanisty.ui.MenuActivity.java

public void logout() {
    Thread t = new Thread(new Runnable() {
        @Override/*from   w  ww.  j  a v a2s.c  om*/
        public void run() {
            try {
                FacebookSession.logout(MenuActivity.this);
                Toast t1 = Toast.makeText(getApplicationContext(), "Logout successful", Toast.LENGTH_LONG);
                t1.show();
                Intent i = new Intent(MenuActivity.this, SplashLoadingActivity.class);
                startActivity(i);
                finish();
            } catch (Exception ex) {
                Toast t1 = Toast.makeText(getApplicationContext(), "Logout not successful", Toast.LENGTH_LONG);
                t1.show();
                ex.printStackTrace();
            }

        }
    });
    t.run();
}

From source file:com.softanalle.scma.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Intent intent = null;/*from  www. ja v a  2 s .  c o  m*/
    switch (item.getItemId()) {
    case R.id.scma_settings:
        logger.debug("Menu action: settings: begin");
        // Toast.makeText(getApplicationContext(), "SCMA Settings menu", Toast.LENGTH_LONG).show();
        intent = new Intent(getApplicationContext(), AppPreferenceActivity.class);
        startActivityForResult(intent, RESULT_SETTINGS_ACTIVITY);
        logger.debug("Menu action: settings: done");
        return true;

    case R.id.reset_settings:
        logger.debug("Menu action: reset settings: begin");
        resetSettings();
        logger.debug("Menu action: reset settings: done");
        return true;

    case R.id.calibration:
        logger.debug("Menu action: calibration: begin");
        ledIndicator_.setLedState(LED_INDEX_CALIBRATE, true);
        mPreview.takeCalibrationPicture(saveModeRAW, mStorageDir);
        ledIndicator_.setLedState(LED_INDEX_CALIBRATE, false);
        logger.debug("Menu action: calibration: done");
        return true;

    case R.id.about_info:
        logger.debug("Menu action: about: begin");
        intent = new Intent(getApplicationContext(), SplashActivity.class);
        startActivity(intent);
        logger.debug("Menu action: about: done");
        return true;

    case R.id.resetIOIO:
        logger.debug("IOIO reset requested");
        doIOIOreset = true;
        return true;

    case R.id.changelog_full:

        intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.delektre.com/Scma/Changelog.txt"));
        startActivity(intent);

        return true;
    case R.id.itemCopyAssets: {
        logger.debug("Copy assets: begin");
        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                copyTestAssets();
                logger.debug("Copy assets: done");
            }
        });
        t.run();
        return true;
    }
    //
    case R.id.itemTest1: {
        logger.debug("Start areaselector test");
        intent = new Intent(getApplicationContext(), ImageActivity.class);
        intent.putExtra(ARG_WORKDIR, mStorageDir);
        File f = new File(mStorageDir);

        String foundFileName = "testimg";

        if (foundFileName != null) {
            intent.putExtra(ARG_IMAGE_PREFIX, foundFileName);
        }
        startActivity(intent);
        return true;
    }

    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.untangle.app.license.LicenseManagerImpl.java

/**
 * Reload all of the licenses from the file system.
 *
 * @param//from ww  w . j  av  a2s.c om
 *     blocking If true, block the current context until we're finished.  Otherwise, launch a new non-blocking thread.
 */
@Override
public final void reloadLicenses(boolean blocking) {
    if (blocking) {
        try {
            _syncLicensesWithServer();
        } catch (Exception ex) {
            logger.warn("Unable to reload the licenses.", ex);
        }
    } else {
        Thread t = new Thread(new Runnable() {
            /**
             * Launch the license synchronize routine.
             */
            public void run() {
                try {
                    _syncLicensesWithServer();
                } catch (Exception ex) {
                    logger.warn("Unable to reload the licenses.", ex);
                }
            }
        });
        t.run();
    }
}

From source file:io.reign.zk.ResilientZkClient.java

synchronized void spawnReconnectThread() {
    if (zooKeeper == null || zooKeeper.getState() == ZooKeeper.States.CLOSED) {
        // do connection in another thread so as to not block the ZK event thread
        Thread reconnectThread = new Thread() {
            @Override//from  ww  w.j a v  a  2s  .  c o m
            public void run() {
                connect(backoffStrategyFactory.get(), true);
            }
        };
        reconnectThread
                .setName(this.getClass().getSimpleName() + ".zkConnectThread-" + reconnectThread.hashCode());
        reconnectThread.setPriority(Thread.MIN_PRIORITY);
        reconnectThread.run();
    }
}

From source file:com.idega.slide.business.IWSlideServiceBean.java

/**
 * Synchronized for now because it doesn't seem to be thread safe (deadlock)
 *
 * @param uploadPath/*w w  w. ja  v  a 2s . c om*/
 * @param fileName
 * @param contentType
 * @param fileInputStream
 * @param closeStream
 * @return
 */
private boolean uploadFile(String uploadPath, String fileName, String contentType, InputStream stream,
        boolean closeStream) {
    if (StringUtil.isEmpty(uploadPath) || StringUtil.isEmpty(fileName) || stream == null) {
        LOGGER.warning("Unable to upload file: invalid parameters provided: upload path: " + uploadPath
                + ", file name: " + fileName + ", stream: " + stream);
        return false;
    }

    ByteArrayOutputStream tmp = null;
    byte[] memory = null;
    if (IWMainApplication.getDefaultIWMainApplication().getSettings().getBoolean("slide.copy_stream_for_upload",
            true)) {
        try {
            tmp = new ByteArrayOutputStream();
            FileUtil.streamToOutputStream(stream, tmp);
            memory = tmp.toByteArray();
        } catch (Exception e) {
        } finally {
            if (memory != null && closeStream)
                IOUtil.close(stream);
            IOUtil.close(tmp);
        }
    }

    boolean success = false;
    stream = memory == null ? stream : new ByteArrayInputStream(memory);
    UploadWorker uw = new UploadWorker(this, uploadPath, fileName, contentType, stream, closeStream);
    try {
        Thread uploader = new Thread(uw);
        uploader.run(); //   We want "synchronous" execution
        success = uw.isWorkFinishedSuccessfully();
    } catch (Throwable t) {
        LOGGER.log(Level.WARNING, "Error while uploading: ".concat(uploadPath).concat(fileName), t);
    } finally {
        removeFromQueue(uploadPath, uw.getWorkId());

        if (success && closeStream)
            IOUtil.close(stream);
    }
    if (success)
        return Boolean.TRUE;

    try {
        stream = memory == null ? stream : new ByteArrayInputStream(memory);
        success = CoreUtil.doWriteFileToRepository(uploadPath, fileName, stream);
        if (success) {
            getLogger().info("Wrote file " + fileName + " to " + uploadPath + " using files system");
        } else {
            getLogger()
                    .warning("Failed to write file " + fileName + " to " + uploadPath + " using files system");
        }
        return success;
    } catch (IOException e) {
        String message = "Error writing to the repository (" + uploadPath + fileName + ") using files system";
        LOGGER.log(Level.WARNING, message, e);
        CoreUtil.sendExceptionNotification(message, e);
        return false;
    } finally {
        if (closeStream)
            IOUtil.close(stream);
    }
}