package com.hubspot.singularity.resources;

import javax.servlet.http.HttpServletRequest;

import org.apache.curator.framework.recipes.leader.LeaderLatch;

import com.hubspot.horizon.HttpClient;
import com.hubspot.horizon.HttpRequest;
import com.hubspot.horizon.HttpRequest.Method;
import com.hubspot.horizon.HttpResponse;
import com.hubspot.singularity.WebExceptions;

public class AbstractLeaderAwareResource {
  protected final HttpClient httpClient;
  protected final LeaderLatch leaderLatch;

  public AbstractLeaderAwareResource(HttpClient httpClient, LeaderLatch leaderLatch) {
    this.httpClient = httpClient;
    this.leaderLatch = leaderLatch;
  }

  protected <T> T proxyToLeader(HttpServletRequest request, Class<T> clazz) {
    String leaderUri;
    try {
      leaderUri = leaderLatch.getLeader().getId();
    } catch (Exception e) {
      throw new RuntimeException("Could not get leader uri to proxy request");
    }
    HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
        .setUrl(String.format("%s%s", leaderUri, request.getServletPath()))
        .setMethod(Method.valueOf(request.getMethod()));
    copyHeadersAndParams(requestBuilder, request);
    HttpResponse response = httpClient.execute(requestBuilder.build());
    if (response.isServerError()) {
      throw WebExceptions.badRequest(response.getAsString());
    } else if (response.isServerError()) {
      throw new RuntimeException(response.getAsString());
    } else {
      return response.getAs(clazz);
    }
  }

  private void copyHeadersAndParams(HttpRequest.Builder requestBuilder, HttpServletRequest request) {
    while (request.getHeaderNames().hasMoreElements()) {
      String headerName = request.getHeaderNames().nextElement();
      requestBuilder.addHeader(headerName, request.getHeader(headerName));
    }
    while (request.getParameterNames().hasMoreElements()) {
      String parameterName = request.getParameterNames().nextElement();
      requestBuilder.setQueryParam(parameterName).to(request.getParameter(parameterName));
    }
  }

  protected boolean useWebCache(Boolean useWebCache) {
    return useWebCache != null && useWebCache.booleanValue();
  }
}

@@ -147,16 +147,73 @@
 erLatch;
+%0Aimport org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;
 %0A%0Aimport
@@ -463,16 +463,113 @@
 ource %7B%0A
+  private static final Logger LOG = LoggerFactory.getLogger(AbstractLeaderAwareResource.class);%0A%0A
   protec
@@ -1076,24 +1076,266 @@
 est%22);%0A    %7D
+%0A%0A    String protocol = request.getRequestURI().contains(%22https%22) ? %22https://%22 : %22http://%22;%0A    String url = protocol + leaderUri + request.getContextPath() + request.getPathInfo();%0A    LOG.debug(%22No the leader, proxying request to %7B%7D%22, url);
 %0A    HttpReq
@@ -1409,66 +1409,11 @@
 Url(
-String.format(%22%25s%25s%22, leaderUri, request.getServletPath())
+url
 )%0A  

fix proxy to leader