Example usage for java.util Iterator hasNext

List of usage examples for java.util Iterator hasNext

Introduction

In this page you can find the example usage for java.util Iterator hasNext.

Prototype

boolean hasNext();

Source Link

Document

Returns true if the iteration has more elements.

Usage

From source file:gsn.utils.VSMonitor.java

public static void main(String[] args) {

    String configFileName;//  w  w  w . j  a va 2 s .  co m

    if (args.length >= 2) {
        configFileName = args[0];
        System.out.println("Using config file: " + configFileName);
        for (int i = 1; i < args.length; i++) {
            System.out.println("Adding e-mail: " + args[i]);
            listOfMails.add(args[i]);
        }
    } else {
        System.out.println("Usage java -jar VSMonitor.jar <config_file> <list_of_mails>");
        System.out.println("e.g.  java -jar VSMonitor.jar conf/monitoring.cfg user@gmail.com admin@gmail.com");
        return;
    }

    initFromFile(configFileName);

    // for each monitored GSN server
    Iterator iter = listOfGSNSessions.iterator();
    while (iter.hasNext()) {

        try {
            readStatus((GSNSessionAddress) iter.next());
        } catch (Exception e) {
            logger.error("Exception: " + e.getMessage());
            logger.error("StackTrace:\n" + getStackTrace(e));
        }
    }

    checkUpdateTimes();

    // Generate Report
    report.append("\n[ERROR]\n" + errorsBuffer).append("\n[WARNING]\n" + warningsBuffer)
            .append("\n[INFO]\n" + infosBuffer);

    if ((nSensorsLate > 0) || (nHostsDown > 0)) {
        summary.append("WARNING: ");
        if (nHostsDown > 0)
            summary.append(nHostsDown + " host(s) down. ");
        if (nSensorsLate > 0)
            summary.append(nSensorsLate + " sensor(s) not updated. ");

        // Send e-mail only if there are errors
        try {
            sendMail();
        } catch (EmailException e) {
            logger.error("Cannot send e-mail. " + e.getMessage());
            logger.error("StackTrace:\n" + getStackTrace(e));
        }
    }

    // Showing report
    System.out.println(summary);
    System.out.println(report);
}

From source file:org.openiot.gsn.utils.GSNMonitor.java

public static void main(String[] args) {

    PropertyConfigurator.configure(DEFAULT_GSN_LOG4J_PROPERTIES);
    String configFileName;/*from w ww . j a  v a2 s .com*/

    if (args.length >= 2) {
        configFileName = args[0];
        System.out.println("Using config file: " + configFileName);
        for (int i = 1; i < args.length; i++) {
            System.out.println("Adding e-mail: " + args[i]);
            listOfMails.add(args[i]);
        }
    } else {
        System.out.println("Usage java -jar VSMonitor.jar <config_file> <list_of_mails>");
        System.out.println("e.g.  java -jar VSMonitor.jar conf/monitoring.cfg user@gmail.com admin@gmail.com");
        return;
    }

    initFromFile(configFileName);

    // for each monitored GSN server
    Iterator iter = listOfGSNSessions.iterator();
    while (iter.hasNext()) {

        try {
            readStatus((GSNSessionAddress) iter.next());
        } catch (Exception e) {
            logger.error("Exception: " + e.getMessage());
            logger.error("StackTrace:\n" + getStackTrace(e));
        }
    }

    checkUpdateTimes();

    // Generate Report
    report.append("\n[ERROR]\n" + errorsBuffer).append("\n[WARNING]\n" + warningsBuffer)
            .append("\n[INFO]\n" + infosBuffer);

    if ((nSensorsLate > 0) || (nHostsDown > 0)) {
        summary.append("WARNING: ");
        if (nHostsDown > 0)
            summary.append(nHostsDown + " host(s) down. ");
        if (nSensorsLate > 0)
            summary.append(nSensorsLate + " sensor(s) not updated. ");

        // Send e-mail only if there are errors
        try {
            sendMail();
        } catch (EmailException e) {
            logger.error("Cannot send e-mail. " + e.getMessage());
            logger.error("StackTrace:\n" + getStackTrace(e));
        }
    }

    // Showing report
    System.out.println(summary);
    System.out.println(report);

    System.exit(status);
}

