List of usage examples for java.util List add
boolean add(E e);
From source file:edu.vt.middleware.ldap.search.PeopleSearch.java
/** * This provides command line access to a <code>PeopleSearch</code>. * * @param args <code>String[]</code> * * @throws Exception if an error occurs *///ww w .j a v a2s.co m public static void main(final String[] args) throws Exception { final PeopleSearch ps = createFromSpringContext("/peoplesearch-context.xml", "peopleSearch"); final Query query = new Query(); final List<String> attrs = new ArrayList<String>(); try { for (int i = 0; i < args.length; i++) { if ("-query".equals(args[i])) { query.setRawQuery(args[++i]); } else { attrs.add(args[i]); } } if (query.getRawQuery() == null) { throw new ArrayIndexOutOfBoundsException(); } if (!attrs.isEmpty()) { query.setQueryAttributes(attrs.toArray(new String[0])); } ps.search(query, OutputFormat.LDIF, new BufferedWriter(new OutputStreamWriter(System.out))); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Usage: java " + PeopleSearch.class.getName() + " -query <query> <attributes>"); System.exit(1); } }
From source file:edu.umd.cloud9.example.bigram.AnalyzeBigramRelativeFrequency.java
@SuppressWarnings({ "static-access" }) public static void main(String[] args) { Options options = new Options(); options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT)); CommandLine cmdline = null;//from w w w . j a va2 s .c om CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(INPUT)) { System.out.println("args: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(AnalyzeBigramRelativeFrequency.class.getName(), options); ToolRunner.printGenericCommandUsage(System.out); System.exit(-1); } String inputPath = cmdline.getOptionValue(INPUT); System.out.println("input path: " + inputPath); List<PairOfWritables<PairOfStrings, FloatWritable>> pairs = SequenceFileUtils .readDirectory(new Path(inputPath)); List<PairOfWritables<PairOfStrings, FloatWritable>> list1 = Lists.newArrayList(); List<PairOfWritables<PairOfStrings, FloatWritable>> list2 = Lists.newArrayList(); for (PairOfWritables<PairOfStrings, FloatWritable> p : pairs) { PairOfStrings bigram = p.getLeftElement(); if (bigram.getLeftElement().equals("light")) { list1.add(p); } if (bigram.getLeftElement().equals("contain")) { list2.add(p); } } Collections.sort(list1, new Comparator<PairOfWritables<PairOfStrings, FloatWritable>>() { public int compare(PairOfWritables<PairOfStrings, FloatWritable> e1, PairOfWritables<PairOfStrings, FloatWritable> e2) { if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) { return e1.getLeftElement().compareTo(e2.getLeftElement()); } return e2.getRightElement().compareTo(e1.getRightElement()); } }); Iterator<PairOfWritables<PairOfStrings, FloatWritable>> iter1 = Iterators.limit(list1.iterator(), 10); while (iter1.hasNext()) { PairOfWritables<PairOfStrings, FloatWritable> p = iter1.next(); PairOfStrings bigram = p.getLeftElement(); System.out.println(bigram + "\t" + p.getRightElement()); } Collections.sort(list2, new Comparator<PairOfWritables<PairOfStrings, FloatWritable>>() { public int compare(PairOfWritables<PairOfStrings, FloatWritable> e1, PairOfWritables<PairOfStrings, FloatWritable> e2) { if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) { return e1.getLeftElement().compareTo(e2.getLeftElement()); } return e2.getRightElement().compareTo(e1.getRightElement()); } }); Iterator<PairOfWritables<PairOfStrings, FloatWritable>> iter2 = Iterators.limit(list2.iterator(), 10); while (iter2.hasNext()) { PairOfWritables<PairOfStrings, FloatWritable> p = iter2.next(); PairOfStrings bigram = p.getLeftElement(); System.out.println(bigram + "\t" + p.getRightElement()); } }
From source file:com.maxpowered.amazon.advertising.api.app.App.java
public static void main(final String... args) throws FileNotFoundException, IOException, JAXBException, XMLStreamException, InterruptedException { try (ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("application-context.xml")) { /*/*from w ww .jav a 2s. c o m*/ * Get default options based on spring configs */ final String inputDefault = getOptionDefaultBasedOnSpringProperty(ctx, PROPERTY_APP_INPUT, STD_IN_STR); final String processedDefault = inputDefault.equals(STD_IN_STR) ? DEFAULT_PROCESSED_FILE_BASE : inputDefault + PROCESSED_EXT; final String outputDefault = getOptionDefaultBasedOnSpringProperty(ctx, PROPERTY_APP_OUTPUT, STD_OUT_STR); int throttleDefault = Integer.valueOf(getOptionDefaultBasedOnSpringProperty(ctx, PROPERTY_APP_THROTTLE, String.valueOf(DEFAULT_APP_THROTTLE))); // Maximum of 25000 requests per hour throttleDefault = Math.min(throttleDefault, MAX_APP_THROTTLE); /* * Get options from the CLI args */ final Options options = new Options(); options.addOption("h", false, "Display this help."); options.addOption("i", true, "Set the file to read ASINs from. " + DEFAULT_STR + inputDefault); options.addOption("p", true, "Set the file to store processed ASINs in. " + DEFAULT_STR + processedDefault + " or '" + PROCESSED_EXT + "' appended to the input file name."); // Add a note that the output depends on the configured processors. If none are configured, it defaults to a // std.out processor options.addOption("o", true, "Set the file to write fetched info xml to via FileProcessor. " + DEFAULT_STR + outputDefault); options.addOption("1", false, "Override output file and always output fetched info xml to std.out."); options.addOption("t", true, "Set the requests per hour throttle (max of " + MAX_APP_THROTTLE + "). " + DEFAULT_STR + throttleDefault); final CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; boolean needsHelp = false; try { cmd = parser.parse(options, args); } catch (final ParseException e) { needsHelp = true; } if (cmd.hasOption("h") || needsHelp) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("App", options); return; } // Get throttle rate final int throttle = Math.min( cmd.hasOption("t") ? Integer.valueOf(cmd.getOptionValue("t")) : throttleDefault, MAX_APP_THROTTLE); LOG.debug("Throttle (default {}) is {} requests per hour", throttleDefault, throttle); // We don't want to hit our limit, just under an hour worth of milliseconds final int requestWait = 3540000 / throttle; // Get input stream String input; if (cmd.hasOption("i")) { input = cmd.getOptionValue("i"); } else { input = inputDefault; } LOG.debug("Input name (default {}) is {}", inputDefault, input); // Get processed file String processed; if (cmd.hasOption("p")) { processed = cmd.getOptionValue("p"); } else { processed = input + PROCESSED_EXT; } LOG.debug("Processed file name (default {}) is {}", processedDefault, processed); final File processedFile = new File(processed); processedFile.createNewFile(); try (final InputStream inputStream = getInputStream(input)) { // Get output stream String output; if (cmd.hasOption("o")) { output = cmd.getOptionValue("o"); } else { output = outputDefault; } if (cmd.hasOption("1")) { output = STD_OUT_STR; } LOG.debug("Output (default {}) name is {}", outputDefault, output); // Special logic to set the FileProcessor output if (output.equals(STD_OUT_STR)) { final FileProcessor fileProcessor = ctx.getBeanFactory().getBean(FileProcessor.class); fileProcessor.setOutputStream(System.out); } else if (!output.equals(outputDefault)) { final FileProcessor fileProcessor = ctx.getBeanFactory().getBean(FileProcessor.class); fileProcessor.setOutputFile(output); } // This could be easily configured through CLI or properties final List<String> responseGroups = Lists.newArrayList(); for (final ResponseGroup responseGroup : new ResponseGroup[] { ResponseGroup.IMAGES, ResponseGroup.ITEM_ATTRIBUTES }) { responseGroups.add(responseGroup.getResponseGroupName()); } final String responseGroupString = Joiner.on(",").join(responseGroups); // Search the list of remaining ASINs final ProductFetcher fetcher = ctx.getBeanFactory().getBean(ProductFetcher.class); fetcher.setProcessedFile(processedFile); fetcher.setRequestWait(requestWait); fetcher.setInputStream(inputStream); fetcher.setResponseGroups(responseGroupString); // This ensures that statistics of processed asins should almost always get printed at the end Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { fetcher.logStatistics(); } }); fetcher.fetchProductInformation(); } } }
From source file:Main.java
public static void main(String[] args) throws Exception { List<Element> elementList = new ArrayList<Element>(); List<Item> itemList = new ArrayList<Item>(); Element element1 = new Element(); Element element2 = new Element(); Item item1 = new Item(); Item item2 = new Item(); Elements elements = new Elements(); item1.setId(1);/* w w w . jav a2s . c om*/ item1.setName("Test1"); item2.setId(2); item2.setName("Test2"); itemList.add(item1); itemList.add(item2); element1.setProperty1("prop1"); element1.setProperty2("prop2"); element1.setType(2); element1.setItems(itemList); element2.setProperty1("prop11"); element2.setProperty2("prop22"); element2.setType(22); element2.setItems(itemList); elementList.add(element1); elementList.add(element2); elements.setElements(elementList); System.out.println("------- Object to XML -----------\n"); JAXBContext jaxbContext = JAXBContext.newInstance(Elements.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // output pretty printed jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(elements, System.out); System.out.println("\n------- XML to Object -----------\n"); String xml = "<elements><element><items><item><id>1</id><name>Test1</name></item><item><id>2</id><name>Test2</name></item></items><property1>prop1</property1><property2>prop2</property2><type>2</type></element><element><items><item><id>1</id><name>Test1</name></item><item><id>2</id><name>Test2</name></item></items><property1>prop11</property1><property2>prop22</property2><type>22</type></element></elements>"; StringReader reader = new StringReader(xml); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Elements elementsOut = (Elements) jaxbUnmarshaller.unmarshal(reader); System.out.println(elementsOut); }
From source file:de.tudarmstadt.ukp.argumentation.data.roomfordebate.DataFetcher.java
public static void main(String[] args) throws Exception { File crawledPagesFolder = new File(args[0]); if (!crawledPagesFolder.exists()) { crawledPagesFolder.mkdirs();//from ww w . ja va 2 s.c o m } File outputFolder = new File(args[1]); if (!outputFolder.exists()) { outputFolder.mkdirs(); } // read links from text file final String urlsResourceName = "roomfordebate-urls.txt"; InputStream urlsStream = DataFetcher.class.getClassLoader().getResourceAsStream(urlsResourceName); if (urlsStream == null) { throw new IOException("Cannot find resource " + urlsResourceName + " on the classpath"); } // read list of urls List<String> urls = new ArrayList<>(); LineIterator iterator = IOUtils.lineIterator(urlsStream, "utf-8"); while (iterator.hasNext()) { // ignore commented url (line starts with #) String line = iterator.nextLine(); if (!line.startsWith("#") && !line.trim().isEmpty()) { urls.add(line.trim()); } } // download all crawlPages(urls, crawledPagesFolder); List<File> files = new ArrayList<>(FileUtils.listFiles(crawledPagesFolder, null, false)); Collections.sort(files, new Comparator<File>() { @Override public int compare(File o1, File o2) { return o1.getName().compareTo(o2.getName()); } }); int idCounter = 0; for (File file : files) { NYTimesCommentsScraper commentsScraper = new NYTimesCommentsScraper(); NYTimesArticleExtractor extractor = new NYTimesArticleExtractor(); String html = FileUtils.readFileToString(file, "utf-8"); idCounter++; File outputFileArticle = new File(outputFolder, String.format("Cx%03d.txt", idCounter)); File outputFileComments = new File(outputFolder, String.format("Dx%03d.txt", idCounter)); try { List<Comment> comments = commentsScraper.extractComments(html); Article article = extractor.extractArticle(html); saveArticleToText(article, outputFileArticle); System.out.println("Saved to " + outputFileArticle); saveCommentsToText(comments, outputFileComments, article); System.out.println("Saved to " + outputFileComments); } catch (IOException ex) { System.err.println(file.getName() + "\n" + ex.getMessage()); } } }
From source file:com.topsem.common.io.excel.ExportExcel.java
/** * //from w ww .j a v a 2 s. co m */ public static void main(String[] args) throws Throwable { List<String> headerList = Lists.newArrayList(); for (int i = 1; i <= 10; i++) { headerList.add("" + i); } List<String> dataRowList = Lists.newArrayList(); for (int i = 1; i <= headerList.size(); i++) { dataRowList.add("?" + i); } List<List<String>> dataList = Lists.newArrayList(); for (int i = 1; i <= 100; i++) { dataList.add(dataRowList); } ExportExcel ee = new ExportExcel("", headerList); for (int i = 0; i < dataList.size(); i++) { Row row = ee.addRow(); for (int j = 0; j < dataList.get(i).size(); j++) { ee.addCell(row, j, dataList.get(i).get(j)); } } ee.writeFile("target/export.xlsx"); ee.dispose(); log.debug("Export success."); }
From source file:ch.sdi.core.impl.ftp.FTPClientExample.java
public static void main(String[] aArgs) throws UnknownHostException { List<String> args = new ArrayList<String>(Arrays.asList(aArgs)); args.add("-s"); // store file on sesrver args.add("-b"); // binary transfer mode args.add("-#"); args.add("192.168.99.1"); args.add("heri"); // user args.add("heri"); // pw args.add("/var/www/log4j2.xml"); URL url = ClassLoader.getSystemResource("sdimain_test.properties"); // URL url = ClassLoader.getSystemResource( "log4j2.xml" ); args.add(url.getFile());//from w w w .ja va 2s .co m FTPClientExample example = new FTPClientExample(); try { example.init(args.toArray(new String[args.size()])); example.run(); } catch (Throwable t) { myLog.error("Exception caught", t); myLog.info(USAGE); System.exit(1); } }
From source file:org.ala.harvester.HarvestRunner.java
/** * Main method//from w w w. ja va 2 s .c o m * * @param args */ public static void main(String[] args) { // Get Spring context context = new ClassPathXmlApplicationContext("classpath*:spring.xml"); //InfoSourceDAO infoSourceDAORO = (InfoSourceDAO) context.getBean("infoSourceDao"); HarvestRunner hr = (HarvestRunner) context.getBean("harvestRunner"); if (args.length < 1) { System.out.println( "Please enter an info source ID to harvest OR enter \"all\" " + "to harvest all info sources"); System.exit(-1); } else if (args.length < 2 && args[0].equalsIgnoreCase("all")) { logger.info("Harvesting all info sources..."); List<Integer> infoSourceIds = hr.getAllIds(); hr.harvest(infoSourceIds); } else if (args.length < 2) { try { Integer infoSourceId = Integer.parseInt(args[0]); List<Integer> infoSourceIds = new ArrayList<Integer>(); infoSourceIds.add(infoSourceId); hr.harvest(infoSourceIds); } catch (NumberFormatException ex) { logger.error("info source id was not recognised as a number: " + ex.getMessage()); } } else if (args.length < 3 && args[0].equalsIgnoreCase("all")) { try { Integer timeGap = Integer.parseInt(args[1]); logger.info("Harvesting all info sources..."); List<Integer> infoSourceIds = hr.getAllIds(); hr.harvest(infoSourceIds, timeGap); } catch (NumberFormatException ex) { logger.error("time gap was not recognised as a number: " + ex.getMessage()); } } else if (args.length < 3) { try { Integer infoSourceId = Integer.parseInt(args[0]); Integer timeGap = Integer.parseInt(args[1]); List<Integer> infoSourceIds = new ArrayList<Integer>(); infoSourceIds.add(infoSourceId); hr.harvest(infoSourceIds, timeGap); } catch (NumberFormatException ex) { logger.error("info source id was not recognised as a number: " + ex.getMessage()); } } }