// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.restapi;

import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.container.jdisc.HttpResponse;
import com.yahoo.container.jdisc.LoggingRequestHandler;

/**
 * @author bjorncs
 */
public abstract class RestApiRequestHandler<T extends RestApiRequestHandler<T>> extends LoggingRequestHandler {

    private final RestApi restApi;

    @FunctionalInterface public interface RestApiProvider<T> { RestApi createRestApi(T self); }

    /**
     * RestApi will usually refer to handler methods of subclass, which are not accessible before super constructor has completed.
     * This is hack to leak reference to subclass instance's "this" reference.
     * Caller must ensure that provider instance does not try to access any uninitialized fields.
     */
    @SuppressWarnings("unchecked")
    protected RestApiRequestHandler(LoggingRequestHandler.Context context, RestApiProvider<T> provider) {
        super(context);
        this.restApi = provider.createRestApi((T)this);
    }

    protected RestApiRequestHandler(LoggingRequestHandler.Context context, RestApi restApi) {
        super(context);
        this.restApi = restApi;
    }

    @Override public final HttpResponse handle(HttpRequest request) { return restApi.handleRequest(request); }

    public RestApi restApi() { return restApi; }
}

@@ -282,16 +282,86 @@
 Handler;
+%0Aimport com.yahoo.jdisc.Metric;%0A%0Aimport java.util.concurrent.Executor;
 %0A%0A/**%0A *
@@ -1187,119 +1187,589 @@
     
-protected RestApiRequestHandler(LoggingRequestHandler.Context context, RestApi restApi) %7B%0A        super(context
+/**%0A     * @see #RestApiRequestHandler(Context, RestApiProvider)%0A     */%0A    @SuppressWarnings(%22unchecked%22)%0A    protected RestApiRequestHandler(Executor executor, Metric metric, RestApiProvider%3CT%3E provider) %7B%0A        super(executor, metric);%0A        this.restApi = provider.createRestApi((T)this);%0A    %7D%0A%0A    protected RestApiRequestHandler(LoggingRequestHandler.Context context, RestApi restApi) %7B%0A        super(context);%0A        this.restApi = restApi;%0A    %7D%0A%0A    protected RestApiRequestHandler(Executor executor, Metric metric, RestApi restApi) %7B%0A        super(executor, metric
 );%0A 

Add additional constructor overloads