From source file:akori.AKORI.java

public static void main(String[] args) throws IOException, InterruptedException {
    System.out.println("esto es AKORI");

    URL = "http://www.mbauchile.cl";
    PATH = "E:\\NetBeansProjects\\AKORI\\";
    NAME = "mbauchile.png";
    // Extrar DOM tree

    Document doc = Jsoup.connect(URL).timeout(0).get();

    // The Firefox driver supports javascript 
    WebDriver driver = new FirefoxDriver();
    driver.manage().window().maximize();
    System.out.println(driver.manage().window().getSize().toString());
    System.out.println(driver.manage().window().getPosition().toString());
    int xmax = driver.manage().window().getSize().width;
    int ymax = driver.manage().window().getSize().height;

    // Go to the URL page
    driver.get(URL);/*from  w  w  w.  jav  a  2 s  . c  om*/

    File screen = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(screen, new File(PATH + NAME));

    BufferedImage img = ImageIO.read(new File(PATH + NAME));
    //Graphics2D graph = img.createGraphics();

    BufferedImage img1 = new BufferedImage(xmax, ymax, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graph1 = img.createGraphics();
    double[][] matrix = new double[ymax][xmax];
    BufferedReader in = new BufferedReader(new FileReader("et.txt"));
    String linea;
    double max = 0;
    graph1.drawImage(img, 0, 0, null);
    HashMap<String, Integer> lista = new HashMap<String, Integer>();
    int count = 0;
    for (int i = 0; (linea = in.readLine()) != null && i < 10000; ++i) {
        String[] datos = linea.split(",");
        int x = (int) Double.parseDouble(datos[0]);
        int y = (int) Double.parseDouble(datos[2]);
        long time = Double.valueOf(datos[4]).longValue();
        if (x >= xmax || y >= ymax)
            continue;
        if (time < 691215)
            continue;
        if (time > 705648)
            break;
        if (lista.containsKey(x + "," + y))
            lista.put(x + "," + y, lista.get(x + "," + y) + 1);
        else
            lista.put(x + "," + y, 1);
        ++count;
    }
    System.out.println(count);
    in.close();
    Iterator iter = lista.entrySet().iterator();
    Map.Entry e;
    for (String key : lista.keySet()) {
        Integer i = lista.get(key);
        if (max < i)
            max = i;
    }
    System.out.println(max);
    max = 0;
    while (iter.hasNext()) {
        e = (Map.Entry) iter.next();
        String xy = (String) e.getKey();
        String[] datos = xy.split(",");
        int x = Integer.parseInt(datos[0]);
        int y = Integer.parseInt(datos[1]);
        matrix[y][x] += (int) e.getValue();
        double aux;
        if ((aux = normalMatrix(matrix, y, x, ((int) e.getValue()) * 4)) > max) {
            max = aux;
        }
        //normalMatrix(matrix,x,y,20);
        if (matrix[y][x] > max)
            max = matrix[y][x];
    }
    int A, R, G, B, n;
    for (int i = 0; i < xmax; ++i) {
        for (int j = 0; j < ymax; ++j) {
            if (matrix[j][i] != 0) {
                n = (int) Math.round(matrix[j][i] * 100 / max);
                R = Math.round((255 * n) / 100);
                G = Math.round((255 * (100 - n)) / 100);
                B = 0;
                A = Math.round((255 * n) / 100);
                ;
                if (R > 255)
                    R = 255;
                if (R < 0)
                    R = 0;
                if (G > 255)
                    G = 255;
                if (G < 0)
                    G = 0;
                if (R < 50)
                    A = 0;
                graph1.setColor(new Color(R, G, B, A));
                graph1.fillOval(i, j, 1, 1);
            }
        }
    }
    //graph1.dispose();

    ImageIO.write(img, "png", new File("example.png"));
    System.out.println(max);

    graph1.setColor(Color.RED);
    // Extraer elementos
    Elements e1 = doc.body().getAllElements();
    int i = 1;
    ArrayList<String> tags = new ArrayList<String>();
    for (Element temp : e1) {

        if (tags.indexOf(temp.tagName()) == -1) {
            tags.add(temp.tagName());

            List<WebElement> query = driver.findElements(By.tagName(temp.tagName()));
            for (WebElement temp1 : query) {
                Point po = temp1.getLocation();
                Dimension d = temp1.getSize();
                if (d.width <= 0 || d.height <= 0 || po.x < 0 || po.y < 0)
                    continue;
                System.out.println(i + " " + temp.nodeName());
                System.out.println("  x: " + po.x + " y: " + po.y);
                System.out.println("  width: " + d.width + " height: " + d.height);
                graph1.draw(new Rectangle(po.x, po.y, d.width, d.height));
                ++i;
            }
        }
    }

    graph1.dispose();
    ImageIO.write(img, "png", new File(PATH + NAME));

    driver.quit();

}

From source file:gsn.utils.GSNMonitor.java

public static void main(String[] args) {

    String configFileName;/*from   w w w  .j ava2  s .  c o  m*/

    if (args.length >= 2) {
        configFileName = args[0];
        System.out.println("Using config file: " + configFileName);
        for (int i = 1; i < args.length; i++) {
            System.out.println("Adding e-mail: " + args[i]);
            listOfMails.add(args[i]);
        }
    } else {
        System.out.println("Usage java -jar VSMonitor.jar <config_file> <list_of_mails>");
        System.out.println("e.g.  java -jar VSMonitor.jar conf/monitoring.cfg user@gmail.com admin@gmail.com");
        return;
    }

    initFromFile(configFileName);

    // for each monitored GSN server
    Iterator iter = listOfGSNSessions.iterator();
    while (iter.hasNext()) {

        try {
            readStatus((GSNSessionAddress) iter.next());
        } catch (Exception e) {
            logger.error("Exception: " + e.getMessage());
            logger.error("StackTrace:\n" + getStackTrace(e));
        }
    }

    checkUpdateTimes();

    // Generate Report
    report.append("\n[ERROR]\n" + errorsBuffer).append("\n[WARNING]\n" + warningsBuffer)
            .append("\n[INFO]\n" + infosBuffer);

    if ((nSensorsLate > 0) || (nHostsDown > 0)) {
        summary.append("WARNING: ");
        if (nHostsDown > 0)
            summary.append(nHostsDown + " host(s) down. ");
        if (nSensorsLate > 0)
            summary.append(nSensorsLate + " sensor(s) not updated. ");

        // Send e-mail only if there are errors
        try {
            sendMail();
        } catch (EmailException e) {
            logger.error("Cannot send e-mail. " + e.getMessage());
            logger.error("StackTrace:\n" + getStackTrace(e));
        }
    }

    // Showing report
    System.out.println(summary);
    System.out.println(report);

    System.exit(status);
}

From source file:esiptestbed.mudrod.ontology.process.LocalOntology.java

public static void main(String[] args) throws Exception {

    // boolean options
    Option helpOpt = new Option("h", "help", false, "show this help message");
    // argument options
    Option ontDirOpt = Option.builder(ONT_DIR).required(true).numberOfArgs(1).hasArg(true)
            .desc("A directory containing .owl files.").argName(ONT_DIR).build();

    // create the options
    Options options = new Options();
    options.addOption(helpOpt);/*w ww.  j  a va  2 s . c o m*/
    options.addOption(ontDirOpt);

    String ontDir;
    CommandLineParser parser = new DefaultParser();
    try {
        CommandLine line = parser.parse(options, args);

        if (line.hasOption(ONT_DIR)) {
            ontDir = line.getOptionValue(ONT_DIR).replace("\\", "/");
        } else {
            ontDir = LocalOntology.class.getClassLoader().getResource("ontology").getFile();
        }
        if (!ontDir.endsWith("/")) {
            ontDir += "/";
        }
    } catch (Exception e) {
        LOG.error("Error whilst processing main method of LocalOntology.", e);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LocalOntology: 'ontDir' argument is mandatory. ", options, true);
        return;
    }
    File fileDir = new File(ontDir);
    //Fail if the input is not a directory.
    if (fileDir.isDirectory()) {
        List<String> owlFiles = new ArrayList<>();
        for (File owlFile : fileDir.listFiles()) {
            owlFiles.add(owlFile.toString());
        }
        MudrodEngine mEngine = new MudrodEngine();
        Properties props = mEngine.loadConfig();
        Ontology ontology = new OntologyFactory(props).getOntology();
        //convert to correct iput for ontology loading.
        String[] owlArray = new String[owlFiles.size()];
        owlArray = owlFiles.toArray(owlArray);
        ontology.load(owlArray);

        String[] terms = new String[] { "Glacier ice" };
        //Demonstrate that we can do basic ontology heirarchy navigation and log output.
        for (Iterator<OntClass> i = getParser().rootClasses(getModel()); i.hasNext();) {

            //print Ontology Class Hierarchy
            OntClass c = i.next();
            renderHierarchy(System.out, c, new LinkedList<>(), 0);

            for (Iterator<OntClass> subClass = c.listSubClasses(true); subClass.hasNext();) {
                OntClass sub = subClass.next();
                //This means that the search term is present as an OntClass
                if (terms[0].equalsIgnoreCase(sub.getLabel(null))) {
                    //Add the search term(s) above to the term cache.
                    for (int j = 0; j < terms.length; j++) {
                        addSearchTerm(terms[j], sub);
                    }

                    //Query the ontology and return subclasses of the search term(s)
                    for (int k = 0; k < terms.length; k++) {
                        Iterator<String> iter = ontology.subclasses(terms[k]);
                        while (iter.hasNext()) {
                            LOG.info("Subclasses >> " + iter.next());
                        }
                    }

                    //print any synonymic relationships to demonstrate that we can 
                    //undertake synonym-based query expansion
                    for (int l = 0; l < terms.length; l++) {
                        Iterator<String> iter = ontology.synonyms(terms[l]);
                        while (iter.hasNext()) {
                            LOG.info("Synonym >> " + iter.next());
                        }
                    }
                }
            }
        }

        mEngine.end();
    }

}

From source file:application.ReviewDocumentIndexer.java

/**
 * @param args/*from w w  w.ja  va2  s  .c o m*/
 */
@SuppressWarnings("deprecation")
public static void main(String[] args) {
    // Parse command line arguments. Exit program is provided arguments are insufficient
    ReviewDocumentIndexer indexer = new ReviewDocumentIndexer(args);
    if (indexer == null)
        return;

    // Open a new index
    IndexWriter index = null;
    try {
        index = new IndexWriter(new SimpleFSDirectory(new File(Paths.luceneIndex)),
                new ReviewTextAnalyzer(indexer), indexer.new_index ? true : false, MaxFieldLength.UNLIMITED);
        if (indexer.pause_every > 2) {
            index.setMaxBufferedDocs(indexer.pause_every);
        }
        index.setMaxMergeDocs(Config.maxMergeDocs);
        index.setMergeFactor(Config.mergeFactor);
    } catch (CorruptIndexException e) {
        AppLogger.error.log(Level.SEVERE,
                "Lucene detected an inconsistency upon opening the index located at " + Paths.luceneIndex);
        throw new RuntimeException("Exiting application", e);
    } catch (LockObtainFailedException e) {
        AppLogger.error.log(Level.SEVERE,
                "Index located at " + Paths.luceneIndex + " is already open by another Lucene process");
        throw new RuntimeException("Exiting application", e);
    } catch (IOException e) {
        AppLogger.error.log(Level.SEVERE, "Could not access location " + Paths.luceneIndex);
        throw new RuntimeException("Exiting application", e);
    }

    // Load a number of reviews from database
    NumberFormat docIdFormat = TokenListsCollector.defaultDocIdFormat();
    try {
        DatabaseReviewCollection reviews = new DatabaseReviewCollection(indexer.pause_every);
        reviews.setLimits(indexer.min_reviewid, indexer.stop_after);
        int indexed_counter = 0;

        while (reviews.hasNextSegment()) {

            System.out.print(Calendar.getInstance().getTime().toGMTString());

            System.out.print(" Loading from DB... ");
            reviews.loadNextSegment();
            Iterator<Review> reviewsIterator = reviews.getIterator();

            System.out.print(" Indexing... ");
            while (reviewsIterator.hasNext()) {
                DatabaseReview dbr = (DatabaseReview) reviewsIterator.next();
                int dbr_id = dbr.getReviewid();
                int dbr_rating = dbr.getRating();

                try {
                    indexer.theReviewId.set(dbr_id);
                    indexer.theStats.setCurrent(dbr_id, dbr_rating);

                    index.addDocument(dbr.getDocumentForIndexing());
                    indexed_counter++;

                    // Also, keep track of the rating and length of this review
                    indexer.theStats.storeCurrent();

                } catch (CorruptIndexException e) {
                    AppLogger.error.log(Level.SEVERE,
                            "Lucene detected an inconsistency upon saving review #"
                                    + Integer.toString(dbr.getReviewid()) + "to the index located at "
                                    + Paths.luceneIndex);
                    return;
                } catch (IOException e) {
                    AppLogger.error.log(Level.WARNING,
                            "Review #" + Integer.toString(dbr.getReviewid()) + " could not be indexed");
                }
            }

            // Backup everything
            System.out.print("Indexed " + indexed_counter + " reviews total. ");
            if (indexer.pause_every > 0) {
                System.out.print("Saving tokenlists... ");
                indexer.theTokenLists.writeNextFile(docIdFormat);

                System.out.print("Saving state... ");
                try {
                    index.commit();
                    indexer.saveState();
                } catch (CorruptIndexException e) {
                    AppLogger.error.log(Level.SEVERE, "Committing index changes failed on review #"
                            + indexer.theReviewId.get() + "due to CorruptIndexException");
                    return;
                } catch (IOException e) {
                    AppLogger.error.log(Level.WARNING, "Committing index changes failed on review #"
                            + indexer.theReviewId.get() + "due to IOException");
                }
            }
            System.out.print("DONE\n");

            reviews.reset();
        }
    } catch (SQLException e) {
        AppLogger.error.log(Level.SEVERE,
                "An exception occured while trying to access the database.\n" + e.getMessage());
        return;
    }

    try {
        index.close();
        indexer.backupIndex();
    } catch (CorruptIndexException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.err.println("Indexing successfully completed!");
    return;
}

From source file:gov.nasa.jpl.mudrod.ontology.process.LocalOntology.java

public static void main(String[] args) throws Exception {

    // boolean options
    Option helpOpt = new Option("h", "help", false, "show this help message");
    // argument options
    Option ontDirOpt = OptionBuilder.hasArg(true).withArgName(ONT_DIR)
            .withDescription("A directory containing .owl files.").isRequired(false).create();

    // create the options
    Options options = new Options();
    options.addOption(helpOpt);/*from w w  w .  j a v a 2  s.co  m*/
    options.addOption(ontDirOpt);

    String ontDir;
    CommandLineParser parser = new GnuParser();
    try {
        CommandLine line = parser.parse(options, args);

        if (line.hasOption(ONT_DIR)) {
            ontDir = line.getOptionValue(ONT_DIR).replace("\\", "/");
        } else {
            ontDir = LocalOntology.class.getClassLoader().getResource("ontology").getFile();
        }
        if (!ontDir.endsWith("/")) {
            ontDir += "/";
        }
    } catch (Exception e) {
        LOG.error("Error whilst processing main method of LocalOntology.", e);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LocalOntology: 'ontDir' argument is mandatory. ", options, true);
        return;
    }
    File fileDir = new File(ontDir);
    //Fail if the input is not a directory.
    if (fileDir.isDirectory()) {
        List<String> owlFiles = new ArrayList<>();
        for (File owlFile : fileDir.listFiles()) {
            owlFiles.add(owlFile.toString());
        }
        MudrodEngine mEngine = new MudrodEngine();
        Properties props = mEngine.loadConfig();
        Ontology ontology = new OntologyFactory(props).getOntology();
        //convert to correct iput for ontology loading.
        String[] owlArray = new String[owlFiles.size()];
        owlArray = owlFiles.toArray(owlArray);
        ontology.load(owlArray);

        String[] terms = new String[] { "Glacier ice" };
        //Demonstrate that we can do basic ontology heirarchy navigation and log output.
        for (Iterator<OntClass> i = getParser().rootClasses(getModel()); i.hasNext();) {

            //print Ontology Class Hierarchy
            OntClass c = i.next();
            renderHierarchy(System.out, c, new LinkedList<>(), 0);

            for (Iterator<OntClass> subClass = c.listSubClasses(true); subClass.hasNext();) {
                OntClass sub = subClass.next();
                //This means that the search term is present as an OntClass
                if (terms[0].equalsIgnoreCase(sub.getLabel(null))) {
                    //Add the search term(s) above to the term cache.
                    for (int j = 0; j < terms.length; j++) {
                        addSearchTerm(terms[j], sub);
                    }

                    //Query the ontology and return subclasses of the search term(s)
                    for (int k = 0; k < terms.length; k++) {
                        Iterator<String> iter = ontology.subclasses(terms[k]);
                        while (iter.hasNext()) {
                            LOG.info("Subclasses >> " + iter.next());
                        }
                    }

                    //print any synonymic relationships to demonstrate that we can 
                    //undertake synonym-based query expansion
                    for (int l = 0; l < terms.length; l++) {
                        Iterator<String> iter = ontology.synonyms(terms[l]);
                        while (iter.hasNext()) {
                            LOG.info("Synonym >> " + iter.next());
                        }
                    }
                }
            }
        }

        mEngine.end();
    }

}

From source file:com.bluemarsh.jswat.console.Main.java

/**
 * Kicks off the application./*  w  w w .  ja v a2 s  .  c o m*/
 *
 * @param  args  the command line arguments.
 */
public static void main(String[] args) {
    //
    // An attempt was made early on to use the Console class in java.io,
    // but that is not designed to handle asynchronous output from
    // multiple threads, so we just use the usual System.out for output
    // and System.in for input. Note that automatic flushing is used to
    // ensure output is shown in a timely fashion.
    //

    //
    // Where console mode seems to work:
    // - bash
    // - emacs
    //
    // Where console mode does not seem to work:
    // - NetBeans: output from event listeners is never shown and the
    //   cursor sometimes lags behind the output
    //

    // Turn on flushing so printing the prompt will flush
    // all buffered output generated from other threads.
    PrintWriter output = new PrintWriter(System.out, true);

    // Make sure we have the JPDA classes.
    try {
        Bootstrap.virtualMachineManager();
    } catch (NoClassDefFoundError ncdfe) {
        output.println(NbBundle.getMessage(Main.class, "MSG_Main_NoJPDA"));
        System.exit(1);
    }

    // Ensure we can create the user directory by requesting the
    // platform service. Simply asking for it has the desired effect.
    PlatformProvider.getPlatformService();

    // Define the logging configuration.
    LogManager manager = LogManager.getLogManager();
    InputStream is = Main.class.getResourceAsStream("logging.properties");
    try {
        manager.readConfiguration(is);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.exit(1);
    }

    // Print out some useful debugging information.
    logSystemDetails();

    // Add a shutdown hook to make sure we exit cleanly.
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

        @Override
        public void run() {
            // Save the command aliases.
            CommandParser parser = CommandProvider.getCommandParser();
            parser.saveSettings();
            // Save the runtimes to persistent storage.
            RuntimeManager rm = RuntimeProvider.getRuntimeManager();
            rm.saveRuntimes();
            // Save the sessions to persistent storage and have them
            // close down in preparation to exit.
            SessionManager sm = SessionProvider.getSessionManager();
            sm.saveSessions(true);
        }
    }));

    // Initialize the command parser and load the aliases.
    CommandParser parser = CommandProvider.getCommandParser();
    parser.loadSettings();
    parser.setOutput(output);

    // Create an OutputAdapter to display debuggee output.
    OutputAdapter adapter = new OutputAdapter(output);
    SessionManager sessionMgr = SessionProvider.getSessionManager();
    sessionMgr.addSessionManagerListener(adapter);
    // Create a SessionWatcher to monitor the session status.
    SessionWatcher swatcher = new SessionWatcher();
    sessionMgr.addSessionManagerListener(swatcher);
    // Create a BreakpointWatcher to monitor the breakpoints.
    BreakpointWatcher bwatcher = new BreakpointWatcher();
    sessionMgr.addSessionManagerListener(bwatcher);

    // Add the watchers and adapters to the open sessions.
    Iterator<Session> iter = sessionMgr.iterateSessions();
    while (iter.hasNext()) {
        Session s = iter.next();
        s.addSessionListener(adapter);
        s.addSessionListener(swatcher);
    }

    // Find and run the RC file.
    try {
        runStartupFile(parser, output);
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
    }

    // Process command line arguments.
    try {
        processArguments(args);
    } catch (ParseException pe) {
        // Report the problem and keep going.
        System.err.println("Option parsing failed: " + pe.getMessage());
        logger.log(Level.SEVERE, null, pe);
    }

    // Display a helpful greeting.
    output.println(NbBundle.getMessage(Main.class, "MSG_Main_Welcome"));
    if (jdbEmulationMode) {
        output.println(NbBundle.getMessage(Main.class, "MSG_Main_Jdb_Emulation"));
    }

    // Enter the main loop of processing user input.
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    while (true) {
        // Keep the prompt format identical to jdb for compatibility
        // with emacs and other possible wrappers.
        output.print("> ");
        output.flush();
        try {
            String command = input.readLine();
            // A null value indicates end of stream.
            if (command != null) {
                performCommand(output, parser, command);
            }
            // Sleep briefly to give the event processing threads,
            // and the automatic output flushing, a chance to catch
            // up before printing the input prompt again.
            Thread.sleep(250);
        } catch (InterruptedException ie) {
            logger.log(Level.WARNING, null, ie);
        } catch (IOException ioe) {
            logger.log(Level.SEVERE, null, ioe);
            output.println(NbBundle.getMessage(Main.class, "ERR_Main_IOError", ioe));
        } catch (Exception x) {
            // Don't ever let an internal bug (e.g. in the command parser)
            // hork the console, as it really irritates people.
            logger.log(Level.SEVERE, null, x);
            output.println(NbBundle.getMessage(Main.class, "ERR_Main_Exception", x));
        }
    }
}

