1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied.  See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 *
19 */
20package org.apache.qpid.management.common.sasl;
21
22import org.apache.harmony.javax.security.auth.callback.Callback;
23import org.apache.harmony.javax.security.auth.callback.CallbackHandler;
24import org.apache.harmony.javax.security.auth.callback.NameCallback;
25import org.apache.harmony.javax.security.auth.callback.PasswordCallback;
26import org.apache.harmony.javax.security.auth.callback.UnsupportedCallbackException;
27import java.io.IOException;
28
29public class UserPasswordCallbackHandler implements CallbackHandler
30{
31    private String user;
32    private char[] pwchars;
33
34    public UserPasswordCallbackHandler(String user, String password)
35    {
36        this.user = user;
37        this.pwchars = password.toCharArray();
38    }
39
40    public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
41    {
42        for (int i = 0; i < callbacks.length; i++)
43        {
44            if (callbacks[i] instanceof NameCallback)
45            {
46                NameCallback ncb = (NameCallback) callbacks[i];
47                ncb.setName(user);
48            }
49            else if (callbacks[i] instanceof PasswordCallback)
50            {
51                PasswordCallback pcb = (PasswordCallback) callbacks[i];
52                pcb.setPassword(pwchars);
53            }
54            else
55            {
56                throw new UnsupportedCallbackException(callbacks[i]);
57            }
58        }
59    }
60
61    private void clearPassword()
62    {
63        if (pwchars != null)
64        {
65            for (int i = 0 ; i < pwchars.length ; i++)
66            {
67                pwchars[i] = 0;
68            }
69            pwchars = null;
70        }
71    }
72
73    protected void finalize()
74    {
75        clearPassword();
76    }
77}
78