/********************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ********************************************************************/
package gov.va.med.esr.common.security;

import java.io.IOException;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;

/**
 * CallbackHandler implementation that supports only username and 
 * password callbacks.
 * It supports NameCallback for username callback
 * and PasswordCallback for password callback.
 * 
 * @author Ghazenfer Mansoor
 */
public class UserPasswordCallbackHandler implements CallbackHandler {
    private String username;
    private char[] password;

    public UserPasswordCallbackHandler(String username, String password) {
        this.username = username;
        this.password = password.toCharArray();
    }

    /* 
     * Handles the callbacks. It supports NameCallback for username 
     * callback and PasswordCallback for password callback.
     * 
     * @see javax.security.auth.callback.CallbackHandler#handle(javax.security.auth.callback.Callback[])
     */
    public void handle(Callback[] callbacks) throws IOException,
            UnsupportedCallbackException {
        for (int i = 0; i < callbacks.length; i++) {
            if (callbacks[i] instanceof NameCallback) {
                ((NameCallback) callbacks[i]).setName(username);
            } else if (callbacks[i] instanceof PasswordCallback) {
                ((PasswordCallback) callbacks[i]).setPassword(password);
            } else {
                throw new UnsupportedCallbackException(callbacks[i],
                        "Unsupported Callback - only supports username and password");
            }
        }
    }
}