Example usage for javax.servlet.http HttpServletResponse setIntHeader

List of usage examples for javax.servlet.http HttpServletResponse setIntHeader

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse setIntHeader.

Prototype

public void setIntHeader(String name, int value);

Source Link

Document

Sets a response header with the given name and integer value.

Usage

From source file:com.orange.mmp.api.ws.jsonrpc.MMPJsonRpcServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

    ExecutionContext executionContext = ExecutionContext.newInstance(request);
    executionContext.setName("JSON-RCP Request");

    executionContext.executionStart();/*  w  w w .j a  va  2  s.  c  o  m*/
    String requestInfo = "";
    try {

        // Use protected method in case someone wants to override it
        JSONRPCBridge json_bridge = findBridge(request);

        // Encode using UTF-8, although We are actually ASCII clean as
        // all unicode data is JSON escaped using backslash u. This is
        // less data efficient for foreign character sets but it is
        // needed to support naughty browsers such as Konqueror and Safari
        // which do not honour the charset set in the response
        response.setContentType("application/json");
        response.setCharacterEncoding(Constants.DEFAULT_ENCODING);
        OutputStream out = response.getOutputStream();

        // Decode using the charset in the request if it exists otherwise
        // use UTF-8 as this is what all browser implementations use.
        // The JSON-RPC-Java JavaScript client is ASCII clean so it
        // although here we can correctly handle data from other clients
        // that do not escape non ASCII data
        String charset = request.getCharacterEncoding();
        if (charset == null) {
            charset = Constants.DEFAULT_ENCODING;
        }

        String receiveString = null;

        // Test HTTP GET
        if (request.getQueryString() != null) {
            String id = request.getParameter(HTTP_PARAM_ID);
            if (id != null) {
                executionContext.setApiName(id);

                StringBuilder receiveStringBuilder = new StringBuilder("{\"id\":").append(id)
                        .append(",\"method\":\"");
                String method = request.getParameter(HTTP_PARAM_METHOD);
                // Get params
                if (method != null) {
                    executionContext.setMethodName(method);

                    receiveStringBuilder.append(method);
                    String param = request.getParameter(HTTP_PARAM_PARAM);
                    // There is parameters
                    if (param != null) {
                        receiveStringBuilder.append("\",\"params\":").append(param).append("}");
                    }
                    // Empty params
                    else {
                        receiveStringBuilder.append("\",\"params\":[]}");
                    }
                }
                // Default method (list API)
                else {
                    receiveStringBuilder.append("system.listMethods\",\"params\":[]}");
                }

                // Set JSON-RPC call string
                receiveString = receiveStringBuilder.toString();

                //Trace request
                executionContext.setName("JSON-RCP Request: " + receiveString);
            }
        }

        // Test HTTP POST
        if (receiveString == null) {
            BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), charset));

            // Read the request
            CharArrayWriter data = new CharArrayWriter();
            char buf[] = new char[4096];
            int ret;
            while ((ret = in.read(buf, 0, 4096)) != -1) {
                data.write(buf, 0, ret);
            }

            receiveString = data.toString();
            requestInfo = receiveString;
        }

        // Process the request
        JSONObject json_req;
        JSONRPCResult json_res;
        try {
            json_req = new JSONObject(receiveString);
            json_res = json_bridge.call(new Object[] { request, response }, json_req);
        } catch (JSONException e) {
            json_res = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, JSONRPCResult.MSG_ERR_PARSE);
        }

        String sendString = json_res.toString();

        // Write the response
        byte[] bout = sendString.getBytes(Constants.DEFAULT_ENCODING);

        // if the request header says that the browser can take gzip compressed
        // output, then gzip the output
        // but only if the response is large enough to warrant it and if the
        // resultant compressed output is
        // actually smaller.
        String ae = request.getHeader("accept-encoding");
        if (ae != null && ae.indexOf("gzip") != -1) {
            byte[] gzippedOut = gzip(bout);

            // if gzip didn't actually help, abort
            if (bout.length > gzippedOut.length) {
                bout = gzippedOut;
                response.addHeader("Content-Encoding", "gzip");
            }
        }

        response.setIntHeader("Content-Length", bout.length);

        out.write(bout);

    } catch (Throwable error) {
        //Catch exception
        throw new IOExceptionWithCause("Error during request processing", error);
    } finally {
        executionContext.executionStop();
        printMonitoredRequest(requestInfo);
        executionContext.close();
    }
}

From source file:org.jabsorb.JSONRPCServlet.java

