Example usage for java.util List add

List of usage examples for java.util List add

Introduction

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

Prototype

boolean add(E e);

Source Link

Document

Appends the specified element to the end of this list (optional operation).

Usage

From source file:fr.inria.atlanmod.kyanos.benchmarks.KyanosMapCreator.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input file");
    inputOpt.setArgs(1);//w  w  w .  j a  v  a  2  s  .  c o m
    inputOpt.setRequired(true);

    Option outputOpt = OptionBuilder.create(OUT);
    outputOpt.setArgName("OUTPUT");
    outputOpt.setDescription("Output directory");
    outputOpt.setArgs(1);
    outputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(outputOpt);
    options.addOption(inClassOpt);

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoMapURI.NEO_MAP_SCHEME,
                new MapPersistenceBackendFactory());

        CommandLine commandLine = parser.parse(options, args);

        URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN));
        URI targetUri = NeoMapURI.createNeoMapURI(new File(commandLine.getOptionValue(OUT)));

        Class<?> inClazz = KyanosMapCreator.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();

        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoMapURI.NEO_MAP_SCHEME,
                PersistentResourceFactory.eINSTANCE);

        Resource sourceResource = resourceSet.createResource(sourceUri);
        Map<String, Object> loadOpts = new HashMap<String, Object>();
        if ("zxmi".equals(sourceUri.fileExtension())) {
            loadOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE);
        }

        Runtime.getRuntime().gc();
        long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory before loading: {0}",
                MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
        LOG.log(Level.INFO, "Loading source resource");
        sourceResource.load(loadOpts);

        LOG.log(Level.INFO, "Source resource loaded");
        Runtime.getRuntime().gc();
        long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory after loading: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
        LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));

        Resource targetResource = resourceSet.createResource(targetUri);

        Map<String, Object> saveOpts = new HashMap<String, Object>();
        List<StoreOption> storeOptions = new ArrayList<StoreOption>();
        storeOptions.add(MapResourceOptions.EStoreMapOption.AUTOCOMMIT);
        saveOpts.put(MapResourceOptions.STORE_OPTIONS, storeOptions);
        targetResource.save(saveOpts);

        LOG.log(Level.INFO, "Start moving elements");
        targetResource.getContents().clear();
        targetResource.getContents().addAll(sourceResource.getContents());
        LOG.log(Level.INFO, "End moving elements");
        LOG.log(Level.INFO, "Start saving");
        targetResource.save(saveOpts);
        LOG.log(Level.INFO, "Saved");

        if (targetResource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) targetResource);
        } else {
            targetResource.unload();
        }

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
        e.printStackTrace();
    }
}

From source file:com.manydesigns.portofino.utils.JsonMapper.java

/**
 * //  ww w. j a  v  a2 s. co m
 */
public static void main(String[] args) {
    // 
    List<String> months = Lists.newArrayList();
    for (int t_i = 1; t_i <= 12; t_i++) {
        months.add(t_i + "");
    }
    String json = JsonMapper.getInstance().toJson(months);
    System.out.println(json);

    List<Map<String, Object>> list = Lists.newArrayList();
    Map<String, Object> map = Maps.newHashMap();
    map.put("id", 1);
    map.put("pId", -1);
    map.put("name", "");
    list.add(map);
    map = Maps.newHashMap();
    map.put("id", 2);
    map.put("pId", 1);
    map.put("name", "");
    map.put("open", true);
    list.add(map);
    json = JsonMapper.getInstance().toJson(list);
    System.out.println(json);
}

From source file:ZipFileViewer.java

public static void main(String[] arg) throws Exception {
    String zipFileName = arg[0];//from w ww.ja va2  s. co m
    List zipFileList = null;
    ZipFile zipFile = new ZipFile(zipFileName);
    Enumeration zipEntries = zipFile.entries();
    zipFileList = new ArrayList();
    while (zipEntries.hasMoreElements()) {
        zipFileList.add((ZipEntry) (zipEntries.nextElement()));
    }
    ZipFileViewer zipFileViewer = new ZipFileViewer(zipFileName, zipFileList);
}

