/**
 * Copyright (c) 2007-2014 Kaazing Corporation. All rights reserved.
 * 
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.kaazing.net.auth;

import java.util.ServiceLoader;

/**
 * A ChallengeHandler is responsible for producing responses to authentication challenges.
 * <p/>
 * When an attempt to access a protected URI is made, the server responsible for serving the resource
 * may respond with a challenge, indicating that credentials need be provided before access to the
 * resource is granted.  The specific type of challenge is indicated in a HTTP header called "WWW-Authenticate".
 * This response and that header are converted into a {@link ChallengeRequest} and sent to a
 * registered ChallengeHandler for authentication challenge responses.  The {@link ChallengeResponse} credentials
 * generated by a registered challenge handler are included in a replay of the original HTTP request to the server, which
 * (assuming the credentials are sufficient) allows access to the resource.
 * <p/>
 * Public subclasses of ChallengeHandler can be loaded and instantiated using {@link ChallengeHandlers},
 * and registered to handle server challenges for specific URI locations
 * using {@link DispatchChallengeHandler#register(String, ChallengeHandler)}.
 * <p/>
 * Any challenge responses to requests matching the registered location may be handled by the registered {@link ChallengeHandler}
 * as long as {@link #canHandle(ChallengeRequest)} returns true.  In the case where multiple registered challenge handlers
 * could respond to a challenge request, the earliest challenge handler registered at the most specific location matching
 * the protected URI is selected.
 *
 */
public abstract class ChallengeHandler {
    /**
     * Creates a new instance of the sub-class of {@link ChallengeHandler} using
     * the {@link ServiceLoader} API with the implementation specified under
     * META-INF/services.
     * 
     * @param T        sub-class of ChallengeHandler
     * @param clazz    Class object of the sub-type
     * @return ChallengeHandler
     */
    protected static <T extends ChallengeHandler> T create(Class<T> clazz) {
        return load0(clazz, ServiceLoader.load(clazz));
    }

    /**
     * Creates a new instance of the sub-class of {@link ChallengeHandler} with
     * specified {@link ClassLoader} using the {@link ServiceLoader} API with
     * the implementation specified under META-INF/services.
     * 
     * @param  T                    sub-type of ChallengeHandler
     * @param  clazz                Class object of the sub-type
     * @param  classLoader          ClassLoader to be used to instantiate
     * @return ChallengeHandler
     */
    protected static <T extends ChallengeHandler> T create(Class<T>    clazz, 
                                                           ClassLoader clazzLoader) {
        return load0(clazz, ServiceLoader.load(clazz, clazzLoader));
    }

    /**
     * Can the presented challenge be potentially handled by this challenge handler?
     *
     * @param challengeRequest a challenge request object containing a challenge
     * @return true iff this challenge handler could potentially respond meaningfully to the challenge.
     */
    public abstract boolean canHandle(ChallengeRequest challengeRequest);

    /**
     * Handle the presented challenge by creating a challenge response or returning {@code null}.
     * This responsibility is usually achieved
     * by using the associated {@link LoginHandler} to obtain user credentials, and transforming those credentials
     * into a {@link ChallengeResponse}.
     * <p/>
     * When it is not possible to create a {@link ChallengeResponse}, this method MUST return {@code null}.
     *
     * @param challengeRequest a challenge object
     * @return a challenge response object or {@code null} if no response is possible.
     */
    public abstract ChallengeResponse handle(ChallengeRequest challengeRequest);
    
    // ----------------------- Private Methods -------------------------------

    private static <T extends ChallengeHandler> T load0(Class<T>         clazz, 
                                                 ServiceLoader<T> serviceLoader) {
        for (ChallengeHandler challengeHandler: serviceLoader) {
            Class<?> c = challengeHandler.getClass();
            if ((clazz != null) && clazz.isAssignableFrom(c)) {
                try {
                    return clazz.cast(c.newInstance());
                } catch (InstantiationException e) {
                    String s = "Failed to instantiate class " + c;
                    throw new RuntimeException(s,e);
                } catch (IllegalAccessException e) {
                    String s = "Failed to access and instantiate class " + c;
                    throw new RuntimeException(s, e);
                }
            }
        }
        return null;
    }

}
