List of usage examples for java.lang System in
InputStream in
To view the source code for java.lang System in.
Click Source Link
From source file:keepassj.cli.KeepassjCli.java
/** * @param args the command line arguments * @throws org.apache.commons.cli.ParseException * @throws java.io.IOException// w w w . j ava2s. c o m */ public static void main(String[] args) throws ParseException, IOException { Options options = KeepassjCli.getOptions(); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (!KeepassjCli.validateOptions(cmd)) { HelpFormatter help = new HelpFormatter(); help.printHelp("Usage: java -jar KeepassjCli -f dbfile [options]", options); } else { String password; if (cmd.hasOption('p')) { password = cmd.getOptionValue('p'); } else { Console console = System.console(); char[] hiddenString = console.readPassword("Enter password for %s\n", cmd.getOptionValue('f')); password = String.valueOf(hiddenString); } KeepassjCli instance = new KeepassjCli(cmd.getOptionValue('f'), password, cmd.getOptionValue('k')); System.out.println("Description:" + instance.db.getDescription()); PwGroup rootGroup = instance.db.getRootGroup(); System.out.println(String.valueOf(rootGroup.GetEntriesCount(true)) + " entries"); if (cmd.hasOption('l')) { instance.printEntries(rootGroup.GetEntries(true), false); } else if (cmd.hasOption('s')) { PwObjectList<PwEntry> results = instance.search(cmd.getOptionValue('s')); System.out.println("Found " + results.getUCount() + " results for:" + cmd.getOptionValue('s')); instance.printEntries(results, false); } else if (cmd.hasOption('i')) { System.out.println("Entering interactive mode."); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); String input = null; PwObjectList<PwEntry> results = null; while (!"\\q".equals(input)) { if (results != null) { System.out.println("Would you like to view a specific entry? y/n"); input = bufferedReader.readLine(); if ("y".equalsIgnoreCase(input)) { System.out.print("Enter the title number:"); input = bufferedReader.readLine(); instance.printCompleteEntry(results.GetAt(Integer.parseInt(input) - 1)); // Since humans start counting at 1 } results = null; System.out.println(); } else { System.out.print("Enter something to search for (or \\q to quit):"); input = bufferedReader.readLine(); if (!"\\q".equalsIgnoreCase(input)) { results = instance.search(input); instance.printEntries(results, true); } } } } // Close before exit instance.db.Close(); } }
From source file:cc.altruix.econsimtr01.App.java
public static void main(final String[] args) { new App().run(System.in); }
From source file:com.genentech.chemistry.openEye.apps.SDFMCSSSphereExclusion.java
public static void main(String... args) throws IOException { CommandLineParser parser = new PosixParser(); CommandLine cmd = null;/*from ww w.j a v a 2 s .c om*/ try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println(e.getMessage()); exitWithHelp(); } 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; double radius = Double.parseDouble(cmd.getOptionValue("radius")); String inFile = cmd.getOptionValue("in"); String outFile = cmd.getOptionValue("out"); String refFile = cmd.getOptionValue("ref"); SimComparatorFactory<OEMolBase, OEMolBase, SimComparator<OEMolBase>> compFact; compFact = getComparatorFactory(cmd); SphereExclusion<OEMolBase, SimComparator<OEMolBase>> alg = new SphereExclusion<OEMolBase, SimComparator<OEMolBase>>( compFact, refFile, outFile, radius, reverseMatch, printSphereMatchCount, printAll); alg.run(inFile); alg.close(); }
From source file:at.tuwien.aic.Main.java
/** * Main entry point/*from 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(); } } }
From source file:ArraySet.java
public static void main(String[] args) throws java.io.IOException { ArraySet set = new ArraySet(); java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); while (true) { System.out.print(set.size() + ":"); //OK for (Iterator it = set.iterator(); it.hasNext();) { System.out.print(" " + it.next()); //OK }//from w w w .jav a 2s . com System.out.println(); //OK System.out.print("> "); //OK String cmd = in.readLine(); if (cmd == null) break; cmd = cmd.trim(); if (cmd.equals("")) { ; } else if (cmd.startsWith("+")) { set.add(cmd.substring(1)); } else if (cmd.startsWith("-")) { set.remove(cmd.substring(1)); } else if (cmd.startsWith("?")) { boolean ret = set.contains(cmd.substring(1)); System.out.println(" " + ret); //OK } else { System.out.println("unrecognized command"); //OK } } }
From source file:info.fetter.logstashforwarder.Forwarder.java
public static void main(String[] args) { try {// w w w . j a va2 s .c o m parseOptions(args); setupLogging(); watcher = new FileWatcher(); watcher.setMaxSignatureLength(signatureLength); watcher.setTail(tailSelected); watcher.setSincedb(sincedbFile); configManager = new ConfigurationManager(config); configManager.readConfiguration(); for (FilesSection files : configManager.getConfig().getFiles()) { for (String path : files.getPaths()) { watcher.addFilesToWatch(path, new Event(files.getFields()), files.getDeadTimeInSeconds() * 1000); } } watcher.initialize(); fileReader = new FileReader(spoolSize); inputReader = new InputReader(spoolSize, System.in); connectToServer(); infiniteLoop(); } catch (Exception e) { e.printStackTrace(); System.exit(3); } }
From source file:Service.java
public static void main(String[] args) { StringWriter sw = new StringWriter(); try {//from w w w. j a v a2s . c o m JsonGenerator g = factory.createGenerator(sw); g.writeStartObject(); g.writeNumberField("code", 200); g.writeArrayFieldStart("languages"); for (Language l : Languages.get()) { g.writeStartObject(); g.writeStringField("name", l.getName()); g.writeStringField("locale", l.getLocaleWithCountryAndVariant().toString()); g.writeEndObject(); } g.writeEndArray(); g.writeEndObject(); g.flush(); } catch (Exception e) { throw new RuntimeException(e); } String languagesResponse = sw.toString(); String errorResponse = codeResponse(500); String okResponse = codeResponse(200); Scanner sc = new Scanner(System.in); while (sc.hasNextLine()) { try { String line = sc.nextLine(); JsonParser p = factory.createParser(line); String cmd = ""; String text = ""; String language = ""; while (p.nextToken() != JsonToken.END_OBJECT) { String name = p.getCurrentName(); if ("command".equals(name)) { p.nextToken(); cmd = p.getText(); } if ("text".equals(name)) { p.nextToken(); text = p.getText(); } if ("language".equals(name)) { p.nextToken(); language = p.getText(); } } p.close(); if ("check".equals(cmd)) { sw = new StringWriter(); JsonGenerator g = factory.createGenerator(sw); g.writeStartObject(); g.writeNumberField("code", 200); g.writeArrayFieldStart("matches"); for (RuleMatch match : new JLanguageTool(Languages.getLanguageForShortName(language)) .check(text)) { g.writeStartObject(); g.writeNumberField("offset", match.getFromPos()); g.writeNumberField("length", match.getToPos() - match.getFromPos()); g.writeStringField("message", substituteSuggestion(match.getMessage())); if (match.getShortMessage() != null) { g.writeStringField("shortMessage", substituteSuggestion(match.getShortMessage())); } g.writeArrayFieldStart("replacements"); for (String replacement : match.getSuggestedReplacements()) { g.writeString(replacement); } g.writeEndArray(); Rule rule = match.getRule(); g.writeStringField("ruleId", rule.getId()); if (rule instanceof AbstractPatternRule) { String subId = ((AbstractPatternRule) rule).getSubId(); if (subId != null) { g.writeStringField("ruleSubId", subId); } } g.writeStringField("ruleDescription", rule.getDescription()); g.writeStringField("ruleIssueType", rule.getLocQualityIssueType().toString()); if (rule.getUrl() != null) { g.writeArrayFieldStart("ruleUrls"); g.writeString(rule.getUrl().toString()); g.writeEndArray(); } Category category = rule.getCategory(); CategoryId catId = category.getId(); if (catId != null) { g.writeStringField("ruleCategoryId", catId.toString()); g.writeStringField("ruleCategoryName", category.getName()); } g.writeEndObject(); } g.writeEndArray(); g.writeEndObject(); g.flush(); System.out.println(sw.toString()); } else if ("languages".equals(cmd)) { System.out.println(languagesResponse); } else if ("quit".equals(cmd)) { System.out.println(okResponse); return; } else { System.out.println(errorResponse); } } catch (Exception e) { System.out.println(errorResponse); } } }
From source file:smtpsend.java
/** * Example of how to extend the SMTPTransport class. * This example illustrates how to issue the XACT * command before the SMTPTransport issues the DATA * command./*from ww w .j a v a 2 s . co m*/ * public static class SMTPExtension extends SMTPTransport { public SMTPExtension(Session session, URLName url) { super(session, url); // to check that we're being used System.out.println("SMTPExtension: constructed"); } protected synchronized OutputStream data() throws MessagingException { if (supportsExtension("XACCOUNTING")) issueCommand("XACT", 250); return super.data(); } } */ public static void main(String[] argv) { String to, subject = null, from = null, cc = null, bcc = null, url = null; String mailhost = null; 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; String prot = "smtp"; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int optind; /* * Process command line arguments. */ 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")) { prot = "smtps"; } 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 { /* * Prompt for To and Subject, if not specified. */ 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); } /* * Initialize the JavaMail Session. */ Properties props = System.getProperties(); if (mailhost != null) props.put("mail." + prot + ".host", mailhost); if (auth) props.put("mail." + prot + ".auth", "true"); /* * Create a Provider representing our extended SMTP transport * and set the property to use our provider. * Provider p = new Provider(Provider.Type.TRANSPORT, prot, "smtpsend$SMTPExtension", "JavaMail demo", "no version"); props.put("mail." + prot + ".class", "smtpsend$SMTPExtension"); */ // Get a Session object Session session = Session.getInstance(props, null); if (debug) session.setDebug(true); /* * Register our extended SMTP transport. * session.addProvider(p); */ /* * Construct the message and send it. */ 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(prot); 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."); /* * Save a copy of the message, 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) { /* * Handle SMTP-specific exceptions. */ 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:com.l2jfree.loginserver.tools.L2AccountManager.java
/** * Launches the interactive account manager. * //w ww . j av a 2 s . co 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.hernandez.rey.crypto.TripleDES.java
/** * @param args The program. The first argument must be -e, -d, or -g to encrypt, decrypt, or generate a key. The * second argument is the name of a file from which the key is read or to which it is written for -g. The * -e and -d arguments cause the program to read from standard input and encrypt or decrypt to standard * output./*from ww w . j a v a 2 s . c o m*/ */ public static void main(final String[] args) { try { // Check to see whether there is a provider that can do TripleDES // encryption. If not, explicitly install the SunJCE provider. try { Cipher.getInstance("DESede"); } catch (final Exception e) { // An exception here probably means the JCE provider hasn't // been permanently installed on this system by listing it // in the $JAVA_HOME/jre/lib/security/java.security file. // Therefore, we have to install the JCE provider explicitly. System.err.println("Installing SunJCE provider."); @SuppressWarnings("restriction") final Provider sunjce = new com.sun.crypto.provider.SunJCE(); Security.addProvider(sunjce); } // This is where we'll read the key from or write it to final File keyfile = new File(args[1]); // Now check the first arg to see what we're going to do if (args[0].equals("-g")) { // Generate a key System.out.print("Generating key. This may take some time..."); System.out.flush(); final SecretKey key = generateKey(); writeKey(key, keyfile); System.out.println("done."); System.out.println("Secret key written to " + args[1] + ". Protect that file carefully!"); } else if (args[0].equals("-e")) { // Encrypt stdin to stdout final SecretKey key = readKey(keyfile); encrypt(key, System.in, System.out); } else if (args[0].equals("-d")) { // Decrypt stdin to stdout final SecretKey key = readKey(keyfile); decrypt(key, System.in, System.out); } } catch (final Exception e) { System.err.println(e); System.err.println("Usage: java " + TripleDES.class.getName() + " -d|-e|-g <keyfile>"); } }