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