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 2009 Sun Microsystems Inc.
015 * Portions Copyright 2010–2011 ApexIdentity Inc.
016 * Portions Copyright 2011-2014 ForgeRock AS.
017 */
018
019package org.forgerock.openig.handler;
020
021import static org.forgerock.openig.http.HttpClient.*;
022
023import java.io.IOException;
024
025import org.forgerock.openig.heap.GenericHeaplet;
026import org.forgerock.openig.heap.HeapException;
027import org.forgerock.openig.http.Exchange;
028import org.forgerock.openig.http.HttpClient;
029
030/**
031 * Submits exchange requests to remote servers. In this implementation, requests are dispatched through the {@link
032 * HttpClient} this handler is configured to use (defaults to system's HttpClient provided under the {@literal
033 * HttpClient} name).
034 * <p>
035 * <pre>
036 *   {
037 *     "name": "Client",
038 *     "type": "ClientHandler",
039 *     "config": {
040 *       "httpClient": "MyHttpClient"
041 *     }
042 *   }
043 * </pre>
044 */
045public class ClientHandler extends GenericHandler {
046
047    /** The HTTP client to transmit requests through. */
048    private final HttpClient client;
049
050    /**
051     * Creates a new client handler.
052     *
053     * @param client The HTTP client implementation.
054     */
055    public ClientHandler(HttpClient client) {
056        this.client = client;
057    }
058
059    @Override
060    public void handle(Exchange exchange) throws HandlerException, IOException {
061        client.execute(exchange);
062    }
063
064    /** Creates and initializes a client handler in a heap environment. */
065    public static class Heaplet extends GenericHeaplet {
066        @Override
067        public Object create() throws HeapException {
068            HttpClient httpClient = heap.resolve(
069                    config.get("httpClient").defaultTo(HTTP_CLIENT_HEAP_KEY),
070                    HttpClient.class);
071            return new ClientHandler(httpClient);
072        }
073    }
074}