package eu.freme.bservices.filter.proxy;

import java.io.IOException;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mashape.unirest.http.exceptions.UnirestException;
import com.mashape.unirest.request.HttpRequest;

import eu.freme.bservices.filter.proxy.exception.BadGatewayException;
import eu.freme.common.exception.ExceptionHandlerService;

@Controller("ProxyController")
public class ProxyController{

	Logger logger = Logger.getLogger(ProxyController.class);

	@Autowired
	ProxyService proxyService;

	@Autowired
	ExceptionHandlerService exceptionHandlerService;

	Map<String, String> proxies;

	@PostConstruct
	public void init() {
		proxies = proxyService.getProxies();
	}

	private ResponseEntity<String> doProxy(HttpServletRequest request) {
		try {
			HttpRequest proxy = proxyService.createProxy(request,
					proxies.get(request.getServletPath()));
			return proxyService.createResponse(proxy);
		} catch (IOException | UnirestException e) {
			logger.error("failed", e);
			throw new BadGatewayException("Proxy failed: " + e.getMessage());
		}
	}

	@RequestMapping
	public ResponseEntity<String> doPost(HttpServletRequest request) {
		return doProxy(request);
	}
}

@@ -666,16 +666,79 @@
 Service;
+%0Aimport eu.freme.common.exception.InternalServerErrorException;
 %0A%0A@Contr
@@ -1153,67 +1153,216 @@
 %0A%09%09%09
-HttpRequest proxy = proxyService.createProxy(request,%0A%09%09%09%09%09
+for( String prefix : proxies.keySet() )%7B%0A%09%09%09%09if( request.getServletPath().startsWith(prefix))%7B%0A%09%09%09%09%09%0A%09%09%09%09%09String pathParam = request.getServletPath().substring(prefix.length());%0A%09%09%09%09%09%0A%09%09%09%09%09String targetUrl = 
 prox
@@ -1373,36 +1373,303 @@
 get(
+p
 re
-quest.getServletPath())
+fix);%0A%09%09%09%09%09if( pathParam.length() %3E 0)%7B%0A%09%09%09%09%09%09if( !targetUrl.endsWith(%22/%22))%7B%0A%09%09%09%09%09%09%09targetUrl += %22/%22;%0A%09%09%09%09%09%09%7D%0A%09%09%09%09%09%09%0A%09%09%09%09%09%09if( pathParam.startsWith(%22/%22))%7B%0A%09%09%09%09%09%09%09pathParam = pathParam.substring(1);%0A%09%09%09%09%09%09%7D%0A%09%09%09%09%09%7D%0A%09%09%09%09%09%0A%09%09%09%09%09HttpRequest proxy = proxyService.createProxy(request, targetUrl
 );%0A
+%09%09
 %09%09%09r
@@ -1709,16 +1709,85 @@
 (proxy);
+%09%09%09%09%09%0A%09%09%09%09%7D%0A%09%09%09%7D%0A%09%09%09%0A%09%09%09throw new InternalServerErrorException();%0A%09%09%09
 %0A%09%09%7D cat

fix problem in proxy redirect with path parameters