List of usage examples for java.util List iterator
Iterator<E> iterator();
From source file:edu.umd.cloud9.example.bigram.AnalyzeBigramCount.java
@SuppressWarnings({ "static-access" }) public static void main(String[] args) { Options options = new Options(); options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT)); CommandLine cmdline = null;/*w w w . j a v a2 s. c o m*/ CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(INPUT)) { System.out.println("args: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(AnalyzeBigramCount.class.getName(), options); ToolRunner.printGenericCommandUsage(System.out); System.exit(-1); } String inputPath = cmdline.getOptionValue(INPUT); System.out.println("input path: " + inputPath); List<PairOfWritables<Text, IntWritable>> bigrams = SequenceFileUtils.readDirectory(new Path(inputPath)); Collections.sort(bigrams, new Comparator<PairOfWritables<Text, IntWritable>>() { public int compare(PairOfWritables<Text, IntWritable> e1, PairOfWritables<Text, IntWritable> e2) { if (e2.getRightElement().compareTo(e1.getRightElement()) == 0) { return e1.getLeftElement().compareTo(e2.getLeftElement()); } return e2.getRightElement().compareTo(e1.getRightElement()); } }); int singletons = 0; int sum = 0; for (PairOfWritables<Text, IntWritable> bigram : bigrams) { sum += bigram.getRightElement().get(); if (bigram.getRightElement().get() == 1) { singletons++; } } System.out.println("total number of unique bigrams: " + bigrams.size()); System.out.println("total number of bigrams: " + sum); System.out.println("number of bigrams that appear only once: " + singletons); System.out.println("\nten most frequent bigrams: "); Iterator<PairOfWritables<Text, IntWritable>> iter = Iterators.limit(bigrams.iterator(), 10); while (iter.hasNext()) { PairOfWritables<Text, IntWritable> bigram = iter.next(); System.out.println(bigram.getLeftElement() + "\t" + bigram.getRightElement()); } }
From source file:com.zimbra.cs.lmtpserver.utils.LmtpInject.java
public static void main(String[] args) { CliUtil.toolSetup();/*from w w w .j a va 2 s. c om*/ CommandLine cl = parseArgs(args); if (cl.hasOption("h")) { usage(null); } boolean quietMode = cl.hasOption("q"); int threads = 1; if (cl.hasOption("t")) { threads = Integer.valueOf(cl.getOptionValue("t")).intValue(); } String host = null; if (cl.hasOption("a")) { host = cl.getOptionValue("a"); } else { host = "localhost"; } int port; Protocol proto = null; if (cl.hasOption("smtp")) { proto = Protocol.SMTP; port = 25; } else port = 7025; if (cl.hasOption("p")) port = Integer.valueOf(cl.getOptionValue("p")).intValue(); String[] recipients = cl.getOptionValues("r"); String sender = cl.getOptionValue("s"); boolean tracingEnabled = cl.hasOption("T"); int everyN; if (cl.hasOption("N")) { everyN = Integer.valueOf(cl.getOptionValue("N")).intValue(); } else { everyN = 100; } // Process files from the -d option. List<File> files = new ArrayList<File>(); if (cl.hasOption("d")) { File dir = new File(cl.getOptionValue("d")); if (!dir.isDirectory()) { System.err.format("%s is not a directory.\n", dir.getPath()); System.exit(1); } File[] fileArray = dir.listFiles(); if (fileArray == null || fileArray.length == 0) { System.err.format("No files found in directory %s.\n", dir.getPath()); } Collections.addAll(files, fileArray); } // Process files specified as arguments. for (String arg : cl.getArgs()) { files.add(new File(arg)); } // Validate file content. if (!cl.hasOption("noValidation")) { Iterator<File> i = files.iterator(); while (i.hasNext()) { InputStream in = null; File file = i.next(); boolean valid = false; try { in = new FileInputStream(file); if (FileUtil.isGzipped(file)) { in = new GZIPInputStream(in); } in = new BufferedInputStream(in); // Required for RFC 822 check if (!EmailUtil.isRfc822Message(in)) { System.err.format("%s does not contain a valid RFC 822 message.\n", file.getPath()); } else { valid = true; } } catch (IOException e) { System.err.format("Unable to validate %s: %s.\n", file.getPath(), e.toString()); } finally { ByteUtil.closeStream(in); } if (!valid) { i.remove(); } } } if (files.size() == 0) { System.err.println("No files to inject."); System.exit(1); } if (!quietMode) { System.out.format( "Injecting %d message(s) to %d recipient(s). Server %s, port %d, using %d thread(s).\n", files.size(), recipients.length, host, port, threads); } int totalFailed = 0; int totalSucceeded = 0; long startTime = System.currentTimeMillis(); boolean verbose = cl.hasOption("v"); boolean skipTLSCertValidation = cl.hasOption("skipTLSCertValidation"); LmtpInject injector = null; try { injector = new LmtpInject(threads, sender, recipients, files, host, port, proto, quietMode, tracingEnabled, verbose, skipTLSCertValidation); } catch (Exception e) { mLog.error("Unable to initialize LmtpInject", e); System.exit(1); } injector.setReportEvery(everyN); injector.markStartTime(); try { injector.run(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } int succeeded = injector.getSuccessCount(); int failedThisTime = injector.getFailureCount(); long elapsedMS = System.currentTimeMillis() - startTime; double elapsed = elapsedMS / 1000.0; double msPerMsg = 0.0; double msgSizeKB = 0.0; if (succeeded > 0) { msPerMsg = elapsedMS; msPerMsg /= succeeded; msgSizeKB = injector.mFileSizeTotal / 1024.0; msgSizeKB /= succeeded; } double msgPerSec = ((double) succeeded / (double) elapsedMS) * 1000; if (!quietMode) { System.out.println(); System.out.printf( "LmtpInject Finished\n" + "submitted=%d failed=%d\n" + "%.2fs, %.2fms/msg, %.2fmsg/s\n" + "average message size = %.2fKB\n", succeeded, failedThisTime, elapsed, msPerMsg, msgPerSec, msgSizeKB); } totalFailed += failedThisTime; totalSucceeded += succeeded; if (totalFailed != 0) System.exit(1); }
From source file:de.codesourcery.geoip.Main.java
public static void main(String[] args) throws Exception { final IGeoLocator<StringSubject> locator = createGeoLocator(); final JFrame frame = new JFrame("GeoIP"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { try { locator.dispose();/*from w w w . j a v a2s. c o m*/ } catch (Exception e1) { e1.printStackTrace(); } }; }); final MapImage image = MapImage.getRobinsonWorldMap(); // MapImage.getMillerWorldMap(); final MapCanvas canvas = new MapCanvas(image); for (GeoLocation<StringSubject> loc : locator.locate(getSpammers())) { if (loc.hasValidCoordinates()) { canvas.addCoordinate(PointRenderer.createPoint(loc, Color.YELLOW)); } } // canvas.addCoordinate( PointRenderer.createPoint( ZERO , Color.YELLOW ) ); // canvas.addCoordinate( PointRenderer.createPoint( WELLINGTON , Color.RED ) ); // canvas.addCoordinate( PointRenderer.createPoint( MELBOURNE , Color.RED ) ); // canvas.addCoordinate( PointRenderer.createPoint( HAMBURG , Color.RED ) ); final double heightToWidth = image.height() / (double) image.width(); // preserve aspect ratio of map canvas.setPreferredSize(new Dimension(640, (int) Math.round(640 * heightToWidth))); JPanel panel = new JPanel(); panel.setLayout(new FlowLayout()); panel.add(new JLabel("Scale-X")); final JTextField scaleX = new JTextField(Double.toString(image.getScaleX())); scaleX.setColumns(5); final JTextField scaleY = new JTextField(Double.toString(image.getScaleY())); scaleY.setColumns(5); final ActionListener listener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { double x = Double.parseDouble(scaleX.getText()); double y = Double.parseDouble(scaleY.getText()); image.setScale(x, y); canvas.repaint(); } }; scaleX.addActionListener(listener); scaleY.addActionListener(listener); panel.add(new JLabel("Scale-X")); panel.add(scaleX); panel.add(new JLabel("Scale-Y")); panel.add(scaleY); final JTextField ipAddress = new JTextField("www.kickstarter.com"); ipAddress.setColumns(20); final ActionListener ipListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final String destinationIP = ipAddress.getText(); if (StringUtils.isBlank(destinationIP)) { return; } /* * Perform traceroute. */ final List<String> hops; try { if (TracePath.isPathTracingAvailable()) { hops = TracePath.trace(destinationIP); } else { System.err.println("tracepath not available."); if (TracePath.isValidAddress(destinationIP)) { hops = new ArrayList<>(); hops.add(destinationIP); } else { System.err.println(destinationIP + " is no valid IP"); return; } } } catch (Exception ex) { System.err.println("Failed to trace " + destinationIP); ex.printStackTrace(); return; } System.out.println("Trace contains " + hops.size() + " IPs"); /* * Gather locations. */ final List<StringSubject> subjects = new ArrayList<>(); for (String ip : hops) { subjects.add(new StringSubject(ip)); } final List<GeoLocation<StringSubject>> locations; try { long time = -System.currentTimeMillis(); locations = locator.locate(subjects); time += System.currentTimeMillis(); System.out.println("Locating hops for " + destinationIP + " returned " + locations.size() + " valid locations ( time: " + time + " ms)"); System.out.flush(); } catch (Exception e2) { e2.printStackTrace(); return; } /* * Weed-out invalid/unknown locations. */ { GeoLocation<StringSubject> previous = null; for (Iterator<GeoLocation<StringSubject>> it = locations.iterator(); it.hasNext();) { final GeoLocation<StringSubject> location = it.next(); if (!location.hasValidCoordinates() || (previous != null && previous.coordinate().equals(location.coordinate()))) { it.remove(); System.err.println("Ignoring invalid/duplicate location for " + location); } else { previous = location; } } } /* * Populate chart. */ System.out.println("Adding " + locations.size() + " hops to chart"); System.out.flush(); canvas.removeAllCoordinates(); if (locations.size() == 1) { canvas.addCoordinate( PointRenderer.createPoint(locations.get(0), getLabel(locations.get(0)), Color.BLACK)); } else if (locations.size() > 1) { GeoLocation<StringSubject> previous = locations.get(0); MapPoint previousPoint = PointRenderer.createPoint(previous, getLabel(previous), Color.BLACK); final int len = locations.size(); for (int i = 1; i < len; i++) { final GeoLocation<StringSubject> current = locations.get(i); // final MapPoint currentPoint = PointRenderer.createPoint( current , getLabel( current ) , Color.BLACK ); final MapPoint currentPoint = PointRenderer.createPoint(current, Color.BLACK); // canvas.addCoordinate( LineRenderer.createLine( previousPoint , currentPoint , Color.RED ) ); canvas.addCoordinate(CurvedLineRenderer.createLine(previousPoint, currentPoint, Color.RED)); previous = locations.get(i); previousPoint = currentPoint; } } System.out.println("Finished adding"); System.out.flush(); canvas.repaint(); } }; ipAddress.addActionListener(ipListener); panel.add(new JLabel("IP")); panel.add(ipAddress); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(panel, BorderLayout.NORTH); frame.getContentPane().add(canvas, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); }
From source file:com.zimbra.cs.util.ProxyPurgeUtil.java
public static void main(String[] args) throws ServiceException { CommandLine commandLine;/*from w w w .jav a 2s . com*/ ArrayList<String> servers; ArrayList<String> accounts; String outputformat; boolean purge = false; Provisioning prov; List<Server> memcachedServers; String logLevel = "ERROR"; /* Parse the command-line arguments, and display usage if necessary */ try { commandLine = parseCommandLine(args); } catch (ParseException pe) { commandLine = null; } if ((commandLine == null) || commandLine.hasOption("h") || commandLine.hasOption("u")) { usage(); System.exit(1); } if (commandLine.hasOption("v")) { logLevel = "DEBUG"; } ZimbraLog.toolSetupLog4j(logLevel, null, false); /* Initialize the logging system and the zimbra environment */ prov = Provisioning.getInstance(); /* Get the list of servers running the memcached service this is equivalent to the $(zmprov gamcs) command */ memcachedServers = prov.getAllServers(Provisioning.SERVICE_MEMCACHED); servers = new ArrayList<String>(); for (Iterator<Server> it = memcachedServers.iterator(); it.hasNext();) { Server s = it.next(); String serverName = s.getAttr(Provisioning.A_zimbraServiceHostname, "localhost"); String servicePort = s.getAttr(Provisioning.A_zimbraMemcachedBindPort, memcachedPort); servers.add(serverName + ":" + servicePort); } accounts = getAccounts(commandLine); servers.addAll(getCacheServers(commandLine)); if (servers.size() == 0) { System.err.println("No memcached servers found, and none specified (--help for help)"); System.exit(1); } if (accounts.size() == 0) { System.err.println("No accounts specified (--help for help)"); System.exit(1); } /* Assume purge unless `-i' is specified */ /* -i (info) indicates that account route info should be printed -p (purge) indicates that account route info should be purged */ purge = (commandLine.hasOption("i") == false); /* parse the format string */ if (commandLine.hasOption("o")) { outputformat = commandLine.getOptionValue("o"); } else { outputformat = "[%1$s] %2$s -- %3$s"; } purgeAccounts(servers, accounts, purge, outputformat); }
From source file:com.g2inc.scap.library.domain.SCAPContentManager.java
/** * A main method only used for testing/*from www . j av a 2 s . co m*/ * * @param args Command-line arguments * */ public static void main(String[] args) throws Exception { BasicConfigurator.configure(); LOG.trace("SchemaParser starting, schemaVersion =" + args[0] + ", xsd File=" + args[1]); File xsdFile = new File(args[1]); if (!xsdFile.exists()) { LOG.error("Usage: java SchemaParser <name of xsd file>"); } SCAPDocumentTypeEnum version = SCAPDocumentTypeEnum.valueOf(args[0]); SCAPContentManager mgr = SCAPContentManager.getInstance(new File(args[1])); // schema-related data should now be populated List<String> platformTypes = mgr.getValidPlatforms(version); LOG.trace("STARTING PLATFORMS"); for (int i = 0; i < platformTypes.size(); i++) { LOG.trace(platformTypes.get(i)); } String[] platforms = { "windows", "independent" }; List<NameDoc> list = null; Iterator<NameDoc> iter = null; LOG.trace("STARTING TESTS"); list = mgr.getValidTestTypes(version, platforms); iter = list.iterator(); while (iter.hasNext()) { NameDoc testName = iter.next(); LOG.trace("\t" + testName); } LOG.trace("STARTING OBJECTS"); list = mgr.getValidObjectTypes(version, platforms); iter = list.iterator(); while (iter.hasNext()) { NameDoc objName = iter.next(); LOG.trace("\t" + objName); LOG.trace("STARTING OBJECT ENTITIES FOR " + objName.getName()); List<OvalEntity> entityList = mgr.getValidObjectEntityTypes(version, "windows", objName.getName()); if (entityList != null && entityList.size() > 0) { for (int i = 0; i < entityList.size(); i++) { LOG.trace("\t\t" + entityList.get(i).toString()); } } } LOG.trace("STARTING STATES"); list = mgr.getValidStateTypes(version, platforms); iter = list.iterator(); while (iter.hasNext()) { NameDoc stateName = iter.next(); LOG.trace("\t" + stateName); LOG.trace("STARTING STATE ENTITIES FOR " + stateName.getName()); List<OvalEntity> entityList = mgr.getValidStateEntityTypes(version, "windows", stateName.getName()); if (entityList != null && entityList.size() > 0) { for (int i = 0; i < entityList.size(); i++) { LOG.trace("\t\t" + entityList.get(i).toString()); } } } }
From source file:com.cyclopsgroup.waterview.jelly.JellyRunner.java
/** * Main entry to run a script/*from w w w. j a v a2 s . co m*/ * * @param args Script paths * @throws Exception Throw it out */ public static final void main(String[] args) throws Exception { List scripts = new ArrayList(); for (int i = 0; i < args.length; i++) { String path = args[i]; File file = new File(path); if (file.isFile()) { scripts.add(file.toURL()); } else { Enumeration enu = JellyRunner.class.getClassLoader().getResources(path); CollectionUtils.addAll(scripts, enu); } } if (scripts.isEmpty()) { System.out.println("No script to run, return!"); return; } String basedir = new File("").getAbsolutePath(); Properties initProperties = new Properties(System.getProperties()); initProperties.setProperty("basedir", basedir); initProperties.setProperty("plexus.home", basedir); WaterviewPlexusContainer container = new WaterviewPlexusContainer(); for (Iterator j = initProperties.keySet().iterator(); j.hasNext();) { String initPropertyName = (String) j.next(); container.addContextValue(initPropertyName, initProperties.get(initPropertyName)); } container.addContextValue(Waterview.INIT_PROPERTIES, initProperties); container.initialize(); container.start(); JellyEngine je = (JellyEngine) container.lookup(JellyEngine.ROLE); JellyContext jc = new JellyContext(je.getGlobalContext()); for (Iterator i = scripts.iterator(); i.hasNext();) { URL script = (URL) i.next(); System.out.print("Running script " + script); jc.runScript(script, XMLOutput.createDummyXMLOutput()); System.out.println("... Done!"); } container.dispose(); }
From source file:com.cyclopsgroup.waterview.jelly.JellyScriptsRunner.java
/** * Main entry to run a script/*from w w w . j av a 2s. c o m*/ * * @param args Script paths * @throws Exception Throw it out */ public static final void main(String[] args) throws Exception { List scripts = new ArrayList(); for (int i = 0; i < args.length; i++) { String path = args[i]; File file = new File(path); if (file.isFile()) { scripts.add(file.toURL()); } else { Enumeration enu = JellyScriptsRunner.class.getClassLoader().getResources(path); CollectionUtils.addAll(scripts, enu); } } if (scripts.isEmpty()) { System.out.println("No script to run, return!"); return; } String basedir = new File("").getAbsolutePath(); Properties initProperties = new Properties(System.getProperties()); initProperties.setProperty("basedir", basedir); initProperties.setProperty("plexus.home", basedir); WaterviewPlexusContainer container = new WaterviewPlexusContainer(); for (Iterator j = initProperties.keySet().iterator(); j.hasNext();) { String initPropertyName = (String) j.next(); container.addContextValue(initPropertyName, initProperties.get(initPropertyName)); } container.addContextValue(Waterview.INIT_PROPERTIES, initProperties); container.initialize(); container.start(); JellyEngine je = (JellyEngine) container.lookup(JellyEngine.ROLE); JellyContext jc = new JellyContext(je.getGlobalContext()); XMLOutput output = XMLOutput.createXMLOutput(System.out); for (Iterator i = scripts.iterator(); i.hasNext();) { URL script = (URL) i.next(); System.out.print("Running script " + script); ExtendedProperties ep = new ExtendedProperties(); ep.putAll(initProperties); ep.load(script.openStream()); for (Iterator j = ep.getKeys("script"); j.hasNext();) { String name = (String) j.next(); if (name.endsWith(".file")) { File file = new File(ep.getString(name)); if (file.exists()) { System.out.println("Runner jelly file " + file); jc.runScript(file, output); } } else if (name.endsWith(".resource")) { Enumeration k = JellyScriptsRunner.class.getClassLoader().getResources(ep.getString(name)); while (j != null && k.hasMoreElements()) { URL s = (URL) k.nextElement(); System.out.println("Running jelly script " + s); jc.runScript(s, output); } } } //jc.runScript( script, XMLOutput.createDummyXMLOutput() ); System.out.println("... Done!"); } container.dispose(); }
From source file:edu.umd.cloud9.example.bigram.AnalyzeBigramRelativeFrequencyJson.java
@SuppressWarnings({ "static-access" }) public static void main(String[] args) { Options options = new Options(); options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT)); CommandLine cmdline = null;/* w w w .jav a2 s . c o m*/ CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(INPUT)) { System.out.println("args: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(AnalyzeBigramRelativeFrequencyJson.class.getName(), options); ToolRunner.printGenericCommandUsage(System.out); System.exit(-1); } String inputPath = cmdline.getOptionValue(INPUT); System.out.println("input path: " + inputPath); List<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> pairs = SequenceFileUtils .readDirectory(new Path(inputPath)); List<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> list1 = Lists.newArrayList(); List<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> list2 = Lists.newArrayList(); for (PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> p : pairs) { BigramRelativeFrequencyJson.MyTuple bigram = p.getLeftElement(); if (bigram.getJsonObject().get("Left").getAsString().equals("light")) { list1.add(p); } if (bigram.getJsonObject().get("Left").getAsString().equals("contain")) { list2.add(p); } } Collections.sort(list1, new Comparator<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>>() { public int compare(PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> e1, PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> e2) { if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) { return e1.getLeftElement().compareTo(e2.getLeftElement()); } return e2.getRightElement().compareTo(e1.getRightElement()); } }); Iterator<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> iter1 = Iterators .limit(list1.iterator(), 10); while (iter1.hasNext()) { PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> p = iter1.next(); BigramRelativeFrequencyJson.MyTuple bigram = p.getLeftElement(); System.out.println(bigram + "\t" + p.getRightElement()); } Collections.sort(list2, new Comparator<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>>() { public int compare(PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> e1, PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> e2) { if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) { return e1.getLeftElement().compareTo(e2.getLeftElement()); } return e2.getRightElement().compareTo(e1.getRightElement()); } }); Iterator<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> iter2 = Iterators .limit(list2.iterator(), 10); while (iter2.hasNext()) { PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> p = iter2.next(); BigramRelativeFrequencyJson.MyTuple bigram = p.getLeftElement(); System.out.println(bigram + "\t" + p.getRightElement()); } }
From source file:com.cloud.test.stress.StressTestDirectAttach.java
public static void main(String[] args) { String host = "http://localhost"; String port = "8092"; String devPort = "8080"; String apiUrl = "/client/api"; try {// ww w . ja v a 2 s .co m // 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("-dp")) { devPort = iter.next(); } if (arg.equals("-t")) { numThreads = Integer.parseInt(iter.next()); } if (arg.equals("-s")) { sleepTime = Long.parseLong(iter.next()); } if (arg.equals("-a")) { accountName = 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("-i")) { internet = Boolean.parseBoolean(iter.next()); } if (arg.equals("-w")) { wait = Integer.parseInt(iter.next()); } if (arg.equals("-z")) { zoneId = iter.next(); } if (arg.equals("-so")) { serviceOfferingId = iter.next(); } } final String server = host + ":" + port + "/"; final String developerServer = host + ":" + devPort + apiUrl; 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"); for (int i = 0; i < numThreads; i++) { new Thread(new Runnable() { @Override public void run() { do { String username = null; try { long now = System.currentTimeMillis(); Random ran = new Random(); username = Math.abs(ran.nextInt()) + "-user"; NDC.push(username); s_logger.info("Starting test for the user " + username); int response = executeDeployment(server, developerServer, username); boolean success = false; String reason = null; if (response == 200) { success = true; if (internet) { s_logger.info("Deploy successful...waiting 5 minute before SSH tests"); Thread.sleep(300000L); // Wait 60 // seconds so // the windows VM // can boot up and do a sys prep. s_logger.info("Begin Linux SSH test for account " + _account.get()); reason = sshTest(_linuxIP.get(), _linuxPassword.get()); if (reason == null) { s_logger.info( "Linux SSH test successful for account " + _account.get()); } } if (reason == null) { if (internet) { s_logger.info( "Windows SSH test successful for account " + _account.get()); } 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 (usageIterator >= numThreads) { int eventsAndBillingResponseCode = executeEventsAndBilling(server, developerServer); s_logger.info( "events and usage records command finished with response code: " + eventsAndBillingResponseCode); usageIterator = 1; } else { s_logger.info( "Skipping events and usage records for this user: usageIterator " + usageIterator + " and number of Threads " + numThreads); usageIterator++; } if ((users == null) && (accountName == null)) { s_logger.info("Sending cleanup command"); int cleanupResponseCode = executeCleanup(server, developerServer, username); s_logger.info("cleanup command finished with response code: " + cleanupResponseCode); success = (cleanupResponseCode == 200); } else { s_logger.info("Sending stop DomR / destroy VM command"); int stopResponseCode = executeStop(server, developerServer, username); s_logger.info("stop(destroy) command finished with response code: " + stopResponseCode); success = (stopResponseCode == 200); } } else { // Just stop but don't destroy the // VMs/Routers s_logger.info("SSH test failed for account " + _account.get() + "with reason '" + reason + "', stopping VMs"); int stopResponseCode = executeStop(server, developerServer, username); s_logger.info( "stop command finished with response code: " + stopResponseCode); success = false; // since the SSH test // failed, mark the // whole test as // failure } } else { // Just stop but don't destroy the // VMs/Routers s_logger.info("Deploy test failed with reason '" + reason + "', stopping VMs"); int stopResponseCode = executeStop(server, developerServer, username); s_logger.info("stop command finished with response code: " + stopResponseCode); success = false; // since the deploy test // failed, mark the // whole test as failure } 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); } s_logger.info("Sleeping for " + wait + " seconds before starting next iteration"); Thread.sleep(wait); } catch (Exception e) { s_logger.warn("Error in thread", e); try { int stopResponseCode = executeStop(server, developerServer, username); s_logger.info("stop response code: " + stopResponseCode); } catch (Exception e1) { } } finally { NDC.clear(); } } while (repeat); } }).start(); } } catch (Exception e) { s_logger.error(e); } }
From source file:com.cyberway.issue.crawler.extractor.ExtractorTool.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(new Option("h", "help", false, "Prints this message and exits.")); StringBuffer defaultExtractors = new StringBuffer(); for (int i = 0; i < DEFAULT_EXTRACTORS.length; i++) { if (i > 0) { defaultExtractors.append(", "); }/* w ww.j ava 2s . co m*/ defaultExtractors.append(DEFAULT_EXTRACTORS[i]); } options.addOption(new Option("e", "extractor", true, "List of comma-separated extractor class names. " + "Run in order listed. " + "If no extractors listed, runs following: " + defaultExtractors.toString() + ".")); options.addOption( new Option("s", "scratch", true, "Directory to write scratch files to. Default: '/tmp'.")); PosixParser parser = new PosixParser(); CommandLine cmdline = parser.parse(options, args, false); List cmdlineArgs = cmdline.getArgList(); Option[] cmdlineOptions = cmdline.getOptions(); HelpFormatter formatter = new HelpFormatter(); // If no args, print help. if (cmdlineArgs.size() <= 0) { usage(formatter, options, 0); } // Now look at options passed. String[] extractors = DEFAULT_EXTRACTORS; String scratch = null; for (int i = 0; i < cmdlineOptions.length; i++) { switch (cmdlineOptions[i].getId()) { case 'h': usage(formatter, options, 0); break; case 'e': String value = cmdlineOptions[i].getValue(); if (value == null || value.length() <= 0) { // Allow saying NO extractors so we can see // how much it costs just reading through // ARCs. extractors = new String[0]; } else { extractors = value.split(","); } break; case 's': scratch = cmdlineOptions[i].getValue(); break; default: throw new RuntimeException("Unexpected option: " + +cmdlineOptions[i].getId()); } } ExtractorTool tool = new ExtractorTool(extractors, scratch); for (Iterator i = cmdlineArgs.iterator(); i.hasNext();) { tool.extract((String) i.next()); } }