Example usage for java.util Collection add

List of usage examples for java.util Collection add

Introduction

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

Prototype

boolean add(E e);

Source Link

Document

Ensures that this collection contains the specified element (optional operation).

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);//from   w  w w . j  ava 2  s .  c  om
  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:Main.java

public static void main(String[] args) {
    // create array list
    List<Character> list = new ArrayList<Character>();

    // populate the list
    list.add('X');
    list.add('Y');

    System.out.println("Initial list: " + list);

    Collection<Character> immutablelist = Collections.unmodifiableCollection(list);

    // try to modify the list
    immutablelist.add('Z');
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    KeyPair pair = generateRSAKeyPair();

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    bOut.write(generateV1Certificate(pair).getEncoded());
    bOut.close();//w w w .  j  a v  a  2 s .com

    InputStream in = new ByteArrayInputStream(bOut.toByteArray());

    CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");

    X509Certificate x509Cert;
    Collection collection = new ArrayList();

    while ((x509Cert = (X509Certificate) fact.generateCertificate(in)) != null) {
        collection.add(x509Cert);
    }

    Iterator it = collection.iterator();
    while (it.hasNext()) {
        System.out.println("version: " + ((X509Certificate) it.next()).getVersion());
    }
}

From source file:cu.uci.gws.sdlcrawler.PdfCrawlController.java