/**
 * Called when a JSON-RPC requests comes in.
 * Looks in the session for a JSONRPCBridge and if not found there,
 * uses the global bridge; then passes off the
 * JSON-PRC call to be handled by the JSONRPCBridge found.
 *
 * @param request servlet request from browser.
 * @param response servlet response to browser.
 *
 * @throws IOException if an IOException occurs during processing.
 *//* ww w  .j  a  va2 s.  c om*/
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Use protected method in case someone wants to override it
    JSONRPCBridge json_bridge = findBridge(request);

    // Decode using the charset in the request if it exists otherwise
    // use UTF-8 as this is what all browser implementations use.
    // The JSON-RPC-Java JavaScript client is ASCII clean so it
    // although here we can correctly handle data from other clients
    // that do not escape non ASCII data
    String charset = request.getCharacterEncoding();
    if (charset == null) {
        charset = "UTF-8";
    }

    BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), charset));

    String receiveString = (String) request.getAttribute("_jabsorb_beenHere");

    // if JSON data is found in a special request attribute, it means
    // that a continuation was used and this request is being retried
    // as a consequence of a Jetty continuation
    // see http://blogs.webtide.com/gregw/2007/11/18/1195421880000.html
    if (receiveString == null) {
        // Read the request
        CharArrayWriter data = new CharArrayWriter();
        char buf[] = new char[buf_size];
        int ret;
        while ((ret = in.read(buf, 0, buf_size)) != -1) {
            data.write(buf, 0, ret);
        }
        receiveString = data.toString();
        int begin = receiveString.indexOf("{");
        int end = receiveString.lastIndexOf("}") + 1;
        receiveString = receiveString.substring(begin, end);

        // save the json-rpc data in a special request attribute, in case a jetty 
        // continuation exception (org.mortbay.jetty.RetryRequest) is thrown and this 
        // request is retried by the container
        request.setAttribute("_jabsorb_beenHere", receiveString);
    } else {
        log.debug("jetty continuation resumed...");
    }

    if (log.isDebugEnabled()) {
        log.debug("receive: " + receiveString);
        log.debug("receive: " + prettyPrintJson(receiveString));
    }

    // Process the request
    JSONObject json_req;
    JSONRPCResult json_res;
    try {
        json_req = new JSONObject(receiveString);
        json_res = json_bridge.call(new Object[] { request, response }, json_req);
    } catch (JSONException e) {
        log.error("can't parse call" + receiveString, e);
        json_res = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, JSONRPCResult.MSG_ERR_PARSE);
    }

    String sendString = json_res.toString();

    // dump the received string
    if (log.isDebugEnabled()) {
        log.debug("send: " + sendString);
        log.debug("send: " + prettyPrintJson(sendString));
    }

    // Write the response
    byte[] bout = sendString.getBytes("UTF-8");

    // handle gzipping of the response if it is turned on
    if (JSONRPCServlet.GZIP_THRESHOLD != -1) {
        // if the request header says that the browser can take gzip compressed output, then gzip the output
        // but only if the response is large enough to warrant it and if the resultant compressed output is
        // actually smaller.
        if (acceptsGzip(request)) {
            if (bout.length > JSONRPCServlet.GZIP_THRESHOLD) {
                byte[] gzippedOut = gzip(bout);
                log.debug(
                        "gzipping! original size =  " + bout.length + "  gzipped size = " + gzippedOut.length);

                // if gzip didn't actually help, abort
                if (bout.length <= gzippedOut.length) {
                    log.warn("gzipping resulted in a larger output size!  "
                            + "aborting (sending non-gzipped response)... "
                            + "you may want to increase the gzip threshold if this happens a lot!"
                            + " original size = " + bout.length + "  gzipped size = " + gzippedOut.length);
                } else {
                    // go with the gzipped output
                    bout = gzippedOut;
                    response.addHeader("Content-Encoding", "gzip");
                }
            } else {
                log.debug("not gzipping because size is " + bout.length + " (less than the GZIP_THRESHOLD of "
                        + JSONRPCServlet.GZIP_THRESHOLD + " bytes)");
            }
        } else {
            // this should be rare with modern user agents
            log.debug("not gzipping because user agent doesn't accept gzip encoding...");
        }
    }

    // Encode using UTF-8, although We are actually ASCII clean as
    // all unicode data is JSON escaped using backslash u. This is
    // less data efficient for foreign character sets but it is
    // needed to support naughty browsers such as Konqueror and Safari
    // which do not honour the charset set in the response
    response.setContentType("application/json;charset=utf-8");
    OutputStream out = response.getOutputStream();

    response.setIntHeader("Content-Length", bout.length);

    out.write(bout);
    out.flush();
    out.close();
}

From source file:org.jabsorb.ng.JSONRPCServlet.java

/**
 * Called when a JSON-RPC requests comes in. Looks in the session for a
 * JSONRPCBridge and if not found there, uses the global bridge; then passes
 * off the JSON-PRC call to be handled by the JSONRPCBridge found.
 * /* w w w .  j  av a2s  . c  o m*/
 * @param request
 *            servlet request from browser.
 * @param response
 *            servlet response to browser.
 * 
 * @throws IOException
 *             if an IOException occurs during processing.
 */
