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:SafeListCopy.java

public static void main(String[] args) {
    List wordList = Collections.synchronizedList(new ArrayList());

    wordList.add("Synchronization");
    wordList.add("is");
    wordList.add("important");

    String[] wordA = (String[]) wordList.toArray(new String[0]);

    printWords(wordA);/*from  w w w .j  a  v a2 s.  c  o  m*/

    String[] wordB;
    synchronized (wordList) {
        int size = wordList.size();
        wordB = new String[size];
        wordList.toArray(wordB);
    }

    printWords(wordB);

    // Third technique (the 'synchronized' *is* necessary)
    String[] wordC;
    synchronized (wordList) {
        wordC = (String[]) wordList.toArray(new String[wordList.size()]);
    }

    printWords(wordC);
}

From source file:com.cloudera.recordbreaker.analyzer.FormatAnalyzer.java

/**
 * Describe <code>main</code> method here.
 *
 * @param argv[] a <code>String</code> value
 * @exception IOException if an error occurs
 *//*  w  w w . j  a va  2 s.  c om*/
public static void main(String argv[]) throws IOException {
    if (argv.length < 1) {
        System.err.println("Usage: FormatAnalyzer <inputfile> <schemaDbDir>");
        return;
    }

    FileSystem fs = FileSystem.getLocal(null);
    Path inputFile = new Path(new File(argv[0]).getCanonicalPath());
    File schemaDbDir = new File(argv[1]).getCanonicalFile();
    FormatAnalyzer fa = new FormatAnalyzer(schemaDbDir);

    DataDescriptor descriptor = fa.describeData(fs, inputFile);
    System.err.println("Filename: " + descriptor.getFilename());
    System.err.println("Filetype identifier: " + descriptor.getFileTypeIdentifier());
    List<SchemaDescriptor> schemas = descriptor.getSchemaDescriptor();
    if (schemas == null) {
        System.err.println("No schema found.");
    } else {
        System.err.println("Num schemas found: " + schemas.size());
        System.err.println();
        for (SchemaDescriptor sd : schemas) {
            Schema s = sd.getSchema();
            System.err.println("Schema src desc: " + sd.getSchemaSourceDescription());
            System.err.println();
            System.err.println("Schema identifier: " + sd.getSchemaIdentifier());
            System.err.println();
            int i = 0;
            for (Iterator it = sd.getIterator(); it.hasNext();) {
                GenericData.Record curRow = (GenericData.Record) it.next();
                System.err.println(i + ". Elt: " + curRow);
                i++;
            }
        }
    }
}

From source file:com.aerospike.examples.frequencycap.FrequencyCap.java

public static void main(String[] args) throws AerospikeException {
    try {// w w w . ja v a2s .  c  o  m
        Options options = new Options();
        options.addOption("h", "host", true, "Server hostname (default: 172.28.128.6)");
        options.addOption("p", "port", true, "Server port (default: 3000)");
        options.addOption("n", "namespace", true, "Namespace (default: test)");
        options.addOption("u", "usage", false, "Print usage.");

        options.addOption("l", "load", false, "Load data.");

        CommandLineParser parser = new PosixParser();
        CommandLine cl = parser.parse(options, args, false);

        String host = cl.getOptionValue("h", "172.28.128.6");
        String portString = cl.getOptionValue("p", "3000");
        int port = Integer.parseInt(portString);
        String namespace = cl.getOptionValue("n", "test");
        String set = cl.getOptionValue("s", "demo");
        log.debug("Host: " + host);
        log.debug("Port: " + port);
        log.debug("Namespace: " + namespace);
        log.debug("Set: " + set);

        @SuppressWarnings("unchecked")
        List<String> cmds = cl.getArgList();
        if (cmds.size() == 0 && cl.hasOption("u")) {
            logUsage(options);
            return;
        }

        FrequencyCap as = new FrequencyCap(host, port, namespace, set);
        if (cl.hasOption("l")) {
            as.generateDataDateInKey();
            as.generateDataDateInBin();
        } else {
            as.simulateWorkDateInKey();
            as.simulateWorkDateInBin();
        }
    } catch (Exception e) {
        log.error("Critical error", e);
    }
}

