Example usage for java.util List size

List of usage examples for java.util List size

Introduction

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

Prototype

int size();

Source Link

Document

Returns the number of elements in this list.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    List<String> list1 = new ArrayList();
    List<String> list2 = new ArrayList();

    list1.addAll(list2);/*from www  .  j ava2  s. c o  m*/

    list1.removeAll(list2);

    list1.retainAll(list2);

    list1.clear();

    int newSize = 2;
    list1.subList(newSize, list1.size()).clear();
}

From source file:cz.muni.fi.mir.mathmlunificator.MathMLUnificatorCommandLineTool.java

/**
 * Main (starting) method of the command line application.
 *
 * @param argv Array of command line arguments that are expected to be
 * filesystem paths to input XML documents with MathML to be unified.
 * @throws ParserConfigurationException If a XML DOM builder cannot be
 * created with the configuration requested.
 *//*from   w w  w  .jav a 2  s .c  om*/
public static void main(String argv[]) throws ParserConfigurationException {

    final Options options = new Options();
    options.addOption("p", "operator-unification", false, "unify operator in addition to other types of nodes");
    options.addOption("h", "help", false, "print help");

    final CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, argv);
    } catch (ParseException ex) {
        printHelp(options);
        System.exit(1);
    }

    if (line != null) {
        if (line.hasOption('h')) {
            printHelp(options);
            System.exit(0);
        }
        operatorUnification = line.hasOption('p');

        final List<String> arguments = Arrays.asList(line.getArgs());
        if (arguments.size() > 0) {

            Document outerDocument = DOMBuilder.getDocumentBuilder().newDocument();
            Node rootNode = outerDocument.createElementNS(UNIFIED_MATHML_NS,
                    UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ROOT_ELEM);
            outerDocument.appendChild(rootNode);

            for (String filepath : arguments) {
                try {

                    Document doc = DOMBuilder.buildDocFromFilepath(filepath);
                    MathMLUnificator.unifyMathML(doc, operatorUnification);
                    if (arguments.size() == 1) {
                        xmlStdoutSerializer(doc);
                    } else {
                        Node itemNode = rootNode.getOwnerDocument().createElementNS(UNIFIED_MATHML_NS,
                                UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ITEM_ELEM);
                        Attr filenameAttr = itemNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS,
                                UNIFIED_MATHML_NS_PREFIX + ":"
                                        + UNIFIED_MATHML_BATCH_OUTPUT_ITEM_FILEPATH_ATTR);
                        filenameAttr.setTextContent(String.valueOf(filepath));
                        ((Element) itemNode).setAttributeNodeNS(filenameAttr);
                        itemNode.appendChild(
                                rootNode.getOwnerDocument().importNode(doc.getDocumentElement(), true));
                        rootNode.appendChild(itemNode);

                    }

                } catch (SAXException | IOException ex) {
                    Logger.getLogger(MathMLUnificatorCommandLineTool.class.getName()).log(Level.SEVERE,
                            "Failed processing of file: " + filepath, ex);
                }
            }

            if (rootNode.getChildNodes().getLength() > 0) {
                xmlStdoutSerializer(rootNode.getOwnerDocument());
            }

        } else {
            printHelp(options);
            System.exit(0);
        }
    }

}

From source file:jk.kamoru.test.IMAPMail.java