public static void main(String[] args) throws Exception {
    Properties cm = PdfCrawlerConfigManager.getInstance().loadConfigFile();
    long startTime = System.currentTimeMillis();
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = new Date();
    System.out.println(dateFormat.format(date));
    int numberOfCrawlers = Integer.parseInt(cm.getProperty("sdlcrawler.NumberOfCrawlers"));
    String pdfFolder = cm.getProperty("sdlcrawler.CrawlPdfFolder");

    CrawlConfig config = new CrawlConfig();

    config.setCrawlStorageFolder(cm.getProperty("sdlcrawler.CrawlStorageFolder"));
    config.setProxyHost(cm.getProperty("sdlcrawler.ProxyHost"));
    if (!"".equals(cm.getProperty("sdlcrawler.ProxyPort"))) {
        config.setProxyPort(Integer.parseInt(cm.getProperty("sdlcrawler.ProxyPort")));
    }/*from www .  ja  va 2s  .  c  o m*/
    config.setProxyUsername(cm.getProperty("sdlcrawler.ProxyUser"));
    config.setProxyPassword(cm.getProperty("sdlcrawler.ProxyPass"));
    config.setMaxDownloadSize(Integer.parseInt(cm.getProperty("sdlcrawler.MaxDownloadSize")));
    config.setIncludeBinaryContentInCrawling(
            Boolean.parseBoolean(cm.getProperty("sdlcrawler.IncludeBinaryContent")));
    config.setFollowRedirects(Boolean.parseBoolean(cm.getProperty("sdlcrawler.Redirects")));
    config.setUserAgentString(cm.getProperty("sdlcrawler.UserAgent"));
    config.setMaxDepthOfCrawling(Integer.parseInt(cm.getProperty("sdlcrawler.MaxDepthCrawl")));
    config.setMaxConnectionsPerHost(Integer.parseInt(cm.getProperty("sdlcrawler.MaxConnectionsPerHost")));
    config.setSocketTimeout(Integer.parseInt(cm.getProperty("sdlcrawler.SocketTimeout")));
    config.setMaxOutgoingLinksToFollow(Integer.parseInt(cm.getProperty("sdlcrawler.MaxOutgoingLinks")));
    config.setResumableCrawling(Boolean.parseBoolean(cm.getProperty("sdlcrawler.ResumableCrawling")));
    config.setIncludeHttpsPages(Boolean.parseBoolean(cm.getProperty("sdlcrawler.IncludeHttpsPages")));
    config.setMaxTotalConnections(Integer.parseInt(cm.getProperty("sdlcrawler.MaxTotalConnections")));
    config.setMaxPagesToFetch(Integer.parseInt(cm.getProperty("sdlcrawler.MaxPagesToFetch")));
    config.setPolitenessDelay(Integer.parseInt(cm.getProperty("sdlcrawler.PolitenessDelay")));
    config.setConnectionTimeout(Integer.parseInt(cm.getProperty("sdlcrawler.ConnectionTimeout")));

    System.out.println(config.toString());
    Collection<BasicHeader> defaultHeaders = new HashSet<>();
    defaultHeaders
            .add(new BasicHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
    defaultHeaders.add(new BasicHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3"));
    defaultHeaders.add(new BasicHeader("Accept-Language", "en-US,en,es-ES,es;q=0.8"));
    defaultHeaders.add(new BasicHeader("Connection", "keep-alive"));
    config.setDefaultHeaders(defaultHeaders);

    List<String> list = Files.readAllLines(Paths.get("config/" + cm.getProperty("sdlcrawler.SeedFile")),
            StandardCharsets.UTF_8);
    String[] crawlDomains = list.toArray(new String[list.size()]);

    PageFetcher pageFetcher = new PageFetcher(config);
    RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
    RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
    CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
    for (String domain : crawlDomains) {
        controller.addSeed(domain);
    }

    PdfCrawler.configure(crawlDomains, pdfFolder);
    controller.start(PdfCrawler.class, numberOfCrawlers);
    DateFormat dateFormat1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date1 = new Date();
    System.out.println(dateFormat1.format(date1));
    long endTime = System.currentTimeMillis();
    long totalTime = endTime - startTime;
    System.out.println("Total time:" + totalTime);
}

From source file:org.apache.droids.examples.cli.SimpleRuntime.java

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

    if (args.length < 1) {
        System.out.println("Please specify a URL to crawl");
        System.exit(-1);/*w  ww. j  a  v a 2 s  .c  o  m*/
    }
    String targetURL = args[0];

    // Create parser factory. Support basic HTML markup only
    ParserFactory parserFactory = new ParserFactory();
    TikaDocumentParser tikaParser = new TikaDocumentParser();
    parserFactory.getMap().put("text/html", tikaParser);

    // Create protocol factory. Support HTTP/S only.
    ProtocolFactory protocolFactory = new ProtocolFactory();

    // Create and configure HTTP client
    HttpParams params = new BasicHttpParams();
    HttpProtocolParamBean hppb = new HttpProtocolParamBean(params);
    HttpConnectionParamBean hcpb = new HttpConnectionParamBean(params);
    ConnManagerParamBean cmpb = new ConnManagerParamBean(params);

    // Set protocol parametes
    hppb.setVersion(HttpVersion.HTTP_1_1);
    hppb.setContentCharset(HTTP.ISO_8859_1);
    hppb.setUseExpectContinue(true);
    // Set connection parameters
    hcpb.setStaleCheckingEnabled(false);
    // Set connection manager parameters
    ConnPerRouteBean connPerRouteBean = new ConnPerRouteBean();
    connPerRouteBean.setDefaultMaxPerRoute(2);
    cmpb.setConnectionsPerRoute(connPerRouteBean);

    DroidsHttpClient httpclient = new DroidsHttpClient(params);

    HttpProtocol httpProtocol = new HttpProtocol(httpclient);
    protocolFactory.getMap().put("http", httpProtocol);
    protocolFactory.getMap().put("https", httpProtocol);

    // Create URL filter factory.
    URLFiltersFactory filtersFactory = new URLFiltersFactory();
    RegexURLFilter defaultURLFilter = new RegexURLFilter();
    defaultURLFilter.setFile("classpath:/regex-urlfilter.txt");
    filtersFactory.getMap().put("default", defaultURLFilter);

    // Create handler factory. Provide sysout handler only.
    HandlerFactory handlerFactory = new HandlerFactory();
    SysoutHandler defaultHandler = new SysoutHandler();
    handlerFactory.getMap().put("default", defaultHandler);

    // Create droid factory. Leave it empty for now.
    DroidFactory<Link> droidFactory = new DroidFactory<Link>();

    // Create default droid
    SimpleDelayTimer simpleDelayTimer = new SimpleDelayTimer();
    simpleDelayTimer.setDelayMillis(100);

    Queue<Link> simpleQueue = new LinkedList<Link>();

    SequentialTaskMaster<Link> taskMaster = new SequentialTaskMaster<Link>();
    taskMaster.setDelayTimer(simpleDelayTimer);
    taskMaster.setExceptionHandler(new DefaultTaskExceptionHandler());

    CrawlingDroid helloCrawler = new SysoutCrawlingDroid(simpleQueue, taskMaster);
    helloCrawler.setFiltersFactory(filtersFactory);
    helloCrawler.setParserFactory(parserFactory);
    helloCrawler.setProtocolFactory(protocolFactory);

    Collection<String> initialLocations = new ArrayList<String>();
    initialLocations.add(targetURL);
    helloCrawler.setInitialLocations(initialLocations);

    // Initialize and start the crawler
    helloCrawler.init();
    helloCrawler.start();

    // Await termination
    helloCrawler.getTaskMaster().awaitTermination(0, TimeUnit.MILLISECONDS);
    // Shut down the HTTP connection manager
    httpclient.getConnectionManager().shutdown();
}

From source file:com.google.appengine.tools.pipeline.impl.util.JsonUtils.java

public static void main(String[] args) throws Exception {
    JSONObject x = new JSONObject();
    x.put("first", 5);
    x.put("second", 7);
    debugPrint("hello");
    debugPrint(7);//  w w w.ja  va 2s.c  om
    debugPrint(3.14159);
    debugPrint("");
    debugPrint('x');
    debugPrint(x);
    debugPrint(null);

    Map<String, Integer> map = new HashMap<>();
    map.put("first", 5);
    map.put("second", 7);
    debugPrint(map);

    int[] array = new int[] { 5, 7 };
    debugPrint(array);

    ArrayList<Integer> arrayList = new ArrayList<>(2);
    arrayList.add(5);
    arrayList.add(7);
    debugPrint(arrayList);

    Collection<Integer> collection = new HashSet<>(2);
    collection.add(5);
    collection.add(7);
    debugPrint(collection);

    Object object = new Object();
    debugPrint(object);

    Map<String, String> map1 = new HashMap<>();
    map1.put("a", "hello");
    map1.put("b", "goodbye");

    Object[] array2 = new Object[] { 17, "yes", "no", map1 };

    Map<String, Object> map2 = new HashMap<>();
    map2.put("first", 5.4);
    map2.put("second", array2);
    map2.put("third", map1);

    debugPrint(map2);

    class MyBean {
        @SuppressWarnings("unused")
        public int getX() {
            return 11;
        }

        @SuppressWarnings("unused")
        public boolean isHot() {
            return true;
        }

        @SuppressWarnings("unused")
        public String getName() {
            return "yellow";
        }
    }
    debugPrint(new MyBean());

}

From source file:com.glaf.core.util.JsonUtils.java

public static void main(String[] args) throws Exception {
    Map<String, Object> dataMap = new java.util.HashMap<String, Object>();
    dataMap.put("key01", "");
    dataMap.put("key02", 12345);
    dataMap.put("key03", 789.85D);
    dataMap.put("date", new Date());
    Collection<Object> actorIds = new HashSet<Object>();
    actorIds.add("sales01");
    actorIds.add("sales02");
    actorIds.add("sales03");
    actorIds.add("sales04");
    actorIds.add("sales05");
    dataMap.put("actorIds", actorIds.toArray());
    dataMap.put("x_sale_actor_actorIds", actorIds);

    Map<String, Object> xxxMap = new java.util.HashMap<String, Object>();
    xxxMap.put("0", "--------");
    xxxMap.put("1", "?");
    xxxMap.put("2", "");
    xxxMap.put("3", "");

    dataMap.put("trans", xxxMap);

    String str = JsonUtils.encode(dataMap);
    System.out.println(str);/*from   www .j  a  va  2  s.  com*/
    Map<?, ?> p = JsonUtils.decode(str);
    System.out.println(p);
    System.out.println(p.get("date").getClass().getName());

    String xx = "{name:\"trans\",nodeType:\"select\",children:{\"1\":\"?\",\"3\":\"\",\"2\":\"\",\"0\":\"--------\"}}";
    Map<String, Object> xMap = JsonUtils.decode(xx);
    System.out.println(xMap);
    Set<Entry<String, Object>> entrySet = xMap.entrySet();
    for (Entry<String, Object> entry : entrySet) {
        String key = entry.getKey();
        Object value = entry.getValue();
        System.out.println(key + " = " + value);
        System.out.println(key.getClass().getName() + "  " + value.getClass().getName());
        if (value instanceof JSONObject) {
            JSONObject json = (JSONObject) value;
            Iterator<?> iter = json.keySet().iterator();
            while (iter.hasNext()) {
                String kk = (String) iter.next();
                System.out.println(kk + " = " + json.get(kk));
            }
        }
    }
}

From source file:FileDialogMultipleFileNameSelection.java

public static void main(String[] args) {
    Display display = new Display();
    final Shell shell = new Shell(display);

    FileDialog dlg = new FileDialog(shell, SWT.MULTI);
    Collection files = new ArrayList();
    if (dlg.open() != null) {
        String[] names = dlg.getFileNames();
        for (int i = 0, n = names.length; i < n; i++) {
            StringBuffer buf = new StringBuffer(dlg.getFilterPath());
            if (buf.charAt(buf.length() - 1) != File.separatorChar)
                buf.append(File.separatorChar);
            buf.append(names[i]);//from   w  w w .  ja  va 2  s  .  com
            files.add(buf.toString());
        }
    }
    System.out.println(files);
    display.dispose();

}

From source file:edu.umn.msi.tropix.proteomics.tools.DTAToMzXML.java

public static void main(final String[] args) throws Exception {
    if (args.length < 1) {
        usage();//from   ww w  .ja  va2s . c om
        System.exit(0);
    }
    Collection<File> files = null;

    if (args[0].equals("-files")) {
        if (args.length < 2) {
            out.println("No files specified.");
            usage();
            exit(-1);
        } else {
            files = new ArrayList<File>(args.length - 1);
            for (int i = 1; i < args.length; i++) {
                files.add(new File(args[i]));
            }
        }
    } else if (args[0].equals("-directory")) {
        File directory;
        if (args.length < 2) {
            directory = new File(System.getProperty("user.dir"));
        } else {
            directory = new File(args[2]);
        }
        files = FileUtilsFactory.getInstance().listFiles(directory, new String[] { "dta" }, false);
    } else {
        usage();
        exit(-1);
    }

    final InMemoryDTAListImpl dtaList = new InMemoryDTAListImpl();
    File firstFile = null;
    if (files.size() == 0) {
        out.println("No files found.");
        exit(-1);
    } else {
        firstFile = files.iterator().next();
    }
    for (final File file : files) {
        dtaList.add(FileUtils.readFileToByteArray(file), file.getName());
    }

    final DTAToMzXMLConverter dtaToMzXMLConverter = new DTAToMzXMLConverterImpl();
    final MzXML mzxml = dtaToMzXMLConverter.dtaToMzXML(dtaList, null);
    final String mzxmlName = firstFile.getName().substring(0, firstFile.getName().indexOf(".")) + ".mzXML";
    new MzXMLUtility().serialize(mzxml, mzxmlName);
}

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;/* www. j av  a  2  s.  c om*/
    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");
}