From source file:com.cyberway.issue.io.Arc2Warc.java

/**
 * Command-line interface to Arc2Warc./*from   ww w.j av a  2 s. c  om*/
 *
 * @param args Command-line arguments.
 * @throws ParseException Failed parse of the command line.
 * @throws IOException
 * @throws java.text.ParseException
 */
public static void main(String[] args) throws ParseException, IOException, java.text.ParseException {
    Options options = new Options();
    options.addOption(new Option("h", "help", false, "Prints this message and exits."));
    options.addOption(new Option("f", "force", false, "Force overwrite of target file."));
    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.
    boolean force = false;
    for (int i = 0; i < cmdlineOptions.length; i++) {
        switch (cmdlineOptions[i].getId()) {
        case 'h':
            usage(formatter, options, 0);
            break;

        case 'f':
            force = true;
            break;

        default:
            throw new RuntimeException("Unexpected option: " + +cmdlineOptions[i].getId());
        }
    }

    // If no args, print help.
    if (cmdlineArgs.size() != 2) {
        usage(formatter, options, 0);
    }
    (new Arc2Warc()).transform(new File(cmdlineArgs.get(0).toString()), new File(cmdlineArgs.get(1).toString()),
            force);
}

From source file:com.ibm.watson.app.qaclassifier.tools.PopulateAnswerStore.java

public static void main(String[] args) throws Exception {
    Option urlOption = createOption(URL_OPTION, URL_OPTION_LONG, true,
            "The root URL of the application to connect to. If omitted, the default will be used ("
                    + DEFAULT_URL + ")",
            false, URL_OPTION_LONG);
    Option fileOption = createOption(FILE_OPTION, FILE_OPTION_LONG, true,
            "The file to be used to populate the answers, can point to the file system or the class path", true,
            FILE_OPTION_LONG);//from  w w w . ja v  a2 s.c om
    Option dirOption = createOption(DIR_OPTION, DIR_OPTION_LONG, true,
            "The directory containing the html answer files, can point to the file system or the class path",
            true, DIR_OPTION_LONG);
    Option userOption = createOption(USER_OPTION, USER_OPTION_LONG, true, "The username for the manage API",
            true, USER_OPTION_LONG);
    Option passwordOption = createOption(PASSWORD_OPTION, PASSWORD_OPTION_LONG, true,
            "The password for the manage API", true, PASSWORD_OPTION_LONG);

    final Options options = buildOptions(urlOption, fileOption, dirOption, userOption, passwordOption);

    CommandLine cmd;
    try {
        CommandLineParser parser = new GnuParser();
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(MessageKey.AQWQAC24008E_could_not_parse_cmd_line_args_1.getMessage(e.getMessage())
                .getFormattedMessage());

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(120, "java " + PopulateAnswerStore.class.getName(), null, options, null);
        return;
    }

    final String url = cmd.getOptionValue(URL_OPTION, DEFAULT_URL);
    final String file = cmd.getOptionValue(FILE_OPTION);
    final String dir = cmd.getOptionValue(DIR_OPTION);
    final String user = cmd.getOptionValue(USER_OPTION);
    final String password = cmd.getOptionValue(PASSWORD_OPTION);

    System.out.println(MessageKey.AQWQAC20002I_checking_answer_store_at_url_2.getMessage(url, DEFAULT_ENDPOINT)
            .getFormattedMessage());

    try {
        AnswerStoreRestClient client = new AnswerStoreRestClient(url, user, password);

        // we only want to populate if there is nothing in the database already
        // start with the assumption that we do want to populate and stop if we find answers in there already
        boolean doPopulate = true;
        String answersResult = getAnswers(client);
        if (answersResult != null && !answersResult.isEmpty()) {
            Gson gson = new Gson();
            Type type = new TypeToken<List<ManagedAnswer>>() {
            }.getType();
            List<ManagedAnswer> answers = gson.fromJson(answersResult, type);
            if (answers != null && answers.size() > 0) {
                System.out.println(MessageKey.AQWQAC20006I_found_answers_in_stop_1.getMessage(answers.size())
                        .getFormattedMessage());
                doPopulate = false;
            }
        }

        if (doPopulate) {
            System.out.println(MessageKey.AQWQAC20003I_populating_answer_store_at_url_2
                    .getMessage(url, DEFAULT_ENDPOINT).getFormattedMessage());
            boolean success = populate(client, file, dir);
            if (!success) {
                throw new RuntimeException(MessageKey.AQWQAC24005E_error_populating_answer_store.getMessage()
                        .getFormattedMessage());
            }
        } else {
            System.out.println(MessageKey.AQWQAC20001I_answer_store_already_populated_doing_nothing.getMessage()
                    .getFormattedMessage());
        }

        System.out.println(MessageKey.AQWQAC20005I_done_population_answers.getMessage().getFormattedMessage());
    } catch (IOException e) {
        System.err.println(MessageKey.AQWQAC24007E_error_populating_answer_store_1.getMessage(e.getMessage())
                .getFormattedMessage());
        e.printStackTrace(System.err);
    }
}

