Example usage for java.util Collection size

List of usage examples for java.util Collection size

Introduction

In this page you can find the example usage for java.util Collection size.

Prototype

int size();

Source Link

Document

Returns the number of elements in this collection.

Usage

From source file:Main.java

  public static void main(String[] args) {
  Collection<String> names = new ArrayList<>();
  System.out.printf("Size = %d, Elements = %s%n", names.size(), names);
  names.add("XML");
  names.add("HTML");
  names.add("CSS");
  System.out.printf("Size   = %d, Elements   = %s%n",
      names.size(), names);/*  w w  w. j  a va2  s . co m*/
  names.remove("CSS");
  System.out.printf("Size   = %d, Elements   = %s%n",
      names.size(), names);
  names.clear();
  System.out.printf("Size   = %d, Elements   = %s%n",
      names.size(), names);
}

From source file:com.music.tools.HeaderManager.java

public static void main(String[] args) throws Exception {
    String path = args[0];//from  w w w  . j a  v a2  s . co m
    String header = FileUtils.readFileToString(new File(path, "src/main/resources/license/AGPL-3-header.txt"),
            Charsets.UTF_8);

    File sourceRoot = new File(path, "src");
    System.out.println("Source root is: " + sourceRoot);
    Collection<File> files = FileUtils.listFiles(sourceRoot, new String[] { "java" }, true);
    System.out.println("Ammending " + files.size() + " source files");
    for (File file : files) {
        System.out.println("Checking file " + file);
        String content = FileUtils.readFileToString(file, Charsets.UTF_8);
        if (content.contains("Copyright")) {
            System.out.println("Skipping file " + file);
            continue;
        }
        content = header + LS + LS + content;
        FileUtils.write(file, content);
    }
}

From source file:com.twitter.bazel.checkstyle.PythonCheckstyle.java

public static void main(String[] args) throws IOException {
    CommandLineParser parser = new DefaultParser();

    // create the Options
    Options options = new Options();
    options.addOption(Option.builder("f").required(true).hasArg().longOpt("extra_action_file")
            .desc("bazel extra action protobuf file").build());
    options.addOption(Option.builder("p").required(true).hasArg().longOpt("pylint_file")
            .desc("Executable pylint file to invoke").build());

    try {//from   w w w. j a v a  2s  .  c  o  m
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        String extraActionFile = line.getOptionValue("f");
        String pylintFile = line.getOptionValue("p");

        Collection<String> sourceFiles = getSourceFiles(extraActionFile);
        if (sourceFiles.size() == 0) {
            LOG.info("No python files found by checkstyle");
            return;
        }

        LOG.info(sourceFiles.size() + " python files found by checkstyle");

        // Create and run the command
        List<String> commandBuilder = new ArrayList<>();
        commandBuilder.add(pylintFile);
        commandBuilder.addAll(sourceFiles);
        runLinter(commandBuilder);

    } catch (ParseException exp) {
        LOG.severe(String.format("Invalid input to %s: %s", CLASSNAME, exp.getMessage()));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java " + CLASSNAME, options);
    }
}

From source file:com.appunity.ant.util.NewClass.java

public static void main(String[] args) throws FileNotFoundException, IOException {

    Collection<File> listFiles = FileUtils.listFiles(srcDir, new String[] { "java" }, true);
    int size = 0;
    System.out.println("listFiles = " + listFiles.size());
    for (final File file : listFiles) {
        CharsetDetector charsetDetector = new CharsetDetector();
        String[] detectAllCharset = charsetDetector.detectCharset(file);
        if (detectAllCharset != null && detectAllCharset.length == 1 && "GB2312".equals(detectAllCharset[0])) {
            System.out.println(Arrays.toString(detectAllCharset) + file.getAbsolutePath());
        } else {//from w  w  w.jav a 2s.  c  om
            System.out.println(Arrays.toString(detectAllCharset) + file.getAbsolutePath());
        }
    }
}

