Subversion Repositories bacoAlunos

Rev

Rev 367 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package pt.estgp.estgweb.web;

import org.apache.commons.httpclient.util.URIUtil;
import org.apache.log4j.Logger;
import pt.estgp.estgweb.utils.ConfigProperties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
import java.util.Date;
import java.util.zip.ZipInputStream;
import java.util.zip.InflaterInputStream;
import java.util.zip.GZIPInputStream;

/**
 * @author Jorge Machado
 * @date 26/Fev/2008
 * @time 12:46:16
 * @see pt.estgp.estgweb.web
 */

public class WebProxy extends HttpServlet
{

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     */


    private static final 1.5.0/docs/api/java/util/logging/Logger.html">Logger logger = 1.5.0/docs/api/java/util/logging/Logger.html">Logger.getLogger(WebProxy.class);


    protected static void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, 1.5.0/docs/api/java/io/IOException.html">IOException
    {
        1.5.0/docs/api/java/lang/String.html">String path = (1.5.0/docs/api/java/lang/String.html">String) request.getAttribute("path");
        1.5.0/docs/api/java/lang/String.html">String server = (1.5.0/docs/api/java/lang/String.html">String) request.getAttribute("server");
        1.5.0/docs/api/java/lang/String.html">String useOutputStream = (1.5.0/docs/api/java/lang/String.html">String) request.getAttribute("useOutputStream");
        1.5.0/docs/api/java/lang/String.html">String encoding = (1.5.0/docs/api/java/lang/String.html">String) request.getAttribute("encoding");
        1.5.0/docs/api/java/lang/String.html">String proxyHost = (1.5.0/docs/api/java/lang/String.html">String) request.getAttribute("proxy.host");
        1.5.0/docs/api/java/lang/String.html">String proxyPort = (1.5.0/docs/api/java/lang/String.html">String) request.getAttribute("proxy.port");
        logger.info("server:" + server);
        logger.info("path:" + path);
        logger.info("proxyHost:" + proxyHost);
        logger.info("proxyPort:" + proxyPort);
        if (path != null)
        {
            try
            {
                5+0%2Fdocs%2Fapi+Proxy">Proxy proxy = null;
                if (proxyHost != null && proxyHost.length() > 0)
                {
                    proxy = new 5+0%2Fdocs%2Fapi+Proxy">Proxy(5+0%2Fdocs%2Fapi+Proxy">Proxy.1.5.0/docs/api/java/lang/reflect/Type.html">Type.HTTP, new 1.5.0/docs/api/java/net/InetSocketAddress.html">InetSocketAddress(proxyHost, 1.5.0/docs/api/java/lang/Integer.html">Integer.parseInt(proxyPort)));
                }


                1.5.0/docs/api/java/lang/String.html">String finalURL = server + URIUtil.encodePath(path, "ISO-8859-1");
                1.5.0/docs/api/java/net/URL.html">URL url = new 1.5.0/docs/api/java/net/URL.html">URL(finalURL);

                1.5.0/docs/api/java/net/URLConnection.html">URLConnection con = url.openConnection();
                response.setContentType(con.getContentType());
                response.setContentLength(con.getContentLength());


                5+0%2Fdocs%2Fapi+InputStream">InputStream stream = openStream(finalURL,proxy);

                byte[] buf = new byte[1024];
                int readedBytes;
                if (useOutputStream != null && useOutputStream.equals("true"))
                {

                    5+0%2Fdocs%2Fapi+OutputStream">OutputStream os = response.getOutputStream();
                    while ((readedBytes = stream.read(buf)) > 0)
                    {
                        os.write(buf, 0, readedBytes);
                    }
                    os.close();
                }
                else
                {
                    while ((readedBytes = stream.read(buf)) > 0)
                    {
                        1.5.0/docs/api/java/lang/String.html">String s = new 1.5.0/docs/api/java/lang/String.html">String(buf, 0, readedBytes, encoding);
                        response.getWriter().write(s);
                    }
                }
            }
            catch (1.5.0/docs/api/java/io/FileNotFoundException.html">FileNotFoundException e)
            {
                logger.warn("url not found for server:" + server + " and path:" + path);
                response.sendError(404);
            }
            catch (1.5.0/docs/api/java/lang/Exception.html">Exception e)
            {
                throw new 1.5.0/docs/api/java/io/IOException.html">IOException(e.toString());
            }
        }
        else
        {
            logger.warn("url not found for server:" + server + " and path:" + path);
            response.sendError(404);
        }

    }

    private static 5+0%2Fdocs%2Fapi+InputStream">InputStream openStream(1.5.0/docs/api/java/lang/String.html">String requestURL, 5+0%2Fdocs%2Fapi+Proxy">Proxy proxy) throws 1.5.0/docs/api/java/io/IOException.html">IOException
    {
        5+0%2Fdocs%2Fapi+InputStream">InputStream in = null;
        1.5.0/docs/api/java/net/URL.html">URL url = new 1.5.0/docs/api/java/net/URL.html">URL(requestURL);

        1.5.0/docs/api/java/net/HttpURLConnection.html">HttpURLConnection con = null;
        int responseCode = 0;
        do
        {
            if (proxy != null)
                con = (1.5.0/docs/api/java/net/HttpURLConnection.html">HttpURLConnection) url.openConnection(proxy);
            else
                con = (1.5.0/docs/api/java/net/HttpURLConnection.html">HttpURLConnection) url.openConnection();
            con.setRequestProperty("User-Agent", "ESTG-Baco/1.0");
            con.setRequestProperty("Accept-Encoding", "compress, gzip, identify");
            try
            {
                responseCode = con.getResponseCode();
                logger.debug("responseCode=" + responseCode);
            }
            catch (1.5.0/docs/api/java/io/FileNotFoundException.html">FileNotFoundException e)
            {
                // assume it's a 503 response
                logger.info(requestURL, e);
                responseCode = 1.5.0/docs/api/java/net/HttpURLConnection.html">HttpURLConnection.HTTP_UNAVAILABLE;
            }

            if (responseCode == 1.5.0/docs/api/java/net/HttpURLConnection.html">HttpURLConnection.HTTP_UNAVAILABLE)
            {
                long retrySeconds = con.getHeaderFieldInt("Retry-After", -1);
                if (retrySeconds == -1)
                {
                    long now = (new 5+0%2Fdocs%2Fapi+Date">Date()).getTime();
                    long retryDate = con.getHeaderFieldDate("Retry-After", now);
                    retrySeconds = retryDate - now;
                }
                if (retrySeconds == 0)
                { // Apparently, it's a bad URL
                    throw new 1.5.0/docs/api/java/io/FileNotFoundException.html">FileNotFoundException("Bad URL?");
                }
                logger.error("Server response: Retry-After=" + retrySeconds);
                if (retrySeconds > 0)
                {
                    try
                    {
                        1.5.0/docs/api/java/lang/Thread.html">Thread.sleep(retrySeconds * 1000);
                    }
                    catch (1.5.0/docs/api/java/lang/InterruptedException.html">InterruptedException ex)
                    {
                        ex.printStackTrace();
                    }
                }
            }
        }
        while (responseCode == 1.5.0/docs/api/java/net/HttpURLConnection.html">HttpURLConnection.HTTP_UNAVAILABLE);
        1.5.0/docs/api/java/lang/String.html">String contentEncoding = con.getHeaderField("Content-Encoding");
        logger.debug("contentEncoding=" + contentEncoding);
        if ("compress".equals(contentEncoding))
        {
            1.5.0/docs/api/java/util/zip/ZipInputStream.html">ZipInputStream zis = new 1.5.0/docs/api/java/util/zip/ZipInputStream.html">ZipInputStream(con.getInputStream());
            zis.getNextEntry();
            in = zis;
        }
        else if ("gzip".equals(contentEncoding))
        {
            in = new 1.5.0/docs/api/java/util/zip/GZIPInputStream.html">GZIPInputStream(con.getInputStream());
        }
        else if ("deflate".equals(contentEncoding))
        {
            in = new 1.5.0/docs/api/java/util/zip/InflaterInputStream.html">InflaterInputStream(con.getInputStream());
        }
        else
        {
            in = con.getInputStream();
        }
        return in;
    }

    public static void processHttpRequestService(JspWriter out, 1.5.0/docs/api/java/lang/String.html">String server, 1.5.0/docs/api/java/lang/String.html">String path) throws 1.5.0/docs/api/java/io/IOException.html">IOException, ServletException
    {
        1.5.0/docs/api/java/lang/String.html">String serverUrl = ConfigProperties.getProperty("server." + server);
        1.5.0/docs/api/java/lang/String.html">String serverEncoding = ConfigProperties.getProperty(server + ".encoding");
        1.5.0/docs/api/java/lang/String.html">String confStartPath = ConfigProperties.getProperty("server." + server + ".start.path");
        if (confStartPath != null)
            path = confStartPath + path;


        try
        {
            1.5.0/docs/api/java/net/URL.html">URL url = new 1.5.0/docs/api/java/net/URL.html">URL(serverUrl + URIUtil.encodePath(path, "ISO-8859-1"));
            1.5.0/docs/api/java/net/URLConnection.html">URLConnection con = url.openConnection();
            5+0%2Fdocs%2Fapi+InputStream">InputStream stream = con.getInputStream();

            byte[] buf = new byte[1024];
            int readedBytes;

            while ((readedBytes = stream.read(buf)) > 0)
            {
                1.5.0/docs/api/java/lang/String.html">String str = new 1.5.0/docs/api/java/lang/String.html">String(buf, 0, readedBytes, serverEncoding);
                out.print(str);
            }
        }
        catch (1.5.0/docs/api/java/io/FileNotFoundException.html">FileNotFoundException e)
        {
            throw new 1.5.0/docs/api/java/io/FileNotFoundException.html">FileNotFoundException("url not found for server:" + server + " and path:" + path);
        }
        catch (1.5.0/docs/api/java/lang/Exception.html">Exception e)
        {
            throw new 1.5.0/docs/api/java/io/IOException.html">IOException(e.toString());
        }

    }


    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request  servlet request
     * @param response servlet response
     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, 1.5.0/docs/api/java/io/IOException.html">IOException
    {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request  servlet request
     * @param response servlet response
     */

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, 1.5.0/docs/api/java/io/IOException.html">IOException
    {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     */

    public 1.5.0/docs/api/java/lang/String.html">String getServletInfo()
    {
        return "Proxy Servlet to forward to HTTP or FTP Proxy";
    }
    // </editor-fold>
}