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:co.edu.uniajc.vtf.ar.ARViewActivity.java

public void callARView() {
    ExtendedApplicationContext loContext = (ExtendedApplicationContext) this.getApplication();
    ArrayList<PointOfInterestEntity> loPoints = loContext.getBufferPoints();
    if (loPoints != null) {
        this.coPois = this.createJsonArray(loPoints).toString();
        //here we create a thread to call the AR View
        final Thread loThread = new Thread(this.coLoadData);
        loThread.run();
    }// ww  w.ja  v a 2 s . com
}

From source file:arena.mail.MailSender.java

public void sendThreaded(MailMessage message, SendingFailureCallback... failureCallbacks) {
    Session session = makeSession(this.smtpServer, this.smtpServerDelimiter, this.mailProperties);
    Thread th = new Thread(new SendingRunnable(message, session, failureCallbacks),
            "mail to:" + message.getToAddress() + " subject:" + message.getSubject());
    th.setDaemon(true);//from   w w  w  .  j  a v  a2  s  .c om
    th.run();
}

From source file:fm.last.irccat.IRCCat.java

public void handleMessage(String channel_, String sender, String message) {
    String cmd;/*from   w w  w .  j  a  v  a2  s  .co m*/
    String respondTo = channel_ == null ? sender : channel_;

    if (message.startsWith(nick)) {
        // someone said something to us.
        // we don't care.
        return;
    }

    if (message.startsWith("!")) {
        if (!isTrusted(sender)) {
            System.out.println("UNTRUSTED (ignoring): [" + respondTo + "] <" + sender + "> " + message);
            return;
        }
        // irccat builtin command processing:
        String resp = handleBuiltInCommand(message.substring(1).trim(), sender);
        if (!(resp == null || resp.equals("")))
            sendMessage(respondTo, resp);

        System.out.println("Built-in: [" + respondTo + "] <" + sender + "> " + message);
        return;
    }

    if (message.startsWith("?")) {
        // external script command.
        cmd = message.substring(1).trim();
    } else {
        // just a normal message which we ignore
        return;
    }

    if (cmd.trim().length() < 1)
        return;

    // if a PM, you gotta be trusted.
    if (channel_ == null && !isTrusted(sender)) {
        System.out.println("UNTRUSTED (ignoring): [" + respondTo + "] <" + sender + "> " + message);
        return;
    }

    // now "cmd" contains the message, minus the address prefix (eg: ?)
    // hand off msg to thread that executes shell script
    System.out.println("Scripter: [" + respondTo + "] <" + sender + "> " + message);
    Thread t = new Scripter(sender, channel_, respondTo, cmd, this);
    t.run();
}

From source file:org.grouplens.lenskit.eval.algorithm.ExternalAlgorithmInstance.java

@Override
public RecommenderInstance makeTestableRecommender(TTDataSet data,
        Provider<? extends PreferenceSnapshot> snapshot, ExecutionInfo info) throws RecommenderBuildException {
    final File train;
    try {/*w w w . ja va 2 s  .  c  o  m*/
        train = trainingFile(data);
    } catch (IOException e) {
        throw new RecommenderBuildException("error preparing training file", e);
    }
    final File test;
    try {
        test = testFile(data);
    } catch (IOException e) {
        throw new RecommenderBuildException("error preparing test file", e);
    }
    final File output = new File(workDir, String.format("%s-%s.predictions.csv", getName(), data.getName()));
    List<String> args = Lists.transform(command, new Function<String, String>() {
        @Nullable
        @Override
        public String apply(@Nullable String input) {
            if (input == null) {
                throw new IllegalArgumentException("cannot have null command element");
            }
            String s = input.replace("{OUTPUT}", output.getAbsolutePath());
            s = s.replace("{TRAIN_DATA}", train.getAbsolutePath());
            s = s.replace("{TEST_DATA}", test.getAbsolutePath());
            return s;
        }
    });

    logger.info("running {}", StringUtils.join(args, " "));

    Process proc;
    try {
        proc = new ProcessBuilder().command(args).directory(workDir).start();
    } catch (IOException e) {
        throw new RecommenderBuildException("error creating process", e);
    }
    Thread listen = new ProcessErrorHandler(proc.getErrorStream());
    listen.run();

    int result = -1;
    boolean done = false;
    while (!done) {
        try {
            result = proc.waitFor();
            done = true;
        } catch (InterruptedException e) {
            /* try again */
        }
    }

    if (result != 0) {
        logger.error("external command exited with status {}", result);
        throw new RecommenderBuildException("recommender exited with code " + result);
    }

    Long2ObjectMap<SparseVector> vectors;
    try {
        vectors = readPredictions(output);
    } catch (FileNotFoundException e) {
        logger.error("cannot find expected output file {}", output);
        throw new RecommenderBuildException("recommender produced no output", e);
    }

    return new RecInstance(data.getTrainingData().getUserEventDAO(), vectors);
}

From source file:io.kazuki.v0.store.keyvalue.KeyValueStoreBasicOperationsTest.java