From source file:com.twitter.bazel.checkstyle.CppCheckstyle.java

public static void main(String[] args) throws IOException {
    CommandLineParser parser = new DefaultParser();

    // create the Options
    Options options = new Options();
    options.addOption(Option.builder("f").required(true).hasArg().longOpt("extra_action_file")
            .desc("bazel extra action protobuf file").build());
    options.addOption(Option.builder("c").required(true).hasArg().longOpt("cpplint_file")
            .desc("Executable cpplint file to invoke").build());

    try {/*from   ww  w.  j a v  a  2 s. c om*/
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        String extraActionFile = line.getOptionValue("f");
        String cpplintFile = line.getOptionValue("c");

        Collection<String> sourceFiles = getSourceFiles(extraActionFile);
        if (sourceFiles.size() == 0) {
            LOG.fine("No cpp files found by checkstyle");
            return;
        }

        LOG.fine(sourceFiles.size() + " cpp files found by checkstyle");

        // Create and run the command
        List<String> commandBuilder = new ArrayList<>();
        commandBuilder.add(cpplintFile);
        commandBuilder.add("--linelength=100");
        // TODO: https://github.com/twitter/heron/issues/466,
        // Remove "runtime/references" when we fix all non-const references in our codebase.
        // TODO: https://github.com/twitter/heron/issues/467,
        // Remove "runtime/threadsafe_fn" when we fix all non-threadsafe libc functions
        commandBuilder.add("--filter=-build/header_guard,-runtime/references,-runtime/threadsafe_fn");
        commandBuilder.addAll(sourceFiles);
        runLinter(commandBuilder);

    } catch (ParseException exp) {
        LOG.severe(String.format("Invalid input to %s: %s", CLASSNAME, exp.getMessage()));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java " + CLASSNAME, options);
    }
}

From source file:ImportKey.java

/**
 * <p>//  w  w w.  j  a v a  2 s .c om
 * Takes two file names for a key and the certificate for the key, and
 * imports those into a keystore. Optionally it takes an alias for the key.
 * <p>
 * The first argument is the filename for the key. The key should be in
 * PKCS8-format.
 * <p>
 * The second argument is the filename for the certificate for the key.
 * <p>
 * If a third argument is given it is used as the alias. If missing, the key
 * is imported with the alias importkey
 * <p>
 * The name of the keystore file can be controlled by setting the keystore
 * property (java -Dkeystore=mykeystore). If no name is given, the file is
 * named <code>keystore.ImportKey</code> and placed in your home directory.
 * 
 * @param args
 *            [0] Name of the key file, [1] Name of the certificate file [2]
 *            Alias for the key.
 **/
