List of usage examples for java.lang Runnable Runnable
Runnable
From source file:com.cloud.test.utils.TestClient.java
public static void main(String[] args) { String host = "http://localhost"; String port = "8080"; String testUrl = "/client/test"; int numThreads = 1; try {//w ww. j a va 2 s.c om // Parameters List<String> argsList = Arrays.asList(args); Iterator<String> iter = argsList.iterator(); while (iter.hasNext()) { String arg = iter.next(); // host if (arg.equals("-h")) { host = "http://" + iter.next(); } if (arg.equals("-p")) { port = iter.next(); } if (arg.equals("-t")) { numThreads = Integer.parseInt(iter.next()); } if (arg.equals("-s")) { sleepTime = Long.parseLong(iter.next()); } if (arg.equals("-c")) { cleanUp = Boolean.parseBoolean(iter.next()); if (!cleanUp) sleepTime = 0L; // no need to wait if we don't ever cleanup } if (arg.equals("-r")) { repeat = Boolean.parseBoolean(iter.next()); } if (arg.equals("-u")) { numOfUsers = Integer.parseInt(iter.next()); } if (arg.equals("-i")) { internet = Boolean.parseBoolean(iter.next()); } } final String server = host + ":" + port + testUrl; s_logger.info("Starting test against server: " + server + " with " + numThreads + " thread(s)"); if (cleanUp) s_logger.info("Clean up is enabled, each test will wait " + sleepTime + " ms before cleaning up"); if (numOfUsers > 0) { s_logger.info("Pre-generating users for test of size : " + numOfUsers); users = new String[numOfUsers]; Random ran = new Random(); for (int i = 0; i < numOfUsers; i++) { users[i] = Math.abs(ran.nextInt()) + "-user"; } } for (int i = 0; i < numThreads; i++) { new Thread(new Runnable() { public void run() { do { String username = null; try { long now = System.currentTimeMillis(); Random ran = new Random(); if (users != null) { username = users[Math.abs(ran.nextInt()) % numOfUsers]; } else { username = Math.abs(ran.nextInt()) + "-user"; } NDC.push(username); String url = server + "?email=" + username + "&password=" + username + "&command=deploy"; s_logger.info("Launching test for user: " + username + " with url: " + url); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int responseCode = client.executeMethod(method); boolean success = false; String reason = null; if (responseCode == 200) { if (internet) { s_logger.info("Deploy successful...waiting 5 minute before SSH tests"); Thread.sleep(300000L); // Wait 60 seconds so the linux VM can boot up. s_logger.info("Begin Linux SSH test"); reason = sshTest(method.getResponseHeader("linuxIP").getValue()); if (reason == null) { s_logger.info("Linux SSH test successful"); s_logger.info("Begin Windows SSH test"); reason = sshWinTest(method.getResponseHeader("windowsIP").getValue()); } } if (reason == null) { if (internet) { s_logger.info("Windows SSH test successful"); } else { s_logger.info("deploy test successful....now cleaning up"); if (cleanUp) { s_logger.info( "Waiting " + sleepTime + " ms before cleaning up vms"); Thread.sleep(sleepTime); } else { success = true; } } if (users == null) { s_logger.info("Sending cleanup command"); url = server + "?email=" + username + "&password=" + username + "&command=cleanup"; } else { s_logger.info("Sending stop DomR / destroy VM command"); url = server + "?email=" + username + "&password=" + username + "&command=stopDomR"; } method = new GetMethod(url); responseCode = client.executeMethod(method); if (responseCode == 200) { success = true; } else { reason = method.getStatusText(); } } else { // Just stop but don't destroy the VMs/Routers s_logger.info("SSH test failed with reason '" + reason + "', stopping VMs"); url = server + "?email=" + username + "&password=" + username + "&command=stop"; responseCode = client.executeMethod(new GetMethod(url)); } } else { // Just stop but don't destroy the VMs/Routers reason = method.getStatusText(); s_logger.info("Deploy test failed with reason '" + reason + "', stopping VMs"); url = server + "?email=" + username + "&password=" + username + "&command=stop"; client.executeMethod(new GetMethod(url)); } if (success) { s_logger.info("***** Completed test for user : " + username + " in " + ((System.currentTimeMillis() - now) / 1000L) + " seconds"); } else { s_logger.info("##### FAILED test for user : " + username + " in " + ((System.currentTimeMillis() - now) / 1000L) + " seconds with reason : " + reason); } } catch (Exception e) { s_logger.warn("Error in thread", e); try { HttpClient client = new HttpClient(); String url = server + "?email=" + username + "&password=" + username + "&command=stop"; client.executeMethod(new GetMethod(url)); } catch (Exception e1) { } } finally { NDC.clear(); } } while (repeat); } }).start(); } } catch (Exception e) { s_logger.error(e); } }
From source file:framework.httpclient.nio.NHttpClient.java
public static void main(String[] args) throws Exception { // Create HTTP protocol processing chain HttpProcessor httpproc = HttpProcessorBuilder.create() // Use standard client-side protocol interceptors .add(new RequestContent()).add(new RequestTargetHost()).add(new RequestConnControl()) .add(new RequestUserAgent("LinkedHashSetVsTreeSet/1.1")).add(new RequestExpectContinue(true)) .build();/* www . ja va 2s . co m*/ // Create client-side HTTP protocol handler HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor(); // Create client-side I/O event dispatch // IO final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, ConnectionConfig.DEFAULT); // Create client-side I/O reactor // IO reactor final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(); // Create HTTP connection pool // HTTP BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, ConnectionConfig.DEFAULT); // Limit total number of connections to just two pool.setDefaultMaxPerRoute(2); pool.setMaxTotal(2); // Run the I/O reactor in a separate thread Thread t = new Thread(new Runnable() { public void run() { try { // Ready to go! ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } System.out.println("Shutdown"); } }); // Start the client thread t.start(); // Create HTTP requester // HTTP HttpAsyncRequester requester = new HttpAsyncRequester(httpproc); // Execute HTTP GETs to the following hosts and HttpHost[] targets = new HttpHost[] { new HttpHost("www.baidu.org", -1, "https"), // new HttpHost("www.zhihu.com", -1, "https"), new HttpHost("www.bilibili.com", -1, "https") }; final CountDownLatch latch = new CountDownLatch(targets.length); for (final HttpHost target : targets) { BasicHttpRequest request = new BasicHttpRequest("GET", "/"); HttpCoreContext coreContext = HttpCoreContext.create(); requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(), pool, coreContext, // Handle HTTP response from a callback new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { latch.countDown(); System.out.println(target + "->" + response.getStatusLine()); } public void failed(final Exception ex) { latch.countDown(); System.err.println(target + "->" + ex); ex.printStackTrace(); } public void cancelled() { latch.countDown(); System.out.println(target + " cancelled"); } }); } latch.await(); System.out.println("Shutting down I/O reactor"); ioReactor.shutdown(); System.out.println("Done"); }
From source file:me.philnate.textmanager.windows.MainWindow.java
/** * Launch the application./*ww w. ja v a 2 s . c om*/ */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { MainWindow window = new MainWindow(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); }
From source file:de.rub.syssec.saaf.Main.java
public static void main(String[] args) throws Exception { // make sure log4j configuration is read before doing anything else updateLog4jConfiguration(false, false); try {/*from w ww . j a va 2 s .c om*/ //Setup the commandline buildOptions(); Config conf = Config.getInstance(); //Parse the arguments and adjust configuration accordingly processCommandline(args); //Check if the adjusted configuration contains any errors/inconsistencies conf.validate(); //prepare database and filesystem prepare(conf); //should we just watch a folder for incoming apks? if (conf.getBooleanConfigValue(ConfigKeys.DAEMON_ENABLED)) { String watched = conf.getConfigValue(ConfigKeys.DAEMON_DIRECTORY); long interval = conf.getIntConfigValue(ConfigKeys.DAEMON_POLLING_INTERVAL, 5000); FolderWatcher watcher = new FolderWatcher(watched, interval); watcher.startWatching(); } // Create GUI? else if (conf.getBooleanConfigValue(ConfigKeys.ANALYSIS_IS_HEADLESS)) { // no GUI Headless.startAnalysis(apkPath); } else { // yes, I want a GUI // Schedule a job for the event-dispatching thread: // creating and showing this Application's GUI. // TODO: use apk_path in gui mode! javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { MainWindow m = new MainWindow(); m.createAndShowGUI(); } }); } } catch (Exception e) { LOGGER.error("An error occured", e); System.exit(0); } }
From source file:layout.CardLayoutDemo.java
public static void main(String[] args) { /* Use an appropriate Look and Feel */ try {/* ww w . jav a 2 s . co m*/ //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); 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 dispatch thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); }
From source file:eu.mrbussy.pdfsplitter.Application.java
/** * Start the main program.// ww w.j a v a 2s. c o m * * @param args * - Arguments passed on to the program */ public static void main(String[] args) { // Read configurations try { String configDirname = FilenameUtils.concat(System.getProperty("user.home"), String.format(".%1$s%2$s", NAME, IOUtils.DIR_SEPARATOR)); String filename = FilenameUtils.concat(configDirname, CONFIGURATION_FILE); // Check to see if the directory exists and the file can be created/opened File configDir = new File(configDirname); if (!configDir.exists()) configDir.mkdir(); // Check to see if the file exists. If not create it File file = new File(filename); if (!file.exists()) { file.createNewFile(); } Configuration = new PropertiesConfiguration(file); // Automatically store the settings that change Configuration.setAutoSave(true); } catch (ConfigurationException | IOException ex) { // Unable to read the file. Probably because it does not exist --> create it. ex.printStackTrace(); } // Set locale to a configured language Locale.setDefault( new Locale(Configuration.getString("language", "nl"), Configuration.getString("country", "NL"))); // Start by parsing the command line ParseCommandline(args); // Display the help if required and leave the app if (arguments.hasOption("h")) { showHelp(); } // Display the app version and leave the app. if (arguments.hasOption("v")) { showVersion(); } // Not command line so start the app GUI if (!arguments.hasOption("c")) { try { // Change the look and feel UIManager.setLookAndFeel( Configuration.getString("LookAndFeel", "com.sun.java.swing.plaf.gtk.GTKLookAndFeel")); javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { (new MainWindow()).setVisible(true); } }); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // Something terrible happened so show the help showHelp(); } } }
From source file:CheckThreadViolationRepaintManager.java
public static void main(String[] args) throws Exception { // set CheckThreadViolationRepaintManager RepaintManager.setCurrentManager(new CheckThreadViolationRepaintManager()); // Valid code SwingUtilities.invokeAndWait(new Runnable() { public void run() { test();//from w ww . j av a 2s . c o m } }); System.out.println("Valid code passed..."); repaintTest(); System.out.println("Repaint test - correct code"); // Invalide code (stack trace expected) test(); }
From source file:org.eclipse.swt.snippets.Snippet341.java
public static void main(String[] args) { final Display display = new Display(); Shell shell = new Shell(display); shell.setLayout(new FormLayout()); GLData data = new GLData(); data.doubleBuffer = true;/*from w ww. j av a 2s .c o m*/ final GLCanvas canvas = new GLCanvas(shell, SWT.NONE, data); canvas.setCurrent(); GL.createCapabilities(); canvas.addListener(SWT.Resize, event -> { Rectangle bounds = canvas.getBounds(); float fAspect = (float) bounds.width / (float) bounds.height; canvas.setCurrent(); GL.createCapabilities(); GL11.glViewport(0, 0, bounds.width, bounds.height); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); float near = 0.5f; float bottom = -near * (float) Math.tan(45.f / 2); float left = fAspect * bottom; GL11.glFrustum(left, -left, bottom, -bottom, near, 400.f); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); }); GL11.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); GL11.glColor3f(1.0f, 0.0f, 0.0f); GL11.glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT, GL11.GL_NICEST); GL11.glClearDepth(1.0); GL11.glLineWidth(2); GL11.glEnable(GL11.GL_DEPTH_TEST); Button button = new Button(shell, SWT.PUSH); button.setText("Capture"); button.addListener(SWT.Selection, event -> capture(canvas)); FormData formData = new FormData(640, 480); formData.top = new FormAttachment(0, 0); formData.left = new FormAttachment(0, 0); formData.bottom = new FormAttachment(button, 0); formData.right = new FormAttachment(100, 0); canvas.setLayoutData(formData); formData = new FormData(); formData.left = new FormAttachment(0, 0); formData.bottom = new FormAttachment(100, 0); formData.right = new FormAttachment(100, 0); button.setLayoutData(formData); shell.pack(); shell.open(); display.asyncExec(new Runnable() { int rot = 0; @Override public void run() { if (!canvas.isDisposed()) { canvas.setCurrent(); GL.createCapabilities(); GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); GL11.glClearColor(.3f, .5f, .8f, 1.0f); GL11.glLoadIdentity(); GL11.glTranslatef(0.0f, 0.0f, -10.0f); float frot = rot; GL11.glRotatef(0.15f * rot, 2.0f * frot, 10.0f * frot, 1.0f); GL11.glRotatef(0.3f * rot, 3.0f * frot, 1.0f * frot, 1.0f); rot++; GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE); GL11.glColor3f(0.9f, 0.9f, 0.9f); drawTorus(1, 1.9f + ((float) Math.sin((0.004f * frot))), 15, 15); canvas.swapBuffers(); display.asyncExec(this); } } }); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); }
From source file:layout.Find.java
public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { try { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); // "com.sun.java.swing.plaf.motif.MotifLookAndFeel"); //UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception ex) { ex.printStackTrace();/*from w ww.java 2 s . c o m*/ } new Find().setVisible(true); } }); }
From source file:com.ln.gui.Main.java
public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { createandshowgui();// w w w . ja v a2s .co m } catch (Exception e) { //Kill&print on errors e.printStackTrace(); JOptionPane.showMessageDialog(null, e.getStackTrace(), "Error", JOptionPane.WARNING_MESSAGE); } } }); }