List of usage examples for java.lang Thread sleep
public static native void sleep(long millis) throws InterruptedException;
From source file:popo.defcon.MsgMeCDC.java
/** * @param args the command line arguments *//*from w ww. j av a 2 s.com*/ public static void main(String[] args) { MsgMeCDC m = new MsgMeCDC(); while (true) { m.Parse(); try { System.out.println("\n Starting Sleep"); Thread.sleep((long) 600000); System.out.println("\n SLEEP Finished"); } catch (InterruptedException ex) { System.out.println("\n SLEPP FAILED \n"); Logger.getLogger(MsgMeCDC.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:com.linkedin.pinotdruidbenchmark.DruidThroughput.java
@SuppressWarnings("InfiniteLoopStatement") public static void main(String[] args) throws Exception { if (args.length != 3 && args.length != 4) { System.err.println(//from w w w .ja v a 2 s. c om "3 or 4 arguments required: QUERY_DIR, RESOURCE_URL, NUM_CLIENTS, TEST_TIME (seconds)."); return; } File queryDir = new File(args[0]); String resourceUrl = args[1]; final int numClients = Integer.parseInt(args[2]); final long endTime; if (args.length == 3) { endTime = Long.MAX_VALUE; } else { endTime = System.currentTimeMillis() + Integer.parseInt(args[3]) * MILLIS_PER_SECOND; } File[] queryFiles = queryDir.listFiles(); assert queryFiles != null; Arrays.sort(queryFiles); final int numQueries = queryFiles.length; final HttpPost[] httpPosts = new HttpPost[numQueries]; for (int i = 0; i < numQueries; i++) { HttpPost httpPost = new HttpPost(resourceUrl); httpPost.addHeader("content-type", "application/json"); StringBuilder stringBuilder = new StringBuilder(); try (BufferedReader bufferedReader = new BufferedReader(new FileReader(queryFiles[i]))) { int length; while ((length = bufferedReader.read(CHAR_BUFFER)) > 0) { stringBuilder.append(new String(CHAR_BUFFER, 0, length)); } } String query = stringBuilder.toString(); httpPost.setEntity(new StringEntity(query)); httpPosts[i] = httpPost; } final AtomicInteger counter = new AtomicInteger(0); final AtomicLong totalResponseTime = new AtomicLong(0L); final ExecutorService executorService = Executors.newFixedThreadPool(numClients); for (int i = 0; i < numClients; i++) { executorService.submit(new Runnable() { @Override public void run() { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { while (System.currentTimeMillis() < endTime) { long startTime = System.currentTimeMillis(); CloseableHttpResponse httpResponse = httpClient .execute(httpPosts[RANDOM.nextInt(numQueries)]); httpResponse.close(); long responseTime = System.currentTimeMillis() - startTime; counter.getAndIncrement(); totalResponseTime.getAndAdd(responseTime); } } catch (IOException e) { e.printStackTrace(); } } }); } executorService.shutdown(); long startTime = System.currentTimeMillis(); while (System.currentTimeMillis() < endTime) { Thread.sleep(REPORT_INTERVAL_MILLIS); double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND; int count = counter.get(); double avgResponseTime = ((double) totalResponseTime.get()) / count; System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: " + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms"); } }
From source file:com.ibm.jaql.MiniCluster.java
/** * @param args//from ww w . j av a 2 s. co m */ public static void main(String[] args) throws IOException { String clusterHome = System.getProperty("hadoop.minicluster.dir"); if (clusterHome == null) { clusterHome = "./minicluster"; System.setProperty("hadoop.minicluster.dir", clusterHome); } LOG.info("hadoop.minicluster.dir=" + clusterHome); File clusterFile = new File(clusterHome); if (!clusterFile.exists()) { clusterFile.mkdirs(); } if (!clusterFile.isDirectory()) { throw new IOException("minicluster home directory must be a directory: " + clusterHome); } if (!clusterFile.canRead() || !clusterFile.canWrite()) { throw new IOException("minicluster home directory must be readable and writable: " + clusterHome); } String logDir = System.getProperty("hadoop.log.dir"); if (logDir == null) { logDir = clusterHome + File.separator + "logs"; System.setProperty("hadoop.log.dir", logDir); } File logFile = new File(logDir); if (!logFile.exists()) { logFile.mkdirs(); } String confDir = System.getProperty("hadoop.conf.override"); if (confDir == null) { confDir = clusterHome + File.separator + "conf"; System.setProperty("hadoop.conf.override", confDir); } File confFile = new File(confDir); if (!confFile.exists()) { confFile.mkdirs(); } System.out.println("starting minicluster in " + clusterHome); MiniCluster mc = new MiniCluster(args); // To find the ports in the // hdfs: search for: Web-server up at: localhost:#### // mapred: search for: mapred.JobTracker: JobTracker webserver: #### Configuration conf = mc.getConf(); System.out.println("fs.default.name: " + conf.get("fs.default.name")); System.out.println("dfs.http.address: " + conf.get("dfs.http.address")); System.out.println("mapred.job.tracker.http.address: " + conf.get("mapred.job.tracker.http.address")); boolean waitForInterrupt; try { System.out.println("press enter to end minicluster (or eof to run forever)..."); waitForInterrupt = System.in.read() < 0; // wait for any input or eof } catch (Exception e) { // something odd happened. Just shutdown. LOG.error("error reading from stdin", e); waitForInterrupt = false; } // eof means that we will wait for a kill signal while (waitForInterrupt) { System.out.println("minicluster is running until interrupted..."); try { Thread.sleep(60 * 60 * 1000); } catch (InterruptedException e) { waitForInterrupt = false; } } System.out.println("shutting down minicluster..."); try { mc.tearDown(); } catch (Exception e) { LOG.error("error while shutting down minicluster", e); } }
From source file:com.bachelor.boulmier.workmaster.WorkMaster.java
public static void main(String[] args) throws IOException, InterruptedException { defineOptions();/*from ww w .ja v a2s .c o m*/ CommandLineParser parser = new BasicParser(); CommandLine cmd; try { cmd = parser.parse(options, args); if (cmd.hasOption(MasterConfig.CMD.CLILONGOPT)) { cliEnabled = true; } if (cmd.hasOption(MasterConfig.CMD.DEBUGLONGOPT)) { debug = true; } if (cmd.hasOption(MasterConfig.CMD.MAXVMLONGOPT)) { maxVM = Integer.valueOf(cmd.getOptionValue(MasterConfig.CMD.MAXVMLONGOPT)); } if (cmd.hasOption(MasterConfig.CMD.VERBOSELONGOPT)) { verbose = true; } if (cmd.hasOption(MasterConfig.CMD.REMOTEWSLONGOPT)) { webServer = cmd.getOptionValue(MasterConfig.CMD.REMOTEWSLONGOPT); if (!MasterConfig.DEFAULT.IP_PORT_PATTERN.matcher(webServer).matches()) { throw new ParseException("Given IP:PORT does not match pattern"); } } if (cmd.hasOption(MasterConfig.CMD.HELPLONGOPT)) { printHelp(); } logger = LoggerFactory.getLogger(); QueuingService.get() .send(RequestBuilder.builder().withExecutableName(ExecutableName.CAT) .with(RequestProperty.CLIENT_EMAIL, "anthony.boulmier.cfpt@gmail.com") .with(RequestProperty.JOB_IDENTIFIER, UUID.randomUUID().toString()) .with(RequestProperty.ARGS, "JobExecutor.log").create()); Thread.sleep(3000); } catch (ParseException pe) { logger.error(pe.getMessage()); printHelp(); } }
From source file:org.wso2.carbon.appmgt.sampledeployer.main.ApplicationPublisher.java
public static void main(String[] args) { tomcatPort = args[0];/* ww w . ja v a2s . c om*/ appmPath = args[1]; username = args[2]; password = args[3]; tomcatPath = args[4]; lampPath = args[5]; ipAddress = args[6]; hitCount = Integer.parseInt(args[7]); System.setProperty("javax.net.ssl.trustStore", appmPath + "/repository/resources/security/wso2carbon.jks"); System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon"); System.setProperty("javax.net.ssl.trustStoreType", "JKS"); log.info("initialising properties"); log.info("Tomcat port : " + tomcatPort); log.info("APPM path : " + appmPath); log.info("Username : " + username); log.info("Password : " + password); log.info("Tomcat path : " + tomcatPath); log.info("LAMP path : " + lampPath); log.info("IP Address : " + ipAddress); log.info("Hit count : " + hitCount); trackingCodes = new ConcurrentHashMap<String, String>(); configure(); //startServers(); try { log.info("Starting Servers....."); Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } /*trackingCodes.put("/notifi","AM_995364166653157224"); trackingCodes.put("/travelBooking","AM_14359451055881852910"); trackingCodes.put("/travel","AM_10574531036724348945");*/ for (String key : trackingCodes.keySet()) { accsesWebPages(key, trackingCodes.get(key), hitCount); } }
From source file:info.sugoiapps.xoclient.XOverClient.java
/** * @param args the command line arguments *//*from ww w .j a v a 2 s . c o m*/ public static void main(String[] args) { // System.getProperty("user.dir")); gets working directory in the form: C:\Users\Munyosz\etc...\ final String SEPARATOR = " - "; XOverClient client = new XOverClient(); String ladrs = getLocalAddress(); if (client.validAddress(ladrs)) { MACHINE_IP = ladrs; } else { JOptionPane.showMessageDialog(null, "Your machine's internal IP couldn't be retreived, program will exit."); System.exit(0); } REMOTE_IP = null; if (!new File(CONFIG_FILENAME).exists()) { while (REMOTE_IP == null || REMOTE_IP.equalsIgnoreCase("")) REMOTE_IP = JOptionPane .showInputDialog("Enter the internal IP of the machine you want to connect to.\n" + "Must be in the format 192.168.xxx.xxx"); String machinename = JOptionPane.showInputDialog("Now enter a name for the machine with internal IP " + "\"" + REMOTE_IP + "\"" + "\n" + "You will be able to select this machine from a list the next time you start the program."); new ListWriter(CONFIG_FILENAME).writeList(machinename + SEPARATOR + REMOTE_IP, APPEND); } else { MachineChooser mc = new MachineChooser(CONFIG_FILENAME, SEPARATOR, client); mc.setVisible(true); mc.setAddressInfo(MACHINE_IP); while (REMOTE_IP == null) { try { Thread.sleep(1000); } catch (InterruptedException ex) { JOptionPane.showMessageDialog(null, ex.getMessage()); Logger.getLogger(XOverClient.class.getName()).log(Level.SEVERE, null, ex); } } } new XOverClientGUI(REMOTE_IP, MACHINE_IP).setVisible(true); new FileServer().execute(); }
From source file:jfutbol.com.jfutbol.GcmSender.java
public static void main(String[] args) { log.info("GCM - Sender running"); do {/*from w w w .j a v a 2 s . c o m*/ Connection conn = null; Connection conn2 = null; Statement stmt = null; Statement stmt2 = null; try { // STEP 2: Register JDBC driver Class.forName(JDBC_DRIVER); // STEP 3: Open a connection // System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); conn2 = DriverManager.getConnection(DB_URL, USER, PASS); // STEP 4: Execute a query // System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT userId FROM notifications WHERE sentByGCM=0 GROUP BY userId"; ResultSet rs = stmt.executeQuery(sql); // STEP 5: Extract data from result set while (rs.next()) { log.info("Notification found"); int userId = rs.getInt("userId"); stmt2 = conn2.createStatement(); String sql2; sql2 = "SELECT COUNT(id) notificationCounter FROM notifications WHERE status=0 AND userId=" + userId; ResultSet rs2 = stmt2.executeQuery(sql2); int notificationCounter = rs2.getInt("notificationCounter"); rs2.close(); stmt2.close(); // Retrieve by column name // Display values // System.out.print("userId: " + userId); // System.out.print(", notificationCounter: " + // notificationCounter); SendNotification(userId, notificationCounter); } // STEP 6: Clean-up environment rs.close(); stmt.close(); conn.close(); conn2.close(); } catch (SQLException se) { // Handle errors for JDBC log.error(se.getMessage()); se.printStackTrace(); } catch (Exception e) { // Handle errors for Class.forName log.error(e.getMessage()); e.printStackTrace(); } finally { // finally block used to close resources try { if (stmt != null) stmt.close(); } catch (SQLException se2) { log.error(se2.getMessage()); } // nothing we can do try { if (conn != null) conn.close(); } catch (SQLException se) { log.error(se.getMessage()); se.printStackTrace(); } // end finally try } // end try try { Thread.sleep(1000); } catch (InterruptedException e) { log.error(e.getMessage()); e.printStackTrace(); } } while (1 != 0); }
From source file:edu.indiana.d2i.sloan.internal.LaunchVMSimulator.java
/** * @param args/* w w w . j a v a 2 s. c o m*/ */ public static void main(String[] args) { LaunchVMSimulator simulator = new LaunchVMSimulator(); CommandLineParser parser = new PosixParser(); try { CommandLine line = simulator.parseCommandLine(parser, args); String wdir = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR)); String mode = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE)); String policyFilePath = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.POLICY_PATH)); if (!HypervisorCmdSimulator.resourceExist(wdir)) { logger.error(String.format("Cannot find VM working dir: %s", wdir)); System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_EXIST)); } VMMode vmmode = HypervisorCmdSimulator.getVMMode(mode); if (vmmode == null) { logger.error(String.format("Invalid requested mode: %s, can only be %s or %s", mode, VMMode.MAINTENANCE.toString(), VMMode.SECURE.toString())); System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_VM_MODE)); } if (!HypervisorCmdSimulator.resourceExist(policyFilePath)) { logger.error(String.format("Cannot find plicy file: %s", policyFilePath)); System.exit(ERROR_CODE.get(ERROR_STATE.FIREWALL_POLICY_NOT_EXIST)); } // load VM status info Properties prop = new Properties(); String filename = HypervisorCmdSimulator.cleanPath(wdir) + HypervisorCmdSimulator.VM_INFO_FILE_NAME; prop.load(new FileInputStream(new File(filename))); // can only launch VM when it is in shutdown state VMState currentState = VMState.valueOf(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE))); if (!currentState.equals(VMState.SHUTDOWN)) { logger.error(String.format("Can only launch VM when it is in %s state, current VM state is %s", VMState.SHUTDOWN.toString(), currentState.toString())); System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_SHUTDOWN)); } // launch VM try { Thread.sleep(1000); } catch (InterruptedException e) { logger.error(e.getMessage()); } // update VM state file // set following properties prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.POLICY_PATH), policyFilePath); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE), vmmode.toString()); // set VM state to running prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE), VMState.RUNNING.toString()); // save VM state file back prop.store(new FileOutputStream(new File(filename)), ""); // success System.exit(0); } catch (ParseException e) { logger.error(String.format("Cannot parse input arguments: %s%n, expected:%n%s", StringUtils.join(args, " "), simulator.getUsage(100, "", 5, 5, ""))); System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_INPUT_ARGS)); } catch (FileNotFoundException e) { logger.error(String.format("Cannot find vm state file: %s", e.getMessage())); System.exit(ERROR_CODE.get(ERROR_STATE.VM_STATE_FILE_NOT_FOUND)); } catch (IOException e) { logger.error(e.getMessage(), e); System.exit(ERROR_CODE.get(ERROR_STATE.IO_ERR)); } }
From source file:io.fluo.cluster.WorkerApp.java
public static void main(String[] args) throws ConfigurationException, Exception { AppOptions options = new AppOptions(); JCommander jcommand = new JCommander(options, args); if (options.displayHelp()) { jcommand.usage();//from w w w.jav a 2s . c o m System.exit(-1); } Logging.init("worker", options.getFluoHome() + "/conf", "STDOUT"); File configFile = new File(options.getFluoHome() + "/conf/fluo.properties"); FluoConfiguration config = new FluoConfiguration(configFile); if (!config.hasRequiredWorkerProps()) { log.error("fluo.properties is missing required properties for worker"); System.exit(-1); } Environment env = new Environment(config); YarnConfiguration yarnConfig = new YarnConfiguration(); yarnConfig.addResource(new Path(options.getHadoopPrefix() + "/etc/hadoop/core-site.xml")); yarnConfig.addResource(new Path(options.getHadoopPrefix() + "/etc/hadoop/yarn-site.xml")); TwillRunnerService twillRunner = new YarnTwillRunnerService(yarnConfig, env.getZookeepers()); twillRunner.startAndWait(); TwillPreparer preparer = twillRunner.prepare(new WorkerApp(options, config)); // Add any observer jars found in lib observers File observerDir = new File(options.getFluoHome() + "/lib/observers"); for (File f : observerDir.listFiles()) { String jarPath = "file:" + f.getCanonicalPath(); log.debug("Adding observer jar " + jarPath + " to YARN app"); preparer.withResources(new URI(jarPath)); } TwillController controller = preparer.start(); controller.start(); while (controller.isRunning() == false) { Thread.sleep(2000); } env.close(); System.exit(0); }
From source file:com.interacciones.mxcashmarketdata.driver.client.DriverClient.java
public static void main(String[] args) throws Throwable { init(args);/* w w w.ja v a 2 s . c om*/ NioSocketConnector connector = new NioSocketConnector(); // Configure the service. connector.setConnectTimeoutMillis(CONNECT_TIMEOUT); if (USE_CUSTOM_CODEC) { connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new SumUpProtocolCodecFactory(false))); } else { connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); } int[] values = new int[] {}; connector.getFilterChain().addLast("logger", new LoggingFilter()); connector.setHandler(new ClientSessionHandler(values)); long time = System.currentTimeMillis(); IoSession session; for (;;) { try { System.out.println(host + " " + port + " " + fileTest); ConnectFuture future = connector.connect(new InetSocketAddress(host, port)); future.awaitUninterruptibly(); session = future.getSession(); File file = new File(fileTest); FileInputStream is = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); int data = br.read(); int count = 0; IoBuffer ib = IoBuffer.allocate(274); ib.setAutoExpand(true); boolean flagcount = false; while (data != -1) { data = br.read(); ib.put((byte) data); if (flagcount) { count++; } if (data == 13) { count = 1; flagcount = true; LOGGER.debug(ib.toString()); } if (count == 4) { ib.flip(); session.write(ib); ib = IoBuffer.allocate(274); ib.setAutoExpand(true); flagcount = false; count = 0; //Thread.sleep(500); } } break; } catch (RuntimeIoException e) { LOGGER.error("Failed to connect."); e.printStackTrace(); Thread.sleep(5000); } } time = System.currentTimeMillis() - time; LOGGER.info("Time " + time); // wait until the summation is done session.getCloseFuture().awaitUninterruptibly(); connector.dispose(); }