@Override
public void service(final HttpServletRequest request, final HttpServletResponse response) throws IOException {

    // Use protected method in case someone wants to override it
    JSONRPCBridge json_bridge = findBridge(request);

    // Decode using the charset in the request if it exists otherwise
    // use UTF-8 as this is what all browser implementations use.
    // The JSON-RPC-Java JavaScript client is ASCII clean so it
    // although here we can correctly handle data from other clients
    // that do not escape non ASCII data
    String charset = request.getCharacterEncoding();
    if (charset == null) {
        charset = "UTF-8";
    }

    BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), charset));

    String receiveString = (String) request.getAttribute("_jabsorb_beenHere");

    // if JSON data is found in a special request attribute, it means
    // that a continuation was used and this request is being retried
    // as a consequence of a Jetty continuation
    // see http://blogs.webtide.com/gregw/2007/11/18/1195421880000.html
    if (receiveString == null) {
        // Read the request
        CharArrayWriter data = new CharArrayWriter();
        char buf[] = new char[buf_size];
        int ret;
        while ((ret = in.read(buf, 0, buf_size)) != -1) {
            data.write(buf, 0, ret);
        }
        receiveString = data.toString();

        // save the json-rpc data in a special request attribute, in case a
        // jetty
        // continuation exception (org.mortbay.jetty.RetryRequest) is thrown
        // and this
        // request is retried by the container
        request.setAttribute("_jabsorb_beenHere", receiveString);
    } else {
        log.debug("service", "jetty continuation resumed...");
    }

    if (log.isDebugEnabled()) {
        log.debug("service", "receive: " + receiveString);
        log.debug("service", "receive: " + prettyPrintJson(receiveString));
    }

    // Process the request
    JSONObject json_req;
    JSONRPCResult json_res;
    try {
        json_req = new JSONObject(receiveString);
        json_res = json_bridge.call(new Object[] { request, response }, json_req);
    } catch (JSONException e) {
        log.error("service", "can't parse call" + receiveString, e);
        json_res = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, JSONRPCResult.MSG_ERR_PARSE);
    }

    String sendString = json_res.toString();

    // dump the received string
    if (log.isDebugEnabled()) {
        log.debug("service", "send: " + sendString);
        log.debug("service", "send: " + prettyPrintJson(sendString));
    }

    // Write the response
    byte[] bout = sendString.getBytes("UTF-8");

    // handle gzipping of the response if it is turned on
    if (JSONRPCServlet.GZIP_THRESHOLD != -1) {
        // if the request header says that the browser can take gzip
        // compressed output, then gzip the output
        // but only if the response is large enough to warrant it and if the
        // resultant compressed output is
        // actually smaller.
        if (acceptsGzip(request)) {
            if (bout.length > JSONRPCServlet.GZIP_THRESHOLD) {
                byte[] gzippedOut = gzip(bout);
                log.debug("service",
                        "gzipping! original size =  " + bout.length + "  gzipped size = " + gzippedOut.length);

                // if gzip didn't actually help, abort
                if (bout.length <= gzippedOut.length) {
                    log.warning("service", "gzipping resulted in a larger output size!  "
                            + "aborting (sending non-gzipped response)... "
                            + "you may want to increase the gzip threshold if this happens a lot!"
                            + " original size = " + bout.length + "  gzipped size = " + gzippedOut.length);
                } else {
                    // go with the gzipped output
                    bout = gzippedOut;
                    response.addHeader("Content-Encoding", "gzip");
                }
            } else {
                log.debug("service", "not gzipping because size is " + bout.length
                        + " (less than the GZIP_THRESHOLD of " + JSONRPCServlet.GZIP_THRESHOLD + " bytes)");
            }
        } else {
            // this should be rare with modern user agents
            log.debug("service", "not gzipping because user agent doesn't accept gzip encoding...");
        }
    }

    // Encode using UTF-8, although We are actually ASCII clean as
    // all unicode data is JSON escaped using backslash u. This is
    // less data efficient for foreign character sets but it is
    // needed to support naughty browsers such as Konqueror and Safari
    // which do not honour the charset set in the response
    response.setContentType("application/json;charset=utf-8");
    OutputStream out = response.getOutputStream();

    response.setIntHeader("Content-Length", bout.length);

    out.write(bout);
    out.flush();
    out.close();
}

From source file:org.ireland.jnetty.webapp.ErrorPageManager.java

