List of usage examples for java.lang Runnable Runnable
Runnable
From source file:org.apache.uima.examples.as.GetMetaRequest.java
/** * retrieve meta information for a UIMA-AS Service attached to a broker * It uses the port 1099 as the JMX port on the broker, unless overridden * by defining the system property activemq.broker.jmx.port with a value of another port number * It uses the default JMX ActiveMQ Domain "org.apache.activemq", unless overridden * by defining the system property activemq.broker.jmx.domain with a value of the domain to use * This normally never needs to be done unless multiple brokers are run on the same node * as is sometimes done for unit tests. * @param args - brokerUri serviceName [-verbose] */// w w w . ja v a 2 s. c o m public static void main(String[] args) { if (args.length < 2) { System.err.println("Need arguments: brokerURI serviceName [-verbose]"); System.exit(1); } String brokerURI = args[0]; String queueName = args[1]; boolean printReply = false; if (args.length > 2) { if (args[2].equalsIgnoreCase("-verbose")) { printReply = true; } else { System.err.println("Unknown argument: " + args[2]); System.exit(1); } } final Connection connection; Session producerSession = null; Queue producerQueue = null; MessageProducer producer; MessageConsumer consumer; Session consumerSession = null; TemporaryQueue consumerDestination = null; long startTime = 0; // Check if JMX server port number was specified jmxPort = System.getProperty("activemq.broker.jmx.port"); if (jmxPort == null || jmxPort.trim().length() == 0) { jmxPort = "1099"; // default } try { // First create connection to a broker ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI); connection = factory.createConnection(); connection.start(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { try { if (connection != null) { connection.close(); } if (jmxc != null) { jmxc.close(); } } catch (Exception ex) { } } })); URI target = new URI(brokerURI); String brokerHost = target.getHost(); attachToRemoteBrokerJMXServer(brokerURI); if (isQueueAvailable(queueName) == QueueState.exists) { System.out.println("Queue " + queueName + " found on " + brokerURI); System.out.println("Sending getMeta..."); } else if (isQueueAvailable(queueName) == QueueState.existsnot) { System.err.println("Queue " + queueName + " does not exist on " + brokerURI); System.exit(1); } else { System.out.println("Cannot see queues on JMX port " + brokerHost + ":" + jmxPort); System.out.println("Sending getMeta anyway..."); } producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); producerQueue = producerSession.createQueue(queueName); producer = producerSession.createProducer(producerQueue); consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); consumerDestination = consumerSession.createTemporaryQueue(); // ----------------------------------------------------------------------------- // Create message consumer. The consumer uses a selector to filter out messages other // then GetMeta replies. Currently UIMA AS service returns two messages for each request: // ServiceInfo message and GetMeta message. The ServiceInfo message is returned by the // service immediately upon receiving a message from a client. This serves dual purpose, // 1) to make sure the client reply destination exists // 2) informs the client which service is processing its request // ----------------------------------------------------------------------------- consumer = consumerSession.createConsumer(consumerDestination, "Command=2001"); TextMessage msg = producerSession.createTextMessage(); msg.setStringProperty(AsynchAEMessage.MessageFrom, consumerDestination.getQueueName()); msg.setStringProperty(UIMAMessage.ServerURI, brokerURI); msg.setIntProperty(AsynchAEMessage.MessageType, AsynchAEMessage.Request); msg.setIntProperty(AsynchAEMessage.Command, AsynchAEMessage.GetMeta); msg.setJMSReplyTo(consumerDestination); msg.setText(""); producer.send(msg); startTime = System.nanoTime(); System.out.println("Sent getMeta request to " + queueName + " at " + brokerURI); System.out.println("Waiting for getMeta reply..."); ActiveMQTextMessage reply = (ActiveMQTextMessage) consumer.receive(); long waitTime = (System.nanoTime() - startTime) / 1000000; System.out.println( "Reply from " + reply.getStringProperty("ServerIP") + " received in " + waitTime + " ms"); if (printReply) { System.out.println("Reply MessageText: " + reply.getText()); } } catch (Exception e) { System.err.println(e.toString()); } System.exit(0); }
From source file:de.cosmocode.palava.core.Main.java
/** * Application entry point.//from w w w . j av a2s .c o m * * @param args command line arguments */ public static void main(String[] args) { AsciiArt.print(); final Main main; try { main = new Main(args); /* CHECKSTYLE:OFF */ } catch (RuntimeException e) { /* CHECKSTYLE:ON */ LOG.error("configuration error", e); printToStdErr(e); System.exit(1); throw e; } main.start(); LOG.debug("Adding shutdown hook"); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { main.stop(); synchronized (main) { main.notify(); } } })); main.waitIfNecessary(); System.exit(0); }
From source file:de.mpi_bremen.mgg.FastaValidatorUi.java
/** * @param args the command line arguments *//*from w w w . j av a 2 s . co m*/ public static void main(String[] args) { // create Options object Options options = new Options(); // add verbose option options.addOption("v", "verbose", false, "verbose mode"); // add inputfile option options.addOption("f", "file", true, "FASTA-formatted input file"); // add help option options.addOption("h", "help", false, "print this help message"); // add sequencetype option options.addOption("t", "seqtype", true, "sequence type (allowed values: all|dna|rna|protein)"); // add gui-mode option options.addOption("nogui", false, "start in non-interactive mode"); //create the cmdline-parser GnuParser parser = new GnuParser(); // parse the command line arguments try { //get cmdline arguments cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println(exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("FastaValidatorUi", options, true); System.exit(1); //indicate error to external environment } if (cmdline.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("FastaValidatorUi", options, true); System.exit(0); //indicate no errors to external environment } //which mode? (gui or cmdline) if (cmdline.hasOption("nogui")) { //cmdline-mode //create new cmdline-gui FvCmdline cmdlinegui = new FvCmdline(); //set verbosity cmdlinegui.setVerbose(cmdline.hasOption("v")); //handle input file if (cmdline.hasOption("f")) { cmdlinegui.setInput(cmdline.getOptionValue("f")); } //set sequencetype if (cmdline.hasOption("t")) { cmdlinegui.setSequencetype(getSeqtype(cmdline.getOptionValue("t"))); } else { cmdlinegui.setSequencetype(FastaValidator.Sequencetype.ALL); } //trigger validation and exit with exitcode int exitcode = cmdlinegui.validate().getValue(); System.exit(exitcode); } else { //gui-mode //start gui in its own thread SwingUtilities.invokeLater(new Runnable() { public void run() { FvGui w = new FvGui(); } }); } }
From source file:friendsandfollowers.FilesThreaderFriendsIDs.java
public static void main(String[] args) throws InterruptedException { // Check how many arguments were passed in if ((args == null) || (args.length < 4)) { System.err.println("4 Parameters are required plus one optional " + "parameter to launch a Job."); System.err.println("First: String 'INPUT: /path/to/files/'"); System.err.println("Second: String 'OUTPUT: /output/path/'"); System.err.println("Third: (int) Total Number Of Jobs"); System.err.println("Fourth: (int) Number of seconds to pause"); System.err// ww w. j av a2s.c o m .println("Fifth: (int) Number of ids to fetch. " + "Provide number which increment by 5000 eg " + "(5000, 10000, 15000 etc) " + "or -1 to fetch all ids."); System.err.println("Example: fileToRun /input/path/ " + "/output/path/ 10 2 75000"); System.exit(-1); } // to write output in a file ThreadPrintStream.replaceSystemOut(); try { INPUT = StringEscapeUtils.escapeJava(args[0]); } catch (Exception e) { System.err.println("Argument" + args[0] + " must be an String."); System.exit(-1); } try { OUTPUT = StringEscapeUtils.escapeJava(args[1]); } catch (Exception e) { System.err.println("Argument" + args[1] + " must be an String."); System.exit(-1); } try { TOTAL_JOBS_STR = StringEscapeUtils.escapeJava(args[2]); } catch (Exception e) { System.err.println("Argument" + args[2] + " must be an integer."); System.exit(-1); } try { PAUSE_STR = StringEscapeUtils.escapeJava(args[3]); } catch (Exception e) { System.err.println("Argument" + args[3] + " must be an integer."); System.exit(-1); } if (args.length == 5) { try { IDS_TO_FETCH = StringEscapeUtils.escapeJava(args[4]); } catch (Exception e) { System.err.println("Argument" + args[4] + " must be an integer."); System.exit(-1); } } try { PAUSE = Integer.parseInt(args[3]); } catch (NumberFormatException e) { System.err.println("Argument" + args[3] + " must be an integer."); System.exit(-1); } try { TOTAL_JOBS = Integer.parseInt(TOTAL_JOBS_STR); } catch (NumberFormatException e) { System.err.println("Argument" + TOTAL_JOBS_STR + " must be an integer."); System.exit(-1); } System.out.println("Going to launch jobs. " + "Please see logs files to track jobs."); ExecutorService threadPool = Executors.newFixedThreadPool(TOTAL_JOBS); for (int i = 0; i < TOTAL_JOBS; i++) { final String JOB_NO = Integer.toString(i); threadPool.submit(new Runnable() { public void run() { try { // Creating a text file where System.out.println() // will send its output for this thread. String name = Thread.currentThread().getName(); FileOutputStream fos = null; try { fos = new FileOutputStream(name + "-logs.txt"); } catch (Exception e) { System.err.println(e.getMessage()); System.exit(0); } // Create a PrintStream that will write to the new file. PrintStream stream = new PrintStream(new BufferedOutputStream(fos)); // Install the PrintStream to be used as // System.out for this thread. ((ThreadPrintStream) System.out).setThreadOut(stream); // Output three messages to System.out. System.out.println(name); System.out.println(); System.out.println(); FilesThreaderFriendsIDs.execTask(INPUT, OUTPUT, TOTAL_JOBS_STR, JOB_NO, PAUSE_STR, IDS_TO_FETCH); } catch (IOException | ClassNotFoundException | SQLException | JSONException e) { // e.printStackTrace(); System.out.println(e.getMessage()); } } }); helpers.pause(PAUSE); } threadPool.shutdown(); }
From source file:SourceInDemo.java
public static void main(String... args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new SourceInDemo().setVisible(true); }/*ww w . j a v a 2 s . c om*/ }); }
From source file:friendsandfollowers.FilesThreaderFollowersIDs.java
public static void main(String[] args) throws InterruptedException { // Check how many arguments were passed in if ((args == null) || (args.length < 4)) { System.err.println("4 Parameters are required plus one optional " + "parameter to launch a Job."); System.err.println("First: String 'INPUT: /path/to/files/'"); System.err.println("Second: String 'OUTPUT: /output/path/'"); System.err.println("Third: (int) Total Number Of Jobs"); System.err.println("Fourth: (int) Number of seconds to pause"); System.err/*from www.ja v a 2s. c om*/ .println("Fifth: (int) Number of ids to fetch. " + "Provide number which increment by 5000 eg " + "(5000, 10000, 15000 etc) " + "or -1 to fetch all ids."); System.err.println("Example: fileToRun /input/path/ " + "/output/path/ 10 2 75000"); System.exit(-1); } // to write output in a file ThreadPrintStream.replaceSystemOut(); try { INPUT = StringEscapeUtils.escapeJava(args[0]); } catch (Exception e) { System.err.println("Argument" + args[0] + " must be an String."); System.exit(-1); } try { OUTPUT = StringEscapeUtils.escapeJava(args[1]); } catch (Exception e) { System.err.println("Argument" + args[1] + " must be an String."); System.exit(-1); } try { TOTAL_JOBS_STR = StringEscapeUtils.escapeJava(args[2]); } catch (Exception e) { System.err.println("Argument" + args[2] + " must be an integer."); System.exit(-1); } try { PAUSE_STR = StringEscapeUtils.escapeJava(args[3]); } catch (Exception e) { System.err.println("Argument" + args[3] + " must be an integer."); System.exit(-1); } if (args.length == 5) { try { IDS_TO_FETCH = StringEscapeUtils.escapeJava(args[4]); } catch (Exception e) { System.err.println("Argument" + args[4] + " must be an integer."); System.exit(-1); } } try { PAUSE = Integer.parseInt(args[3]); } catch (NumberFormatException e) { System.err.println("Argument" + args[3] + " must be an integer."); System.exit(-1); } try { TOTAL_JOBS = Integer.parseInt(TOTAL_JOBS_STR); } catch (NumberFormatException e) { System.err.println("Argument" + TOTAL_JOBS_STR + " must be an integer."); System.exit(-1); } System.out.println("Going to launch jobs. " + "Please see logs files to track jobs."); ExecutorService threadPool = Executors.newFixedThreadPool(TOTAL_JOBS); for (int i = 0; i < TOTAL_JOBS; i++) { final String JOB_NO = Integer.toString(i); threadPool.submit(new Runnable() { public void run() { try { // Creating a text file where System.out.println() // will send its output for this thread. String name = Thread.currentThread().getName(); FileOutputStream fos = null; try { fos = new FileOutputStream(name + "-logs.txt"); } catch (Exception e) { System.err.println(e.getMessage()); System.exit(0); } // Create a PrintStream that will write to the new file. PrintStream stream = new PrintStream(new BufferedOutputStream(fos)); // Install the PrintStream to be used as // System.out for this thread. ((ThreadPrintStream) System.out).setThreadOut(stream); // Output three messages to System.out. System.out.println(name); System.out.println(); System.out.println(); FilesThreaderFollowersIDs.execTask(INPUT, OUTPUT, TOTAL_JOBS_STR, JOB_NO, PAUSE_STR, IDS_TO_FETCH); } catch (IOException | ClassNotFoundException | SQLException | JSONException e) { // e.printStackTrace(); System.out.println(e.getMessage()); } } }); helpers.pause(PAUSE); } threadPool.shutdown(); }
From source file:com.ga.forms.DailyLogAddUI.java
/** * @param args the command line arguments *//* www . j a va 2 s . co m*/ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(DailyLogAddUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(DailyLogAddUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(DailyLogAddUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(DailyLogAddUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new DailyLogAddUI().setVisible(true); } }); }
From source file:misc.DesktopDemo.java
public static void main(String args[]) { /* Use an appropriate Look and Feel */ try {//from ww w . j a v a2 s .c o m //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); //UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); } catch (UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } catch (InstantiationException ex) { ex.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } /* Turn off metal's use of bold fonts */ UIManager.put("swing.boldMetal", Boolean.FALSE); //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. SwingUtilities.invokeLater(new Runnable() { public void run() { new DesktopDemo().setVisible(true); } }); }
From source file:com.alertlogic.aws.kinesis.test1.StreamWriter.java
/** * Start a number of threads and send randomly generated {@link HttpReferrerPair}s to a Kinesis Stream until the * program is terminated./*from w w w. j a va2 s . c o m*/ * * @param args Expecting 3 arguments: A numeric value indicating the number of threads to use to send * data to Kinesis and the name of the stream to send records to, and the AWS region in which these resources * exist or should be created. * @throws InterruptedException If this application is interrupted while sending records to Kinesis. */ public static void main(String[] args) throws InterruptedException { if (args.length != 3) { System.err.println( "Usage: " + StreamWriter.class.getSimpleName() + " <number of threads> <stream name> <region>"); System.exit(1); } int numberOfThreads = Integer.parseInt(args[0]); String streamName = args[1]; Region region = SampleUtils.parseRegion(args[2]); AWSCredentialsProvider credentialsProvider = new DefaultAWSCredentialsProviderChain(); ClientConfiguration clientConfig = SampleUtils.configureUserAgentForSample(new ClientConfiguration()); AmazonKinesis kinesis = new AmazonKinesisClient(credentialsProvider, clientConfig); kinesis.setRegion(region); // The more resources we declare the higher write IOPS we need on our DynamoDB table. // We write a record for each resource every interval. // If interval = 500ms, resource count = 7 we need: (1000/500 * 7) = 14 write IOPS minimum. List<String> resources = new ArrayList<>(); resources.add("/index.html"); // These are the possible referrers to use when generating pairs List<String> referrers = new ArrayList<>(); referrers.add("http://www.amazon.com"); referrers.add("http://www.google.com"); referrers.add("http://www.yahoo.com"); referrers.add("http://www.bing.com"); referrers.add("http://www.stackoverflow.com"); referrers.add("http://www.reddit.com"); HttpReferrerPairFactory pairFactory = new HttpReferrerPairFactory(resources, referrers); // Creates a stream to write to with 2 shards if it doesn't exist StreamUtils streamUtils = new StreamUtils(kinesis); streamUtils.createStreamIfNotExists(streamName, 2); LOG.info(String.format("%s stream is ready for use", streamName)); final HttpReferrerKinesisPutter putter = new HttpReferrerKinesisPutter(pairFactory, kinesis, streamName); ExecutorService es = Executors.newCachedThreadPool(); Runnable pairSender = new Runnable() { @Override public void run() { try { putter.sendPairsIndefinitely(DELAY_BETWEEN_RECORDS_IN_MILLIS, TimeUnit.MILLISECONDS); } catch (Exception ex) { LOG.warn( "Thread encountered an error while sending records. Records will no longer be put by this thread.", ex); } } }; for (int i = 0; i < numberOfThreads; i++) { es.submit(pairSender); } LOG.info(String.format("Sending pairs with a %dms delay between records with %d thread(s).", DELAY_BETWEEN_RECORDS_IN_MILLIS, numberOfThreads)); es.shutdown(); es.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); }
From source file:de.topobyte.livecg.LiveCG.java
public static void main(String[] args) { // @formatter:off Options options = new Options(); OptionHelper.add(options, OPTION_CONFIG, true, false, "path", "config file"); // @formatter:on CommandLineParser clp = new GnuParser(); CommandLine line = null;/*from w ww .ja v a2 s. c om*/ try { line = clp.parse(options, args); } catch (ParseException e) { System.err.println("Parsing command line failed: " + e.getMessage()); new HelpFormatter().printHelp(HELP_MESSAGE, options); System.exit(1); } StringOption config = ArgumentHelper.getString(line, OPTION_CONFIG); if (config.hasValue()) { String configPath = config.getValue(); LiveConfig.setPath(configPath); } Configuration configuration = PreferenceManager.getConfiguration(); String lookAndFeel = configuration.getSelectedLookAndFeel(); if (lookAndFeel == null) { lookAndFeel = UIManager.getSystemLookAndFeelClassName(); } try { UIManager.setLookAndFeel(lookAndFeel); } catch (Exception e) { logger.error("error while setting look and feel '" + lookAndFeel + "': " + e.getClass().getSimpleName() + ", message: " + e.getMessage()); } Content content = null; String filename = "res/presets/Startup.geom"; String[] extra = line.getArgs(); if (extra.length > 0) { filename = extra[0]; } ContentReader reader = new ContentReader(); InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename); try { content = reader.read(input); } catch (Exception e) { logger.info("unable to load startup geometry file", e); logger.info("Exception: " + e.getClass().getSimpleName()); logger.info("Message: " + e.getMessage()); } final LiveCG runner = new LiveCG(); final Content c = content; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { runner.setup(true, c); } }); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { runner.frame.requestFocus(); } }); }