From source file:com.spotify.helios.Utils.java

public static ByteArrayOutputStream main(final List<String> args) throws Exception {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final ByteArrayOutputStream err = new ByteArrayOutputStream();
    final CliMain main = new CliMain(new PrintStream(out), new PrintStream(err),
            args.toArray(new String[args.size()]));
    main.run();/*from  ww w. j  a  va 2  s.c  o  m*/
    return out;
}

From source file:AmazonKinesisGet.java

public static void main(String[] args) throws Exception {
    init();/*ww  w.  j a va  2 s  .  c  o m*/

    final String myStreamName = "philsteststream";
    final Integer myStreamSize = 1;

    // list all of my streams
    ListStreamsRequest listStreamsRequest = new ListStreamsRequest();
    listStreamsRequest.setLimit(10);
    ListStreamsResult listStreamsResult = kinesisClient.listStreams(listStreamsRequest);
    List<String> streamNames = listStreamsResult.getStreamNames();
    while (listStreamsResult.isHasMoreStreams()) {
        if (streamNames.size() > 0) {
            listStreamsRequest.setExclusiveStartStreamName(streamNames.get(streamNames.size() - 1));
        }

        listStreamsResult = kinesisClient.listStreams(listStreamsRequest);

        streamNames.addAll(listStreamsResult.getStreamNames());

    }
    LOG.info("Printing my list of streams : ");

    // print all of my streams.
    if (!streamNames.isEmpty()) {
        System.out.println("List of my streams: ");
    }
    for (int i = 0; i < streamNames.size(); i++) {
        System.out.println(streamNames.get(i));
    }

    //System.out.println(streamNames.get(0));
    String myownstream = streamNames.get(0);

    // Retrieve the Shards from a Stream
    DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest();
    describeStreamRequest.setStreamName(myownstream);
    DescribeStreamResult describeStreamResult;
    List<Shard> shards = new ArrayList<>();
    String lastShardId = null;

    do {
        describeStreamRequest.setExclusiveStartShardId(lastShardId);
        describeStreamResult = kinesisClient.describeStream(describeStreamRequest);
        shards.addAll(describeStreamResult.getStreamDescription().getShards());
        if (shards.size() > 0) {
            lastShardId = shards.get(shards.size() - 1).getShardId();
        }
    } while (describeStreamResult.getStreamDescription().getHasMoreShards());

    // Get Data from the Shards in a Stream
    // Hard-coded to use only 1 shard
    String shardIterator;
    GetShardIteratorRequest getShardIteratorRequest = new GetShardIteratorRequest();
    getShardIteratorRequest.setStreamName(myownstream);
    //get(0) shows hardcoded to 1 stream
    getShardIteratorRequest.setShardId(shards.get(0).getShardId());
    // using TRIM_HORIZON but could use alternatives
    getShardIteratorRequest.setShardIteratorType("TRIM_HORIZON");

    GetShardIteratorResult getShardIteratorResult = kinesisClient.getShardIterator(getShardIteratorRequest);
    shardIterator = getShardIteratorResult.getShardIterator();

    // Continuously read data records from shard.
    List<Record> records;

    while (true) {
        // Create new GetRecordsRequest with existing shardIterator.
        // Set maximum records to return to 1000.

        GetRecordsRequest getRecordsRequest = new GetRecordsRequest();
        getRecordsRequest.setShardIterator(shardIterator);
        getRecordsRequest.setLimit(1000);

        GetRecordsResult result = kinesisClient.getRecords(getRecordsRequest);

        // Put result into record list. Result may be empty.
        records = result.getRecords();

        // Print records
        for (Record record : records) {
            ByteBuffer byteBuffer = record.getData();
            System.out.println(String.format("Seq No: %s - %s", record.getSequenceNumber(),
                    new String(byteBuffer.array())));
        }

        try {
            Thread.sleep(1000);
        } catch (InterruptedException exception) {
            throw new RuntimeException(exception);
        }

        shardIterator = result.getNextShardIterator();
    }

}