From source file:edu.cmu.lti.oaqa.annographix.apps.SolrQueryApp.java

public static void main(String[] args) {
    Options options = new Options();

    options.addOption("u", null, true, "Solr URI");
    options.addOption("q", null, true, "Query");
    options.addOption("n", null, true, "Max # of results");
    options.addOption("o", null, true, "An optional TREC-style output file");
    options.addOption("w", null, false, "Do a warm-up query call, before each query");

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    BufferedWriter trecOutFile = null;

    try {/*www . ja v  a  2  s .  c om*/
        CommandLine cmd = parser.parse(options, args);
        String queryFile = null, solrURI = null;

        if (cmd.hasOption("u")) {
            solrURI = cmd.getOptionValue("u");
        } else {
            Usage("Specify Solr URI");
        }

        SolrServerWrapper solr = new SolrServerWrapper(solrURI);

        if (cmd.hasOption("q")) {
            queryFile = cmd.getOptionValue("q");
        } else {
            Usage("Specify Query file");
        }

        int numRet = 100;

        if (cmd.hasOption("n")) {
            numRet = Integer.parseInt(cmd.getOptionValue("n"));
        }

        if (cmd.hasOption("o")) {
            trecOutFile = new BufferedWriter(new FileWriter(new File(cmd.getOptionValue("o"))));
        }

        List<String> fieldList = new ArrayList<String>();
        fieldList.add(UtilConst.ID_FIELD);
        fieldList.add(UtilConst.SCORE_FIELD);

        double totalTime = 0;
        double retQty = 0;

        ArrayList<Double> queryTimes = new ArrayList<Double>();

        boolean bDoWarmUp = cmd.hasOption("w");

        if (bDoWarmUp) {
            System.out.println("Using a warmup step!");
        }

        int queryQty = 0;
        for (String t : FileUtils.readLines(new File(queryFile))) {
            t = t.trim();
            if (t.isEmpty())
                continue;
            int ind = t.indexOf('|');
            if (ind < 0)
                throw new Exception("Wrong format, line: '" + t + "'");
            String qID = t.substring(0, ind);
            String q = t.substring(ind + 1);

            SolrDocumentList res = null;

            if (bDoWarmUp) {
                res = solr.runQuery(q, fieldList, numRet);
            }

            Long tm1 = System.currentTimeMillis();
            res = solr.runQuery(q, fieldList, numRet);
            Long tm2 = System.currentTimeMillis();
            retQty += res.getNumFound();
            System.out.println(qID + " Obtained: " + res.getNumFound() + " entries in " + (tm2 - tm1) + " ms");
            double delta = (tm2 - tm1);
            totalTime += delta;
            queryTimes.add(delta);
            ++queryQty;

            if (trecOutFile != null) {

                ArrayList<SolrRes> resArr = new ArrayList<SolrRes>();
                for (SolrDocument doc : res) {
                    String id = (String) doc.getFieldValue(UtilConst.ID_FIELD);
                    float score = (Float) doc.getFieldValue(UtilConst.SCORE_FIELD);
                    resArr.add(new SolrRes(id, "", score));
                }
                SolrRes[] results = resArr.toArray(new SolrRes[resArr.size()]);
                Arrays.sort(results);

                SolrEvalUtils.saveTrecResults(qID, results, trecOutFile, TREC_RUN, results.length);
            }
        }
        double devTime = 0, meanTime = totalTime / queryQty;
        for (int i = 0; i < queryQty; ++i) {
            double d = queryTimes.get(i) - meanTime;
            devTime += d * d;
        }
        devTime = Math.sqrt(devTime / (queryQty - 1));
        System.out.println(String.format("Query time, mean/standard dev: %.2f/%.2f (ms)", meanTime, devTime));
        System.out.println(String.format("Avg # of docs returned: %.2f", retQty / queryQty));

        solr.close();
        trecOutFile.close();
    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }

}

From source file:com.sm.store.server.ClusterServer.java