@Test
public void emptySchema() throws Exception {
    final Thread t = new Thread(new Runnable() {
        @Override//from www .  j  a  va 2 s  . c  o m
        public void run() {
            try {
                schema.createSchema("record", Record.SCHEMA);
            } catch (KazukiException e) {
                e.printStackTrace();
            }
        }
    });
    t.run();
    t.join();
    try (final KeyValueIterable<KeyValuePair<Record>> kvi = kvStore.iterators().entries("record", Record.class,
            SortDirection.ASCENDING)) {
        for (KeyValuePair<Record> kv : kvi) {
            System.out.println(kv.getValue().getKey() + " = " + kv.getValue().getValue());
        }
    }
}

From source file:org.grouplens.lenskit.eval.traintest.ExternalEvalJob.java

@Override
protected void buildRecommender() throws RecommenderBuildException {
    Preconditions.checkState(userPredictions == null, "recommender already built");
    File dir = getStagingDir();//from   ww w  . ja v a2 s .  c o  m
    logger.info("using output/staging directory {}", dir);
    if (!dir.exists()) {
        logger.info("creating directory {}", dir);
        dir.mkdirs();
    }

    final File train;
    try {
        train = trainingFile(dataSet);
    } catch (IOException e) {
        throw new RecommenderBuildException("error preparing training file", e);
    }
    final File test;
    try {
        test = testFile(dataSet);
    } catch (IOException e) {
        throw new RecommenderBuildException("error preparing test file", e);
    }
    final File output = getFile("predictions.csv");
    List<String> args = Lists.transform(algorithm.getCommand(), new Function<String, String>() {
        @Nullable
        @Override
        public String apply(@Nullable String input) {
            if (input == null) {
                throw new NullPointerException("command element");
            }
            String s = input.replace("{OUTPUT}", output.getAbsolutePath());
            s = s.replace("{TRAIN_DATA}", train.getAbsolutePath());
            s = s.replace("{TEST_DATA}", test.getAbsolutePath());
            return s;
        }
    });

    logger.info("running {}", StringUtils.join(args, " "));

    Process proc;
    try {
        proc = new ProcessBuilder().command(args).directory(algorithm.getWorkDir()).start();
    } catch (IOException e) {
        throw new RecommenderBuildException("error creating process", e);
    }
    Thread listen = new LoggingStreamSlurper("external-algo", proc.getErrorStream(), logger, "external: ");
    listen.run();

    int result = -1;
    boolean done = false;
    while (!done) {
        try {
            result = proc.waitFor();
            done = true;
        } catch (InterruptedException e) {
            logger.info("thread interrupted, killing subprocess");
            proc.destroy();
            throw new RecommenderBuildException("recommender build interrupted", e);
        }
    }

    if (result != 0) {
        logger.error("external command exited with status {}", result);
        throw new RecommenderBuildException("recommender exited with code " + result);
    }

    Long2ObjectMap<SparseVector> vectors;
    try {
        vectors = readPredictions(output);
    } catch (FileNotFoundException e) {
        logger.error("cannot find expected output file {}", output);
        throw new RecommenderBuildException("recommender produced no output", e);
    }

    userPredictions = vectors;

    userTrainingEvents = dataSet.getTrainingData().getUserEventDAO();
    userTestEvents = dataSet.getTestData().getUserEventDAO();
}

From source file:com.xpn.xwiki.plugin.graphviz.GraphVizPlugin.java

/**
 * Executes GraphViz, writes the resulting image (in the requested format) in a temporary file on disk, and returns
 * the generated content from that file.
 * //from  www.  j av a2  s.c om
 * @param hashCode the hascode of the content, to be used as the temporary file name
 * @param content the dot source code
 * @param extension the output file extension
 * @param dot which engine to execute: {@code dot} if {@code true}, {@code neato} if {@code false}
 * @return the content of the generated file
 * @throws IOException if writing the input or output files to the disk fails, or if writing the response body fails
 */
private byte[] getDotImage(int hashCode, String content, String extension, boolean dot) throws IOException {
    File dfile = getTempFile(hashCode, "input.dot", dot);
    if (!dfile.exists()) {
        FileUtils.write(dfile, content, XWiki.DEFAULT_ENCODING);
    }

    File ofile = getTempFile(hashCode, extension, dot);
    if (!ofile.exists()) {
        Runtime rt = Runtime.getRuntime();
        String[] command = new String[5];
        command[0] = dot ? this.dotPath : this.neatoPath;
        command[1] = "-T" + extension;
        command[2] = dfile.getAbsolutePath();
        command[3] = "-o";
        command[4] = ofile.getAbsolutePath();
        Process p = rt.exec(command);
        int exitValue = -1;
        final Thread thisThread = Thread.currentThread();
        Thread t = new Thread(new Hangcheck(thisThread), "dot-hangcheck");
        t.run();
        try {
            exitValue = p.waitFor();
            t.interrupt();
        } catch (InterruptedException ex) {
            p.destroy();
            LOGGER.error("Timeout while generating image from dot", ex);
        }

        if (exitValue != 0) {
            LOGGER.error("Error while generating image from dot: "
                    + IOUtils.toString(p.getErrorStream(), XWiki.DEFAULT_ENCODING));
        }
    }
    return FileUtils.readFileToByteArray(ofile);
}