From source file:com.appeligo.epg.EpgIndexer.java

public static void main(String[] args) throws Exception {
    HessianProxyFactory factory = new HessianProxyFactory();
    EPGProvider epg = (EPGProvider) factory.create(EPGProvider.class, "http://localhost/epg/channel.epg");
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR, -5);//  ww  w. ja  va 2 s.  co m
    cal.set(Calendar.DATE, 1);
    String[] lineups = new String[] { "SDTW-C", "P-C", "P-DC", "P-S", "M-C", "M-DC", "M-S", "E-C", "E-DC",
            "E-S", "H-C", "H-DC", "H-S" };
    List<String> ids = epg.getModifiedProgramIds(cal.getTime());
    int count = 0;
    long average = 0;
    int counter = 0;
    int added = 0;
    while (count < ids.size()) {
        System.err.println("in loop: " + counter + ", " + count + "," + ids.size());
        int subsetSize = (ids.size() < 100 ? ids.size() : 100);
        counter++;
        if (count % 1000 == 0) {
            log.debug("Index programs into the Lucene Index. Current have processed " + count
                    + " programs out of " + ids.size());
        }
        int endIndex = (count + subsetSize > ids.size() ? ids.size() : count + subsetSize);
        List<String> subset = ids.subList(count, endIndex);
        count += subsetSize;

        long time = System.currentTimeMillis();
        HashMap<String, List<ScheduledProgram>> schedules = new HashMap<String, List<ScheduledProgram>>();
        for (String lineup : lineups) {
            ScheduledProgram[] programs = epg.getNextShowingList(lineup, subset);
            for (ScheduledProgram program : programs) {
                if (program != null) {
                    List<ScheduledProgram> schedule = schedules.get(program.getProgramId());
                    if (schedule == null) {
                        schedule = new ArrayList<ScheduledProgram>();
                        schedules.put(program.getProgramId(), schedule);
                    }
                    schedule.add(program);
                    added++;
                }
            }
        }
        long after = System.currentTimeMillis();
        long diff = after - time;
        average += diff;
        System.err.println(diff + " - " + (average / counter) + " added: " + added);
    }
    //      EpgIndexer indexer = new EpgIndexer(programIndex, epg, lineup);
    //      Calendar cal = Calendar.getInstance();
    //      cal.set(Calendar.DAY_OF_MONTH, 24);
    //      cal.set(Calendar.HOUR_OF_DAY, 0);
    //      indexer.updateEpgIndex(cal.getTime());
}

From source file:fr.ign.cogit.simplu3d.exe.DistributionGeneration.java

/**
 * @param args//w  w w.  j av a 2  s .com
 * @throws Exception
 */