public static void main(String[] args) {
    String[] opts = new String[] { "-host", "-configPath", "-dataPath", "-port", "replicaPort", "-start",
            "-freq" };
    String[] defaults = new String[] { "", "", "", "0", "0", "true", "0" };
    String[] paras = getOpts(args, opts, defaults);

    String configPath = paras[1];
    if (configPath.length() == 0) {
        logger.error("missing config path");
        throw new RuntimeException("missing -configPath");
    }/*w ww  .  j ava  2s.  co  m*/
    //set configPath to system properties
    System.setProperty("configPath", configPath);
    NodeConfig nodeConfig = getNodeConfig(configPath + "/node.properties");
    //int clusterNo = Integer.valueOf( paras[0]);
    String dataPath = paras[2];
    if (dataPath.length() == 0) {
        dataPath = "./data";
    }
    int port = Integer.valueOf(paras[3]);
    int replicaPort = Integer.valueOf(paras[4]);
    //get from command line, if not form nodeConfig
    if (port == 0)
        port = nodeConfig.getPort();
    if (port == 0) {
        throw new RuntimeException("port is 0");
    } else {
        if (replicaPort == 0)
            replicaPort = port + 1;
    }
    boolean start = Boolean.valueOf(paras[5]);
    String host = paras[0];
    //get from command line, if not form nodeConfig or from getHost
    if (host.length() == 0)
        host = nodeConfig.getHost();
    if (host.length() == 0)
        host = getLocalHost();
    int freq = Integer.valueOf(paras[6]);
    logger.info("read clusterNode and storeConfig from " + configPath);
    BuildClusterNodes bcn = new BuildClusterNodes(configPath + "/clusters.xml");
    //BuildStoreConfig bsc = new BuildStoreConfig(configPath+"/stores.xml");
    BuildRemoteConfig brc = new BuildRemoteConfig(configPath + "/stores.xml");
    List<ClusterNodes> clusterNodesList = bcn.build();
    short clusterNo = findClusterNo(host + ":" + port, clusterNodesList);
    logger.info("create cluster server config for cluster " + clusterNo + " host " + host + " port " + port
            + " replica port " + replicaPort);
    ClusterServerConfig serverConfig = new ClusterServerConfig(clusterNodesList, brc.build().getConfigList(),
            clusterNo, dataPath, configPath, port, replicaPort, host);
    //over write config from command line if freq > 0
    if (freq > 0)
        serverConfig.setFreq(freq);
    logger.info("create cluster server");
    ClusterStoreServer cs = new ClusterStoreServer(serverConfig, new HessianSerializer());
    // start replica server
    cs.startReplicaServer();
    logger.info("hookup jvm shutdown process");
    cs.hookShutdown();
    if (start) {
        logger.info("server is starting " + cs.getServerConfig().toString());
        cs.start();
    } else
        logger.warn("server is staged and wait to be started");

    List list = new ArrayList();
    //add jmx metric
    List<String> stores = cs.getAllStoreNames();
    for (String store : stores) {
        list.add(cs.getStore(store));
    }
    list.add(cs);
    stores.add("ClusterServer");
    JmxService jms = new JmxService(list, stores);
}

From source file:com.coderadar.controller.MainController.java

