001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  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 */
017package org.apache.activemq.jaas;
018
019import java.io.IOException;
020
021import javax.security.auth.callback.Callback;
022import javax.security.auth.callback.CallbackHandler;
023import javax.security.auth.callback.NameCallback;
024import javax.security.auth.callback.PasswordCallback;
025import javax.security.auth.callback.UnsupportedCallbackException;
026
027/**
028 * A JASS username password CallbackHandler.
029 */
030public class JassCredentialCallbackHandler implements CallbackHandler {
031
032    private final String username;
033    private final String password;
034
035    public JassCredentialCallbackHandler(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            Callback callback = callbacks[i];
043            if (callback instanceof PasswordCallback) {
044                PasswordCallback passwordCallback = (PasswordCallback)callback;
045                if (password == null) {
046                    passwordCallback.setPassword(null);
047                } else {
048                    passwordCallback.setPassword(password.toCharArray());
049                }
050            } else if (callback instanceof NameCallback) {
051                NameCallback nameCallback = (NameCallback)callback;
052                if (username == null) {
053                    nameCallback.setName(null);
054                } else {
055                    nameCallback.setName(username);
056                }
057            }
058        }
059    }
060}