public static void main(String args[]) {

    // change this if you want another password by default
    String keypass = "password";

    // change this if you want another alias by default
    String defaultalias = "tomcat";

    // change this if you want another keystorefile by default
    String keystorename = null;

    // parsing command line input
    String keyfile = "";
    String certfile = "";
    if (args.length < 3 || args.length > 4) {
        System.out.println("Usage: java comu.ImportKey keystore keyfile certfile [alias]");
        System.exit(0);
    } else {
        keystorename = args[0];
        keyfile = args[1];
        certfile = args[2];
        if (args.length > 3)
            defaultalias = args[3];
    }

    try {
        // initializing and clearing keystore
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        ks.load(null, keypass.toCharArray());
        System.out.println("Using keystore-file : " + keystorename);
        ks.store(new FileOutputStream(keystorename), keypass.toCharArray());
        ks.load(new FileInputStream(keystorename), keypass.toCharArray());

        // loading Key
        InputStream fl = fullStream(keyfile);
        byte[] key = new byte[fl.available()];
        KeyFactory kf = KeyFactory.getInstance("RSA");
        fl.read(key, 0, fl.available());
        fl.close();
        PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(key);
        PrivateKey ff = kf.generatePrivate(keysp);

        // loading CertificateChain
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream certstream = fullStream(certfile);

        Collection c = cf.generateCertificates(certstream);
        Certificate[] certs = new Certificate[c.toArray().length];

        if (c.size() == 1) {
            certstream = fullStream(certfile);
            System.out.println("One certificate, no chain.");
            Certificate cert = cf.generateCertificate(certstream);
            certs[0] = cert;
        } else {
            System.out.println("Certificate chain length: " + c.size());
            certs = (Certificate[]) c.toArray(new Certificate[c.size()]);
        }

        // storing keystore
        ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), certs);
        System.out.println("Key and certificate stored.");
        System.out.println("Alias:" + defaultalias + "  Password:" + keypass);
        ks.store(new FileOutputStream(keystorename), keypass.toCharArray());
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.datascience.gal.scripts.MainClient.java

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

    DawidSkeneClient dsclient = new DawidSkeneClient();

    String categoriesfile = null;
    String inputfile = null;// w w  w. j a  v  a 2  s .c o m
    String correctfile = null;
    String costfile = null;
    int iterations = 1;
    boolean incremental = false;

    CommandLineParser parser = new GnuParser();
    CommandLine line = parser.parse(cli_options, args);

    if (!line.hasOption("c") || !line.hasOption("l") || !line.hasOption("g") || !line.hasOption("C")) {
        printHelp();
        System.exit(1);
    }

    categoriesfile = line.getOptionValue("c");
    inputfile = line.getOptionValue("l");

    if (line.hasOption("g"))
        correctfile = line.getOptionValue("g");
    if (line.hasOption("C"))
        costfile = line.getOptionValue("C");
    if (line.hasOption("i"))
        iterations = Integer.parseInt(line.getOptionValue("i"));
    if (line.hasOption("I"))
        incremental = true;

    // see if the thing is awake
    System.out.println(dsclient.isAlive() ? "pinged alive" : "problem with dsclient");
    // hard reset
    System.out.println(dsclient.deleteDS(0) ? "deleted ds 0" : "failed to delete ds 0");

    Collection<Category> categories = loadCategoriesFromFile(categoriesfile);
    if (categories.size() < 2) {
        System.err.println("invalid category input");
        System.exit(1);
    }

    System.out.println("sending to service: " + JSONUtils.toJson(categories));

    System.out.println(
            "response: " + (dsclient.initializeDS(0, categories, incremental) ? "success" : "failure"));

    // check the serialization of the json ds object
    DawidSkene ds = dsclient.getDawidSkene(0);
    System.out.println(ds);

    Collection<MisclassificationCost> costs = loadMisclassificationCosts(costfile);

    System.out.println("response: " + (dsclient.addMisclassificationCosts(0, costs) ? "successfully added costs"
            : "unable to add costs") + " - " + JSONUtils.toJson(costs));

    Collection<AssignedLabel> labels = loadAssignedLabels(inputfile);

    System.out.println("response: "
            + (dsclient.addAssignedLabels(0, labels) ? "successfully added labels" : "unable to add labels")
            + " - " + JSONUtils.toJson(labels));

    Collection<CorrectLabel> gold = loadGoldLabels(correctfile);
    System.out.println("response: "
            + (dsclient.addCorrectLabels(0, gold) ? "successfully added labels" : "unable to add labels")
            + " - " + JSONUtils.toJson(gold));

    Map<String, String> preVotes = dsclient.computeMajorityVotes(0);

    ds = dsclient.getDawidSkene(0);

    System.out.println(ds);
    if (!incremental)
        System.out.println(
                dsclient.iterateBlocking(0, iterations) ? "successfully iterated" : "failed ds iterations");

    ds = dsclient.getDawidSkene(0);
    System.out.println(ds);

    System.out.println(ds.printAllWorkerScores(false));
    System.out.println(ds.printObjectClassProbabilities(0));
    System.out.println(ds.printPriors());

    Map<String, String> postVotes = dsclient.computeMajorityVotes(0);

    System.out.println("note- diff doesnt work with incremental\n" + printDiffVote(preVotes, postVotes));

    System.out.println(JSONUtils.toJson(ds.getMajorityVote()));
    System.out.println(JSONUtils.toJson(ds.getObjectProbs()));

    Collection<String> objectNames = new HashSet<String>();
    String name = null;
    for (AssignedLabel label : labels) {
        objectNames.add(label.getObjectName());
        name = label.getObjectName();
    }

    System.out.println(JSONUtils.toJson(ds.getMajorityVote(objectNames)));
    System.out.println(JSONUtils.toJson(ds.getObjectProbs(objectNames)));

    System.out.println(JSONUtils.toJson(ds.getMajorityVote(name)));
    System.out.println(JSONUtils.toJson(ds.getObjectProbs(name)));

    boolean contains;
    contains = dsclient.hasDSObject(0);
    System.out.println(contains ? "has 0" : "dont have 0");
    contains = dsclient.hasDSObject(1);
    System.out.println(contains ? "has 1" : "dont have 1");
    System.out.println("deleting 0");
    dsclient.deleteDS(0);
    contains = dsclient.hasDSObject(0);
    System.out.println(contains ? "has 0" : "dont have 0");
}