public static void main(String[] args) {
    /*        if (args.length < 3)
            {/*from www  .  j av a  2s .  c o m*/
    System.err.println(
        "Usage: IMAPMail <imap server hostname> <username> <password> [TLS]");
    System.exit(1);
            }
    */
    String server = "imap.handysoft.co.kr";
    String username = "namjk24@handysoft.co.kr";
    String password = "22222";

    String proto = (args.length > 3) ? args[3] : null;

    IMAPClient imap;

    if (proto != null) {
        System.out.println("Using secure protocol: " + proto);
        imap = new IMAPSClient(proto, true); // implicit
        // enable the next line to only check if the server certificate has expired (does not check chain):
        //            ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        // OR enable the next line if the server uses a self-signed certificate (no checks)
        //            ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
    } else {
        imap = new IMAPClient();
    }
    System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort());

    // We want to timeout if a response takes longer than 60 seconds
    imap.setDefaultTimeout(60000);

    File imap_log_file = new File("IMAMP-UNSEEN");
    try {
        System.out.println(imap_log_file.getAbsolutePath());
        PrintStream ps = new PrintStream(imap_log_file);
        // suppress login details
        imap.addProtocolCommandListener(new PrintCommandListener(ps, true));
    } catch (FileNotFoundException e1) {
        imap.addProtocolCommandListener(new PrintCommandListener(System.out, true));
    }

    try {
        imap.connect(server);
    } catch (IOException e) {
        throw new RuntimeException("Could not connect to server.", e);
    }

    try {
        if (!imap.login(username, password)) {
            System.err.println("Could not login to server. Check password.");
            imap.disconnect();
            System.exit(3);
        }

        imap.setSoTimeout(6000);

        //            imap.capability();

        //            imap.select("inbox");

        //            imap.examine("inbox");

        imap.status("inbox", new String[] { "UNSEEN" });

        //            imap.logout();
        imap.disconnect();

        List<String> imap_log = FileUtils.readLines(imap_log_file);
        for (int i = 0; i < imap_log.size(); i++) {
            System.out.println(i + ":" + imap_log.get(i));
        }
        String unseenText = imap_log.get(4);
        unseenText = unseenText.substring(unseenText.indexOf('(') + 1, unseenText.indexOf(')'));
        int unseenCount = Integer.parseInt(unseenText.split(" ")[1]);

        System.out.println(unseenCount);
        //imap_log.indexOf("UNSEEN ")
    } catch (IOException e) {
        System.out.println(imap.getReplyString());
        e.printStackTrace();
        System.exit(10);
        return;
    }
}

From source file:com.javacreed.examples.spring.Example2.java

public static void main(final String[] args) throws Exception {
    final ComboPooledDataSource ds = DbUtils.createDs();
    try {/*from w ww .ja  va 2 s. co m*/
        final JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);

        Example2.LOGGER.debug("Reading all rows");
        final List<Data> rows = jdbcTemplate.query(new StreamingStatementCreator("SELECT * FROM `big_table`"),
                Data.ROW_MAPPER);

        Example2.LOGGER.debug("All records read ({} records)", rows.size());

        // Sleep a bit so that it shows better on the profiler
        TimeUnit.SECONDS.sleep(10);
    } finally {
        DbUtils.closeQuietly(ds);
    }
    Example2.LOGGER.debug("Done");
}

From source file:com.github.ipaas.ifw.front.rewrite.FisRewrite.java

