package com.github.onsdigital.florence.api;

import com.github.davidcarboni.restolino.framework.Filter;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
* Routes all traffic to Tredegar, Unless it is recognised as a florence file being requested.
*/
public class TredegarProxy implements Filter {


    private static final String florenceToken = "/florence";
    private static final String tredegarBaseUrl = "http://localhost:8080";

    private static final List<String> florencePaths = Arrays.asList("/");

    @Override
    public boolean filter(HttpServletRequest request, HttpServletResponse response) {

        try {
            if (florencePaths.contains(request.getRequestURI())
                    || request.getRequestURI().startsWith(florenceToken)) {
                return true; // carry on and serve the file from florence
            }

            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(tredegarBaseUrl + request.getRequestURI());
            CloseableHttpResponse tredegarResponse = httpClient.execute(httpGet);

            try {
                HttpEntity responseEntity = tredegarResponse.getEntity();

                // copy headers from the response
                for (Header header : tredegarResponse.getAllHeaders()) {
                    response.setHeader(header.getName(), header.getValue());
                }

                IOUtils.copy(responseEntity.getContent(), response.getOutputStream());
                EntityUtils.consume(responseEntity);

            } catch (IOException e) {
                return true;
            } finally {
                tredegarResponse.close();
            }

        } catch (IOException e) {
            return true;
        }

        return false;
    }
}
@@ -601,16 +601,46 @@
 Arrays;%0A
+import java.util.Enumeration;%0A
 import j
@@ -1517,24 +1517,358 @@
 uestURI());%0A
+%0A            // copy the request headers.%0A            Enumeration%3CString%3E headerNames = request.getHeaderNames();%0A            while (headerNames.hasMoreElements())%0A            %7B%0A                String headerName = headerNames.nextElement();%0A                httpGet.addHeader(headerName, request.getHeader(headerName));%0A            %7D%0A%0A
             

Copy request headers in tredegar proxy. Collection name cookie was not being passed to tredegar as the proxy was not passing them through.