1 16 package org.jmanage.core.util; 17 18 import java.io.*; 19 import java.util.Arrays ; 20 21 24 25 public class PasswordField { 26 27 31 public static char[] getPassword(String prompt) throws IOException { 32 33 char[] password = new char[1000]; 34 MaskingThread maskingthread = new MaskingThread(prompt); 35 36 Thread thread = new Thread (maskingthread); 37 thread.start(); 38 int index = 0; 39 for(; true; index++) { 40 char c = (char) System.in.read(); 41 maskingthread.stopMasking(); 43 44 if (c == '\r') { 45 c = (char) System.in.read(); 46 if (c == '\n') { 47 break; 48 } else { 49 continue; 50 } 51 } else if (c == '\n') { 52 break; 53 } else { 54 55 password[index] = c; 56 } 57 } 58 char[] passwordEntered = new char[index]; 59 for(int i=0; i<passwordEntered.length; i++){ 60 passwordEntered[i] = password[i]; 61 } 62 63 Arrays.fill(password, '\0'); 64 65 return passwordEntered; 66 } 67 68 71 private static class MaskingThread extends Thread { 72 private boolean stop = false; 73 private String prompt; 74 75 78 public MaskingThread(String prompt) { 79 this.prompt = prompt; 80 } 81 82 83 86 public void run() { 87 while (!stop) { 88 try { 89 this.sleep(1); 91 } catch (InterruptedException iex) { 92 iex.printStackTrace(); 93 } 94 if (!stop) { 95 System.out.print("\r" + prompt + " \r" + prompt); 96 } 97 System.out.flush(); 98 } 99 } 100 101 102 105 public void stopMasking() { 106 this.stop = true; 107 } 108 } 109 } 110 111 | Popular Tags |