public static void main(String[] args) throws MessagingException, IOException { Properties props = new Properties(); try (InputStream in = Files.newInputStream(Paths.get("mail", "mail.properties"))) { props.load(in); } List<String> lines = Files.readAllLines(Paths.get(args[0]), Charset.forName("UTF-8")); String from = lines.get(0); String to = lines.get(1); String subject = lines.get(2); StringBuilder builder = new StringBuilder(); for (int i = 3; i < lines.size(); i++) { builder.append(lines.get(i)); builder.append("\n"); } Console console = System.console(); String password = new String(console.readPassword("Password: ")); Session mailSession = Session.getDefaultInstance(props); // mailSession.setDebug(true); MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress(from)); message.addRecipient(RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setText(builder.toString()); Transport tr = mailSession.getTransport(); try { tr.connect(null, password); tr.sendMessage(message, message.getAllRecipients()); } finally { tr.close(); } }
public static void main(String[] args) { Console console = new Console(); console.clear(); final HashMapVisualiser visualiser = new HashMapVisualiser(console); /*final HashMap<String, Integer> map = new HashMap<>(); map.put("AaAa", 1); map.put("BBBB", 2); map.put("AaBB", 3); map.put("BBAa", 4); map.put("five", 5); map.put("six", 6); map.put("seven", 7); visualiser.visualise(map); console.await();*/ final HashMap<BadHash, String> treeified = new HashMap<>(); for (int i = 0; i < 20; i++) { final String value = String.valueOf(i); treeified.put(new BadHash(value, 1), value); console.clear(); visualiser.visualise(treeified); console.await(); } }
public void collect(String name) { switch (name) { case "stick": if (getCurrentTile().contains("tree")) { console.print("You break some sticks off of the tree."); p.inv.add(new Item("stick"), 2); getCurrentTile().removeEntity("tree"); p.decFood(1); p.decWater(1); } else { console.print("There are no sticks in sight."); } break; case "rock": if (getCurrentTile().contains("rock")) { console.print("You collect a pile of rocks."); p.inv.add(new Item("rock"), 3); getCurrentTile().removeEntity("rock"); p.decFood(2); p.decWater(1); } else { console.print("There are no rocks in sight."); } break; default: } }
/** * Realiza o login no sistema, a partir da entrada do nome de usuário e da senha e registra em um * arquivo de log esse acesso. * * @author Isac * @param args * @throws IOException * @throws SQLException */ public static void main(String[] args) throws IOException, SQLException { // Statement stat = Conecta.getConnection().conn.createStatement(); // stat.executeUpdate("delete from Users"); // AccessControl.cadastroUsuario("admin","admin","admin",1); // AccessControl.cadastroUsuario("cliente","cliente","cliente",2); // AccessControl.cadastroUsuario("fornecedor","fornecedor","fornecedor",3); // Log.getLoginstance(null).info("info"); // Log.getLoginstance(null).error("erro!"); // Log.getLoginstance(null).warn("warning"); // Log.getLoginstance(null).fatal("fatal"); System.out.println("Informe seu nome de usuario:"); String username = Console.readString(); System.out.println("Informe sua senha"); String passwd = Console.readString(); try { if (AccessControl.login(username, passwd)) { Menu.principal(); } else { System.out.println("privilégios administrativos requeridos para acesso ao sistema!!"); } } catch (UserNotFoundException e) { System.out.println("usuário inexistente: " + e.getUsername()); Log.getLoginstance(null).error(e.getMessage()); } catch (PasswordsDontMatchException e) { System.out.println("Password não bateu: " + e.getPasswd()); Log.getLoginstance(null).error(e.getMessage()); } }
public void show() { if (active) c.bold(); else c.normal(); c.position(positionY, positionX); System.out.print("[" + nome + "]"); }
static { Console.setscmd( "bgm", new Console.Command() { public void run(Console cons, String[] args) { int i = 1; String opt; boolean loop = false; if (i < args.length) { while ((opt = args[i]).charAt(0) == '-') { i++; if (opt.equals("-l")) loop = true; } String resnm = args[i++]; int ver = -1; if (i < args.length) ver = Integer.parseInt(args[i++]); Music.play(Resource.remote().load(resnm, ver), loop); } else { Music.play(null, false); } } }); Console.setscmd( "bgmsw", new Console.Command() { public void run(Console cons, String[] args) { if (args.length < 2) enable(!enabled); else enable(Utils.parsebool(args[1], true)); } }); }
private void dumpDocuments() throws IOException { outputBanner("Documents"); int totalDocs = mIndexReader.numDocs(); outputLn(); outputLn("There are " + totalDocs + " documents in this index."); mConsole.debug("Total number of documents: " + totalDocs); for (int i = 0; i < totalDocs; i++) { Document doc = null; try { doc = mIndexReader.document(i, null); } catch (IllegalArgumentException e) { if ("attempt to access a deleted document".equals(e.getMessage())) { mConsole.warn( "encountered exception while dumping document " + i + ": " + e.getMessage()); } else { throw e; } } dumpDocument(i, doc); if ((i + 1) % 100 == 0) { mConsole.debug("Dumped " + (i + 1) + " documents"); } } }
/* * ================== SCR_DrawConsole ================== */ static void DrawConsole() { Console.CheckResize(); if (cls.state == ca_disconnected || cls.state == ca_connecting) { // forced // full // screen // console Console.DrawConsole(1.0f); return; } if (cls.state != ca_active || !cl.refresh_prepped) { // connected, but // can't render Console.DrawConsole(0.5f); re.DrawFill(0, viddef.height / 2, viddef.width, viddef.height / 2, 0); return; } if (scr_con_current != 0) { Console.DrawConsole(scr_con_current); } else { // if (cls.key_dest == key_game || cls.key_dest == key_message) { Console.DrawNotify(); // only draw notify in game // } } }
private void getUserPasswordAndLogIn(Biblioteca biblioteca) { if (inputPasswordIsNotCorrect()) { console.show(PASSWORD_IS_NOT_CORRECT); } else { userLogIn(biblioteca); console.show(LOGGED_IN_SUCCESS); } }
@Override public void doOperation() { console.display("Enter return book title: "); String booktitle = console.getUserInput(); Book book = new Book(booktitle, "UNKNOWN_AUTHOR", UNKNOWN_YEAR); String returnMessage = library.returnBook(book, user); console.display(returnMessage); }
public void displayList(Console console) { console.println("The library has following books :"); console.println("S.no Book Author"); for (Book book : originalBookList) { String string = book.displayBook(); console.println(string); } }
public static void main(String[] args) { int op = -1; RepositorioPacientes repositorioPacientes = new RepositorioPacientes(); do { System.out.println("Menu: "); System.out.println("1- Cadastrar Paciente"); System.out.println("2- Listar Pacientes"); System.out.println("3- Sair da Aplicação"); try { op = Console.scanInt("Digite a opção do menu: "); switch (op) { case 1: try { System.out.println("\nCadastro de Pacientes"); String rg = Console.scanString("RG: "); String nome = Console.scanString("Nome: "); String dataString = Console.scanString("Nascimento (dia/mes/ano): "); Date dataNasc = DateUtil.stringToDate(dataString); Paciente paciente = new Paciente(rg, nome, dataNasc); repositorioPacientes.adicionar(paciente); } catch (ParseException ex) { System.out.println("Formato de data errado! Operação cancelada!"); } break; case 2: System.out.println("\nLista de pacientes"); if (!repositorioPacientes.temPacientes()) { System.out.println("Nenhum paciente foi cadastrado!"); } else { System.out.print(String.format("%-10s", "RG")); System.out.print(String.format("%-20s", "NOME")); System.out.println(String.format("%-10s", "NASCIMENTO")); for (Paciente p : repositorioPacientes.getListaPacientes()) { System.out.print(String.format("%-10s", p.getRg())); System.out.print(String.format("%-20s", p.getNome())); System.out.println( String.format("%-10s", DateUtil.dateToString(p.getDataNascimento()))); } } break; case 3: System.out.println("Saindo da aplicação..."); break; default: System.out.println("Opção Inválida!"); } } catch (InputMismatchException ime) { System.out.println("Opção Inválida! Não pode digitar letras!"); } } while (op != 3); }
private void readDataConsole() { Console c = System.console(); if (c == null) { System.err.println("No console."); System.exit(1); } String login = c.readLine("Enter your login: "); }
@Override public boolean isInitialized() { for (Console console : consoles) { if (console.isInitialized()) { return true; } } return false; }
@ReceiveEvent(components = ClientComponent.class, netFilter = RegisterMode.AUTHORITY) public void onCommand(CommandEvent event, EntityRef entity) { List<String> params = event.getParameters(); ConsoleCommand cmd = console.getCommand(event.getCommandName()); if (cmd.getRequiredParameterCount() == params.size() && cmd.isRunOnServer()) { console.execute(event.getCommandName(), event.getParameters(), entity); } }
// Player actions public void drink() { if (getCurrentTile().contains("pond")) { console.print("You kneel at the pond and drink water."); p.maxWater(); } else if (getCurrentTile().contains("village")) { console.print("You drink some water at the village fountain."); p.maxWater(); } else console.print("There is no water in sight."); }
public void reserveBook(Console console) { System.out.println("Enter the serial no. of book :"); int bookID = console.getNumberFromConsole(); if ((!(bookIssued(bookID))) && bookID < originalBookList.size() && bookID != 0) { issueBook(bookID); console.println("Thank You! Enjoy the book"); return; } if (bookID != 0) console.println("Sorry we don't have that book yet."); }
public static void main(String argv[]) { Console console = System.console(); String username = console.readLine("Username: "******"Password: "******"Entered password: " + new String(password)); // clear the array as soon as the password has been used Arrays.fill(password, ' '); }
/* Create a password to set limits manually */ public void createPassword() { String username, password; System.out.print("Username: "******"Password: "); password = Console.readToken(); }
/** * For "iteration" number of cycles, generate user-visit events within the bounds of customer * range and user range. */ public void run() { final String meth = "run()"; ILdtOperations ldtOps = dbOps.getLdtOps(); long startTimeMs = System.currentTimeMillis(); long endTimeMS = startTimeMs + 1000 * emulationDays * 86400; long checkTimeMS = 0; long secondStartMS = 0; long deltaTimeMS = 0; int interTransactionWaitMS = 10; long secondCount = 1; long opNum = 0; try { // This thread will try to maintain a given TPS load, where it will // measure its performance per second and try to speed up or slow // down accordingly. // In each second, it will attempt to complete "threadTPS" actions // by calling the "working function" doOperation(). console.info( "<%s:%s> ThreadNum(%d) Start: ThreadTPS(%d)", CLASSNAME, meth, threadNumber, threadTPS); do { // We're going to organize ourselves in terms of TPS and // second intervals. For a given number of TPS, we're going // to try to fit in that amount of operations, and then sleep // for the remaining amount if we're ahead of schedule in each // second. If we fall behind, then we're going to shorten the // amount of time between each operation. secondStartMS = System.currentTimeMillis(); for (int i = 0; i < threadTPS; i++) { opNum = (secondCount * threadTPS) + i; doOperation((int) opNum, ldtOps); Thread.sleep(interTransactionWaitMS); } // for each Transaction (per second) secondCount++; checkTimeMS = System.currentTimeMillis(); deltaTimeMS = checkTimeMS - secondStartMS; console.debug( "StartSecond(%d) CheckTime(%d) Delta(%d)", secondStartMS, checkTimeMS, deltaTimeMS); if (deltaTimeMS > 1000) { if (interTransactionWaitMS > 10) { interTransactionWaitMS--; } // otherwise, do nothing. } else { interTransactionWaitMS++; Thread.sleep(Math.abs(1000 - deltaTimeMS)); } } while (checkTimeMS < endTimeMS); // end for each generateCount } catch (Exception e) { e.printStackTrace(); console.error("<%s:%s>Problem with Thread(%d) ", CLASSNAME, meth, opNum); } } // end run()
public void toss(String name, int amount) { String sname = name.substring(0, name.length() - 1); if (!p.inv.contains(name)) { if (p.inv.contains(sname)) name = sname; else console.print("You don't have any " + name + "s."); } if (p.inv.remove(name, amount)) { if (amount > 1) name += "s"; console.print("You toss " + amount + " " + name); } else console.print("You don't have that many " + name + "s."); }
public static void main(String[] args) { // Create a console object. Console objConsole = System.console(); if (objConsole != null) { // readLine method call. String userName = objConsole.readLine("Enter username : "******"You have entered : " + userName); } }
public void playGame() { Joystick joystick = game.getJoystick(); do { printBoard(); String line = console.read(); boolean bomb = false; boolean move = false; for (Character ch : line.toCharArray()) { if (ch == 's' || ch == 'ы') { if (move) { game.tick(); bomb = false; } joystick.down(); move = true; } else if (ch == 'a' || ch == 'ф') { if (move) { game.tick(); bomb = false; } joystick.left(); move = true; } else if (ch == 'd' || ch == 'в') { if (move) { game.tick(); bomb = false; } joystick.right(); move = true; } else if (ch == 'w' || ch == 'ц') { if (move) { game.tick(); bomb = false; } joystick.up(); move = true; } else if (ch == ' ') { if (bomb) { game.tick(); move = false; } joystick.act(); bomb = true; } } game.tick(); } while (!game.isGameOver()); printBoard(); console.print("Game over!"); }
public static String getUniquePath() { String unique = System.getProperty("java.io.tmpdir") + UUID.randomUUID().toString(); File f; try { f = new File(unique); unique = f.getCanonicalPath(); } catch (IOException ex) { Console.error("Strange file error.\n" + ex); } Console.debug("Generated unique path: " + unique, 3); return unique; }
@Override public void onModuleLoad() { Profiler.initialize(); Profiler.enter("ApplicationConfiguration.onModuleLoad"); BrowserInfo browserInfo = BrowserInfo.get(); // Enable iOS6 cast fix (see #10460) if (browserInfo.isIOS() && browserInfo.isWebkit() && browserInfo.getBrowserMajorVersion() == 6) { enableIOS6castFix(); } // Prepare VConsole for debugging if (isDebugMode()) { Console console = GWT.create(Console.class); console.setQuietMode(isQuietDebugMode()); console.init(); VConsole.setImplementation(console); } else { VConsole.setImplementation((Console) GWT.create(NullConsole.class)); } /* * Display some sort of error of exceptions in web mode to debug * console. After this, exceptions are reported to VConsole and possible * GWT hosted mode. */ GWT.setUncaughtExceptionHandler( new UncaughtExceptionHandler() { @Override public void onUncaughtException(Throwable e) { /* * Note in case of null console (without ?debug) we eat * exceptions. "a1 is not an object" style errors helps nobody, * especially end user. It does not work tells just as much. */ VConsole.getImplementation().error(e); } }); Profiler.leave("ApplicationConfiguration.onModuleLoad"); if (SuperDevMode.enableBasedOnParameter()) { // Do not start any application as super dev mode will refresh the // page once done compiling return; } registerCallback(GWT.getModuleName()); }
/* * THIS METHOD IS FOR USE WITH THE INTERACTION CLASS. * USE ITEM FROM THE PLAYER'S INVENTORY ON ENVIRONMENT. */ public void use(String itemName) { Item item = new Item(itemName); if (!p.inv.contains(item.name)) console.print("You don't have a " + itemName + "."); else { Interaction in = Interaction.getInteraction(item, getCurrentTile().entities); if (in == null) console.print("Nothing to use the " + item.name + " with."); else { Interaction.interact(in, getCurrentTile(), p.inv); console.print(in.msg); p.decFood(1); p.decWater(1); } } }
public static void main(String[] args) { // dialog.createMainDialog(); initializeOutputFile(); String pathFileIn = "", pathFileOut = ""; if (args != null) { if (args.length == 1) { pathFileIn = args[0]; Console.setStringWriter(true); } else if (args.length == 2) { pathFileIn = args[0]; pathFileOut = args[1]; Console.setStringWriter(true); } // else if (args.length == 3){ else { pathFileIn = args[0]; pathFileOut = args[1]; PrintStream fileStream; try { fileStream = new PrintStream(new FileOutputStream(args[2], true)); System.setOut(fileStream); System.setErr(fileStream); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Console.setStringWriter(false); } /* else{ Console.setStringWriter(true); Console.out("Path of the profiled XML:"); pathFileIn = Console.in(); Console.out("Name of the output file:"); String nameFileOut = Console.in(); pathFileOut = pathFileIn.substring(0, pathFileIn.lastIndexOf("/") + 1) + nameFileOut; }*/ } Date initialDate = new Date(); document = XMLHandler.openDocument(pathFileIn); profiler.execute(document); XMLHandler.saveDocument(pathFileOut, document); closeOutputFile(); Date finalDate = new Date(); Console.out( "Profiler duration (s) = " + ((finalDate.getTime() - initialDate.getTime()) / 1000)); }
/* User enters manual limits */ public void setLimitManual() { System.out.print("Please enter Heart Rate limit: "); heart_Rate_Manual_Limit = Console.readDouble(); System.out.print("Please enter Temperature limit: "); temperature_Manual_Limit = Console.readDouble(); System.out.print("Please enter Blood Pressure limit: "); blood_Pressure_Manual_Limit = Console.readDouble(); System.out.print("Please enter Blood Glucose Level limit: "); blood_Glucose_Manual_Limit = Console.readDouble(); System.out.println(); }
@ReceiveEvent(components = ClientComponent.class) public void onMessage(MessageEvent event, EntityRef entity) { ClientComponent client = entity.getComponent(ClientComponent.class); if (client.local) { console.addMessage(event.getFormattedMessage()); } }
@Override public void setPosition(int position) { super.setPosition(position); if (CARET != null) { CARET.setVisible(true); } }