From source file:grnet.validation.XMLValidation.java

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method ssstub

    Enviroment enviroment = new Enviroment(args[0]);

    if (enviroment.envCreation) {
        String schemaUrl = enviroment.getArguments().getSchemaURL();
        Core core = new Core(schemaUrl);

        XMLSource source = new XMLSource(args[0]);

        File sourceFile = source.getSource();

        if (sourceFile.exists()) {

            Collection<File> xmls = source.getXMLs();

            System.out.println("Validating repository:" + sourceFile.getName());

            System.out.println("Number of files to validate:" + xmls.size());

            Iterator<File> iterator = xmls.iterator();

            System.out.println("Validating against schema:" + schemaUrl + "...");

            ValidationReport report = null;
            if (enviroment.getArguments().createReport().equalsIgnoreCase("true")) {

                report = new ValidationReport(enviroment.getArguments().getDestFolderLocation(),
                        enviroment.getDataProviderValid().getName());

            }/*  ww  w.jav a  2 s. c  o m*/

            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(enviroment.getArguments().getQueueHost());
            factory.setUsername(enviroment.getArguments().getQueueUserName());
            factory.setPassword(enviroment.getArguments().getQueuePassword());

            while (iterator.hasNext()) {

                StringBuffer logString = new StringBuffer();
                logString.append(sourceFile.getName());
                logString.append(" " + schemaUrl);

                File xmlFile = iterator.next();
                String name = xmlFile.getName();
                name = name.substring(0, name.indexOf(".xml"));

                logString.append(" " + name);

                boolean xmlIsValid = core.validateXMLSchema(xmlFile);

                if (xmlIsValid) {
                    logString.append(" " + "Valid");
                    slf4jLogger.info(logString.toString());

                    Connection connection = factory.newConnection();
                    Channel channel = connection.createChannel();
                    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

                    channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes());
                    channel.close();
                    connection.close();
                    try {
                        if (report != null) {

                            report.raiseValidFilesNum();
                        }

                        FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderValid());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    logString.append(" " + "Invalid");
                    slf4jLogger.info(logString.toString());

                    Connection connection = factory.newConnection();
                    Channel channel = connection.createChannel();
                    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

                    channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes());
                    channel.close();
                    connection.close();

                    try {
                        if (report != null) {

                            if (enviroment.getArguments().extendedReport().equalsIgnoreCase("true"))
                                report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.invalidData,
                                        core.getReason());

                            report.raiseInvalidFilesNum();
                        }
                        FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderInValid());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

            if (report != null) {
                report.writeErrorBank(core.getErrorBank());
                report.appendGeneralInfo();
            }
            System.out.println("Validation is done.");

        }

    }
}