From source file:com.ls.zencat.ZenCat.java

public void handleMessage(String channel_, String sender, String message) {
    String cmd;/*from   w  ww .j  a  v  a 2 s  .  c om*/
    String respondTo = channel_ == null ? sender : channel_;

    if (message.startsWith(nick)) {
        // someone said something to us.
        // we don't care!
        return;
    }

    if (message.startsWith("!")) {
        if (!isTrusted(sender)) {
            System.out.println("UNTRUSTED (ignoring): [" + respondTo + "] <" + sender + "> " + message);
            return;
        }
        // zencat builtin command processing:
        String resp = handleBuiltInCommand(message.substring(1).trim(), sender);
        if (!(resp == null || resp.equals("")))
            sendMessage(respondTo, resp);

        System.out.println("Built-in: [" + respondTo + "] <" + sender + "> " + message);
        return;
    }

    if (message.startsWith("?")) {
        // external script command.
        cmd = message.substring(1).trim();
    } else {
        // just a normal message which we ignore
        return;
    }

    if (cmd.trim().length() < 1)
        return;

    // if a PM, you gotta be trusted.
    if (channel_ == null && !isTrusted(sender)) {
        System.out.println("UNTRUSTED (ignoring): [" + respondTo + "] <" + sender + "> " + message);
        return;
    }

    // now "cmd" contains the message, minus the address prefix (eg: ?)
    // hand off msg to thread that executes shell script
    System.out.println("Scripter: [" + respondTo + "] <" + sender + "> " + message);
    Thread t = new Scripter(sender, channel_, respondTo, cmd, this);
    t.run();
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.TestGroup.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void runTests(List<TestCase> testsToRun, final MobileServiceClient client,
        final TestExecutionCallback callback) {

    try {//from   w w w. j a v a 2 s. c  om
        onPreExecute(client);
    } catch (Exception e) {
        mStatus = TestStatus.Failed;
        if (callback != null)
            callback.onTestGroupComplete(this, null);
        return;
    }

    final TestRunStatus testRunStatus = new TestRunStatus();

    mNewTestRun = true;

    int oldQueueSize = mTestRunQueue.size();
    mTestRunQueue.clear();
    mTestRunQueue.addAll(testsToRun);
    cleanTestsState();
    testRunStatus.results.clear();
    mStatus = TestStatus.NotRun;

    if (oldQueueSize == 0) {
        for (final TestCase test : mTestRunQueue) {

            final CountDownLatch latch = new CountDownLatch(1);

            Thread thread = new Thread() {
                public void run() {
                    executeNextTest(test, client, callback, testRunStatus, latch);
                }
            };

            thread.run();

            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (test.getStatus() == TestStatus.Failed) {
                mFailedTestCount++;
            }
        }

        // End Run
        final CountDownLatch latch = new CountDownLatch(1);

        Thread thread = new Thread() {
            public void run() {
                executeNextTest(null, client, callback, testRunStatus, latch);
            }
        };

        thread.run();

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.apache.hadoop.hdfs.TestCloseFile.java

/**
 * Test that close.replication.min of 2 works
 * @throws Exception//from w  w  w  .  j av a  2  s . c  om
 */
private void testCloseReplication(boolean restartDN) throws Exception {
    String file = "/testRestartDatanodeNode";

    // Create a file with a replication factor of 2 and write data.
    final FSDataOutputStream out = fs.create(new Path(file), (short) 2);
    byte[] buffer = new byte[FILE_LEN];
    random.nextBytes(buffer);
    out.write(buffer);
    ((DFSOutputStream) out.getWrappedStream()).sync();

    // take down one datanode in the pipeline
    DatanodeInfo[] locs = cluster.getNameNode().getBlockLocations(file, 0, FILE_LEN).getLocatedBlocks().get(0)
            .getLocations();
    assertEquals(2, locs.length);
    DatanodeInfo loc = locs[0];
    DataNodeProperties dnprop = cluster.stopDataNode(loc.getName());
    cluster.getNameNode().namesystem.removeDatanode(loc);
    out.write(buffer);
    ((DFSOutputStream) out.getWrappedStream()).sync();
    // the pipeline length drops to 1
    assertEquals(1, (((DFSOutputStream) out.getWrappedStream()).getNumCurrentReplicas()));

    if (restartDN) {
        // restart introduces an invalid replica
        cluster.restartDataNode(dnprop);
        // the number of targets becomes 2 with 1 invalid replica
        locs = cluster.getNameNode().getBlockLocations(file, 0, FILE_LEN).getLocatedBlocks().get(0)
                .getLocations();
        assertEquals(2, locs.length);
    }

    //  now close the file
    Thread closeThread = new Thread() {
        public void run() {
            try {
                out.close();
                pass = true;
                LOG.info("File closed");
            } catch (Exception e) {
                pass = false;
            }
        }
    };
    closeThread.run();

    // wait until the last block is replicated and the file is closed
    closeThread.join(CLOSE_FILE_TIMEOUT);
    assertTrue(pass);
}