public void sendServletErrorImpl(Throwable e, ServletRequest req, ServletResponse res) throws IOException {
    HttpServletResponse response = (HttpServletResponse) res;
    HttpServletRequest request = (HttpServletRequest) req;
    Throwable rootExn = e;//from  w ww.  j  a v  a2 s  .co m
    Throwable errorPageExn = null;
    LineMap lineMap = null;

    try {
        response.reset();
    } catch (IllegalStateException e1) {
    }

    if (req.isAsyncStarted()) {
        AsyncContext async = req.getAsyncContext();

        if (async != null)
            async.complete();
    }

    if (response instanceof HttpServletResponseImpl) {
        HttpServletResponseImpl resFacade = (HttpServletResponseImpl) response;
        resFacade.killCache();
        resFacade.setNoCache(true);
    }

    if (rootExn instanceof ClientDisconnectException)
        throw (ClientDisconnectException) rootExn;

    String location = null;

    String title = "500 Servlet Exception";
    boolean isBadRequest = false;
    boolean doStackTrace = true;
    boolean isCompileException = false;
    boolean isServletException = false;
    Throwable compileException = null;
    String lineMessage = null;

    boolean lookupErrorPage = true;

    while (true) {
        if (rootExn instanceof LineMapException)
            lineMap = ((LineMapException) rootExn).getLineMap();

        if (lookupErrorPage) {
            errorPageExn = rootExn;
        }

        if (rootExn instanceof DisplayableException) {
            doStackTrace = false;
            isCompileException = true;
            if (compileException == null)
                compileException = rootExn;
        } else if (rootExn instanceof CompileException) {
            doStackTrace = false;
            isCompileException = true;

            if (compileException == null) // ! isLineCompileException)
                compileException = rootExn;
        } else if (rootExn instanceof LineException) {
            if (lineMessage == null)
                lineMessage = rootExn.getMessage();
        }

        if (rootExn instanceof BadRequestException) {
            isBadRequest = true;
        }

        if (rootExn instanceof OutOfMemoryError) {
            String msg = "TcpSocketLink OutOfMemory";

            ShutdownSystem.shutdownOutOfMemory(msg);
        }

        if (location != null || !lookupErrorPage) {
        } else if (rootExn instanceof LineMapException && rootExn instanceof ServletException
                && !(rootExn instanceof LineCompileException) && rootExn.getCause() != null) {
            // hack to deal with JSP wrapping
        } else if (!isServletException) {
            // SRV.9.9.2 Servlet 2.4
            // location = getErrorPage(rootExn, ServletException.class);
            location = getErrorPage(rootExn);
            isServletException = true;
        } else {
            location = getErrorPage(rootExn);
            lookupErrorPage = false;
        }

        if (location != null)
            lookupErrorPage = false;

        if (isBadRequest)
            break;

        Throwable cause = null;
        if (rootExn instanceof ServletException && !(rootExn instanceof LineCompileException))
            cause = ((ServletException) rootExn).getRootCause();
        else {
            lookupErrorPage = false;
            cause = rootExn.getCause();
        }

        if (cause != null)
            rootExn = cause;
        else {
            break;
        }
    }

    if (location == null && lookupErrorPage) {
        location = getErrorPage(rootExn);
    }

    if (location == null)
        location = getErrorPage(500);

    if (isBadRequest) {
        // server/05a0, server/0532

        if (rootExn instanceof CompileException)
            title = rootExn.getMessage();
        else
            title = String.valueOf(rootExn);

        doStackTrace = false;
        isBadRequest = true;

        if (request instanceof CauchoRequest)
            ((CauchoRequest) request).killKeepalive("bad request: " + rootExn);

        response.resetBuffer();

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

        /*
         * if (location == null) log.warn(e.toString());
         */
    } else if (rootExn instanceof UnavailableException) {
        UnavailableException unAvail = (UnavailableException) rootExn;

        if (unAvail.isPermanent()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            title = "404 Not Found";

            if (location == null)
                location = getErrorPage(HttpServletResponse.SC_NOT_FOUND);
        } else {
            response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            title = "503 Unavailable";

            if (unAvail.getUnavailableSeconds() > 0)
                response.setIntHeader("Retry-After", unAvail.getUnavailableSeconds());

            if (location == null)
                location = getErrorPage(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } else {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    if (location == null)
        location = _defaultLocation;

    if (log.isTraceEnabled())
        log.trace(e.toString(), e);
    else if (isCompileException) {
        if (isBadRequest)
            log.trace(BadRequestException.class.getSimpleName() + ": " + compileException.getMessage());
        else
            log.trace(compileException.getMessage());
    } else if (!doStackTrace)
        log.trace(rootExn.toString());
    else
        log.trace(e.toString(), e);

    if (location != null) {
        if (errorPageExn == null)
            errorPageExn = rootExn;

        request.setAttribute(JSP_EXCEPTION, errorPageExn);
        request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, errorPageExn);
        request.setAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE, errorPageExn.getClass());
        if (request instanceof HttpServletRequest)
            request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI,
                    ((HttpServletRequest) request).getRequestURI());

        String servletName = getServletName(request);

        if (servletName != null)
            request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME, servletName);

        request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, new Integer(500));
        request.setAttribute(RequestDispatcher.ERROR_MESSAGE, errorPageExn.getMessage());

        try {
            RequestDispatcher disp = null;
            // can't use filters because of error pages due to filters
            // or security.

            WebApp webApp = getWebApp();

            if (webApp != null)
                disp = webApp.getRequestDispatcher(location);
            else if (_host != null)
                disp = _host.getWebAppContainer().getRequestDispatcher(location);

            if (disp != null) {
                ((RequestDispatcherImpl) disp).error(request, response);
                return;
            }
        } catch (Throwable e1) {
            log.info(e1.toString(), e1);
            rootExn = e1;
        }
    }

    response.setContentType("text/html");

    String encoding = CharacterEncoding.getLocalEncoding();

    if (encoding != null)
        response.setCharacterEncoding(encoding);
    else {
        Locale locale = Locale.getDefault();
        if (!"ISO-8859-1".equals(Encoding.getMimeName(locale)))
            response.setLocale(Locale.getDefault());
        else
            response.setCharacterEncoding("utf-8");
    }

    PrintWriter out;

    try {
        out = response.getWriter();
    } catch (IllegalStateException e1) {
        log.trace(e1.toString(), e1);

        out = new PrintWriter(new OutputStreamWriter(response.getOutputStream()));
    }

    if (isDevelopmentModeErrorPage()) {
        out.println("<html>");
        if (!response.isCommitted())
            out.println("<head><title>" + escapeHtml(title) + "</title></head>");
        out.println("<body>");
        out.println("<h1>" + escapeHtml(title) + "</h1>");

        out.println("<code><pre>");

        if (debug && !CurrentTime.isTest())
            doStackTrace = true;

        if (doStackTrace) {
            out.println("<script language='javascript' type='text/javascript'>");
            out.println("function show() { document.getElementById('trace').style.display = ''; }");
            out.println("</script>");
            out.print("<a style=\"text-decoration\" href=\"javascript:show();\">[show]</a> ");
        }

        if (compileException instanceof DisplayableException) {
            // ioc/0000
            // XXX: dispExn.print doesn't normalize user.name
            // dispExn.print(out);
            out.println(escapeHtml(compileException.getMessage()));
        } else if (compileException != null)
            out.println(escapeHtml(compileException.getMessage()));
        else
            out.println(escapeHtml(rootExn.toString()));

        if (doStackTrace) {
            out.println("<span id=\"trace\" style=\"display:none\">");
            printStackTrace(out, lineMessage, e, rootExn, lineMap);
            out.println("</span>");
        }

        /*
         * if (doStackTrace || debug) { printStackTrace(out, lineMessage, e, rootExn, lineMap); }
         */

        out.println("</pre></code>");

        printVersion(out);

        out.println("</body></html>");
    } else { // non-development mode
        out.println("<html>");
        out.println("<title>Server Error</title>");
        out.println("<body>");
        out.println("<h1>Server Error</h1>");
        out.println("<p>The server is temporarily unavailable due to an");
        out.println("internal error.  Please notify the system administrator");
        out.println("of this problem.</p>");

        out.println("<pre><code>");
        out.println("Date: " + QDate.formatISO8601(CurrentTime.getCurrentTime()));

        out.println("</code></pre>");

        printVersion(out);

        out.println("</body></html>");
    }

    String userAgent = request.getHeader("User-Agent");

    if (userAgent != null && userAgent.indexOf("MSIE") >= 0) {
        out.print(MSIE_PADDING);
    }

    out.close();
}