From source file:grnet.filter.XMLFiltering.java

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method ssstub

    Enviroment enviroment = new Enviroment(args[0]);

    if (enviroment.envCreation) {
        Core core = new Core();

        XMLSource source = new XMLSource(args[0]);

        File sourceFile = source.getSource();

        if (sourceFile.exists()) {

            Collection<File> xmls = source.getXMLs();

            System.out.println("Filtering repository:" + enviroment.dataProviderFilteredIn.getName());

            System.out.println("Number of files to filter:" + xmls.size());

            Iterator<File> iterator = xmls.iterator();

            FilteringReport report = null;
            if (enviroment.getArguments().getProps().getProperty(Constants.createReport)
                    .equalsIgnoreCase("true")) {
                report = new FilteringReport(enviroment.getArguments().getDestFolderLocation(),
                        enviroment.getDataProviderFilteredIn().getName());
            }//w  ww.  j  a va 2  s . co  m

            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(enviroment.getArguments().getQueueHost());
            factory.setUsername(enviroment.getArguments().getQueueUserName());
            factory.setPassword(enviroment.getArguments().getQueuePassword());

            while (iterator.hasNext()) {

                StringBuffer logString = new StringBuffer();
                logString.append(enviroment.dataProviderFilteredIn.getName());
                File xmlFile = iterator.next();

                String name = xmlFile.getName();
                name = name.substring(0, name.indexOf(".xml"));
                logString.append(" " + name);

                boolean xmlIsFilteredIn = core.filterXML(xmlFile, enviroment.getArguments().getQueries());

                if (xmlIsFilteredIn) {
                    logString.append(" " + "FilteredIn");
                    slf4jLogger.info(logString.toString());

                    Connection connection = factory.newConnection();
                    Channel channel = connection.createChannel();
                    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

                    channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes());
                    channel.close();
                    connection.close();

                    try {
                        if (report != null) {
                            report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.filteredInData);
                            report.raiseFilteredInFilesNum();
                        }

                        FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderFilteredIn());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        // e.printStackTrace();
                        e.printStackTrace();
                        System.out.println("Filtering failed.");
                    }
                } else {
                    logString.append(" " + "FilteredOut");
                    slf4jLogger.info(logString.toString());

                    Connection connection = factory.newConnection();
                    Channel channel = connection.createChannel();
                    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

                    channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes());
                    channel.close();
                    connection.close();
                    try {
                        if (report != null) {
                            report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.filteredOutData);
                            report.raiseFilteredOutFilesNum();
                        }
                        FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderFilteredOuT());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        // e.printStackTrace();
                        e.printStackTrace();
                        System.out.println("Filtering failed.");
                    }
                }
            }
            if (report != null) {

                report.appendXPathExpression(enviroment.getArguments().getQueries());

                report.appendGeneralInfo();
            }
            System.out.println("Filtering is done.");
        }

    }
}

From source file:mase.jbot.JBotViewer.java

/**
 * @param args the command line arguments
 *//*from   ww w.  j a v  a  2s  .  co m*/
public static void main(String args[]) throws Exception {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(JBotViewer.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(JBotViewer.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(JBotViewer.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(JBotViewer.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);
    }
    //</editor-fold>
    //</editor-fold>

    File jbotConfig;
    final File solution = new File(args[0]);
    if (args.length == 2) {
        jbotConfig = new File(args[1]);
    } else {
        // Search the individual's folder for the jbot config file
        File dir = solution.getParentFile();
        Collection<File> listFiles = FileUtils.listFiles(dir, new String[] { "conf" }, false);
        if (listFiles.size() != 1) {
            System.out.println("Zero or more than one config files found!:\n" + listFiles.toString());
        }
        jbotConfig = listFiles.iterator().next();
    }
    final File jbot = jbotConfig;

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                new JBotViewer(jbot, solution).setVisible(true);
            } catch (Exception ex) {
                Logger.getLogger(JBotViewer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
}