package uk.ac.open.kmi.iserve.elda;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Luca Panziera on 17/09/2014.
 */
public class EldaFilter implements Filter {

    private RequestDispatcher defaultRequestDispatcher;
    private RequestDispatcher salRestRequestDispatcher;

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        res.addHeader("Access-Control-Allow-Origin", "*");
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        res.addHeader("Access-Control-Allow-Headers", "Content-Type");
        if (httpRequest.getRequestURI().equals("/iserve/id/services")) {
            // TODO Fix this by debugging Elda config file
            res.sendRedirect("/iserve/doc/services");
        } else if (httpRequest.getRequestURI().matches("/iserve/id.*") && !httpRequest.getMethod().equalsIgnoreCase("GET")) {
            salRestRequestDispatcher.forward(request, response);
        } else if ((httpRequest.getRequestURI().matches("/iserve/id.*") && httpRequest.getMethod().equalsIgnoreCase("GET")) || (httpRequest.getRequestURI().matches("/iserve/api-docs.*"))) {
            chain.doFilter(request, response);
        } else {
            defaultRequestDispatcher.forward(request, response);
        }

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.defaultRequestDispatcher =
                filterConfig.getServletContext().getNamedDispatcher("default");
        this.salRestRequestDispatcher =
                filterConfig.getServletContext().getNamedDispatcher("iServe SAL REST Endpoint");
    }
}

@@ -664,16 +664,188 @@
 equest;%0A
+        // Obtain the actual request within the web application context%0A        String path = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());%0A
         
@@ -1129,35 +1129,12 @@
 if (
-httpRequest.getRequestURI()
+path
 .equ
@@ -1139,23 +1139,16 @@
 quals(%22/
-iserve/
 id/servi
@@ -1246,23 +1246,16 @@
 irect(%22/
-iserve/
 doc/serv
@@ -1285,35 +1285,12 @@
 if (
-httpRequest.getRequestURI()
+path
 .mat
@@ -1288,39 +1288,32 @@
 (path.matches(%22/
-iserve/
 id.*%22) && !httpR
@@ -1447,35 +1447,12 @@
 f ((
-httpRequest.getRequestURI()
+path
 .mat
@@ -1458,23 +1458,16 @@
 tches(%22/
-iserve/
 id.*%22) &
@@ -1525,35 +1525,12 @@
 %7C%7C (
-httpRequest.getRequestURI()
+path
 .mat
@@ -1540,15 +1540,8 @@
 s(%22/
-iserve/
 api-

Remove hardcoded path to Web app in the filter