001    /**
002     *
003     * Copyright 2004 The Apache Software Foundation
004     *
005     *  Licensed under the Apache License, Version 2.0 (the "License");
006     *  you may not use this file except in compliance with the License.
007     *  You may obtain a copy of the License at
008     *
009     *     http://www.apache.org/licenses/LICENSE-2.0
010     *
011     *  Unless required by applicable law or agreed to in writing, software
012     *  distributed under the License is distributed on an "AS IS" BASIS,
013     *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     *  See the License for the specific language governing permissions and
015     *  limitations under the License.
016     */
017    package org.activemq.security.jassjacc;
018    
019    import javax.security.auth.callback.Callback;
020    import javax.security.auth.callback.CallbackHandler;
021    import javax.security.auth.callback.NameCallback;
022    import javax.security.auth.callback.PasswordCallback;
023    import javax.security.auth.callback.UnsupportedCallbackException;
024    import java.io.IOException;
025    
026    
027    /**
028     * A JASS username password CallbackHandler.
029     */
030    public class UsernamePasswordCallback implements CallbackHandler {
031    
032        private final String username;
033        private final String password;
034    
035        public UsernamePasswordCallback(String username, String password) {
036            this.username = username;
037            this.password = password;
038        }
039    
040        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
041            for (int i = 0; i < callbacks.length; i++) {
042                if (callbacks[i] instanceof PasswordCallback) {
043                    ((PasswordCallback) callbacks[i]).setPassword(password.toCharArray());
044                } else if (callbacks[i] instanceof NameCallback) {
045                    ((NameCallback) callbacks[i]).setName(username);
046                }
047            }
048        }
049    }