List of usage examples for java.io BufferedReader readLine
public String readLine() throws IOException
From source file:NewFingerServer.java
public static void main(String[] arguments) throws Exception { ServerSocketChannel sockChannel = ServerSocketChannel.open(); sockChannel.configureBlocking(false); InetSocketAddress server = new InetSocketAddress("localhost", 79); ServerSocket socket = sockChannel.socket(); socket.bind(server);//w ww. ja va2s . c om Selector selector = Selector.open(); sockChannel.register(selector, SelectionKey.OP_ACCEPT); while (true) { selector.select(); Set keys = selector.selectedKeys(); Iterator it = keys.iterator(); while (it.hasNext()) { SelectionKey selKey = (SelectionKey) it.next(); it.remove(); if (selKey.isAcceptable()) { ServerSocketChannel selChannel = (ServerSocketChannel) selKey.channel(); ServerSocket selSocket = selChannel.socket(); Socket connection = selSocket.accept(); InputStreamReader isr = new InputStreamReader(connection.getInputStream()); BufferedReader is = new BufferedReader(isr); PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()), false); pw.println("NIO Finger Server"); pw.flush(); String outLine = null; String inLine = is.readLine(); if (inLine.length() > 0) { outLine = inLine; } readPlan(outLine, pw); pw.flush(); pw.close(); is.close(); connection.close(); } } } }
From source file:edu.cmu.lti.oaqa.bio.index.medline.annotated.query.SimpleQueryApp.java
public static void main(String[] args) { Options options = new Options(); options.addOption("u", null, true, "Solr URI"); options.addOption("n", null, true, "Max # of results"); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try {//from w ww . j a va 2 s. c o m CommandLine cmd = parser.parse(options, args); String solrURI = null; solrURI = cmd.getOptionValue("u"); if (solrURI == null) { Usage("Specify Solr URI"); } SolrServerWrapper solr = new SolrServerWrapper(solrURI); int numRet = 10; if (cmd.hasOption("n")) { numRet = Integer.parseInt(cmd.getOptionValue("n")); } List<String> fieldList = new ArrayList<String>(); fieldList.add(UtilConstMedline.ID_FIELD); fieldList.add(UtilConstMedline.SCORE_FIELD); fieldList.add(UtilConstMedline.ARTICLE_TITLE_FIELD); fieldList.add(UtilConstMedline.ENTITIES_DESC_FIELD); fieldList.add(UtilConstMedline.ABSTRACT_TEXT_FIELD); BufferedReader sysInReader = new BufferedReader(new InputStreamReader(System.in)); Joiner commaJoiner = Joiner.on(','); while (true) { System.out.println("Input query: "); String query = sysInReader.readLine(); if (null == query) break; QueryTransformer qt = new QueryTransformer(query); String tranQuery = qt.getQuery(); System.out.println("Translated query:"); System.out.println(tranQuery); System.out.println("========================="); SolrDocumentList res = solr.runQuery(tranQuery, fieldList, numRet); System.out.println("Found " + res.getNumFound() + " entries"); for (SolrDocument doc : res) { String id = (String) doc.getFieldValue(UtilConstMedline.ID_FIELD); float score = (Float) doc.getFieldValue(UtilConstMedline.SCORE_FIELD); String title = (String) doc.getFieldValue(UtilConstMedline.ARTICLE_TITLE_FIELD); String titleAbstract = (String) doc.getFieldValue(UtilConstMedline.ABSTRACT_TEXT_FIELD); System.out.println(score + " PMID=" + id + " " + titleAbstract); String entityDesc = (String) doc.getFieldValue(UtilConstMedline.ENTITIES_DESC_FIELD); System.out.println("Entities:"); for (EntityEntry e : EntityEntry.parseEntityDesc(entityDesc)) { System.out.println(String.format("[%d %d] concept=%s concept_ids=%s", e.mStart, e.mEnd, e.mConcept, commaJoiner.join(e.mConceptIds))); } } } solr.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:org.dspace.app.cris.batch.ScriptDeleteRP.java
/** * Batch script to delete a RP. See the technical documentation for further * details./* www.j ava2s . c o m*/ */ public static void main(String[] args) { log.info("#### START DELETE: -----" + new Date() + " ----- ####"); Context dspaceContext = null; ApplicationContext context = null; try { dspaceContext = new Context(); dspaceContext.turnOffAuthorisationSystem(); DSpace dspace = new DSpace(); ApplicationService applicationService = dspace.getServiceManager() .getServiceByName("applicationService", ApplicationService.class); CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption("h", "help", false, "help"); options.addOption("r", "researcher", true, "RP id to delete"); options.addOption("s", "silent", false, "no interactive mode"); CommandLine line = parser.parse(options, args); if (line.hasOption('h')) { HelpFormatter myhelp = new HelpFormatter(); myhelp.printHelp("ScriptHKURPDelete \n", options); System.out.println("\n\nUSAGE:\n ScriptHKURPDelete -r <id> \n"); System.out.println("Please note: add -s for no interactive mode"); System.exit(0); } Integer rpId = null; boolean delete = false; boolean silent = line.hasOption('s'); Item[] items = null; if (line.hasOption('r')) { rpId = ResearcherPageUtils.getRealPersistentIdentifier(line.getOptionValue("r"), ResearcherPage.class); ResearcherPage rp = applicationService.get(ResearcherPage.class, rpId); if (rp == null) { if (!silent) { System.out.println("RP not exist...exit"); } log.info("RP not exist...exit"); System.exit(0); } log.info("Use browse indexing"); BrowseIndex bi = BrowseIndex.getBrowseIndex(plugInBrowserIndex); // now start up a browse engine and get it to do the work for us BrowseEngine be = new BrowseEngine(dspaceContext); String authKey = ResearcherPageUtils.getPersistentIdentifier(rp); // set up a BrowseScope and start loading the values into it BrowserScope scope = new BrowserScope(dspaceContext); scope.setBrowseIndex(bi); // scope.setOrder(order); scope.setFilterValue(authKey); scope.setAuthorityValue(authKey); scope.setResultsPerPage(Integer.MAX_VALUE); scope.setBrowseLevel(1); BrowseInfo binfo = be.browse(scope); log.debug("Find " + binfo.getResultCount() + "item(s) for the reseracher " + authKey); items = binfo.getItemResults(dspaceContext); if (!silent && rp != null) { System.out.println(MESSAGE_ONE); // interactive mode System.out.println("Attempting to remove Researcher Page:"); System.out.println("StaffNo:" + rp.getSourceID()); System.out.println("FullName:" + rp.getFullName()); System.out .println("the researcher has " + items.length + " relation(s) with item(s) in the HUB"); System.out.println(); System.out.println(QUESTION_ONE); InputStreamReader isr = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(isr); String answer = reader.readLine(); if (answer.equals("yes")) { delete = true; } else { System.out.println("Exit without delete"); log.info("Exit without delete"); System.exit(0); } } else { delete = true; } } else { System.out.println("\n\nUSAGE:\n ScriptHKURPDelete <-v> -r <RPid> \n"); System.out.println("-r option is mandatory"); log.error("-r option is mandatory"); System.exit(1); } if (delete) { if (!silent) { System.out.println("Deleting..."); } log.info("Deleting..."); cleanAuthority(dspaceContext, items, rpId); applicationService.delete(ResearcherPage.class, rpId); dspaceContext.complete(); } if (!silent) { System.out.println("Ok...Bye"); } } catch (Exception e) { log.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } finally { if (dspaceContext != null && dspaceContext.isValid()) { dspaceContext.abort(); } if (context != null) { context.publishEvent(new ContextClosedEvent(context)); } } log.info("#### END: -----" + new Date() + " ----- ####"); System.exit(0); }
From source file:org.openimaj.demos.sandbox.PlotFlickrGeo.java
public static void main(String[] args) throws IOException { File inputcsv = new File("/Users/jsh2/Desktop/world-geo.csv"); List<float[]> data = new ArrayList<float[]>(10000000); //read in images BufferedReader br = new BufferedReader(new FileReader(inputcsv)); String line;//w w w. j a v a 2 s .c om int i = 0; while ((line = br.readLine()) != null) { String[] parts = line.split(","); float longitude = Float.parseFloat(parts[0]); float latitude = Float.parseFloat(parts[1]); data.add(new float[] { longitude, latitude }); if (i++ % 10000 == 0) System.out.println(i); } System.out.println("Done reading"); float[][] dataArr = new float[2][data.size()]; for (i = 0; i < data.size(); i++) { dataArr[0][i] = data.get(i)[0]; dataArr[1][i] = data.get(i)[1]; } NumberAxis domainAxis = new NumberAxis("X"); domainAxis.setRange(-180, 180); NumberAxis rangeAxis = new NumberAxis("Y"); rangeAxis.setRange(-90, 90); FastScatterPlot plot = new FastScatterPlot(dataArr, domainAxis, rangeAxis); JFreeChart chart = new JFreeChart("Fast Scatter Plot", plot); chart.getRenderingHints().put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(500, 270)); final ApplicationFrame frame = new ApplicationFrame("Title"); frame.setContentPane(chartPanel); frame.pack(); frame.setVisible(true); }
From source file:metaTile.Main.java
/** * @param args/* w ww .j ava 2s.c om*/ * @throws IOException */ public static void main(String[] args) throws IOException { try { /* parse the command line arguments */ // create the command line parser CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption("i", "input", true, "File to read original tile list from."); options.addOption("o", "output", true, "File to write shorter meta-tile list to."); options.addOption("m", "metatiles", true, "Number of tiles in x and y direction to group into one meta-tile."); // parse the command line arguments CommandLine commandLine = parser.parse(options, args); if (!commandLine.hasOption("input") || !commandLine.hasOption("output") || !commandLine.hasOption("metatiles")) printUsage(options); String inputFileName = commandLine.getOptionValue("input"); String outputFileName = commandLine.getOptionValue("output"); int metaTileSize = Integer.parseInt(commandLine.getOptionValue("metatiles")); ArrayList<RenderingTile> tiles = new ArrayList<RenderingTile>(); BufferedReader tileListReader = new BufferedReader(new FileReader(new File(inputFileName))); BufferedWriter renderMetatileListWriter = new BufferedWriter(new FileWriter(new File(outputFileName))); String line = tileListReader.readLine(); while (line != null) { String[] columns = line.split("/"); if (columns.length == 3) tiles.add(new RenderingTile(Integer.parseInt(columns[0]), Integer.parseInt(columns[1]), Integer.parseInt(columns[2]))); line = tileListReader.readLine(); } tileListReader.close(); int hits = 0; // tiles which we are already rendering as the top left corner of 4x4 metatiles HashSet<RenderingTile> whitelist = new HashSet<RenderingTile>(); // for each tile in the list see if it has a meta-tile in the whitelist already for (int i = 0; i < tiles.size(); i++) { boolean hit = false; // by default we aren't already rendering this tile as part of another metatile for (int dx = 0; dx < metaTileSize; dx++) { for (int dy = 0; dy < metaTileSize; dy++) { RenderingTile candidate = new RenderingTile(tiles.get(i).z, tiles.get(i).x - dx, tiles.get(i).y - dy); if (whitelist.contains(candidate)) { hit = true; // now exit the two for loops iterating over tiles inside a meta-tile dx = metaTileSize; dy = metaTileSize; } } } // if this tile doesn't already have a meta-tile in the whitelist, add it if (hit == false) { hits++; renderMetatileListWriter.write(tiles.get(i).toString() + "/" + metaTileSize + "\n"); whitelist.add(tiles.get(i)); } } renderMetatileListWriter.close(); System.out.println( "Reduced " + tiles.size() + " tiles into " + hits + " metatiles of size " + metaTileSize); } catch (Exception e) { e.printStackTrace(); } }
From source file:net.java.sen.tools.MkCompoundTable.java
/** * Build compound word table.//from w ww. j a va 2s .c o m */ public static void main(String args[]) { ResourceBundle rb = ResourceBundle.getBundle("dictionary"); int pos_start = Integer.parseInt(rb.getString("pos_start")); int pos_size = Integer.parseInt(rb.getString("pos_size")); try { log.info("reading compound word information ... "); HashMap compoundTable = new HashMap(); log.info("load dic: " + rb.getString("compound_word_file")); BufferedReader dicStream = new BufferedReader(new InputStreamReader( new FileInputStream(rb.getString("compound_word_file")), rb.getString("dic.charset"))); String t; int line = 0; StringBuffer pos_b = new StringBuffer(); while ((t = dicStream.readLine()) != null) { CSVParser parser = new CSVParser(t); String csv[] = parser.nextTokens(); if (csv.length < (pos_size + pos_start)) { throw new RuntimeException("format error:" + line); } pos_b.setLength(0); for (int i = pos_start; i < (pos_start + pos_size - 1); i++) { pos_b.append(csv[i]); pos_b.append(','); } pos_b.append(csv[pos_start + pos_size - 1]); pos_b.append(','); for (int i = pos_start + pos_size; i < (csv.length - 2); i++) { pos_b.append(csv[i]); pos_b.append(','); } pos_b.append(csv[csv.length - 2]); compoundTable.put(pos_b.toString(), csv[csv.length - 1]); } dicStream.close(); log.info("done."); log.info("writing compound word table ... "); ObjectOutputStream os = new ObjectOutputStream( new FileOutputStream(rb.getString("compound_word_table"))); os.writeObject(compoundTable); os.close(); log.info("done."); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }
From source file:FlightInfo.java
public static void main(String args[]) { String to, from;/* w ww . j a va 2s. c o m*/ Optimal ob = new Optimal(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); boolean done = false; FlightInfo f; ob.setup(); try { System.out.print("From? "); from = br.readLine(); System.out.print("To? "); to = br.readLine(); do { ob.isflight(from, to); if (ob.btStack.size() == 0) done = true; else { ob.route(to); ob.btStack = new Stack(); } } while (!done); // Display optimal solution. if (ob.optimal != null) { System.out.println("Optimal solution is: "); int num = ob.optimal.size(); for (int i = 0; i < num; i++) { f = (FlightInfo) ob.optimal.pop(); System.out.print(f.from + " to "); } System.out.println(to); System.out.println("Distance is " + ob.minDist); } } catch (IOException exc) { System.out.println("Error on input."); } }
From source file:ASCII2NATIVE.java
public static void main(String[] args) { File f = new File("c:\\mydb.script"); File f2 = new File("c:\\mydb3.script"); if (f.exists() && f.isFile()) { // convert param-file BufferedReader br = null; StringBuffer sb = new StringBuffer(); String line;/*from ww w . j a v a 2 s.com*/ try { br = new BufferedReader(new InputStreamReader(new FileInputStream(f), "JISAutoDetect")); while ((line = br.readLine()) != null) { System.out.println(ascii2Native(line)); sb.append(ascii2Native(line)).append(";\n");//.append(";\n\r") } BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f2), "utf-8")); out.append(sb.toString()); out.flush(); out.close(); } catch (FileNotFoundException e) { System.err.println("file not found - " + f); } catch (IOException e) { System.err.println("read error - " + f); } finally { try { if (br != null) br.close(); } catch (Exception e) { } } } else { // // convert param-data // System.out.print(ascii2native(args[i])); // if (i + 1 < args.length) // System.out.print(' '); } }
From source file:com.tamingtext.classifier.mlt.TestMoreLikeThis.java
public static void main(String[] args) throws Exception { DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); ArgumentBuilder abuilder = new ArgumentBuilder(); GroupBuilder gbuilder = new GroupBuilder(); Option helpOpt = DefaultOptionCreator.helpOption(); Option inputDirOpt = obuilder.withLongName("input").withRequired(true) .withArgument(abuilder.withName("input").withMinimum(1).withMaximum(1).create()) .withDescription("The input directory").withShortName("i").create(); Option modelOpt = obuilder.withLongName("model").withRequired(true) .withArgument(abuilder.withName("index").withMinimum(1).withMaximum(1).create()) .withDescription("The directory containing the index model").withShortName("m").create(); Option categoryFieldOpt = obuilder.withLongName("categoryField").withRequired(true) .withArgument(abuilder.withName("index").withMinimum(1).withMaximum(1).create()) .withDescription("Name of the field containing category information").withShortName("catf") .create();/*from w w w . j av a2 s .c o m*/ Option contentFieldOpt = obuilder.withLongName("contentField").withRequired(true) .withArgument(abuilder.withName("index").withMinimum(1).withMaximum(1).create()) .withDescription("Name of the field containing content information").withShortName("contf") .create(); Option maxResultsOpt = obuilder.withLongName("maxResults").withRequired(false) .withArgument(abuilder.withName("gramSize").withMinimum(1).withMaximum(1).create()) .withDescription("Number of results to retrive, default: 10 ").withShortName("r").create(); Option gramSizeOpt = obuilder.withLongName("gramSize").withRequired(false) .withArgument(abuilder.withName("gramSize").withMinimum(1).withMaximum(1).create()) .withDescription("Size of the n-gram. Default Value: 1 ").withShortName("ng").create(); Option typeOpt = obuilder.withLongName("classifierType").withRequired(false) .withArgument(abuilder.withName("classifierType").withMinimum(1).withMaximum(1).create()) .withDescription("Type of classifier: knn|tfidf. Default: bayes").withShortName("type").create(); Group group = gbuilder.withName("Options").withOption(gramSizeOpt).withOption(helpOpt) .withOption(inputDirOpt).withOption(modelOpt).withOption(typeOpt).withOption(contentFieldOpt) .withOption(categoryFieldOpt).withOption(maxResultsOpt).create(); try { Parser parser = new Parser(); parser.setGroup(group); parser.setHelpOption(helpOpt); CommandLine cmdLine = parser.parse(args); if (cmdLine.hasOption(helpOpt)) { CommandLineUtil.printHelp(group); return; } String classifierType = (String) cmdLine.getValue(typeOpt); int gramSize = 1; if (cmdLine.hasOption(gramSizeOpt)) { gramSize = Integer.parseInt((String) cmdLine.getValue(gramSizeOpt)); } int maxResults = 10; if (cmdLine.hasOption(maxResultsOpt)) { maxResults = Integer.parseInt((String) cmdLine.getValue(maxResultsOpt)); } String inputPath = (String) cmdLine.getValue(inputDirOpt); String modelPath = (String) cmdLine.getValue(modelOpt); String categoryField = (String) cmdLine.getValue(categoryFieldOpt); String contentField = (String) cmdLine.getValue(contentFieldOpt); MatchMode mode; if ("knn".equalsIgnoreCase(classifierType)) { mode = MatchMode.KNN; } else if ("tfidf".equalsIgnoreCase(classifierType)) { mode = MatchMode.TFIDF; } else { throw new IllegalArgumentException("Unkown classifierType: " + classifierType); } Directory directory = FSDirectory.open(new File(modelPath)); IndexReader indexReader = IndexReader.open(directory); Analyzer analyzer //<co id="mlt.analyzersetup"/> = new EnglishAnalyzer(Version.LUCENE_36); MoreLikeThisCategorizer categorizer = new MoreLikeThisCategorizer(indexReader, categoryField); categorizer.setAnalyzer(analyzer); categorizer.setMatchMode(mode); categorizer.setFieldNames(new String[] { contentField }); categorizer.setMaxResults(maxResults); categorizer.setNgramSize(gramSize); File f = new File(inputPath); if (!f.isDirectory()) { throw new IllegalArgumentException(f + " is not a directory or does not exit"); } File[] inputFiles = FileUtil.buildFileList(f); String line = null; //<start id="lucene.examples.mlt.test"/> final ClassifierResult UNKNOWN = new ClassifierResult("unknown", 1.0); ResultAnalyzer resultAnalyzer = //<co id="co.mlt.ra"/> new ResultAnalyzer(categorizer.getCategories(), UNKNOWN.getLabel()); for (File ff : inputFiles) { //<co id="co.mlt.read"/> BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(ff), "UTF-8")); while ((line = in.readLine()) != null) { String[] parts = line.split("\t"); if (parts.length != 2) { continue; } CategoryHits[] hits //<co id="co.mlt.cat"/> = categorizer.categorize(new StringReader(parts[1])); ClassifierResult result = hits.length > 0 ? hits[0] : UNKNOWN; resultAnalyzer.addInstance(parts[0], result); //<co id="co.mlt.an"/> } in.close(); } System.out.println(resultAnalyzer.toString());//<co id="co.mlt.print"/> /* <calloutlist> <callout arearefs="co.mlt.ra">Create <classname>ResultAnalyzer</classname></callout> <callout arearefs="co.mlt.read">Read Test data</callout> <callout arearefs="co.mlt.cat">Categorize</callout> <callout arearefs="co.mlt.an">Collect Results</callout> <callout arearefs="co.mlt.print">Display Results</callout> </calloutlist> */ //<end id="lucene.examples.mlt.test"/> } catch (OptionException e) { log.error("Error while parsing options", e); } }
From source file:com.asquareb.kaaval.MachineKey.java
/** * Main method to execute as a command line utility. Provides the option to * encrypt a string, decrypt a encrypted string or exit from the program *//*from ww w. j a v a2 s .c o m*/ public static void main(String[] args) { String originalPassword = null; String encryptedPassword = null; try { final BufferedReader cin = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter E - Encrypt,D - Decrypt,X - Exit :"); final String choice = cin.readLine(); final Random rand = new Random(); boolean phraseCorrect = false; String app = null; if (choice.equalsIgnoreCase("E")) { System.out.print("Enter the string to encrypt :"); originalPassword = cin.readLine(); System.out.println("Choose a phrase of min 8 chars in length "); System.out.println(" Also the password should include 2 Cap,"); System.out.println(" 2 small letters,2 numeric and 2 non alpha numeric chars"); while (!phraseCorrect) { System.out.print("Enter a phrase to encrypt :"); password = cin.readLine().toCharArray(); phraseCorrect = PasswordRules.verifyPassword(password); } System.out.print("Enter application code :"); app = cin.readLine(); app += (rand.nextInt(10000)); encryptedPassword = encrypt(originalPassword, app); System.out.println("Encrypted password :" + encryptedPassword); System.out.println("Key stored in :" + app); System.out.println("*** Provide the encrypted string to app team"); System.out.println("*** Store the key file in a secure durectory"); System.out.println("*** Inform the key file name and location to app team"); } else if (choice.equalsIgnoreCase("D")) { System.out.print("Enter the string to Decrypt :"); encryptedPassword = cin.readLine(); System.out.print("Enter the name of key file :"); app = cin.readLine(); final String decryptedPassword = decrypt(encryptedPassword, app); System.out.print("Decrypted string :" + decryptedPassword); } return; } catch (KaavalException e) { e.PrintProtectException(); } catch (Exception e) { e.printStackTrace(); } }