From source file:ValidateLicenseHeaders.java

/**
 * ValidateLicenseHeaders jboss-src-root
 * //from  ww  w . j  a v a 2  s  .c  o  m
 * @param args
 */
public static void main(String[] args) throws Exception {
    if (args.length == 0 || args[0].startsWith("-h")) {
        log.info("Usage: ValidateLicenseHeaders [-addheader] jboss-src-root");
        System.exit(1);
    }
    int rootArg = 0;
    if (args.length == 2) {
        if (args[0].startsWith("-add"))
            addDefaultHeader = true;
        else {
            log.severe("Uknown argument: " + args[0]);
            log.info("Usage: ValidateLicenseHeaders [-addheader] jboss-src-root");
            System.exit(1);

        }
        rootArg = 1;
    }

    File jbossSrcRoot = new File(args[rootArg]);
    if (jbossSrcRoot.exists() == false) {
        log.info("Src root does not exist, check " + jbossSrcRoot.getAbsolutePath());
        System.exit(1);
    }

    URL u = Thread.currentThread().getContextClassLoader()
            .getResource("META-INF/services/javax.xml.parsers.DocumentBuilderFactory");
    System.err.println(u);

    // Load the valid copyright statements for the licenses
    File licenseInfo = new File(jbossSrcRoot, "varia/src/etc/license-info.xml");
    if (licenseInfo.exists() == false) {
        log.severe("Failed to find the varia/src/etc/license-info.xml under the src root");
        System.exit(1);
    }
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = factory.newDocumentBuilder();
    Document doc = db.parse(licenseInfo);
    NodeList licenses = doc.getElementsByTagName("license");
    for (int i = 0; i < licenses.getLength(); i++) {
        Element license = (Element) licenses.item(i);
        String key = license.getAttribute("id");
        ArrayList headers = new ArrayList();
        licenseHeaders.put(key, headers);
        NodeList copyrights = license.getElementsByTagName("terms-header");
        for (int j = 0; j < copyrights.getLength(); j++) {
            Element copyright = (Element) copyrights.item(j);
            copyright.normalize();
            String id = copyright.getAttribute("id");
            // The id will be blank if there is no id attribute
            if (id.length() == 0)
                continue;
            String text = getElementContent(copyright);
            if (text == null)
                continue;
            // Replace all duplicate whitespace and '*' with a single space
            text = text.replaceAll("[\\s*]+", " ");
            if (text.length() == 1)
                continue;

            text = text.toLowerCase().trim();
            // Replace any copyright date0-date1,date2 with copyright ...
            text = text.replaceAll(COPYRIGHT_REGEX, "...");
            LicenseHeader lh = new LicenseHeader(id, text);
            headers.add(lh);
        }
    }
    log.fine(licenseHeaders.toString());

    File[] files = jbossSrcRoot.listFiles(dotJavaFilter);
    log.info("Root files count: " + files.length);
    processSourceFiles(files, 0);

    log.info("Processed " + totalCount);
    log.info("Updated jboss headers: " + jbossCount);
    // Files with no headers details
    log.info("Files with no headers: " + noheaders.size());
    FileWriter fw = new FileWriter("NoHeaders.txt");
    for (Iterator iter = noheaders.iterator(); iter.hasNext();) {
        File f = (File) iter.next();
        fw.write(f.getAbsolutePath());
        fw.write('\n');
    }
    fw.close();

    // Files with unknown headers details
    log.info("Files with invalid headers: " + invalidheaders.size());
    fw = new FileWriter("InvalidHeaders.txt");
    for (Iterator iter = invalidheaders.iterator(); iter.hasNext();) {
        File f = (File) iter.next();
        fw.write(f.getAbsolutePath());
        fw.write('\n');
    }
    fw.close();

    // License usage summary
    log.info("Creating HeadersSummary.txt");
    fw = new FileWriter("HeadersSummary.txt");
    for (Iterator iter = licenseHeaders.entrySet().iterator(); iter.hasNext();) {
        Map.Entry entry = (Map.Entry) iter.next();
        String key = (String) entry.getKey();
        fw.write("+++ License type=" + key);
        fw.write('\n');
        List list = (List) entry.getValue();
        Iterator jiter = list.iterator();
        while (jiter.hasNext()) {
            LicenseHeader lh = (LicenseHeader) jiter.next();
            fw.write('\t');
            fw.write(lh.id);
            fw.write(", count=");
            fw.write("" + lh.count);
            fw.write('\n');
        }
    }
    fw.close();
}

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 w w . j a v  a  2s .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);
    }
}