Example usage for javax.security.sasl SaslClient dispose

List of usage examples for javax.security.sasl SaslClient dispose

Introduction

In this page you can find the example usage for javax.security.sasl SaslClient dispose.

Prototype

public abstract void dispose() throws SaslException;

Source Link

Document

Disposes of any system resources or security-sensitive information the SaslClient might be using.

Usage

From source file:com.fluffypeople.managesieve.ManageSieveClient.java

/**
 * Authenticate against the remote server using SASL.
 *
 * The CallbackHandler should be setup appropriately, for example:
 * <pre>/*w  ww .  j  av a  2  s .  c om*/
 * <code>
 *
 * CallbackHandler cbh = new CallbackHandler() {
 *     public void handle(Callback[] clbcks) throws IOException,  UnsupportedCallbackException {
 *         for (Callback cb : clbcks) {
 *             if (cb instanceof NameCallback) {
 *                 NameCallback name = (NameCallback) cb;
 *                 name.setName("user");
 *             } else if (cb instanceof PasswordCallback) {
 *                 PasswordCallback passwd = (PasswordCallback) cb;
 *                 passwd.setPassword("secret".toCharArray());
 *             }
 *         }
 *     }
 * };
 * </code>
 * </pre>
 *
 * @param cbh CallbackHandler[] list of call backs that will be called by
 * the SASL code
 * @return ManageSieveResponse from the server, OK is authenticated, NO
 * means a problem
 * @throws SaslException
 * @throws IOException
 * @throws ParseException
 */
public synchronized ManageSieveResponse authenticate(final CallbackHandler cbh)
        throws SaslException, IOException, ParseException {

    SaslClient sc = Sasl.createSaslClient(cap.getSASLMethods(), null, "sieve", hostname, null, cbh);

    String mechanism = escapeString(sc.getMechanismName());
    if (sc.hasInitialResponse()) {
        byte[] ir = sc.evaluateChallenge(new byte[0]);
        String ready = new String(Base64.encodeBase64(ir));
        ready = encodeString(ready.trim());
        sendCommand("AUTHENTICATE", mechanism, ready);
    } else {
        sendCommand("AUTHENTICATE", mechanism);
    }

    int token;
    ManageSieveResponse resp = null;
    do {
        token = in.nextToken();
        if (token == DQUOTE) {
            // String - so more data for the auth sequence
            in.pushBack();
            String msg = parseString();
            byte[] response = sc.evaluateChallenge(msg.getBytes());
            sendLine(encodeString(new String(response)));
        } else if (token == StreamTokenizer.TT_WORD) {
            in.pushBack();
            resp = parseResponse();
            break;
        } else {
            throw new ParseException(
                    "Expecting DQUOTE/WORD, got " + tokenToString(token) + " at line " + in.lineno());
        }
    } while (!sc.isComplete());

    // Complete
    sc.dispose();
    return resp;
}