1 14 15 package org.quickserver.util.io; 16 17 import java.io.*; 18 import java.util.*; 19 import java.util.logging.*; 20 21 26 public class PasswordField { 27 private static Logger logger = Logger.getLogger(PasswordField.class.getName()); 28 29 33 public static final char[] getPassword(String prompt) 34 throws IOException { 35 return getPassword(System.in, prompt); 36 } 37 38 43 public static final char[] getPassword(InputStream in, String prompt) 44 throws IOException { 45 MaskingThread maskingthread = new MaskingThread(prompt); 46 Thread thread = new Thread (maskingthread); 47 thread.start(); 48 49 char[] lineBuffer; 50 char[] buf; 51 int i; 52 53 buf = lineBuffer = new char[128]; 54 55 int room = buf.length; 56 int offset = 0; 57 int c; 58 59 loop: while(true) { 60 c = in.read(); 61 switch(c) { 62 case -1: 63 case '\n': 64 break loop; 65 66 case '\r': 67 int c2 = in.read(); 68 if((c2 != '\n') && (c2 != -1)) { 69 if(!(in instanceof PushbackInputStream)) { 70 in = new PushbackInputStream(in); 71 } 72 ((PushbackInputStream)in).unread(c2); 73 } else { 74 break loop; 75 } 76 default: 77 if (--room < 0) { 78 buf = new char[offset + 128]; 79 room = buf.length - offset - 1; 80 System.arraycopy(lineBuffer, 0, buf, 0, offset); 81 Arrays.fill(lineBuffer, ' '); 82 lineBuffer = buf; 83 } 84 buf[offset++] = (char) c; 85 break; 86 } 87 } 88 maskingthread.stopMasking(); 89 System.out.print("\010"); 90 String os = System.getProperty("os.name"); 92 if(os!=null && os.toLowerCase().startsWith("windows")) { 93 try { 94 java.awt.Robot robot = new java.awt.Robot (); 95 robot.keyPress(java.awt.event.KeyEvent.VK_ALT); 96 robot.keyPress(java.awt.event.KeyEvent.VK_F7); 97 robot.keyRelease(java.awt.event.KeyEvent.VK_F7); 98 robot.keyRelease(java.awt.event.KeyEvent.VK_ALT); 99 } catch(Exception ignore) { 100 logger.warning("Could not clears command history: "+ignore); 101 } 102 } 103 104 if(offset == 0) { 105 return null; 106 } 107 char[] ret = new char[offset]; 108 System.arraycopy(buf, 0, ret, 0, offset); 109 Arrays.fill(buf, ' '); 110 return ret; 111 } 112 } 113 | Popular Tags |