List of usage examples for java.io BufferedReader BufferedReader
public BufferedReader(Reader in)
From source file:edu.umd.shrawanraina.SequentialPersonalizedPageRank.java
@SuppressWarnings({ "static-access" }) public static void main(String[] args) throws IOException { Options options = new Options(); options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT)); options.addOption(//from w w w . j a v a 2s . c om OptionBuilder.withArgName("val").hasArg().withDescription("random jump factor").create(JUMP)); options.addOption(OptionBuilder.withArgName("node").hasArg() .withDescription("source node (i.e., destination of the random jump)").create(SOURCE)); CommandLine cmdline = null; 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) || !cmdline.hasOption(SOURCE)) { System.out.println("args: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(SequentialPersonalizedPageRank.class.getName(), options); ToolRunner.printGenericCommandUsage(System.out); System.exit(-1); } String infile = cmdline.getOptionValue(INPUT); final String source = cmdline.getOptionValue(SOURCE); float alpha = cmdline.hasOption(JUMP) ? Float.parseFloat(cmdline.getOptionValue(JUMP)) : 0.15f; int edgeCnt = 0; DirectedSparseGraph<String, Integer> graph = new DirectedSparseGraph<String, Integer>(); BufferedReader data = new BufferedReader(new InputStreamReader(new FileInputStream(infile))); String line; while ((line = data.readLine()) != null) { line.trim(); String[] arr = line.split("\\t"); for (int i = 1; i < arr.length; i++) { graph.addEdge(new Integer(edgeCnt++), arr[0], arr[i]); } } data.close(); if (!graph.containsVertex(source)) { System.err.println("Error: source node not found in the graph!"); System.exit(-1); } WeakComponentClusterer<String, Integer> clusterer = new WeakComponentClusterer<String, Integer>(); Set<Set<String>> components = clusterer.transform(graph); int numComponents = components.size(); System.out.println("Number of components: " + numComponents); System.out.println("Number of edges: " + graph.getEdgeCount()); System.out.println("Number of nodes: " + graph.getVertexCount()); System.out.println("Random jump factor: " + alpha); // Compute personalized PageRank. PageRankWithPriors<String, Integer> ranker = new PageRankWithPriors<String, Integer>(graph, new Transformer<String, Double>() { public Double transform(String vertex) { return vertex.equals(source) ? 1.0 : 0; } }, alpha); ranker.evaluate(); // Use priority queue to sort vertices by PageRank values. PriorityQueue<Ranking<String>> q = new PriorityQueue<Ranking<String>>(); int i = 0; for (String pmid : graph.getVertices()) { q.add(new Ranking<String>(i++, ranker.getVertexScore(pmid), pmid)); } // Print PageRank values. System.out.println("\nPageRank of nodes, in descending order:"); Ranking<String> r = null; while ((r = q.poll()) != null) { System.out.println(r.rankScore + "\t" + r.getRanked()); } }
From source file:edu.umd.ujjwalgoel.AnalyzePMI.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;/* w w w .jav a 2s .com*/ 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(AnalyzePMI.class.getName(), options); ToolRunner.printGenericCommandUsage(System.out); System.exit(-1); } String inputPath = cmdline.getOptionValue(INPUT); System.out.println("input path: " + inputPath); BufferedReader br = null; int countPairs = 0; List<PairOfWritables<PairOfStrings, FloatWritable>> pmis = new ArrayList<PairOfWritables<PairOfStrings, FloatWritable>>(); List<PairOfWritables<PairOfStrings, FloatWritable>> cloudPmis = new ArrayList<PairOfWritables<PairOfStrings, FloatWritable>>(); List<PairOfWritables<PairOfStrings, FloatWritable>> lovePmis = new ArrayList<PairOfWritables<PairOfStrings, FloatWritable>>(); PairOfWritables<PairOfStrings, FloatWritable> highestPMI = null; PairOfWritables<PairOfStrings, FloatWritable> highestCloudPMI = null; PairOfWritables<PairOfStrings, FloatWritable> highestCloudPMI2 = null; PairOfWritables<PairOfStrings, FloatWritable> highestCloudPMI3 = null; PairOfWritables<PairOfStrings, FloatWritable> highestLovePMI = null; PairOfWritables<PairOfStrings, FloatWritable> highestLovePMI2 = null; PairOfWritables<PairOfStrings, FloatWritable> highestLovePMI3 = null; try { FileSystem fs = FileSystem.get(new Configuration()); FileStatus[] status = fs.listStatus(new Path(inputPath)); //PairOfStrings pair = new PairOfStrings(); for (int i = 0; i < status.length; i++) { br = new BufferedReader(new InputStreamReader(fs.open(status[i].getPath()))); String line = br.readLine(); while (line != null) { String[] words = line.split("\\t"); float value = Float.parseFloat(words[1].trim()); String[] wordPair = words[0].replaceAll("\\(", "").replaceAll("\\)", "").split(","); PairOfStrings pair = new PairOfStrings(); pair.set(wordPair[0].trim(), wordPair[1].trim()); if (wordPair[0].trim().equals("cloud")) { PairOfWritables<PairOfStrings, FloatWritable> cloudPmi = new PairOfWritables<PairOfStrings, FloatWritable>(); cloudPmi.set(pair, new FloatWritable(value)); cloudPmis.add(cloudPmi); if ((highestCloudPMI == null) || (highestCloudPMI.getRightElement().compareTo(cloudPmi.getRightElement()) < 0)) { highestCloudPMI = cloudPmi; } else if ((highestCloudPMI2 == null) || (highestCloudPMI2.getRightElement().compareTo(cloudPmi.getRightElement()) < 0)) { highestCloudPMI2 = cloudPmi; } else if ((highestCloudPMI3 == null) || (highestCloudPMI3.getRightElement().compareTo(cloudPmi.getRightElement()) < 0)) { highestCloudPMI3 = cloudPmi; } } if (wordPair[0].trim().equals("love")) { PairOfWritables<PairOfStrings, FloatWritable> lovePmi = new PairOfWritables<PairOfStrings, FloatWritable>(); lovePmi.set(pair, new FloatWritable(value)); lovePmis.add(lovePmi); if ((highestLovePMI == null) || (highestLovePMI.getRightElement().compareTo(lovePmi.getRightElement()) < 0)) { highestLovePMI = lovePmi; } else if ((highestLovePMI2 == null) || (highestLovePMI2.getRightElement().compareTo(lovePmi.getRightElement()) < 0)) { highestLovePMI2 = lovePmi; } else if ((highestLovePMI3 == null) || (highestLovePMI3.getRightElement().compareTo(lovePmi.getRightElement()) < 0)) { highestLovePMI3 = lovePmi; } } PairOfWritables<PairOfStrings, FloatWritable> pmi = new PairOfWritables<PairOfStrings, FloatWritable>(); pmi.set(pair, new FloatWritable(value)); pmis.add(pmi); if (highestPMI == null) { highestPMI = pmi; } else if (highestPMI.getRightElement().compareTo(pmi.getRightElement()) < 0) { highestPMI = pmi; } countPairs++; line = br.readLine(); } } } catch (Exception ex) { System.out.println("ERROR" + ex.getMessage()); } /*Collections.sort(pmis, new Comparator<PairOfWritables<PairOfStrings, FloatWritable>>() { public int compare(PairOfWritables<PairOfStrings, FloatWritable> e1, PairOfWritables<PairOfStrings, FloatWritable> e2) { /*if (e2.getRightElement().compareTo(e1.getRightElement()) == 0) { return e1.getLeftElement().getLeftElement().compareTo(e2.getLeftElement().getLeftElement()); } return e2.getRightElement().compareTo(e1.getRightElement()); } }); Collections.sort(cloudPmis, new Comparator<PairOfWritables<PairOfStrings, FloatWritable>>() { public int compare(PairOfWritables<PairOfStrings, FloatWritable> e1, PairOfWritables<PairOfStrings, FloatWritable> e2) { if (e2.getRightElement().compareTo(e1.getRightElement()) == 0) { return e1.getLeftElement().getLeftElement().compareTo(e2.getLeftElement().getLeftElement()); } return e2.getRightElement().compareTo(e1.getRightElement()); } }); Collections.sort(lovePmis, new Comparator<PairOfWritables<PairOfStrings, FloatWritable>>() { public int compare(PairOfWritables<PairOfStrings, FloatWritable> e1, PairOfWritables<PairOfStrings, FloatWritable> e2) { if (e2.getRightElement().compareTo(e1.getRightElement()) == 0) { return e1.getLeftElement().getLeftElement().compareTo(e2.getLeftElement().getLeftElement()); } return e2.getRightElement().compareTo(e1.getRightElement()); } }); PairOfWritables<PairOfStrings, FloatWritable> highestPMI = pmis.get(0); PairOfWritables<PairOfStrings, FloatWritable> highestCloudPMI = cloudPmis.get(0); PairOfWritables<PairOfStrings, FloatWritable> highestCloudPMI2 = cloudPmis.get(1); PairOfWritables<PairOfStrings, FloatWritable> highestCloudPMI3 = cloudPmis.get(2); PairOfWritables<PairOfStrings, FloatWritable> highestLovePMI = lovePmis.get(0); PairOfWritables<PairOfStrings, FloatWritable> highestLovePMI2 = lovePmis.get(1); PairOfWritables<PairOfStrings, FloatWritable> highestLovePMI3 = lovePmis.get(2);*/ System.out.println("Total Distinct Pairs : " + countPairs); System.out.println("Pair with highest PMI : (" + highestPMI.getLeftElement().getLeftElement() + ", " + highestPMI.getLeftElement().getRightElement()); System.out .println("Word with highest PMI with Cloud : " + highestCloudPMI.getLeftElement().getRightElement() + " with value : " + highestCloudPMI.getRightElement().get()); System.out.println( "Word with second highest PMI with Cloud : " + highestCloudPMI2.getLeftElement().getRightElement() + " with value : " + highestCloudPMI2.getRightElement().get()); System.out.println( "Word with third highest PMI with Cloud : " + highestCloudPMI3.getLeftElement().getRightElement() + " with value : " + highestCloudPMI3.getRightElement().get()); System.out.println("Word with highest PMI with Love : " + highestLovePMI.getLeftElement().getRightElement() + " with value : " + highestLovePMI.getRightElement().get()); System.out.println( "Word with second highest PMI with Love : " + highestLovePMI2.getLeftElement().getRightElement() + " with value : " + highestLovePMI2.getRightElement().get()); System.out.println( "Word with third highest PMI with Love : " + highestLovePMI3.getLeftElement().getRightElement() + " with value : " + highestLovePMI3.getRightElement().get()); }
From source file:examples.mail.IMAPImportMbox.java
public static void main(String[] args) throws IOException { if (args.length < 2) { System.err.println(//from www . j a va 2s .co m "Usage: IMAPImportMbox imap[s]://user:password@host[:port]/folder/path <mboxfile> [selectors]"); System.err.println("\tWhere: a selector is a list of numbers/number ranges - 1,2,3-10" + " - or a list of strings to match in the initial From line"); System.exit(1); } final URI uri = URI.create(args[0]); final String file = args[1]; final File mbox = new File(file); if (!mbox.isFile() || !mbox.canRead()) { throw new IOException("Cannot read mailbox file: " + mbox); } String path = uri.getPath(); if (path == null || path.length() < 1) { throw new IllegalArgumentException("Invalid folderPath: '" + path + "'"); } String folder = path.substring(1); // skip the leading / List<String> contains = new ArrayList<String>(); // list of strings to find BitSet msgNums = new BitSet(); // list of message numbers for (int i = 2; i < args.length; i++) { String arg = args[i]; if (arg.matches("\\d+(-\\d+)?(,\\d+(-\\d+)?)*")) { // number,m-n for (String entry : arg.split(",")) { String[] parts = entry.split("-"); if (parts.length == 2) { // m-n int low = Integer.parseInt(parts[0]); int high = Integer.parseInt(parts[1]); for (int j = low; j <= high; j++) { msgNums.set(j); } } else { msgNums.set(Integer.parseInt(entry)); } } } else { contains.add(arg); // not a number/number range } } // System.out.println(msgNums.toString()); // System.out.println(java.util.Arrays.toString(contains.toArray())); // Connect and login final IMAPClient imap = IMAPUtils.imapLogin(uri, 10000, null); int total = 0; int loaded = 0; try { imap.setSoTimeout(6000); final BufferedReader br = new BufferedReader(new FileReader(file)); // TODO charset? String line; StringBuilder sb = new StringBuilder(); boolean wanted = false; // Skip any leading rubbish while ((line = br.readLine()) != null) { if (line.startsWith("From ")) { // start of message; i.e. end of previous (if any) if (process(sb, imap, folder, total)) { // process previous message (if any) loaded++; } sb.setLength(0); total++; wanted = wanted(total, line, msgNums, contains); } else if (startsWith(line, PATFROM)) { // Unescape ">+From " in body text line = line.substring(1); } // TODO process first Received: line to determine arrival date? if (wanted) { sb.append(line); sb.append(CRLF); } } br.close(); if (wanted && process(sb, imap, folder, total)) { // last message (if any) loaded++; } } catch (IOException e) { System.out.println(imap.getReplyString()); e.printStackTrace(); System.exit(10); return; } finally { imap.logout(); imap.disconnect(); } System.out.println("Processed " + total + " messages, loaded " + loaded); }
From source file:DruidResponseTime.java
public static void main(String[] args) throws Exception { try (CloseableHttpClient client = HttpClients.createDefault()) { HttpPost post = new HttpPost("http://localhost:8082/druid/v2/?pretty"); post.addHeader("content-type", "application/json"); CloseableHttpResponse res;//ww w. j a v a 2 s . c om if (STORE_RESULT) { File dir = new File(RESULT_DIR); if (!dir.exists()) { dir.mkdirs(); } } int length; // Make sure all segments online System.out.println("Test if number of records is " + RECORD_NUMBER); post.setEntity(new StringEntity("{" + "\"queryType\":\"timeseries\"," + "\"dataSource\":\"tpch_lineitem\"," + "\"intervals\":[\"1992-01-01/1999-01-01\"]," + "\"granularity\":\"all\"," + "\"aggregations\":[{\"type\":\"count\",\"name\":\"count\"}]}")); while (true) { System.out.print('*'); res = client.execute(post); boolean valid; try (BufferedInputStream in = new BufferedInputStream(res.getEntity().getContent())) { length = in.read(BYTE_BUFFER); valid = new String(BYTE_BUFFER, 0, length, "UTF-8").contains("\"count\" : 6001215"); } res.close(); if (valid) { break; } else { Thread.sleep(5000); } } System.out.println("Number of Records Test Passed"); for (int i = 0; i < QUERIES.length; i++) { System.out.println( "--------------------------------------------------------------------------------"); System.out.println("Start running query: " + QUERIES[i]); try (BufferedReader reader = new BufferedReader( new FileReader(QUERY_FILE_DIR + File.separator + i + ".json"))) { length = reader.read(CHAR_BUFFER); post.setEntity(new StringEntity(new String(CHAR_BUFFER, 0, length))); } // Warm-up Rounds System.out.println("Run " + WARMUP_ROUND + " times to warm up cache..."); for (int j = 0; j < WARMUP_ROUND; j++) { res = client.execute(post); res.close(); System.out.print('*'); } System.out.println(); // Test Rounds int[] time = new int[TEST_ROUND]; int totalTime = 0; System.out.println("Run " + TEST_ROUND + " times to get average time..."); for (int j = 0; j < TEST_ROUND; j++) { long startTime = System.currentTimeMillis(); res = client.execute(post); long endTime = System.currentTimeMillis(); if (STORE_RESULT && j == 0) { try (BufferedInputStream in = new BufferedInputStream(res.getEntity().getContent()); BufferedWriter writer = new BufferedWriter( new FileWriter(RESULT_DIR + File.separator + i + ".json", false))) { while ((length = in.read(BYTE_BUFFER)) > 0) { writer.write(new String(BYTE_BUFFER, 0, length, "UTF-8")); } } } res.close(); time[j] = (int) (endTime - startTime); totalTime += time[j]; System.out.print(time[j] + "ms "); } System.out.println(); // Process Results double avgTime = (double) totalTime / TEST_ROUND; double stdDev = 0; for (int temp : time) { stdDev += (temp - avgTime) * (temp - avgTime) / TEST_ROUND; } stdDev = Math.sqrt(stdDev); System.out.println("The average response time for the query is: " + avgTime + "ms"); System.out.println("The standard deviation is: " + stdDev); } } }
From source file:com.aestel.chemistry.openEye.fp.apps.SDFFPNNFinder.java
public static void main(String... args) throws IOException { CommandLineParser parser = new PosixParser(); CommandLine cmd = null;/*from ww w.ja v a2s.c om*/ try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println(e.getMessage()); exitWithHelp(); } args = cmd.getArgs(); if (args.length > 0) { exitWithHelp("Unknown param: " + args[0]); } if (cmd.hasOption("d")) { System.err.println("Start debugger and press return:"); new BufferedReader(new InputStreamReader(System.in)).readLine(); } int nCpu = 1; int maxNeighbors = 1; double minSim = 0D; String fpTag = cmd.getOptionValue("fpTag"); String idTag = cmd.getOptionValue("idTag"); boolean doMaxTanimoto = cmd.hasOption("maxTanimoto"); boolean printAll = cmd.hasOption("printAll"); String d = cmd.getOptionValue("nCpu"); if (d != null) nCpu = Integer.parseInt(d); d = cmd.getOptionValue("maxNeighbors"); if (d != null) maxNeighbors = Integer.parseInt(d); d = cmd.getOptionValue("minSimilarity"); if (d != null) minSim = Double.parseDouble(d); String countAboveSimilarityStr = cmd.getOptionValue("countSimilarAbove"); String inFile = cmd.getOptionValue("in"); String outFile = cmd.getOptionValue("out"); String refFile = cmd.getOptionValue("ref"); String tabOutput = cmd.getOptionValue("tabOutput"); boolean outputDuplicates = cmd.hasOption("outputDuplicates"); if (outputDuplicates && tabOutput != null) exitWithHelp("-outputDuplicates will not work with tabOutput"); if (outputDuplicates && refFile == null) exitWithHelp("-outputDuplicates requires -ref "); if ("tab".equalsIgnoreCase(tabOutput) && refFile != null) exitWithHelp("-tabOutput tab: does not work with reference file"); if ("tab".equalsIgnoreCase(tabOutput) && maxNeighbors == 1) exitWithHelp("-tabOutput tab: does not make sense with -maxNeighbors = 1"); if (cmd.hasOption("countSimilarAbove") && tabOutput != null) exitWithHelp("-countSimilarAbove not supported for tab or vTab output"); if (printAll && !(maxNeighbors > 1 || minSim > 0)) exitWithHelp("printAll only supported if: maxNeighbors > 1 or minSim > 0"); if (printAll && tabOutput != null) System.err.println("WARNING: printAll ignored tor tab output!\n"); SimComparatorFactory<OEMolBase, FPComparator, FPComparator> compFact = new FPComparatorFact(doMaxTanimoto, fpTag); if (refFile == null) { perfromMatrixNNSearch(inFile, outFile, tabOutput, compFact, minSim, maxNeighbors, idTag, nCpu, countAboveSimilarityStr, printAll); } else { performReferenceSearch(inFile, refFile, outFile, tabOutput, compFact, minSim, maxNeighbors, idTag, nCpu, countAboveSimilarityStr, outputDuplicates, printAll); } }
From source file:edu.wisc.doit.tcrypt.cli.TokenCrypt.java
public static void main(String[] args) throws IOException { // create Options object final Options options = new Options(); // operation opt group final OptionGroup cryptTypeGroup = new OptionGroup(); cryptTypeGroup.addOption(new Option("e", "encrypt", false, "Encrypt a token")); cryptTypeGroup.addOption(new Option("d", "decrypt", false, "Decrypt a token")); cryptTypeGroup/*w w w. j ava 2 s. co m*/ .addOption(new Option("c", "check", false, "Check if the string looks like an encrypted token")); cryptTypeGroup.setRequired(true); options.addOptionGroup(cryptTypeGroup); // token source opt group final OptionGroup tokenGroup = new OptionGroup(); final Option tokenOpt = new Option("t", "token", true, "The token(s) to operate on"); tokenOpt.setArgs(Option.UNLIMITED_VALUES); tokenGroup.addOption(tokenOpt); final Option tokenFileOpt = new Option("f", "file", true, "A file with one token per line to operate on, if - is specified stdin is used"); tokenGroup.addOption(tokenFileOpt); tokenGroup.setRequired(true); options.addOptionGroup(tokenGroup); final Option keyOpt = new Option("k", "keyFile", true, "Key file to use. Must be a private key for decryption and a public key for encryption"); keyOpt.setRequired(true); options.addOption(keyOpt); // create the parser final CommandLineParser parser = new GnuParser(); CommandLine line = null; try { // parse the command line arguments line = parser.parse(options, args); } catch (ParseException exp) { // automatically generate the help statement System.err.println(exp.getMessage()); final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java " + TokenCrypt.class.getName(), options, true); System.exit(1); } final Reader keyReader = createKeyReader(line); final TokenHandler tokenHandler = createTokenHandler(line, keyReader); if (line.hasOption("t")) { //tokens on cli final String[] tokens = line.getOptionValues("t"); for (final String token : tokens) { handleToken(tokenHandler, token); } } else { //tokens from a file final String tokenFile = line.getOptionValue("f"); final BufferedReader fileReader; if ("-".equals(tokenFile)) { fileReader = new BufferedReader(new InputStreamReader(System.in)); } else { fileReader = new BufferedReader(new FileReader(tokenFile)); } while (true) { final String token = fileReader.readLine(); if (token == null) { break; } handleToken(tokenHandler, token); } } }
From source file:com.genentech.chemistry.openEye.apps.SDFRingSystemExtractor.java
/** * @param args/* ww w .j a v a 2 s . com*/ */ public static void main(String... args) throws IOException { // create command line Options object Options options = new Options(); Option opt = new Option(OPT_INFILE, true, "input file oe-supported"); opt.setRequired(true); options.addOption(opt); opt = new Option(OPT_OUTFILE, true, "output file oe-supported"); opt.setRequired(false); options.addOption(opt); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println(e.getMessage()); exitWithHelp(options); } args = cmd.getArgs(); if (cmd.hasOption("d")) { System.err.println("Start debugger and press return:"); new BufferedReader(new InputStreamReader(System.in)).readLine(); } String inFile = cmd.getOptionValue(OPT_INFILE); String outFile = cmd.getOptionValue(OPT_OUTFILE); SDFRingSystemExtractor extractor = new SDFRingSystemExtractor(outFile); extractor.run(inFile); extractor.close(); }
From source file:test.TestJavaService.java
/** * Main. The cmdline arguments either do or don't contain the flag -remote: that's the only supported flag. If it is specified, * we test code on the AWS instance. If it is not, we test code running locally. * The first non-flag argument is the "verb", which (currently) should be one of the verbs set at the top of source file * org.qcert.javasrc.Main. Remaining non-flag arguments are file names. There must be at least one. The number of such * arguments and what they should contain depends on the verb. * @throws Exception// w w w .java2 s . com */ public static void main(String[] args) throws Exception { /* Parse command line */ List<String> files = new ArrayList<>(); String loc = "localhost", verb = null; for (String arg : args) { if (arg.equals("-remote")) loc = REMOTE_LOC; else if (arg.startsWith("-")) illegal(); else if (verb == null) verb = arg; else files.add(arg); } /* Simple consistency checks and verb-specific parsing */ if (files.size() == 0) illegal(); String file = files.remove(0); String schema = null; switch (verb) { case "parseSQL": case "serialRule2CAMP": case "sqlSchema2JSON": if (files.size() != 0) illegal(); break; case "techRule2CAMP": if (files.size() != 1) illegal(); schema = files.get(0); break; case "csv2JSON": if (files.size() < 1) illegal(); break; default: illegal(); } /* Assemble information from arguments */ String url = String.format("http://%s:9879?verb=%s", loc, verb); byte[] contents = Files.readAllBytes(Paths.get(file)); String toSend; if ("serialRule2CAMP".equals(verb)) toSend = Base64.getEncoder().encodeToString(contents); else toSend = new String(contents); if ("techRule2CAMP".equals(verb)) toSend = makeSpecialJson(toSend, schema); else if ("csv2JSON".equals(verb)) toSend = makeSpecialJson(toSend, files); HttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(url); StringEntity entity = new StringEntity(toSend); entity.setContentType("text/plain"); post.setEntity(entity); HttpResponse resp = client.execute(post); int code = resp.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { HttpEntity answer = resp.getEntity(); InputStream s = answer.getContent(); BufferedReader rdr = new BufferedReader(new InputStreamReader(s)); String line = rdr.readLine(); while (line != null) { System.out.println(line); line = rdr.readLine(); } rdr.close(); s.close(); } else System.out.println(resp.getStatusLine()); }
From source file:EchoClient.java
public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try {//from w ww. j a v a 2s .c om serverSocket = new ServerSocket(4444); } catch (IOException e) { System.err.println("Could not listen on port: 4444."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader( clientSocket.getInputStream())); String inputLine, outputLine; KnockKnockProtocol kkp = new KnockKnockProtocol(); outputLine = kkp.processInput(null); out.println(outputLine); while ((inputLine = in.readLine()) != null) { outputLine = kkp.processInput(inputLine); out.println(outputLine); if (outputLine.equals("Bye.")) break; } out.close(); in.close(); clientSocket.close(); serverSocket.close(); }
From source file:com.act.lcms.MassCalculator2.java
public static void main(String[] args) throws Exception { CommandLine cl = CLI_UTIL.parseCommandLine(args); if (cl.hasOption(OPTION_LICENSE_FILE)) { LOGGER.info("Using license file at %s", cl.getOptionValue(OPTION_LICENSE_FILE)); LicenseManager.setLicenseFile(cl.getOptionValue(OPTION_LICENSE_FILE)); }/* w ww .jav a 2 s .c om*/ List<String> inchis = new ArrayList<>(); if (cl.hasOption(OPTION_INPUT_FILE)) { try (BufferedReader reader = new BufferedReader(new FileReader(cl.getOptionValue(OPTION_INPUT_FILE)))) { String line; while ((line = reader.readLine()) != null) { inchis.add(line); } } } if (cl.getArgList().size() > 0) { LOGGER.info("Reading %d InChIs from the command line", cl.getArgList().size()); inchis.addAll(cl.getArgList()); } try (PrintWriter writer = new PrintWriter( cl.hasOption(OPTION_OUTPUT_FILE) ? new FileWriter(cl.getOptionValue(OPTION_OUTPUT_FILE)) : new OutputStreamWriter(System.out))) { writer.format("InChI\tMass\tCharge\n"); for (String inchi : inchis) { try { Pair<Double, Integer> massAndCharge = calculateMassAndCharge(inchi); writer.format("%s\t%.6f\t%3d\n", inchi, massAndCharge.getLeft(), massAndCharge.getRight()); } catch (MolFormatException e) { LOGGER.error("Unable to compute mass for %s: %s", inchi, e.getMessage()); } } } }