public static void main(String[] args) throws Exception {

    IFeatureCollection<IFeature> featC = new FT_FeatureCollection<>();

    /*
     * < Retrieve the singleton instance of the parameters object...
     * initialize the parameters object with the default values provided...
     * parse the command line to eventually change the values >
     */
    Parameters p = Parameters
            .unmarshall(new File("./src/main/resources/scenario/building_parameters_project_expthese_1.xml"));
    EnvironnementOCL env = LoaderSHPOCL.load(p.getString("folder"));
    BasicPropertyUnit bpu = env.getBpU().get(1);

    ModelInstanceGraphConfigurationPredicate<Cuboid> pred = new ModelInstanceGraphConfigurationPredicate<Cuboid>(
            bpu, env.getUrbaZoneOCL().get(0));
    ModelInstanceGraphConfiguration<Cuboid> config = new ModelInstanceGraphConfiguration<>(bpu,
            pred.getRuleChecker().getlModeInstance().get(0), new ConstantEnergy<Cuboid, Cuboid>(0),
            new ConstantEnergy<Cuboid, Cuboid>(0));

    Sampler<ModelInstanceGraphConfiguration<Cuboid>, ModelInstanceModification<Cuboid>> samp = create_sampler(p,
            bpu, pred);

    // int count = 0;

    int testC = 5000;

    // int countTrue = 0;

    for (int i = 0; i < testC; i++) {

        // count++;

        ModelInstanceModification<Cuboid> modif = config.newModification();

        KernelFunctor<ModelInstanceGraphConfiguration<Cuboid>, ModelInstanceModification<Cuboid>> kf = new KernelFunctor<>(
                Random.random(), config, modif);

        RandomApply.randomApply(0, samp.getKernels(), kf);

        boolean test = true; // samp.checkNonUpdateConfiguration(kf);

        List<Cuboid> lAB = (List<Cuboid>) kf.getModif().getBirth();

        if (test) {

            // countTrue++;

            if (lAB.size() != 1) {
                System.out.println("Probabilit suprieure  1 ?");
                return;
            }

            Cuboid c1 = lAB.get(0);

            IFeature f = new DefaultFeature();
            f.setGeom(new GM_Point(new DirectPosition(c1.centerx, c1.centery)));

            AttributeManager.addAttribute(f, "l", c1.length, "Double");
            AttributeManager.addAttribute(f, "w", c1.width, "Double");
            AttributeManager.addAttribute(f, "h", c1.height, "Double");
            AttributeManager.addAttribute(f, "o", c1.orientation, "Double");

            featC.add(f);
        }

    }

    ShapefileWriter.write(featC, "H:/Distrib/dist.shp");

    ShapefileWriter.write(featCD, "H:/Distrib/distdeb.shp");

}

From source file:kellinwood.zipsigner.cmdline.Main.java