public static void main(String[] args) {
    try {//from   w ww .j ava2s. co m
        FisRewrite fr = new FisRewrite();
        List<FisRewriteRule> rules = fr.getRules();
        for (int i = 0; i < rules.size(); i++) {
            FisRewriteRule rule = rules.get(i);
            System.out.println(rule.getRequestUri());
            System.out.println(rule.getTemplateFile());
            List<String> dataFiles = rule.getDataFiles();
            if (null != dataFiles) {
                for (int j = 0, len = dataFiles.size(); i < len; i++) {
                    System.out.println(dataFiles.get(i));
                }
            }

        }
        String requestUri = "/index.shtml";
        FisRewriteRule frRule = fr.findRule(requestUri);
        System.out.println("find : " + frRule.getRequestUri());
    } catch (FisException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:sqsAlertInbound.java

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

    // get credentials
    String user = "jreilly";
    AWSCredentials credentials = whgHelper.getCred(user);

    // use credentials to set access to SQS
    AmazonSQS sqs = whgHelper.setQueueAccess(credentials);

    // define queue that messages will be retrieved from
    String thisQueue = "alertInbound";
    String nextQueue = "alertPersist";

    while (1 > 0) {

        // pull list of current messages (up to 10) in the queue
        List<Message> messages = whgHelper.getMessagesFromQueue(thisQueue, sqs);
        System.out.println("Count of messages in " + thisQueue + ": " + messages.size());

        try {/*from  w  w w . j  a v a 2s . c  o  m*/

            for (Message message : messages) {

                whgHelper.printMessage(message);
                for (Entry<String, String> entry : message.getAttributes().entrySet()) {
                    whgHelper.printMessageEntry(entry);
                }

                // validate JSON for completeness and form and handle errors
                //               if (sqs == null) {
                //                  sqs.sendMessage(new SendMessageRequest("alertErrorHandling", message.getBody()));
                //               }

                // call a function to transform message
                String alertJSON = String.valueOf(Base64.decodeBase64(message.getBody()));
                System.out.println("Transformed JSON: " + alertJSON);

                // send message to next queue
                System.out.println("Sending message to next queue.");
                sqs.sendMessage(new SendMessageRequest(nextQueue, alertJSON));

                // delete message from this queue
                System.out.println("Deleting message.\n");
                String messageRecieptHandle = message.getReceiptHandle();
                sqs.deleteMessage(new DeleteMessageRequest(thisQueue, messageRecieptHandle));

            }
            Thread.sleep(20000); // do nothing for 1000 miliseconds (1 second)

        } catch (AmazonServiceException ase) {
            whgHelper.errorMessagesAse(ase);
        } catch (AmazonClientException ace) {
            whgHelper.errorMessagesAce(ace);
        }
    }
}

From source file:com.google.demo.translate.Translator.java

public static void main(String[] args) {
    parseInputs();//from   ww  w  .java2  s .  c  om

    try {
        String headers = String.join(",", source,
                targets.stream().map(i -> i.toString()).collect(Collectors.joining(",")));

        Files.write(output, Arrays.asList(headers), UTF_8, APPEND, CREATE);

        List<String> texts = new ArrayList<>();
        while (it.hasNext()) {
            texts.add(preTranslationParser(it.next()));
            if (texts.size() == 10 || !it.hasNext()) {
                translate(texts);
                texts = new ArrayList<>();
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        LineIterator.closeQuietly(it);
    }
}

From source file:de.unisb.cs.st.javalanche.mutation.util.CsvWriter.java

public static void main(String[] args) throws IOException {
    // Set<Long> covered = MutationCoverageFile.getCoveredMutations();
    // List<Long> mutationIds = QueryManager.getMutationsWithoutResult(
    // covered, 0);

    Session session = HibernateUtil.getSessionFactory().openSession();
    List<Mutation> mutations = QueryManager.getMutationsForProject(
            ConfigurationLocator.getJavalancheConfiguration().getProjectPrefix(), session);

    logger.info("Got " + mutations.size() + " mutation ids.");
    List<String> lines = new ArrayList<String>();
    lines.add(Mutation.getCsvHead() + ",DETECTED");
    int counter = 0;
    int flushs = 0;
    StopWatch stp = new StopWatch();
    for (Mutation mutation : mutations) {
        // Mutation mutation = QueryManager.getMutationByID(id, session);
        lines.add(mutation.getCsvString() + "," + mutation.isKilled());
        counter++;//from  w ww . j ava 2 s  .com
        if (counter > 20) {
            counter = 0;
            // 20, same as the JDBC batch size
            // flush a batch of inserts and release memory:
            // see
            // http://www.hibernate.org/hib_docs/reference/en/html/batch.html
            stp.reset();
            stp.start();
            flushs++;
            session.flush();
            // session.clear();
            logger.info("Did flush. It took: " + DurationFormatUtils.formatDurationHMS(stp.getTime()));
        }
    }
    session.close();
    logger.info("Starting to write file with " + lines.size() + " entries.");
    FileUtils.writeLines(new File("mutations.csv"), lines);
}

From source file:cz.muni.fi.mir.mathmlcanonicalization.MathMLCanonicalizerCommandLineTool.java

/**
 * @param args the command line arguments
 *///ww w  .  j  a v  a  2s  .c  om
public static void main(String[] args) throws FileNotFoundException, XMLStreamException {
    final Options options = new Options();
    options.addOption("c", true, "load configuration file");
    options.addOption("dtd", false,
            "enforce injection of XHTML + MathML 1.1 DTD reference into input documents");
    options.addOption("w", false, "overwrite input files by canonical outputs");
    options.addOption("h", false, "print help");

    final CommandLineParser parser = new PosixParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (ParseException ex) {
        printHelp(options);
        System.exit(1);
    }

    File config = null;
    boolean overwrite = false;
    boolean dtdInjectionMode = false;
    if (line != null) {
        if (line.hasOption('c')) {
            config = new File(args[1]);
        }

        if (line.hasOption("dtd")) {
            dtdInjectionMode = true;
        }

        if (line.hasOption('w')) {
            overwrite = true;
        }

        if (line.hasOption('h')) {
            printHelp(options);
            System.exit(0);
        }

        final List<String> arguments = Arrays.asList(line.getArgs());
        if (arguments.size() > 0) {
            for (String arg : arguments) {
                try {
                    List<File> files = getFiles(new File(arg));
                    for (File file : files) {
                        canonicalize(file, config, dtdInjectionMode, overwrite);
                    }
                } catch (IOException ex) {
                    Logger.getLogger(MathMLCanonicalizerCommandLineTool.class.getName()).log(Level.SEVERE,
                            ex.getMessage(), ex);
                } catch (ConfigException ex) {
                    Logger.getLogger(MathMLCanonicalizerCommandLineTool.class.getName()).log(Level.SEVERE,
                            ex.getMessage(), ex);
                } catch (JDOMException ex) {
                    Logger.getLogger(MathMLCanonicalizerCommandLineTool.class.getName()).log(Level.SEVERE,
                            ex.getMessage(), ex);
                } catch (ModuleException ex) {
                    Logger.getLogger(MathMLCanonicalizerCommandLineTool.class.getName()).log(Level.SEVERE,
                            ex.getMessage(), ex);
                }
            }
        } else {
            printHelp(options);
            System.exit(0);
        }
    }
}

From source file:com.linkedin.pinot.perf.FilterOperatorBenchmark.java

public static void main(String[] args) throws Exception {
    String rootDir = args[0];/* ww  w  .ja  va 2s.co  m*/
    File[] segmentDirs = new File(rootDir).listFiles();
    String query = args[1];
    AtomicInteger totalDocsMatched = new AtomicInteger(0);
    Pql2Compiler pql2Compiler = new Pql2Compiler();
    BrokerRequest brokerRequest = pql2Compiler.compileToBrokerRequest(query);
    List<Callable<Void>> segmentProcessors = new ArrayList<>();
    long[] timesSpent = new long[segmentDirs.length];
    for (int i = 0; i < segmentDirs.length; i++) {
        File indexSegmentDir = segmentDirs[i];
        System.out.println("Loading " + indexSegmentDir.getName());
        Configuration tableDataManagerConfig = new PropertiesConfiguration();
        List<String> invertedColumns = new ArrayList<>();
        FilenameFilter filter = new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".bitmap.inv");
            }
        };
        String[] indexFiles = indexSegmentDir.list(filter);
        for (String indexFileName : indexFiles) {
            invertedColumns.add(indexFileName.replace(".bitmap.inv", ""));
        }
        tableDataManagerConfig.setProperty(IndexLoadingConfigMetadata.KEY_OF_LOADING_INVERTED_INDEX,
                invertedColumns);
        IndexLoadingConfigMetadata indexLoadingConfigMetadata = new IndexLoadingConfigMetadata(
                tableDataManagerConfig);
        IndexSegmentImpl indexSegmentImpl = (IndexSegmentImpl) Loaders.IndexSegment.load(indexSegmentDir,
                ReadMode.heap, indexLoadingConfigMetadata);
        segmentProcessors
                .add(new SegmentProcessor(i, indexSegmentImpl, brokerRequest, totalDocsMatched, timesSpent));
    }
    ExecutorService executorService = Executors.newCachedThreadPool();
    for (int run = 0; run < 5; run++) {
        System.out.println("START RUN:" + run);
        totalDocsMatched.set(0);
        long start = System.currentTimeMillis();
        List<Future<Void>> futures = executorService.invokeAll(segmentProcessors);
        for (int i = 0; i < futures.size(); i++) {
            futures.get(i).get();
        }
        long end = System.currentTimeMillis();
        System.out.println("Total docs matched:" + totalDocsMatched + " took:" + (end - start));
        System.out.println("Times spent:" + Arrays.toString(timesSpent));
        System.out.println("END RUN:" + run);
    }
    System.exit(0);
}