public static void main(String[] args) {
    List<String> sortList = new ArrayList<String>();
    sortList.add("tc-5.5.x");
    sortList.add("tc-6.0.x");
    sortList.add("tc-7.0.x");
    sortList.add("tc-8.0.x");
    sortList.add("trunk");
    Collections.sort(sortList);//from  w  w w .jav a 2 s.  c  o m
    Collections.sort(sortList, Collections.reverseOrder());
    System.out.println("");
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Map map = new HashMap<String, String>();
    map.put("cluster", "10.200.111.111");
    map.put("cluster1", "10.200.121.111");

    Product xml = new Product();
    List<Top> top1 = new ArrayList<Top>();
    Set<String> keys = map.keySet();
    for (String key : keys) {
        Top top = new Top();
        top.setMode(key);/*from www.  ja v  a2s  . c  o  m*/
        top.setAddress((String) map.get(key));
        top1.add(top);
    }
    xml.setTop(top1);
    File file = new File("C:\\kar\\file.xml");
    JAXBContext jaxbContext = JAXBContext.newInstance(Product.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

    // output pretty printed
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    jaxbMarshaller.marshal(xml, file);
    jaxbMarshaller.marshal(xml, System.out);
}

From source file:com.liferay.nativity.test.TestDriver.java

public static void main(String[] args) {
    _intitializeLogging();//w w  w  .jav a 2 s . co m

    List<String> items = new ArrayList<String>();

    items.add("ONE");

    NativityMessage message = new NativityMessage("BLAH", items);

    try {
        _logger.debug(_objectMapper.writeValueAsString(message));
    } catch (JsonProcessingException jpe) {
        _logger.error(jpe.getMessage(), jpe);
    }

    _logger.debug("main");

    NativityControl nativityControl = NativityControlUtil.getNativityControl();

    FileIconControl fileIconControl = FileIconControlUtil.getFileIconControl(nativityControl,
            new TestFileIconControlCallback());

    ContextMenuControlUtil.getContextMenuControl(nativityControl, new TestContextMenuControlCallback());

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

    nativityControl.connect();

    String read = "";
    boolean stop = false;

    try {
        while (!stop) {
            _list = !_list;

            _logger.debug("Loop start...");

            _logger.debug("_enableFileIcons");
            _enableFileIcons(fileIconControl);

            _logger.debug("_registerFileIcon");
            _registerFileIcon(fileIconControl);

            _logger.debug("_setFilterPath");
            _setFilterPath(nativityControl);

            _logger.debug("_setSystemFolder");
            _setSystemFolder(nativityControl);

            _logger.debug("_updateFileIcon");
            _updateFileIcon(fileIconControl);

            _logger.debug("_clearFileIcon");
            _clearFileIcon(fileIconControl);

            _logger.debug("Ready?");

            if (bufferedReader.ready()) {
                _logger.debug("Reading...");

                read = bufferedReader.readLine();

                _logger.debug("Read {}", read);

                if (read.length() > 0) {
                    stop = true;
                }

                _logger.debug("Stopping {}", stop);
            }
        }
    } catch (IOException e) {
        _logger.error(e.getMessage(), e);
    }

    _logger.debug("Done");
}

From source file:com.github.fge.jsonschema.main.cli.Main.java

public static void main(final String... args) throws IOException, ProcessingException {
    final OptionParser parser = new OptionParser();
    parser.accepts("help", "show this help").forHelp();
    parser.acceptsAll(Arrays.asList("s", "brief"), "only show validation status (OK/NOT OK)");
    parser.acceptsAll(Arrays.asList("q", "quiet"), "no output; exit with the relevant return code (see below)");
    parser.accepts("syntax", "check the syntax of schema(s) given as argument(s)");
    parser.accepts("fakeroot", "pretend that the current directory is absolute URI \"uri\"").withRequiredArg();
    parser.formatHelpWith(HELP);/*  w ww. jav a2s  .  c  o m*/

    final OptionSet optionSet;
    final boolean isSyntax;
    final int requiredArgs;

    Reporter reporter = Reporters.DEFAULT;
    String fakeRoot = null;

    try {
        optionSet = parser.parse(args);
    } catch (OptionException e) {
        System.err.println("unrecognized option(s): " + CustomHelpFormatter.OPTIONS_JOINER.join(e.options()));
        parser.printHelpOn(System.err);
        System.exit(CMD_ERROR.get());
        throw new IllegalStateException("WTF??");
    }

    if (optionSet.has("help")) {
        parser.printHelpOn(System.out);
        System.exit(ALL_OK.get());
    }

    if (optionSet.has("s") && optionSet.has("q")) {
        System.err.println("cannot specify both \"--brief\" and " + "\"--quiet\"");
        parser.printHelpOn(System.err);
        System.exit(CMD_ERROR.get());
    }

    if (optionSet.has("fakeroot"))
        fakeRoot = (String) optionSet.valueOf("fakeroot");

    isSyntax = optionSet.has("syntax");
    requiredArgs = isSyntax ? 1 : 2;

    @SuppressWarnings("unchecked")
    final List<String> arguments = (List<String>) optionSet.nonOptionArguments();

    if (arguments.size() < requiredArgs) {
        System.err.println("missing arguments");
        parser.printHelpOn(System.err);
        System.exit(CMD_ERROR.get());
    }

    final List<File> files = Lists.newArrayList();
    for (final String target : arguments)
        files.add(new File(target).getCanonicalFile());

    if (optionSet.has("brief"))
        reporter = Reporters.BRIEF;
    else if (optionSet.has("quiet")) {
        System.out.close();
        System.err.close();
        reporter = Reporters.QUIET;
    }

    new Main(fakeRoot).proceed(reporter, files, isSyntax);
}

From source file:com.sm.store.server.grizzly.GZClusterServer.java

public static void main(String[] args) {
    String[] opts = new String[] { "-host", "-configPath", "-dataPath", "-port", "replicaPort", "-start",
            "-freq" };
    String[] defaults = new String[] { "", "", "", "0", "0", "true", "10" };
    String[] paras = getOpts(args, opts, defaults);

    String configPath = paras[1];
    if (configPath.length() == 0) {
        logger.error("missing config path");
        throw new RuntimeException("missing -configPath");
    }/*  w ww  .  j a  va2  s.com*/
    System.setProperty("configPath", configPath);
    NodeConfig nodeConfig = getNodeConfig(configPath + "/node.properties");
    //int clusterNo = Integer.valueOf( paras[0]);
    String dataPath = paras[2];
    if (dataPath.length() == 0) {
        dataPath = "./data";
    }
    int port = Integer.valueOf(paras[3]);
    int replicaPort = Integer.valueOf(paras[4]);
    //get from command line, if not form nodeConfig
    if (port == 0)
        port = nodeConfig.getPort();
    if (port == 0) {
        throw new RuntimeException("port is 0");
    } else {
        if (replicaPort == 0)
            replicaPort = port + 1;
    }
    boolean start = Boolean.valueOf(paras[5]);
    String host = paras[0];
    //get from command line, if not form nodeConfig or from getHost
    if (host.length() == 0)
        host = nodeConfig.getHost();
    if (host.length() == 0)
        host = getLocalHost();
    int freq = Integer.valueOf(paras[6]);
    logger.info("read clusterNode and storeConfig from " + configPath);
    BuildClusterNodes bcn = new BuildClusterNodes(configPath + "/clusters.xml");
    //BuildStoreConfig bsc = new BuildStoreConfig(configPath+"/stores.xml");
    BuildRemoteConfig brc = new BuildRemoteConfig(configPath + "/stores.xml");
    List<ClusterNodes> clusterNodesList = bcn.build();
    short clusterNo = findClusterNo(host + ":" + port, clusterNodesList);
    logger.info("create cluster server config for cluster " + clusterNo + " host " + host + " port " + port
            + " replica port " + replicaPort);
    ClusterServerConfig serverConfig = new ClusterServerConfig(clusterNodesList, brc.build().getConfigList(),
            clusterNo, dataPath, configPath, port, replicaPort, host);
    serverConfig.setFreq(freq);
    logger.info("create cluster server");
    GZClusterStoreServer cs = new GZClusterStoreServer(serverConfig, new HessianSerializer());
    // start replica server
    cs.startReplicaServer();
    logger.info("hookup jvm shutdown process");
    cs.hookShutdown();
    if (start) {
        logger.info("server is starting " + cs.getServerConfig().toString());
        cs.start();
    } else
        logger.warn("server is staged and wait to be started");

    List list = new ArrayList();
    //add jmx metric
    List<String> stores = cs.getAllStoreNames();
    for (String store : stores) {
        list.add(cs.getStore(store));
    }
    list.add(cs);
    stores.add("ClusterServer");
    JmxService jms = new JmxService(list, stores);

    try {
        logger.info("Read from console and wait ....");
        int c = System.in.read();
    } catch (IOException e) {
        logger.warn("Error reading " + e.getMessage());
    }
    logger.warn("Exiting from System.in.read()");
}