List of usage examples for java.io BufferedReader BufferedReader
public BufferedReader(Reader in)
From source file:Test.java
public static void main(String[] arstring) throws Exception { SSLServerSocketFactory sslServerSocketFactory = (SSLServerSocketFactory) SSLServerSocketFactory .getDefault();/*w w w . j a v a 2 s.com*/ SSLServerSocket sslServerSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(9999); System.out.println("Waiting for a client ..."); SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); SSLParameters parameters = sslSocket.getSSLParameters(); parameters.setAlgorithmConstraints(new SimpleConstraints()); AlgorithmConstraints constraints = parameters.getAlgorithmConstraints(); System.out.println("Constraint: " + constraints); String endPoint = parameters.getEndpointIdentificationAlgorithm(); System.out.println("End Point: " + endPoint); System.out.println("Local Supported Signature Algorithms"); if (sslSocket.getSession() instanceof ExtendedSSLSession) { ExtendedSSLSession extendedSSLSession = (ExtendedSSLSession) sslSocket.getSession(); String alogrithms[] = extendedSSLSession.getLocalSupportedSignatureAlgorithms(); for (String algorithm : alogrithms) { System.out.println("Algortihm: " + algorithm); } } System.out.println("Peer Supported Signature Algorithms"); if (sslSocket.getSession() instanceof ExtendedSSLSession) { String alogrithms[] = ((ExtendedSSLSession) sslSocket.getSession()) .getPeerSupportedSignatureAlgorithms(); for (String algorithm : alogrithms) { System.out.println("Algortihm: " + algorithm); } } InputStream inputstream = sslSocket.getInputStream(); InputStreamReader inputstreamreader = new InputStreamReader(inputstream); BufferedReader bufferedreader = new BufferedReader(inputstreamreader); SSLSession session = sslSocket.getHandshakeSession(); if (session != null) { System.out.println("Last accessed: " + new Date(session.getLastAccessedTime())); } String string = null; while ((string = bufferedreader.readLine()) != null) { System.out.println(string); System.out.flush(); } }
From source file:com.l2jfree.loginserver.tools.L2AccountManager.java
/** * Launches the interactive account manager. * /*from ww w .j a v a2 s . c o m*/ * @param args ignored */ public static void main(String[] args) { // LOW rework this crap Util.printSection("Account Management"); _log.info("Please choose:"); //_log.info("list - list registered accounts"); _log.info("reg - register a new account"); _log.info("rem - remove a registered account"); _log.info("prom - promote a registered account"); _log.info("dem - demote a registered account"); _log.info("ban - ban a registered account"); _log.info("unban - unban a registered account"); _log.info("quit - exit this application"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); L2AccountManager acm = new L2AccountManager(); String line; try { while ((line = br.readLine()) != null) { line = line.trim(); Connection con = null; switch (acm.getState()) { case USER_NAME: line = line.toLowerCase(); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("SELECT superuser FROM account WHERE username LIKE ?"); ps.setString(1, line); ResultSet rs = ps.executeQuery(); if (!rs.next()) { acm.setUser(line); _log.info("Desired password:"); acm.setState(ManagerState.PASSWORD); } else { _log.info("User name already in use."); acm.setState(ManagerState.INITIAL_CHOICE); } rs.close(); ps.close(); } catch (SQLException e) { _log.error("Could not access database!", e); acm.setState(ManagerState.INITIAL_CHOICE); } finally { L2Database.close(con); } break; case PASSWORD: try { MessageDigest sha = MessageDigest.getInstance("SHA"); byte[] pass = sha.digest(line.getBytes("US-ASCII")); acm.setPass(HexUtil.bytesToHexString(pass)); } catch (NoSuchAlgorithmException e) { _log.fatal("SHA1 is not available!", e); Shutdown.exit(TerminationStatus.ENVIRONMENT_MISSING_COMPONENT_OR_SERVICE); } catch (UnsupportedEncodingException e) { _log.fatal("ASCII is not available!", e); Shutdown.exit(TerminationStatus.ENVIRONMENT_MISSING_COMPONENT_OR_SERVICE); } _log.info("Super user: [y/n]"); acm.setState(ManagerState.SUPERUSER); break; case SUPERUSER: try { if (line.length() != 1) throw new IllegalArgumentException("One char required."); else if (line.charAt(0) == 'y') acm.setSuper(true); else if (line.charAt(0) == 'n') acm.setSuper(false); else throw new IllegalArgumentException("Invalid choice."); _log.info("Date of birth: [yyyy-mm-dd]"); acm.setState(ManagerState.DOB); } catch (IllegalArgumentException e) { _log.info("[y/n]?"); } break; case DOB: try { Date d = Date.valueOf(line); if (d.after(new Date(System.currentTimeMillis()))) throw new IllegalArgumentException("Future date specified."); acm.setDob(d); _log.info("Ban reason ID or nothing:"); acm.setState(ManagerState.SUSPENDED); } catch (IllegalArgumentException e) { _log.info("[yyyy-mm-dd] in the past:"); } break; case SUSPENDED: try { if (line.length() > 0) { int id = Integer.parseInt(line); acm.setBan(L2BanReason.getById(id)); } else acm.setBan(null); try { con = L2Database.getConnection(); PreparedStatement ps = con.prepareStatement( "INSERT INTO account (username, password, superuser, birthDate, banReason) VALUES (?, ?, ?, ?, ?)"); ps.setString(1, acm.getUser()); ps.setString(2, acm.getPass()); ps.setBoolean(3, acm.isSuper()); ps.setDate(4, acm.getDob()); L2BanReason lbr = acm.getBan(); if (lbr == null) ps.setNull(5, Types.INTEGER); else ps.setInt(5, lbr.getId()); ps.executeUpdate(); _log.info("Account " + acm.getUser() + " has been registered."); ps.close(); } catch (SQLException e) { _log.error("Could not register an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); } catch (NumberFormatException e) { _log.info("Ban reason ID or nothing:"); } break; case REMOVE: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con.prepareStatement("DELETE FROM account WHERE username LIKE ?"); ps.setString(1, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been removed."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not remove an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case PROMOTE: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET superuser = ? WHERE username LIKE ?"); ps.setBoolean(1, true); ps.setString(2, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been promoted."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not promote an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case DEMOTE: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET superuser = ? WHERE username LIKE ?"); ps.setBoolean(1, false); ps.setString(2, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been demoted."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not demote an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case UNBAN: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET banReason = ? WHERE username LIKE ?"); ps.setNull(1, Types.INTEGER); ps.setString(2, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been unbanned."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not demote an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case BAN: line = line.toLowerCase(); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("SELECT superuser FROM account WHERE username LIKE ?"); ps.setString(1, line); ResultSet rs = ps.executeQuery(); if (rs.next()) { acm.setUser(line); _log.info("Ban reason ID:"); acm.setState(ManagerState.REASON); } else { _log.info("Account does not exist."); acm.setState(ManagerState.INITIAL_CHOICE); } rs.close(); ps.close(); } catch (SQLException e) { _log.error("Could not access database!", e); acm.setState(ManagerState.INITIAL_CHOICE); } finally { L2Database.close(con); } break; case REASON: try { int ban = Integer.parseInt(line); con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET banReason = ? WHERE username LIKE ?"); ps.setInt(1, ban); ps.setString(2, acm.getUser()); ps.executeUpdate(); _log.info("Account " + acm.getUser() + " has been banned."); ps.close(); } catch (NumberFormatException e) { _log.info("Ban reason ID:"); } catch (SQLException e) { _log.error("Could not ban an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; default: line = line.toLowerCase(); if (line.equals("reg")) { _log.info("Desired user name:"); acm.setState(ManagerState.USER_NAME); } else if (line.equals("rem")) { _log.info("User name:"); acm.setState(ManagerState.REMOVE); } else if (line.equals("prom")) { _log.info("User name:"); acm.setState(ManagerState.PROMOTE); } else if (line.equals("dem")) { _log.info("User name:"); acm.setState(ManagerState.DEMOTE); } else if (line.equals("unban")) { _log.info("User name:"); acm.setState(ManagerState.UNBAN); } else if (line.equals("ban")) { _log.info("User name:"); acm.setState(ManagerState.BAN); } else if (line.equals("quit")) Shutdown.exit(TerminationStatus.MANUAL_SHUTDOWN); else _log.info("Incorrect command."); break; } } } catch (IOException e) { _log.fatal("Could not process input!", e); } finally { IOUtils.closeQuietly(br); } }
From source file:com.aestel.chemistry.openEye.fp.apps.SDFFPSphereExclusion.java
public static void main(String... args) throws IOException { // create command line Options object Options options = new Options(); Option opt = new Option("in", true, "input file [.sdf,...]"); opt.setRequired(true);/* www. j ava 2 s.c o m*/ options.addOption(opt); opt = new Option("out", true, "output file oe-supported"); opt.setRequired(false); options.addOption(opt); opt = new Option("ref", true, "refrence file to be loaded before starting"); opt.setRequired(false); options.addOption(opt); opt = new Option("fpTag", true, "field containing fingerpPrint"); opt.setRequired(true); options.addOption(opt); opt = new Option("maxTanimoto", false, "If given the modified maxTanimoto will be used = common/(2*Max(na,nb)-common)."); opt.setRequired(false); options.addOption(opt); opt = new Option("radius", true, "radius of exclusion sphere, exclude anything with similarity >= radius."); opt.setRequired(true); options.addOption(opt); opt = new Option("printSphereMatchCount", false, "check and print membership of candidates not " + " only to the first centroid which has sim >= radius but to all centroids" + " found up to that input. This will output a candidate multiple times." + " Implies checkSpheresInOrder."); options.addOption(opt); opt = new Option("checkSpheresInOrder", false, "For each candiate: compare to centroids from first to last (default is last to first)"); options.addOption(opt); opt = new Option("printAll", false, "print all molecule, check includeIdx tag"); 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(); } // the only reason not to match centroids in reverse order id if // a non-centroid is to be assigned to multiple centroids boolean printSphereMatchCount = cmd.hasOption("printSphereMatchCount"); boolean reverseMatch = !cmd.hasOption("checkSpheresInOrder") && !printSphereMatchCount; boolean printAll = cmd.hasOption("printAll") || printSphereMatchCount; boolean doMaxTanimoto = cmd.hasOption("maxTanimoto"); String fpTag = cmd.getOptionValue("fpTag"); double radius = Double.parseDouble(cmd.getOptionValue("radius")); String inFile = cmd.getOptionValue("in"); String outFile = cmd.getOptionValue("out"); String refFile = cmd.getOptionValue("ref"); SimComparatorFactory<OEMolBase, FPComparator, FPComparator> compFact = new FPComparatorFact(doMaxTanimoto, fpTag); SphereExclusion<FPComparator, FPComparator> alg = new SphereExclusion<FPComparator, FPComparator>(compFact, refFile, outFile, radius, reverseMatch, printSphereMatchCount, printAll); alg.run(inFile); alg.close(); }
From source file:edu.clemson.cs.nestbed.server.tools.BuildTestbed.java
public static void main(String[] args) { try {/*from w w w . j a v a 2 s .co m*/ BasicConfigurator.configure(); //loadProperties(); if (args.length < 2) { System.out.println("Usage: BuildTestbed <testbedID> <inputfile>"); System.exit(0); } int testbedID = Integer.parseInt(args[0]); String filename = args[1]; Connection conn = null; Statement statement = null; MoteSqlAdapter adapter = new MoteSqlAdapter(); Map<Integer, Mote> motes = adapter.readMotes(); log.info(motes); String connStr = System.getProperty("nestbed.options.databaseConnectionString"); log.info("connStr: " + connStr); conn = DriverManager.getConnection(connStr); statement = conn.createStatement(); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); String line; while ((line = in.readLine()) != null) { StringTokenizer tokenizer = new StringTokenizer(line); int address = Integer.parseInt(tokenizer.nextToken()); String serial = tokenizer.nextToken(); int xLoc = Integer.parseInt(tokenizer.nextToken()); int yLoc = Integer.parseInt(tokenizer.nextToken()); log.info("Input Mote:\n" + "-----------\n" + "address: " + address + "\n" + "serial: " + serial + "\n" + "xLoc: " + xLoc + "\n" + "yLoc: " + yLoc); for (Mote i : motes.values()) { if (i.getMoteSerialID().equals(serial)) { String query = "INSERT INTO MoteTestbedAssignments" + "(testbedID, moteID, moteAddress," + " moteLocationX, moteLocationY) VALUES (" + testbedID + ", " + i.getID() + ", " + address + ", " + xLoc + ", " + yLoc + ")"; log.info(query); statement.executeUpdate(query); } } } conn.commit(); } catch (Exception ex) { log.error("Exception in main", ex); } }
From source file:smtpsend.java
public static void main(String[] argv) { String to, subject = null, from = null, cc = null, bcc = null, url = null; String mailhost = null;//from w ww .j a va2s.c om String mailer = "smtpsend"; String file = null; String protocol = null, host = null, user = null, password = null; String record = null; // name of folder in which to record mail boolean debug = false; boolean verbose = false; boolean auth = false; boolean ssl = false; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int optind; for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { host = argv[++optind]; } else if (argv[optind].equals("-U")) { user = argv[++optind]; } else if (argv[optind].equals("-P")) { password = argv[++optind]; } else if (argv[optind].equals("-M")) { mailhost = argv[++optind]; } else if (argv[optind].equals("-f")) { record = argv[++optind]; } else if (argv[optind].equals("-a")) { file = argv[++optind]; } else if (argv[optind].equals("-s")) { subject = argv[++optind]; } else if (argv[optind].equals("-o")) { // originator from = argv[++optind]; } else if (argv[optind].equals("-c")) { cc = argv[++optind]; } else if (argv[optind].equals("-b")) { bcc = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("-d")) { debug = true; } else if (argv[optind].equals("-v")) { verbose = true; } else if (argv[optind].equals("-A")) { auth = true; } else if (argv[optind].equals("-S")) { ssl = true; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println("Usage: smtpsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]"); System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]"); System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [-a attach-file]"); System.out.println("\t[-v] [-A] [-S] [address]"); System.exit(1); } else { break; } } try { if (optind < argv.length) { // XXX - concatenate all remaining arguments to = argv[optind]; System.out.println("To: " + to); } else { System.out.print("To: "); System.out.flush(); to = in.readLine(); } if (subject == null) { System.out.print("Subject: "); System.out.flush(); subject = in.readLine(); } else { System.out.println("Subject: " + subject); } Properties props = System.getProperties(); if (mailhost != null) props.put("mail.smtp.host", mailhost); if (auth) props.put("mail.smtp.auth", "true"); // Get a Session object Session session = Session.getInstance(props, null); if (debug) session.setDebug(true); // construct the message Message msg = new MimeMessage(session); if (from != null) msg.setFrom(new InternetAddress(from)); else msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); if (cc != null) msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); if (bcc != null) msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); msg.setSubject(subject); String text = collect(in); if (file != null) { // Attach the specified file. // We need a multipart message to hold the attachment. MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(text); MimeBodyPart mbp2 = new MimeBodyPart(); mbp2.attachFile(file); MimeMultipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); msg.setContent(mp); } else { // If the desired charset is known, you can use // setText(text, charset) msg.setText(text); } msg.setHeader("X-Mailer", mailer); msg.setSentDate(new Date()); // send the thing off /* * The simple way to send a message is this: * * Transport.send(msg); * * But we're going to use some SMTP-specific features for demonstration * purposes so we need to manage the Transport object explicitly. */ SMTPTransport t = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp"); try { if (auth) t.connect(mailhost, user, password); else t.connect(); t.sendMessage(msg, msg.getAllRecipients()); } finally { if (verbose) System.out.println("Response: " + t.getLastServerResponse()); t.close(); } System.out.println("\nMail was sent successfully."); // Keep a copy, if requested. if (record != null) { // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, user, password); else store.connect(); } // Get record Folder. Create if it does not exist. Folder folder = store.getFolder(record); if (folder == null) { System.err.println("Can't get record folder."); System.exit(1); } if (!folder.exists()) folder.create(Folder.HOLDS_MESSAGES); Message[] msgs = new Message[1]; msgs[0] = msg; folder.appendMessages(msgs); System.out.println("Mail was recorded successfully."); } } catch (Exception e) { if (e instanceof SendFailedException) { MessagingException sfe = (MessagingException) e; if (sfe instanceof SMTPSendFailedException) { SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe; System.out.println("SMTP SEND FAILED:"); if (verbose) System.out.println(ssfe.toString()); System.out.println(" Command: " + ssfe.getCommand()); System.out.println(" RetCode: " + ssfe.getReturnCode()); System.out.println(" Response: " + ssfe.getMessage()); } else { if (verbose) System.out.println("Send failed: " + sfe.toString()); } Exception ne; while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) { sfe = (MessagingException) ne; if (sfe instanceof SMTPAddressFailedException) { SMTPAddressFailedException ssfe = (SMTPAddressFailedException) sfe; System.out.println("ADDRESS FAILED:"); if (verbose) System.out.println(ssfe.toString()); System.out.println(" Address: " + ssfe.getAddress()); System.out.println(" Command: " + ssfe.getCommand()); System.out.println(" RetCode: " + ssfe.getReturnCode()); System.out.println(" Response: " + ssfe.getMessage()); } else if (sfe instanceof SMTPAddressSucceededException) { System.out.println("ADDRESS SUCCEEDED:"); SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) sfe; if (verbose) System.out.println(ssfe.toString()); System.out.println(" Address: " + ssfe.getAddress()); System.out.println(" Command: " + ssfe.getCommand()); System.out.println(" RetCode: " + ssfe.getReturnCode()); System.out.println(" Response: " + ssfe.getMessage()); } } } else { System.out.println("Got Exception: " + e); if (verbose) e.printStackTrace(); } } }
From source file:JALPTest.java
/** * The main method that gets called to test JALoP. * * @param args the command line arguments */// w w w. j a v a2 s. c o m public static void main(String[] args) { Producer producer = null; try { Options options = createOptions(); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); String pathToXML = null; String type = null; String input = null; String privateKeyPath = null; String publicKeyPath = null; String certPath = null; String socketPath = null; Boolean hasDigest = false; File file = null; ApplicationMetadataXML xml = null; if (cmd.hasOption("h")) { System.out.println(usage); return; } if (cmd.hasOption("a")) { pathToXML = cmd.getOptionValue("a"); } if (cmd.hasOption("t")) { type = cmd.getOptionValue("t"); } if (cmd.hasOption("p")) { file = new File(cmd.getOptionValue("p")); } if (cmd.hasOption("s")) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); String s; while ((s = in.readLine()) != null && s.length() != 0) { sb.append(s); sb.append("\n"); } input = sb.toString(); } if (cmd.hasOption("j")) { socketPath = cmd.getOptionValue("j"); } if (cmd.hasOption("k")) { privateKeyPath = cmd.getOptionValue("k"); } if (cmd.hasOption("b")) { publicKeyPath = cmd.getOptionValue("b"); } if (cmd.hasOption("c")) { certPath = cmd.getOptionValue("c"); } if (cmd.hasOption("d")) { hasDigest = true; } if (pathToXML != null) { xml = createXML(readXML(pathToXML)); } producer = createProducer(xml, socketPath, privateKeyPath, publicKeyPath, certPath, hasDigest); callSend(producer, type, input, file); } catch (IOException e) { if (producer != null) { System.out.println("Failed to open socket: " + producer.getSocketFile()); } else { System.out.println("Failed to create Producer"); } } catch (Exception e) { error(e.toString()); return; } }
From source file:BookRank.java
/** Grab the sales rank off the web page and log it. */ public static void main(String[] args) throws Exception { Properties p = new Properties(); String title = p.getProperty("title", "NO TITLE IN PROPERTIES"); // The url must have the "isbn=" at the very end, or otherwise // be amenable to being string-catted to, like the default. String url = p.getProperty("url", "http://test.ing/test.cgi?isbn="); // The 10-digit ISBN for the book. String isbn = p.getProperty("isbn", "0000000000"); // The RE pattern (MUST have ONE capture group for the number) String pattern = p.getProperty("pattern", "Rank: (\\d+)"); // Looking for something like this in the input: // <b>QuickBookShop.web Sales Rank: </b> // 26,252/*from w ww. j a v a 2s . com*/ // </font><br> Pattern r = Pattern.compile(pattern); // Open the URL and get a Reader from it. BufferedReader is = new BufferedReader(new InputStreamReader(new URL(url + isbn).openStream())); // Read the URL looking for the rank information, as // a single long string, so can match RE across multi-lines. String input = "input from console"; // System.out.println(input); // If found, append to sales data file. Matcher m = r.matcher(input); if (m.find()) { PrintWriter pw = new PrintWriter(new FileWriter(DATA_FILE, true)); String date = // `date +'%m %d %H %M %S %Y'`; new SimpleDateFormat("MM dd hh mm ss yyyy ").format(new Date()); // Paren 1 is the digits (and maybe ','s) that matched; remove comma Matcher noComma = Pattern.compile(",").matcher(m.group(1)); pw.println(date + noComma.replaceAll("")); pw.close(); } else { System.err.println("WARNING: pattern `" + pattern + "' did not match in `" + url + isbn + "'!"); } // Whether current data found or not, draw the graph, using // external plotting program against all historical data. // Could use gnuplot, R, any other math/graph program. // Better yet: use one of the Java plotting APIs. String gnuplot_cmd = "set term png\n" + "set output \"" + GRAPH_FILE + "\"\n" + "set xdata time\n" + "set ylabel \"Book sales rank\"\n" + "set bmargin 3\n" + "set logscale y\n" + "set yrange [1:60000] reverse\n" + "set timefmt \"%m %d %H %M %S %Y\"\n" + "plot \"" + DATA_FILE + "\" using 1:7 title \"" + title + "\" with lines\n"; Process proc = Runtime.getRuntime().exec("/usr/local/bin/gnuplot"); PrintWriter gp = new PrintWriter(proc.getOutputStream()); gp.print(gnuplot_cmd); gp.close(); }
From source file:SequentialPageRank.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 ww w.j ava 2 s. c o m*/ OptionBuilder.withArgName("val").hasArg().withDescription("random jump factor").create(JUMP)); 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)) { System.out.println("args: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(SequentialPageRank.class.getName(), options); ToolRunner.printGenericCommandUsage(System.out); System.exit(-1); } String infile = cmdline.getOptionValue(INPUT); 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(); 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 PageRank. PageRank<String, Integer> ranker = new PageRank<String, Integer>(graph, 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:examples.messages.java
public static final void main(String[] args) { int message;/*from w ww. j a va 2s . c o m*/ String server, username, password; POP3Client pop3; Reader reader; POP3MessageInfo[] messages; if (args.length < 3) { System.err.println("Usage: messages <pop3 server hostname> <username> <password>"); System.exit(1); } server = args[0]; username = args[1]; password = args[2]; pop3 = new POP3Client(); // We want to timeout if a response takes longer than 60 seconds pop3.setDefaultTimeout(60000); try { pop3.connect(server); } catch (IOException e) { System.err.println("Could not connect to server."); e.printStackTrace(); System.exit(1); } try { if (!pop3.login(username, password)) { System.err.println("Could not login to server. Check password."); pop3.disconnect(); System.exit(1); } messages = pop3.listMessages(); if (messages == null) { System.err.println("Could not retrieve message list."); pop3.disconnect(); System.exit(1); } else if (messages.length == 0) { System.out.println("No messages"); pop3.logout(); pop3.disconnect(); System.exit(1); } for (message = 0; message < messages.length; message++) { reader = pop3.retrieveMessageTop(messages[message].number, 0); if (reader == null) { System.err.println("Could not retrieve message header."); pop3.disconnect(); System.exit(1); } printMessageInfo(new BufferedReader(reader), messages[message].number); } pop3.logout(); pop3.disconnect(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } }
From source file:at.tuwien.aic.Main.java
/** * Main entry point// w w w . j av a2 s . co m * * @param args */ @SuppressWarnings("empty-statement") public static void main(String[] args) throws IOException, InterruptedException { try { System.out.println(new java.io.File(".").getCanonicalPath()); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } TweetCrawler tc = null; try { tc = TweetCrawler.getInstance(); } catch (UnknownHostException ex) { logger.severe("Could not connect to mongoDb"); exitWithError(2); return; } int action; while (true) { action = getDecision("The following actions can be executed", new String[] { "Subscribe to topic", "Query topic", "Test preprocessing", "Recreate the evaluation model", "Quit the application" }, "What action do you want to execute?"); switch (action) { case 1: tc.collectTweets(new DefaultTweetHandler() { @Override public boolean isMatch(String topic) { return true; } }, getNonEmptyString( "Which topic do you want to subscribe to (use spaces to specify more than one keyword)?") .split(" ")); System.out.println("Starting to collection tweets"); System.out.println("Press enter to quit collecting"); while (System.in.read() != 10) ; tc.stopCollecting(); break; case 2: System.out.println("Enter tweet"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String tweet = br.readLine(); //double prediction = ClassifyTweet.classifyTweets(c, tweet, 2); System.exit(0); //classifyTopic(); break; case 3: int subAction = getDecision("The following preprocessing steps are available", new String[] { "Stop word removal", "Stemming", "Both" }, "What do you want to test?"); switch (subAction) { case 1: stopWords(); break; case 2: stem(); break; case 3: stem(stopWords()); default: break; } break; case 4: //ClassifyTweet.classifyTweetArff(c, "resources/unlabeled.arff", "resources/train.arff"); ArrayList<String> tweets = new ArrayList<>(); ArrayList<String> processedTweets = new ArrayList<>(); //Positive Tweets tweets.add( "#Office365 is the fastest growing business in Microsofts history, one out of four enterprise clients owns #Office365 in the past 12 months"); tweets.add("oh yeah back to microsoft word it's great haha"); tweets.add( "Microsoft Visual Studio 2013 Ultimate: excellent tool, but a bit pricey at $13K - http://t.co/qbc4MHeOrF"); tweets.add( "Apple 'absolutely' plans to release new product types this year - Design Week: Design WeekApple 'absolutely' p... http://t.co/EK4rIbaHa0"); tweets.add( "RT @ReformedBroker: \"Apple can't innovate.\" Motherf***er you're watching a movie on a 4 ounce plate of glass."); tweets.add( "What's the best brand of shoes?! Lol. There's too damn many, what do you prefer. Me is some Adidas."); tweets.add( "I want ?? @AdorableWords: Tribal/Aztec pattern Nike free runs ?? http://t.co/WBxT8CNsPN?"); tweets.add( "I achieved the Streak Week trophy with my Nike+ FuelBand. #nikeplus http://t.co/OgtpRcoSvp"); tweets.add("RT @DriveOfAthletes: Retweet for Nike! Favorite for UA! http://t.co/sKZ8hb27xH"); //Neutral Tweets tweets.add("This site is giving away Free Microsoft Points #XBOX LIVE http://t.co/ZR1ythfqJ4"); tweets.add( "How To Save The World: 1. Open Microsoft Word. 2. In a size 12-36 font, type \"The World\". 3. Click save."); tweets.add( "Microsoft Special Deals for Education: Microsoft special deals for Students, faculty and staff: http://t.co/Hf0b2ixPZa"); tweets.add( "Microsoft is about to take Windows XP off life support On April 8, Windows XP's life is coming to an end. On that d http://t.co/kcSf4uIqW4"); tweets.add("Microsoft open sources its internet servers http://t.co/oLNTlVjE6Y"); tweets.add( "The Apple Macintosh computer turns 30 - ... http://t.co/CAfq09Jgn7 #CarlIcahn #IsaacsonIt #SteveJobs #WalterIsaacson"); tweets.add( "News Update| Samsung opens 60 dedicated stores in Europe with Carphone Warehouse http://t.co/1voh4yPMpN"); tweets.add("I posted a new photo to Facebook http://t.co/fI40hwklUj"); tweets.add( "Brand New Men's ADIDAS VIGOR TR 3 Athletic Running shoes. Size: 11.5 http://t.co/oPuFoXLpeI"); tweets.add("I just ran 2.58 mi with Nike+. http://t.co/pYLkhBxH4Y #nikeplus"); tweets.add("Why is facebook still a thing"); //Negative Tweets tweets.add("Thank God for microsoft programs....."); tweets.add( "RT @verge: UK government once again threatens to ditch Microsoft Office http://t.co/vhvybI1GwI"); tweets.add("Apple charge far too much for very poor phone cases"); tweets.add("Here's Why Everyone Is Worried About Apple's iPhone Sales http://t.co/Eq3oPt76AG"); tweets.add("Is Apple Ready to Disrupt Another Industry? http://t.co/07gedlN0cs via @zite"); tweets.add( "Tim Cook Officially Admits iPhone 5c Didnt Meet Expectations http://t.co/OdzGZOmdv7 #iPhone #Apple"); tweets.add("@MushIsAJedi @HeyItsAmine i dont rlly like samsung that much"); tweets.add("twitter facebook die shit"); tweets.add( "I am thinking of leaving Facebook for a while... To much spying going on.. I am sick and tired of thinking about... http:/)/t.co/ULydkDEube"); tweets.add("RT @OfficialSheIdon: RIP Facebook, too many of our parents joined."); StopWordRemoval swr = new StopWordRemoval("resources/stopwords.txt"); for (String t : tweets) { t = swr.processText(t); processedTweets.add(t); } for (int i = 0; i < 28; i++) { if (i != 4) { ArrayList<Integer> results = ClassifyTweet.classifyTweets(processedTweets, i); int correctCount = 0; int positiveCorrect = 0; int neutralCorrect = 0; int negativeCorrect = 0; int falsePosNeu = 0; int falsePosNeg = 0; int falseNeuPos = 0; int falseNeuNeg = 0; int falseNegNeu = 0; int falseNegPos = 0; for (int j = 0; j < 30; j++) { int pred = results.get(j); if (j >= 0 && j < 10) { if (pred == 1) { correctCount++; positiveCorrect++; } else if (pred == 0) { falsePosNeu++; } else if (pred == -1) { falsePosNeg++; } } else if (j >= 10 && j < 20) { if (pred == 0) { correctCount++; neutralCorrect++; } else if (pred == 1) { falseNeuPos++; } else if (pred == -1) { falseNeuNeg++; } } else if (j >= 20 && j < 30) { if (pred == -1) { correctCount++; negativeCorrect++; } else if (pred == 0) { falseNegNeu++; } else if (pred == 1) { falseNegPos++; } } } System.out.println("Correct Predictions: " + correctCount + " / 30"); System.out.println("Correct Positive: " + positiveCorrect + " / 10"); System.out.println("Correct Neutral: " + neutralCorrect + " / 10"); System.out.println("Correct Negative: " + negativeCorrect + " / 10"); System.out.println("False Positive as Neutral: " + falsePosNeu); System.out.println("False Positive as Negative: " + falsePosNeg); System.out.println("False Neutral as Positive: " + falseNeuPos); System.out.println("False Neutral as Negative: " + falseNeuNeg); System.out.println("False Negative as Positive: " + falseNegPos); System.out.println("False Negative as Neutral: " + falseNegNeu); } } exit(); case 5: exit(); } } }