Question

I am trying to use jetty7 to build a transparent proxy setup. Idea is to hide origin servers behind the jetty server so that the incoming request can be forwarded in a transparent manner to the origin servers.

I want to know if I can use jetty's ProxyServlet.Transparent implementation to do so. If yes, can anyone give me some examples.

Was it helpful?

Solution

This example is based on Jetty-9. If you want to implement this with Jetty 8, implement the proxyHttpURI method (See Jetty 8 javadocs.). Here is some sample code.

import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.eclipse.jetty.servlets.ProxyServlet;

/**
 * When a request cannot be satisfied on the local machine, it asynchronously
 * proxied to the destination box. Define the rule 
 */
public class ContentBasedProxyServlet extends ProxyServlet {
    private int remotePort = 8080;

    public void setPort(int port) {
        this.remotePort = port;
    }

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException {
        super.service(request, response);
    }

    /**
     *  Applicable to Jetty 9+ only. 
     */
    @Override
    protected URI rewriteURI(HttpServletRequest request) {
        String proxyTo = getProxyTo(request);
        if (proxyTo == null)
            return null;
        String path = request.getRequestURI();
        String query = request.getQueryString();
        if (query != null)
            path += "?" + query;
        return URI.create(proxyTo + "/" + path).normalize();
    }

    private String getProxyTo(HttpServletRequest request) {
    /*
    *   Implement this method: All the magic happens here. Use this method to figure out your destination machine address. You can maintain
    *   a static list of addresses, and depending on the URI or request content you can route your request transparently.
    */
    }
}

Further more, you can implement a Filter that determines whether the request needs to terminate on the local machine or on the destination machine. If the request is meant for the remote machine, forward the request to this servlet.

// Declare this method call in the filter.
request.getServletContext()
    .getNamedDispatcher("ContentBasedProxyServlet")
    .forward(request, response);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top