List of usage examples for java.io InputStreamReader InputStreamReader
public InputStreamReader(InputStream in)
From source file:cc.twittertools.util.ExtractSubcollection.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("dir").hasArg().withDescription("source collection directory") .create(COLLECTION_OPTION)); options.addOption(//from ww w. j a v a 2s. com OptionBuilder.withArgName("file").hasArg().withDescription("list of tweetids").create(ID_OPTION)); 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(COLLECTION_OPTION) || !cmdline.hasOption(ID_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(ExtractSubcollection.class.getName(), options); System.exit(-1); } String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION); LongOpenHashSet tweetids = new LongOpenHashSet(); File tweetidsFile = new File(cmdline.getOptionValue(ID_OPTION)); if (!tweetidsFile.exists()) { System.err.println("Error: " + tweetidsFile + " does not exist!"); System.exit(-1); } LOG.info("Reading tweetids from " + tweetidsFile); FileInputStream fin = new FileInputStream(tweetidsFile); BufferedReader br = new BufferedReader(new InputStreamReader(fin)); String s; while ((s = br.readLine()) != null) { tweetids.add(Long.parseLong(s)); } br.close(); fin.close(); LOG.info("Read " + tweetids.size() + " tweetids."); File file = new File(collectionPath); if (!file.exists()) { System.err.println("Error: " + file + " does not exist!"); System.exit(-1); } PrintStream out = new PrintStream(System.out, true, "UTF-8"); StatusStream stream = new JsonStatusCorpusReader(file); Status status; while ((status = stream.next()) != null) { if (tweetids.contains(status.getId())) { out.println(status.getJsonObject().toString()); } } stream.close(); out.close(); }
From source file:org.mzd.shap.spring.cli.ConfigSetup.java
public static void main(String[] args) { // check args if (args.length != 1) { exitOnError(1, null);/*from w w w.j ava 2s . c o m*/ } // check file existance File analyzerXML = new File(args[0]); if (!analyzerXML.exists()) { exitOnError(1, "'" + analyzerXML.getPath() + "' did not exist\n"); } // prompt user whether existing data should be purged boolean isPurged = false; String ormContext = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { System.out.println("\nDo you wish to purge the database before running setup?"); System.out.println("WARNING: all existing data in SHAP will be lost!"); System.out.println("Really purge? yes/[NO]"); String ans = br.readLine(); if (ans.toLowerCase().equals("yes")) { System.out.println("Purging enabled"); ormContext = "orm-purge-context.xml"; isPurged = true; } else { System.out.println("Purging disabled"); ormContext = "orm-context.xml"; } } catch (IOException ex) { throw new RuntimeException(ex); } // run tool try { // Using a generic application context since we're referencing // both classpath and filesystem resources. GenericApplicationContext ctx = new GenericApplicationContext(); XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx); xmlReader.loadBeanDefinitions(new ClassPathResource("datasource-context.xml"), new ClassPathResource(ormContext), new FileSystemResource(analyzerXML)); ctx.refresh(); /* * Create an base admin user. */ if (isPurged) { //only attempted if we've wiped the old database. RoleDao roleDao = (RoleDao) ctx.getBean("roleDao"); Role adminRole = roleDao.saveOrUpdate(new Role("admin", "ROLE_ADMIN")); Role userRole = roleDao.saveOrUpdate(new Role("user", "ROLE_USER")); UserDao userDao = (UserDao) ctx.getBean("userDao"); userDao.saveOrUpdate(new User("admin", "admin", "shap01", adminRole, userRole)); } /* * Create some predefined analyzers. Users should have modified * the configuration file to suit their environment. */ AnnotatorDao annotatorDao = (AnnotatorDao) ctx.getBean("annotatorDao"); DetectorDao detectorDao = (DetectorDao) ctx.getBean("detectorDao"); ConfigSetup config = (ConfigSetup) ctx.getBean("configuration"); for (Annotator an : config.getAnnotators()) { System.out.println("Adding annotator: " + an.getName()); annotatorDao.saveOrUpdate(an); } for (Detector dt : config.getDetectors()) { System.out.println("Adding detector: " + dt.getName()); detectorDao.saveOrUpdate(dt); } System.exit(0); } catch (Throwable t) { System.err.println(t.getMessage()); System.exit(1); } }
From source file:com.genentech.struchk.OEMDLPercieveChecker.java
public static void main(String[] args) throws ParseException, JDOMException, IOException { // create command line Options object Options options = new Options(); Option opt = new Option("i", true, "input file [.ism,.sdf,...]"); opt.setRequired(true);/*from w ww . ja v a 2 s .c o m*/ options.addOption(opt); opt = new Option("o", true, "output file"); opt.setRequired(false); options.addOption(opt); opt = new Option("d", false, "debug: wait for user to press key at startup."); 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(); } if (args.length != 0) { exitWithHelp(options); } String inFile = cmd.getOptionValue("i"); String outFile = cmd.getOptionValue("o"); OEMDLPercieveChecker checker = null; try { checker = new OEMDLPercieveChecker(); oemolostream out = new oemolostream(outFile); oemolistream in = new oemolistream(inFile); OEGraphMol mol = new OEGraphMol(); while (oechem.OEReadMolecule(in, mol)) { if (!checker.checkMol(mol)) oechem.OEWriteMolecule(out, mol); } checker.delete(); in.close(); in.delete(); out.close(); out.delete(); } catch (Exception e) { throw new Error(e); } System.err.println("Done:"); }
From source file:cc.twittertools.util.VerifySubcollection.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("dir").hasArg().withDescription("source collection directory") .create(COLLECTION_OPTION)); options.addOption(// www . j ava2s. com OptionBuilder.withArgName("file").hasArg().withDescription("list of tweetids").create(ID_OPTION)); 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(COLLECTION_OPTION) || !cmdline.hasOption(ID_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(ExtractSubcollection.class.getName(), options); System.exit(-1); } String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION); LongOpenHashSet tweetids = new LongOpenHashSet(); File tweetidsFile = new File(cmdline.getOptionValue(ID_OPTION)); if (!tweetidsFile.exists()) { System.err.println("Error: " + tweetidsFile + " does not exist!"); System.exit(-1); } LOG.info("Reading tweetids from " + tweetidsFile); FileInputStream fin = new FileInputStream(tweetidsFile); BufferedReader br = new BufferedReader(new InputStreamReader(fin)); String s; while ((s = br.readLine()) != null) { tweetids.add(Long.parseLong(s)); } br.close(); fin.close(); LOG.info("Read " + tweetids.size() + " tweetids."); File file = new File(collectionPath); if (!file.exists()) { System.err.println("Error: " + file + " does not exist!"); System.exit(-1); } LongOpenHashSet seen = new LongOpenHashSet(); TreeMap<Long, String> tweets = Maps.newTreeMap(); PrintStream out = new PrintStream(System.out, true, "UTF-8"); StatusStream stream = new JsonStatusCorpusReader(file); Status status; int cnt = 0; while ((status = stream.next()) != null) { if (!tweetids.contains(status.getId())) { LOG.error("tweetid " + status.getId() + " doesn't belong in collection"); continue; } if (seen.contains(status.getId())) { LOG.error("tweetid " + status.getId() + " already seen!"); continue; } tweets.put(status.getId(), status.getJsonObject().toString()); seen.add(status.getId()); cnt++; } LOG.info("total of " + cnt + " tweets in subcollection."); for (Map.Entry<Long, String> entry : tweets.entrySet()) { out.println(entry.getValue()); } stream.close(); out.close(); }
From source file:edu.cmu.lti.oaqa.apps.Client.java
public static void main(String args[]) { BufferedReader inp = new BufferedReader(new InputStreamReader(System.in)); Options opt = new Options(); Option o = new Option(PORT_SHORT_PARAM, PORT_LONG_PARAM, true, PORT_DESC); o.setRequired(true);//from w ww . j a v a 2s .co m opt.addOption(o); o = new Option(HOST_SHORT_PARAM, HOST_LONG_PARAM, true, HOST_DESC); o.setRequired(true); opt.addOption(o); opt.addOption(K_SHORT_PARAM, K_LONG_PARAM, true, K_DESC); opt.addOption(R_SHORT_PARAM, R_LONG_PARAM, true, R_DESC); opt.addOption(QUERY_TIME_SHORT_PARAM, QUERY_TIME_LONG_PARAM, true, QUERY_TIME_DESC); opt.addOption(RET_OBJ_SHORT_PARAM, RET_OBJ_LONG_PARAM, false, RET_OBJ_DESC); opt.addOption(RET_EXTERN_ID_SHORT_PARAM, RET_EXTERN_ID_LONG_PARAM, false, RET_EXTERN_ID_DESC); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try { CommandLine cmd = parser.parse(opt, args); String host = cmd.getOptionValue(HOST_SHORT_PARAM); String tmp = null; tmp = cmd.getOptionValue(PORT_SHORT_PARAM); int port = -1; try { port = Integer.parseInt(tmp); } catch (NumberFormatException e) { Usage("Port should be integer!"); } boolean retObj = cmd.hasOption(RET_OBJ_SHORT_PARAM); boolean retExternId = cmd.hasOption(RET_EXTERN_ID_SHORT_PARAM); String queryTimeParams = cmd.getOptionValue(QUERY_TIME_SHORT_PARAM); if (null == queryTimeParams) queryTimeParams = ""; SearchType searchType = SearchType.kKNNSearch; int k = 0; double r = 0; if (cmd.hasOption(K_SHORT_PARAM)) { if (cmd.hasOption(R_SHORT_PARAM)) { Usage("Range search is not allowed if the KNN search is specified!"); } tmp = cmd.getOptionValue(K_SHORT_PARAM); try { k = Integer.parseInt(tmp); } catch (NumberFormatException e) { Usage("K should be integer!"); } searchType = SearchType.kKNNSearch; } else if (cmd.hasOption(R_SHORT_PARAM)) { if (cmd.hasOption(K_SHORT_PARAM)) { Usage("KNN search is not allowed if the range search is specified!"); } searchType = SearchType.kRangeSearch; tmp = cmd.getOptionValue(R_SHORT_PARAM); try { r = Double.parseDouble(tmp); } catch (NumberFormatException e) { Usage("The range value should be numeric!"); } } else { Usage("One has to specify either range or KNN-search parameter"); } String separator = System.getProperty("line.separator"); StringBuffer sb = new StringBuffer(); String s; while ((s = inp.readLine()) != null) { sb.append(s); sb.append(separator); } String queryObj = sb.toString(); try { TTransport transport = new TSocket(host, port); transport.open(); TProtocol protocol = new TBinaryProtocol(transport); QueryService.Client client = new QueryService.Client(protocol); if (!queryTimeParams.isEmpty()) client.setQueryTimeParams(queryTimeParams); List<ReplyEntry> res = null; long t1 = System.nanoTime(); if (searchType == SearchType.kKNNSearch) { System.out.println(String.format("Running a %d-NN search", k)); res = client.knnQuery(k, queryObj, retExternId, retObj); } else { System.out.println(String.format("Running a range search (r=%g)", r)); res = client.rangeQuery(r, queryObj, retExternId, retObj); } long t2 = System.nanoTime(); System.out.println(String.format("Finished in %g ms", (t2 - t1) / 1e6)); for (ReplyEntry e : res) { System.out.println(String.format("id=%d dist=%g %s", e.getId(), e.getDist(), retExternId ? "externId=" + e.getExternId() : "")); if (retObj) System.out.println(e.getObj()); } transport.close(); // Close transport/socket ! } catch (TException te) { System.err.println("Apache Thrift exception: " + te); te.printStackTrace(); } } catch (ParseException e) { Usage("Cannot parse arguments"); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }
From source file:httpclient.UploadAction.java
public static void main(String[] args) throws FileNotFoundException { File targetFile1 = new File("F:\\2.jpg"); // File targetFile2 = new File("F:\\1.jpg"); FileInputStream fis1 = new FileInputStream(targetFile1); // FileInputStream fis2 = new FileInputStream(targetFile2); // String targetURL = // "http://static.fangbiandian.com.cn/round_server/upload/uploadFile.do"; String targetURL = "http://www.fangbiandian.com.cn/round_server/user/updateUserInfo.do"; HttpPost filePost = new HttpPost(targetURL); try {//w w w . j a v a2 s . com // ????? HttpClient client = new DefaultHttpClient(); // FormBodyPart fbp1 = new FormBodyPart("file1", new // FileBody(targetFile1)); // FormBodyPart fbp2 = new FormBodyPart("file2", new // FileBody(targetFile2)); // FormBodyPart fbp3 = new FormBodyPart("file3", new // FileBody(targetFile3)); // List<FormBodyPart> picList = new ArrayList<FormBodyPart>(); // picList.add(fbp1); // picList.add(fbp2); // picList.add(fbp3); Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("userId", "65478A5CD8D20C3807EE16CF22AF8A17"); Map<String, Object> map = new HashMap<String, Object>(); String jsonStr = JSON.toJSONString(paramMap); map.put("cid", 321); map.put("request", jsonStr); String jsonString = JSON.toJSONString(map); MultipartEntity multiEntity = new MultipartEntity(); Charset charset = Charset.forName("UTF-8"); multiEntity.addPart("request", new StringBody(jsonString, charset)); multiEntity.addPart("photo", new InputStreamBody(fis1, "2.jpg")); // multiEntity.addPart("licenseUrl", new InputStreamBody(fis2, // "1.jpg")); filePost.setEntity(multiEntity); HttpResponse response = client.execute(filePost); int code = response.getStatusLine().getStatusCode(); System.out.println(code); if (HttpStatus.SC_OK == code) { System.out.println("?"); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { // do something useful BufferedReader reader = new BufferedReader(new InputStreamReader(instream)); String str = null; while ((str = reader.readLine()) != null) { System.out.println(str); } } finally { instream.close(); } } } else { System.out.println(""); } } catch (Exception ex) { ex.printStackTrace(); } finally { filePost.releaseConnection(); } }
From source file:com.janrain.backplane.common.HmacHashUtils.java
public static void main(String[] args) throws IOException { String password;//from w ww . ja v a 2 s . co m if (args.length == 1) { password = args[0]; } else { System.out.print("Password: "); password = new BufferedReader(new InputStreamReader(System.in)).readLine(); } System.out.println("hmac hash: " + hmacHash(password)); }
From source file:edu.scripps.fl.pubchem.app.CIDDownloader.java
public static void main(String[] args) throws Exception { CIDDownloader fetcher = new CIDDownloader(); CommandLineHandler clh = new CommandLineHandler() { public void configureOptions(Options options) { options.addOption(OptionBuilder.withLongOpt("input_file").withType("").withValueSeparator('=') .hasArg().create()); options.addOption(OptionBuilder.withLongOpt("output_file").withType("").withValueSeparator('=') .hasArg().isRequired().create()); }/* w w w. j a v a2 s .c o m*/ }; args = clh.handle(args); String inputFile = clh.getCommandLine().getOptionValue("input_file"); String outputFile = clh.getCommandLine().getOptionValue("output_file"); fetcher.setOutputFile(outputFile); Iterator<?> iterator; if (null == inputFile) { if (args.length == 0) { log.info("Running query to find CIDs in PCAssayResult but not in PCCompound"); SQLQuery query = PubChemDB.getSession().createSQLQuery( "select distinct r.cid from pcassay_result r left join pccompound c on r.cid = c.cid where (r.cid is not null and r.cid > 0 ) and c.cid is null order by r.cid"); ScrollableResults scroll = query.scroll(ScrollMode.FORWARD_ONLY); iterator = new ScrollableResultsIterator<Integer>(Integer.class, scroll); } else { iterator = Arrays.asList(args).iterator(); } } else if ("-".equals(inputFile)) { log.info("Reading CIDs (one per line) from STDIN"); iterator = new LineIterator(new InputStreamReader(System.in)); } else { log.info("Reading CIDs (one per line) from " + inputFile); iterator = new LineIterator(new FileReader(inputFile)); } fetcher.process(iterator); System.exit(0); }
From source file:edu.mit.fss.examples.ISSFederate.java
/** * The main method. This configures the Orekit data path, creates the * ISS federate objects and launches the associated graphical user * interface./*from w ww . j a va 2s . c o m*/ * * @param args the arguments * @throws RTIexception the RTI exception * @throws URISyntaxException */ public static void main(String[] args) throws RTIexception, URISyntaxException { BasicConfigurator.configure(); boolean headless = false; logger.debug("Setting Orekit data path."); System.setProperty(DataProvidersManager.OREKIT_DATA_PATH, new File(ISSFederate.class.getResource("/orekit-data.zip").toURI()).getAbsolutePath()); logger.trace("Creating federate instance."); final ISSFederate federate = new ISSFederate(); logger.trace("Setting minimum step duration and time step."); long timeStep = 60 * 1000, minimumStepDuration = 100; federate.setMinimumStepDuration(minimumStepDuration); federate.setTimeStep(timeStep); try { logger.debug("Loading TLE data from file."); BufferedReader br = new BufferedReader(new InputStreamReader( federate.getClass().getClassLoader().getResourceAsStream("edu/mit/fss/examples/data.tle"))); final SpaceSystem satellite; final SurfaceSystem station1, station2, station3; while (br.ready()) { if (br.readLine().matches(".*ISS.*")) { logger.debug("Found ISS data."); logger.trace("Adding FSS supplier space system."); satellite = new SpaceSystem("FSS Supplier", new TLE(br.readLine(), br.readLine()), 5123e3); federate.addObject(satellite); logger.trace("Adding Keio ground station."); station1 = new SurfaceSystem("Keio", new GeodeticPoint(FastMath.toRadians(35.551929), FastMath.toRadians(139.647119), 300), satellite.getState().getDate(), 5123e3, 5); federate.addObject(station1); logger.trace("Adding SkolTech ground station."); station2 = new SurfaceSystem("SkolTech", new GeodeticPoint(FastMath.toRadians(55.698679), FastMath.toRadians(37.571994), 200), satellite.getState().getDate(), 5123e3, 5); federate.addObject(station2); logger.trace("Adding MIT ground station."); station3 = new SurfaceSystem("MIT", new GeodeticPoint(FastMath.toRadians(42.360184), FastMath.toRadians(-71.093742), 100), satellite.getState().getDate(), 5123e3, 5); federate.addObject(station3); try { logger.trace("Setting inital time."); federate.setInitialTime( satellite.getInitialState().getDate().toDate(TimeScalesFactory.getUTC()).getTime()); } catch (IllegalArgumentException | OrekitException e) { logger.error(e.getMessage()); e.printStackTrace(); } if (!headless) { logger.debug("Launching the graphical user interface."); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { MemberFrame frame = new MemberFrame(federate, new MultiComponentPanel( Arrays.asList(new SpaceSystemPanel(federate, satellite), new SurfaceSystemPanel(federate, station1), new SurfaceSystemPanel(federate, station2), new SurfaceSystemPanel(federate, station3)))); frame.pack(); frame.setVisible(true); } }); } break; } } br.close(); } catch (InvocationTargetException | InterruptedException | OrekitException | IOException e) { e.printStackTrace(); logger.fatal(e); } logger.trace("Setting federate name, type, and FOM path."); federate.getConnection().setFederateName("ISS"); federate.getConnection().setFederateType("FSS Supplier"); federate.getConnection().setFederationName("FSS"); federate.getConnection().setFomPath( new File(federate.getClass().getClassLoader().getResource("edu/mit/fss/hla/fss.xml").toURI()) .getAbsolutePath()); federate.getConnection().setOfflineMode(false); federate.connect(); if (headless) { federate.setMinimumStepDuration(10); federate.initialize(); federate.run(); } }
From source file:edu.msu.cme.rdp.graph.sandbox.BloomFilterInterrogator.java
public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("USAGE: BloomFilterStats <bloom_filter>"); System.exit(1);/*from ww w.j av a2s . c o m*/ } File bloomFile = new File(args[0]); ObjectInputStream ois = ois = new ObjectInputStream( new BufferedInputStream(new FileInputStream(bloomFile))); BloomFilter filter = (BloomFilter) ois.readObject(); ois.close(); printStats(filter, System.out); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String line; CodonWalker walker = null; while ((line = reader.readLine()) != null) { char[] kmer = line.toCharArray(); System.out.print(line + "\t"); try { walker = filter.new RightCodonFacade(kmer); walker.jumpTo(kmer); System.out.print("present"); } catch (Exception e) { System.out.print("not present\t" + e.getMessage()); } System.out.println(); } }