From source file:com.twinsoft.convertigo.engine.servlets.ReverseProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link HttpServletResponse}
 * /*from  w  ww .j  a  v a  2s . c o  m*/
 * @param httpMethodProxyRequest
 *            An object representing the proxy request to be made
 * @param httpServletResponse
 *            An object by which we can send the proxied response back to
 *            the client
 * @throws IOException
 *             Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException
 *             Can be thrown to indicate that another error has occurred
 * @throws EngineException
 */
private void doRequest(HttpMethodType httpMethodType, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    try {
        Engine.logEngine.debug("(ReverseProxyServlet) Starting request handling");

        if (Boolean.parseBoolean(EnginePropertiesManager.getProperty(PropertyName.SSL_DEBUG))) {
            System.setProperty("javax.net.debug", "all");
            Engine.logEngine.trace("(ReverseProxyServlet) Enabling SSL debug mode");
        } else {
            System.setProperty("javax.net.debug", "");
            Engine.logEngine.debug("(ReverseProxyServlet) Disabling SSL debug mode");
        }

        String baseUrl;
        String projectName;
        String connectorName;
        String contextName;
        String extraPath;

        {
            String requestURI = httpServletRequest.getRequestURI();
            Engine.logEngine.trace("(ReverseProxyServlet) Requested URI : " + requestURI);
            Matcher m = reg_fields.matcher(requestURI);
            if (m.matches() && m.groupCount() >= 5) {
                baseUrl = m.group(1);
                projectName = m.group(2);
                connectorName = m.group(3);
                contextName = m.group(4);
                extraPath = m.group(5);
            } else {
                throw new MalformedURLException(
                        "The request doesn't contains needed fields : projectName, connectorName and contextName");
            }
        }

        String sessionID = httpServletRequest.getSession().getId();

        Engine.logEngine.debug("(ReverseProxyServlet) baseUrl : " + baseUrl + " ; projectName : " + projectName
                + " ; connectorName : " + connectorName + " ; contextName : " + contextName + " ; extraPath : "
                + extraPath + " ; sessionID : " + sessionID);

        Context context = Engine.theApp.contextManager.get(null, contextName, sessionID, null, projectName,
                connectorName, null);

        Project project = Engine.theApp.databaseObjectsManager.getProjectByName(projectName);
        context.projectName = projectName;
        context.project = project;

        ProxyHttpConnector proxyHttpConnector = (ProxyHttpConnector) project.getConnectorByName(connectorName);
        context.connector = proxyHttpConnector;
        context.connectorName = proxyHttpConnector.getName();

        HostConfiguration hostConfiguration = proxyHttpConnector.hostConfiguration;

        // Proxy configuration
        String proxyServer = Engine.theApp.proxyManager.getProxyServer();
        String proxyUser = Engine.theApp.proxyManager.getProxyUser();
        String proxyPassword = Engine.theApp.proxyManager.getProxyPassword();
        int proxyPort = Engine.theApp.proxyManager.getProxyPort();

        if (!proxyServer.equals("")) {
            hostConfiguration.setProxy(proxyServer, proxyPort);
            Engine.logEngine.debug("(ReverseProxyServlet) Using proxy: " + proxyServer + ":" + proxyPort);
        } else {
            // Remove old proxy configuration
            hostConfiguration.setProxyHost(null);
        }

        String targetHost = proxyHttpConnector.getServer();
        Engine.logEngine.debug("(ReverseProxyServlet) Target host: " + targetHost);
        int targetPort = proxyHttpConnector.getPort();
        Engine.logEngine.debug("(ReverseProxyServlet) Target port: " + targetPort);

        // Configuration SSL
        Engine.logEngine.debug("(ReverseProxyServlet) Https: " + proxyHttpConnector.isHttps());
        CertificateManager certificateManager = proxyHttpConnector.certificateManager;
        boolean trustAllServerCertificates = proxyHttpConnector.isTrustAllServerCertificates();

        if (proxyHttpConnector.isHttps()) {
            Engine.logEngine.debug("(ReverseProxyServlet) Setting up SSL properties");
            certificateManager.collectStoreInformation(context);

            Engine.logEngine.debug(
                    "(ReverseProxyServlet) CertificateManager has changed: " + certificateManager.hasChanged);
            if (certificateManager.hasChanged || (!targetHost.equalsIgnoreCase(hostConfiguration.getHost()))
                    || (hostConfiguration.getPort() != targetPort)) {
                Engine.logEngine
                        .debug("(ReverseProxyServlet) Using MySSLSocketFactory for creating the SSL socket");
                Protocol myhttps = new Protocol("https",
                        MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore,
                                certificateManager.keyStorePassword, certificateManager.trustStore,
                                certificateManager.trustStorePassword, trustAllServerCertificates),
                        targetPort);

                hostConfiguration.setHost(targetHost, targetPort, myhttps);
            }

            Engine.logEngine.debug("(ReverseProxyServlet) Updated host configuration for SSL purposes");
        } else {
            hostConfiguration.setHost(targetHost, targetPort);
        }

        HttpMethod httpMethodProxyRequest;

        String targetPath = proxyHttpConnector.getBaseDir() + extraPath;

        // Handle the query string
        if (httpServletRequest.getQueryString() != null) {
            targetPath += "?" + httpServletRequest.getQueryString();
        }
        Engine.logEngine.debug("(ReverseProxyServlet) Target path: " + targetPath);

        Engine.logEngine.debug("(ReverseProxyServlet) Requested method: " + httpMethodType);

        if (httpMethodType == HttpMethodType.GET) {
            // Create a GET request
            httpMethodProxyRequest = new GetMethod();
        } else if (httpMethodType == HttpMethodType.POST) {
            // Create a standard POST request
            httpMethodProxyRequest = new PostMethod();
            ((PostMethod) httpMethodProxyRequest)
                    .setRequestEntity(new InputStreamRequestEntity(httpServletRequest.getInputStream()));
        } else {
            throw new IllegalArgumentException("Unknown HTTP method: " + httpMethodType);
        }

        String charset = httpMethodProxyRequest.getParams().getUriCharset();
        URI targetURI;
        try {
            targetURI = new URI(targetPath, true, charset);
        } catch (URIException e) {
            // Bugfix #1484
            String newTargetPath = "";
            for (String part : targetPath.split("&")) {
                if (!newTargetPath.equals("")) {
                    newTargetPath += "&";
                }
                String[] pair = part.split("=");
                try {
                    newTargetPath += URLDecoder.decode(pair[0], "UTF-8") + "="
                            + (pair.length > 1 ? URLEncoder.encode(URLDecoder.decode(pair[1], "UTF-8"), "UTF-8")
                                    : "");
                } catch (UnsupportedEncodingException ee) {
                    newTargetPath = targetPath;
                }
            }

            targetURI = new URI(newTargetPath, true, charset);
        }
        httpMethodProxyRequest.setURI(targetURI);

        // Tells the method to automatically handle authentication.
        httpMethodProxyRequest.setDoAuthentication(true);

        HttpState httpState = getHttpState(proxyHttpConnector, context);

        String basicUser = proxyHttpConnector.getAuthUser();
        String basicPassword = proxyHttpConnector.getAuthPassword();
        String givenBasicUser = proxyHttpConnector.getGivenAuthUser();
        String givenBasicPassword = proxyHttpConnector.getGivenAuthPassword();

        // Basic authentication configuration
        String realm = null;
        if (!basicUser.equals("") || (basicUser.equals("") && (givenBasicUser != null))) {
            String userName = ((givenBasicUser == null) ? basicUser : givenBasicUser);
            String userPassword = ((givenBasicPassword == null) ? basicPassword : givenBasicPassword);
            httpState.setCredentials(new AuthScope(targetHost, targetPort, realm),
                    new UsernamePasswordCredentials(userName, userPassword));
            Engine.logEngine.debug("(ReverseProxyServlet) Credentials: " + userName + ":******");
        }

        // Setting basic authentication for proxy
        if (!proxyServer.equals("") && !proxyUser.equals("")) {
            httpState.setProxyCredentials(new AuthScope(proxyServer, proxyPort),
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
            Engine.logEngine.debug("(ReverseProxyServlet) Proxy credentials: " + proxyUser + ":******");
        }

        // Forward the request headers
        setProxyRequestHeaders(httpServletRequest, httpMethodProxyRequest, proxyHttpConnector);

        // Use the CEMS HttpClient
        HttpClient httpClient = Engine.theApp.httpClient;
        httpMethodProxyRequest.setFollowRedirects(false);

        // Execute the request
        int intProxyResponseCode = httpClient.executeMethod(hostConfiguration, httpMethodProxyRequest,
                httpState);

        // Check if the proxy response is a redirect
        // The following code is adapted from
        // org.tigris.noodle.filters.CheckForRedirect
        // Hooray for open source software
        if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
                && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
            String stringStatusCode = Integer.toString(intProxyResponseCode);
            String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
            if (stringLocation == null) {
                throw new ServletException("Received status code: " + stringStatusCode + " but no "
                        + STRING_LOCATION_HEADER + " header was found in the response");
            }
            // Modify the redirect to go to this proxy servlet rather that
            // the
            // proxied host
            String redirect = handleRedirect(stringLocation, baseUrl, proxyHttpConnector);
            httpServletResponse.sendRedirect(redirect);
            Engine.logEngine.debug("(ReverseProxyServlet) Send redirect (" + redirect + ")");
            return;
        } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
            // 304 needs special handling. See:
            // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
            // We get a 304 whenever passed an 'If-Modified-Since'
            // header and the data on disk has not changed; server
            // responds w/ a 304 saying I'm not going to send the
            // body because the file has not changed.
            httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
            httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            Engine.logEngine.debug("(ReverseProxyServlet) NOT MODIFIED (304)");
            return;
        }

        // Pass the response code back to the client
        httpServletResponse.setStatus(intProxyResponseCode);

        // Pass response headers back to the client
        Engine.logEngine.debug("(ReverseProxyServlet) Response headers back to the client:");
        Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
        for (Header header : headerArrayResponse) {
            String headerName = header.getName();
            String headerValue = header.getValue();
            if (!headerName.equalsIgnoreCase("Transfer-Encoding")
                    && !headerName.equalsIgnoreCase("Set-Cookie")) {
                httpServletResponse.setHeader(headerName, headerValue);
                Engine.logEngine.debug("   " + headerName + "=" + headerValue);
            }
        }

        String contentType = null;
        Header[] contentTypeHeaders = httpMethodProxyRequest.getResponseHeaders("Content-Type");
        for (Header contentTypeHeader : contentTypeHeaders) {
            contentType = contentTypeHeader.getValue();
            break;
        }

        String pageCharset = "UTF-8";
        if (contentType != null) {
            int iCharset = contentType.indexOf("charset=");
            if (iCharset != -1) {
                pageCharset = contentType.substring(iCharset + "charset=".length()).trim();
            }
            Engine.logEngine.debug("(ReverseProxyServlet) Using charset: " + pageCharset);
        }

        InputStream siteIn = httpMethodProxyRequest.getResponseBodyAsStream();

        // Handle gzipped content
        Header[] contentEncodingHeaders = httpMethodProxyRequest.getResponseHeaders("Content-Encoding");
        boolean bGZip = false, bDeflate = false;
        for (Header contentEncodingHeader : contentEncodingHeaders) {
            HeaderElement[] els = contentEncodingHeader.getElements();
            for (int j = 0; j < els.length; j++) {
                if ("gzip".equals(els[j].getName())) {
                    Engine.logBeans.debug("(ReverseProxyServlet) Decode GZip stream");
                    siteIn = new GZIPInputStream(siteIn);
                    bGZip = true;
                } else if ("deflate".equals(els[j].getName())) {
                    Engine.logBeans.debug("(ReverseProxyServlet) Decode Deflate stream");
                    siteIn = new InflaterInputStream(siteIn, new Inflater(true));
                    bDeflate = true;
                }
            }
        }

        byte[] bytesDataResult;

        ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);

        // String resourceUrl = projectName + targetPath;

        String t = context.statistics.start(EngineStatistics.APPLY_USER_REQUEST);

        try {
            // Read either from the cache, either from the remote server
            // InputStream is = proxyCacheManager.getResource(resourceUrl);
            // if (is != null) {
            // Engine.logEngine.debug("(ReverseProxyServlet) Getting data from cache");
            // siteIn = is;
            // }
            int c = siteIn.read();
            while (c > -1) {
                baos.write(c);
                c = siteIn.read();
            }
            // if (is != null) is.close();
        } finally {
            context.statistics.stop(t, true);
        }

        bytesDataResult = baos.toByteArray();
        baos.close();
        Engine.logEngine.debug("(ReverseProxyServlet) Data retrieved!");

        // if (isDynamicContent(httpServletRequest.getPathInfo(),
        // proxyHttpConnector.getDynamicContentFiles())) {
        Engine.logEngine.debug("(ReverseProxyServlet) Dynamic content");

        bytesDataResult = handleStringReplacements(baseUrl, contentType, pageCharset, proxyHttpConnector,
                bytesDataResult);

        String billingClassName = context.getConnector().getBillingClassName();
        if (billingClassName != null) {
            try {
                Engine.logContext.debug("Billing class name required: " + billingClassName);
                AbstractBiller biller = (AbstractBiller) Class.forName(billingClassName).newInstance();
                Engine.logContext.debug("Executing the biller");
                biller.insertBilling(context);
            } catch (Throwable e) {
                Engine.logContext.warn("Unable to execute the biller (the billing is thus ignored): ["
                        + e.getClass().getName() + "] " + e.getMessage());
            }
        }
        // }
        // else {
        // Engine.logEngine.debug("(ReverseProxyServlet) Static content: " +
        // contentType);
        //            
        // // Determine if the resource has already been cached or not
        // CacheEntry cacheEntry =
        // proxyCacheManager.getCacheEntry(resourceUrl);
        // if (cacheEntry instanceof FileCacheEntry) {
        // FileCacheEntry fileCacheEntry = (FileCacheEntry) cacheEntry;
        // File file = new File(fileCacheEntry.fileName);
        // if (!file.exists())
        // proxyCacheManager.removeCacheEntry(cacheEntry);
        // cacheEntry = null;
        // }
        // if (cacheEntry == null) {
        // bytesDataResult = handleStringReplacements(contentType,
        // proxyHttpConnector, bytesDataResult);
        //
        // if (intProxyResponseCode == 200) {
        // Engine.logEngine.debug("(ReverseProxyServlet) Resource stored: "
        // + resourceUrl);
        // cacheEntry = proxyCacheManager.storeResponse(resourceUrl,
        // bytesDataResult);
        // cacheEntry.contentLength = bytesDataResult.length;
        // cacheEntry.contentType = contentType;
        // Engine.logEngine.debug("(ReverseProxyServlet) Cache entry: " +
        // cacheEntry);
        // }
        // }
        // }

        // Send the content to the client
        if (Engine.logEngine.isDebugEnabled() && MimeType.Html.is(contentType)) {
            Engine.logEngine.debug("Data proxied:\n" + new String(bytesDataResult, pageCharset));
        }

        if (bGZip || bDeflate) {
            baos = new ByteArrayOutputStream();
            OutputStream compressedOutputStream = bGZip ? new GZIPOutputStream(baos)
                    : new DeflaterOutputStream(baos,
                            new Deflater(Deflater.DEFAULT_COMPRESSION | Deflater.DEFAULT_STRATEGY, true));
            compressedOutputStream.write(bytesDataResult);
            compressedOutputStream.close();
            bytesDataResult = baos.toByteArray();
            baos.close();
        }

        httpServletResponse.setContentLength(bytesDataResult.length);
        OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
        outputStreamClientResponse.write(bytesDataResult);

        Engine.logEngine.debug("(ReverseProxyServlet) End of document retransmission");
    } catch (Exception e) {
        Engine.logEngine.error("Error while trying to proxy page", e);
        throw new ServletException("Error while trying to proxy page", e);
    }
}