package com.wacai.sdk.jtr;

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.ResourceHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

public class Dispatch extends ResourceHandler {

    private final Collection<String> paths;

    public Dispatch(Collection<String> paths, String base) {
        this.paths = paths;
        setDirectoriesListed(true);
        setResourceBase(base);
    }

    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        final String path = path(target);
        if (!paths.contains(path)) {
            super.handle(target, baseRequest, request, allowCrossOrigin(response));
        } else {
            baseRequest.getContext().getContext(path).getRequestDispatcher(target).forward(request, allowCrossOrigin(response));
        }
    }

    static String path(String target) {
        final StringBuilder sb = new StringBuilder(target);
        final int index = sb.lastIndexOf(".");
        if (index < 0) return null;
        return sb.substring(index).replace('.', '/');
    }

    static HttpServletResponse allowCrossOrigin(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Methods","GET, OPTIONS");
        return response;
    }

}

@@ -770,23 +770,31 @@
  = path(
+suffix(
 target)
+)
 ;%0A      
@@ -1089,20 +1089,22 @@
  String 
-path
+suffix
 (String 
@@ -1271,16 +1271,17 @@
  return 
+ 
 sb.subst
@@ -1291,16 +1291,86 @@
 g(index)
+;%0A    %7D%0A%0A    static String path(String suffix) %7B%0A        return suffix
 .replace

Clean code.