import java.io.*;


/**
 * This is a pure java implementation of a command line password reader,
 * that can mask its input. The class uses a second thread to mask the input,
 * by always resetting the input line.
 * @author Markus Hammori, modfication of code from Qusay H. Mahmoud on java.sun.com
 */
class PasswordReader
{
    public PasswordReader()
    {

    }
    
    /**
     * This method will read a password using the default refresh time of 1. On slow
     * machines you will want to set the refreshRate to a higher value
     * @param prompt the prompt to be shown on the command line during input
     *(e.g. password:>
     */
    public String readPwd(String prompt){
	return readPwd(prompt,1);
    }
    
    /**
     * This method will read a password, and mask the input of the user, for security
     * reasons. During the input the only thing shown is the prompt parameter. 
     * @param prompt the prompt to be shown on the command line during input
     *(e.g. password:>
     * @param refreshTime The time between the refreshing of the masking. The lower the
     * number the higher the refreshRate and the CPU usage
     */
    public String readPwd(String prompt, int refreshTime)
    {
	
	String password = "";
	MaskingThread maskingthread = new MaskingThread(prompt,refreshTime);
	Thread thread = new Thread(maskingthread);
	thread.start();
	try{
	// block until enter is pressed
	while (true) {
	    char c = (char)System.in.read();
	    // assume enter pressed, stop masking
	    maskingthread.stopMasking();

	    // catch Windows "enter"
	    if (c == '\r') {
		c = (char)System.in.read();
		if (c == '\n') {
		    break;
		} else {
		    continue;
		}
	    }
	    // catch unix "enter"
	    else if (c == '\n') {
		break;
	    } else {
		// store the password
		password += c;
	    }
	}
	}catch(IOException e){
	    System.out.println("IO Error:" + e.getMessage());
	}
	return password;
    }

    /**
     * Only for testing purpose
     */
    public static void main(String[] args){
	PasswordReader pr = new PasswordReader();
	String pwd = pr.readPwd("Test: ");
	System.out.println("The password was: " + pwd);
    }
}