public static void main(String[] args) {
    try {//from w  w w  . j  av  a2s  .c  om

        Options options = new Options();
        CommandLine cmdLine = null;
        Option helpOption = new Option("h", "help", false, "Display usage information");

        Option modeOption = new Option("m", "keymode", false,
                "Keymode one of: auto, auto-testkey, auto-none, media, platform, shared, testkey, none");
        modeOption.setArgs(1);

        Option keyOption = new Option("k", "key", false, "PCKS#8 encoded private key file");
        keyOption.setArgs(1);

        Option pwOption = new Option("p", "keypass", false, "Private key password");
        pwOption.setArgs(1);

        Option certOption = new Option("c", "cert", false, "X.509 public key certificate file");
        certOption.setArgs(1);

        Option sbtOption = new Option("t", "template", false, "Signature block template file");
        sbtOption.setArgs(1);

        Option keystoreOption = new Option("s", "keystore", false, "Keystore file");
        keystoreOption.setArgs(1);

        Option aliasOption = new Option("a", "alias", false, "Alias for key/cert in the keystore");
        aliasOption.setArgs(1);

        options.addOption(helpOption);
        options.addOption(modeOption);
        options.addOption(keyOption);
        options.addOption(certOption);
        options.addOption(sbtOption);
        options.addOption(pwOption);
        options.addOption(keystoreOption);
        options.addOption(aliasOption);

        Parser parser = new BasicParser();

        try {
            cmdLine = parser.parse(options, args);
        } catch (MissingOptionException x) {
            System.out.println("One or more required options are missing: " + x.getMessage());
            usage(options);
        } catch (ParseException x) {
            System.out.println(x.getClass().getName() + ": " + x.getMessage());
            usage(options);
        }

        if (cmdLine.hasOption(helpOption.getOpt()))
            usage(options);

        Properties log4jProperties = new Properties();
        log4jProperties.load(new FileReader("log4j.properties"));
        PropertyConfigurator.configure(log4jProperties);
        LoggerManager.setLoggerFactory(new Log4jLoggerFactory());

        List<String> argList = cmdLine.getArgList();
        if (argList.size() != 2)
            usage(options);

        ZipSigner signer = new ZipSigner();

        signer.addAutoKeyObserver(new Observer() {
            @Override
            public void update(Observable observable, Object o) {
                System.out.println("Signing with key: " + o);
            }
        });

        Class bcProviderClass = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider");
        Provider bcProvider = (Provider) bcProviderClass.newInstance();

        KeyStoreFileManager.setProvider(bcProvider);

        signer.loadProvider("org.spongycastle.jce.provider.BouncyCastleProvider");

        PrivateKey privateKey = null;
        if (cmdLine.hasOption(keyOption.getOpt())) {
            if (!cmdLine.hasOption(certOption.getOpt())) {
                System.out.println("Certificate file is required when specifying a private key");
                usage(options);
            }

            String keypw = null;
            if (cmdLine.hasOption(pwOption.getOpt()))
                keypw = pwOption.getValue();
            else {
                keypw = new String(readPassword("Key password"));
                if (keypw.equals(""))
                    keypw = null;
            }
            URL privateKeyUrl = new File(keyOption.getValue()).toURI().toURL();

            privateKey = signer.readPrivateKey(privateKeyUrl, keypw);
        }

        X509Certificate cert = null;
        if (cmdLine.hasOption(certOption.getOpt())) {

            if (!cmdLine.hasOption(keyOption.getOpt())) {
                System.out.println("Private key file is required when specifying a certificate");
                usage(options);
            }

            URL certUrl = new File(certOption.getValue()).toURI().toURL();
            cert = signer.readPublicKey(certUrl);
        }

        byte[] sigBlockTemplate = null;
        if (cmdLine.hasOption(sbtOption.getOpt())) {
            URL sbtUrl = new File(sbtOption.getValue()).toURI().toURL();
            sigBlockTemplate = signer.readContentAsBytes(sbtUrl);
        }

        if (cmdLine.hasOption(keyOption.getOpt())) {
            signer.setKeys("custom", cert, privateKey, sigBlockTemplate);
            signer.signZip(argList.get(0), argList.get(1));
        } else if (cmdLine.hasOption(modeOption.getOpt())) {
            signer.setKeymode(modeOption.getValue());
            signer.signZip(argList.get(0), argList.get(1));
        } else if (cmdLine.hasOption((keystoreOption.getOpt()))) {
            String alias = null;

            if (!cmdLine.hasOption(aliasOption.getOpt())) {

                KeyStore keyStore = KeyStoreFileManager.loadKeyStore(keystoreOption.getValue(), (char[]) null);
                for (Enumeration<String> e = keyStore.aliases(); e.hasMoreElements();) {
                    alias = e.nextElement();
                    System.out.println("Signing with key: " + alias);
                    break;
                }
            } else
                alias = aliasOption.getValue();

            String keypw = null;
            if (cmdLine.hasOption(pwOption.getOpt()))
                keypw = pwOption.getValue();
            else {
                keypw = new String(readPassword("Key password"));
                if (keypw.equals(""))
                    keypw = null;
            }

            CustomKeySigner.signZip(signer, keystoreOption.getValue(), null, alias, keypw.toCharArray(),
                    "SHA1withRSA", argList.get(0), argList.get(1));
        } else {
            signer.setKeymode("auto-testkey");
            signer.signZip(argList.get(0), argList.get(1));
        }

    } catch (Throwable t) {
        t.printStackTrace();
    }
}