001/*
002 * The contents of this file are subject to the terms of the Common Development and
003 * Distribution License (the License). You may not use this file except in compliance with the
004 * License.
005 *
006 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
007 * specific language governing permission and limitations under the License.
008 *
009 * When distributing Covered Software, include this CDDL Header Notice in each file and include
010 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
011 * Header, with the fields enclosed by brackets [] replaced by your own identifying
012 * information: "Portions Copyright [year] [name of copyright owner]".
013 *
014 * Copyright 2015 ForgeRock AS.
015 */
016package org.forgerock.http.spi;
017
018import java.util.Iterator;
019import java.util.ServiceLoader;
020
021import org.forgerock.util.Options;
022
023/**
024 * An SPI interface for implementing alternative service loading strategies. By
025 * default the HTTP framework will use a strategy based on {@link ServiceLoader}
026 * , but applications may choose to override with their own strategy if needed,
027 * for example when running in OSGI environments.
028 */
029public interface Loader {
030    /**
031     * The default {@link Loader} implementation used throughout the HTTP
032     * framework. This implementation uses {@link ServiceLoader} for loading
033     * services.
034     */
035    Loader SERVICE_LOADER = new Loader() {
036        @Override
037        public <S> S load(final Class<S> service, final Options options) {
038            final ServiceLoader<S> loader = ServiceLoader.load(service);
039            final Iterator<S> i = loader.iterator();
040            return i.hasNext() ? i.next() : null;
041        };
042    };
043
044    /**
045     * Loads a service of the specified type. Implementations may customize
046     * their behavior based on the provided options, e.g. by using a user
047     * provided class loader.
048     *
049     * @param <S>
050     *            The type of service to load.
051     * @param service
052     *            The type of service to load.
053     * @param options
054     *            The user provided options.
055     * @return The loaded service, or {@code null} if no corresponding service
056     *         was found.
057     */
058    <S> S load(final Class<S> service, final Options options);
059}