/*
 * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the
 * License at http://www.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.kernel.security;

import com.arsdigita.util.Classes;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;

/**
 * Utility package of static security methods
 *
 * @author Christian
 *            Brechb&uuml;hler
 */
public class Util {
    private static SecurityHelper s_helper = null;

    /** This class needs not to be instantiated. */
    private Util() {}

    /**
     * Returns the security helper instance.
     *
     * @return the security helper instance.
     *
     **/
    public static SecurityHelper getSecurityHelper() {
        if (s_helper == null) {
            s_helper = (DefaultSecurityHelper) Classes.newInstance
                (DefaultSecurityHelper.class);
        }
        return s_helper;
    }

    /**
     * Set the security helper instance.
     * package local
     */
    static void setSecurityHelper(Object helper) {
        s_helper = (SecurityHelper)helper;
    }

    /**
       Get a using a callback.

       @return an HttpServletRequest
       @throws LoginException if an error occurs.
    */
    static HttpServletRequest getRequest(CallbackHandler handler)
        throws LoginException {

        try {
            HTTPRequestCallback cb = new HTTPRequestCallback();
            handler.handle(new Callback[] { cb });
            return cb.getRequest();
        } catch (IOException e) {
            throw new KernelLoginException("IO error getting HTTP request", e);
        } catch (UnsupportedCallbackException e) {
            throw new KernelLoginException("Error getting HTTP request", e);
        }
    }
}
