Example usage for javax.servlet.http HttpServletRequest getProtocol

List of usage examples for javax.servlet.http HttpServletRequest getProtocol

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getProtocol.

Prototype

public String getProtocol();

Source Link

Document

Returns the name and version of the protocol the request uses in the form <i>protocol/majorVersion.minorVersion</i>, for example, HTTP/1.1.

Usage

From source file:org.artifactory.webapp.servlet.RequestFilter.java

@Override
public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain)
        throws IOException, ServletException {
    long start = System.currentTimeMillis();
    //Wrap the response
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;
    CapturingHttpServletResponseWrapper responseWrapper = new CapturingHttpServletResponseWrapper(response);
    try {//from   www. ja v a2 s  . com
        RequestWrapper requestWrapper = new RequestWrapper(request);
        RequestThreadLocal.set(requestWrapper);
        chain.doFilter(req, responseWrapper);
        String servletPath = RequestUtils.getServletPathFromRequest(request);
        String method = request.getMethod();
        long contentLength = 0;
        if ("get".equalsIgnoreCase(method)) {
            contentLength = responseWrapper.getContentLength();
        }
        if (("put".equalsIgnoreCase(method)) || ("post".equalsIgnoreCase(method))) {
            contentLength = HttpUtils.getContentLength(request);
        }
        String username = "non_authenticated_user";
        // First try to get the authentication from the session.
        Authentication authentication = RequestUtils.getAuthentication((HttpServletRequest) req);
        if (authentication != null) {
            username = authentication.getPrincipal().toString();
        } else if (RequestUtils.isAuthHeaderPresent(request)
                || RequestUtils.getApiKeyTokenKeyValue(request) != null) {
            // since we do not have an authentication here, and a session was not opened since this
            // is a non UI request, we are forced to extract it out of the authentication header.
            username = RequestUtils.extractUsernameFromRequest(request);
            // in case of token request fetch user name
            username = findPropAuthUserNameByToken(request, username);
        }
        String remoteAddress = new HttpAuthenticationDetails(request).getRemoteAddress();
        RequestLogger.request(remoteAddress, username, method, servletPath, request.getProtocol(),
                responseWrapper.getStatus(), contentLength, System.currentTimeMillis() - start);
    } finally {
        RequestThreadLocal.destroy();
    }
}

From source file:helma.servlet.AbstractServletClient.java

void sendRedirect(HttpServletRequest req, HttpServletResponse res, String url, int status) {
    String location = url;/*w  ww .jav a  2s.c o m*/

    if (url.indexOf("://") == -1) {
        // need to transform a relative URL into an absolute one
        String scheme = req.getScheme();
        StringBuffer loc = new StringBuffer(scheme);

        loc.append("://");
        loc.append(req.getServerName());

        int p = req.getServerPort();

        // check if we need to include server port
        if ((p > 0) && (("http".equals(scheme) && (p != 80)) || ("https".equals(scheme) && (p != 443)))) {
            loc.append(":");
            loc.append(p);
        }

        if (!url.startsWith("/")) {
            String requri = req.getRequestURI();
            int lastSlash = requri.lastIndexOf("/");

            if (lastSlash == (requri.length() - 1)) {
                loc.append(requri);
            } else if (lastSlash > -1) {
                loc.append(requri.substring(0, lastSlash + 1));
            } else {
                loc.append("/");
            }
        }

        loc.append(url);
        location = loc.toString();
    }

    // if status code was explicitly set use that, or use 303 for HTTP 1.1,
    // 302 for earlier protocol versions
    if (status >= 301 && status <= 303) {
        res.setStatus(status);
    } else if (isOneDotOne(req.getProtocol())) {
        res.setStatus(HttpServletResponse.SC_SEE_OTHER);
    } else {
        res.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    }

    res.setContentType("text/html");
    res.setHeader("Location", location);
}

From source file:org.metis.pull.WdsResourceBean.java

/**
 * This method gets called by the WdsRdbMapper bean to handle a HTTP
 * request. This method must be multi-thread capable. Note that since we're
 * not using Views, this method must return null.
 * /*from www .j  a  v a 2  s. c  o m*/
 * @param request
 *            the http request that is being serviced
 * @param response
 *            the response that will be sent back to the service consumer
 * @return must return null since we're not using a view
 * @throws Exception
 */
@SuppressWarnings("unchecked")
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    LOG.debug(getBeanName() + ": handleRequestInternal - **** new request ****");

    // dump the request if trace is on
    if (LOG.isTraceEnabled()) {
        LOG.trace(getBeanName() + ":handleRequestInternal - method = " + request.getMethod());
        LOG.trace(getBeanName() + ":handleRequestInternal - uri  = " + request.getRequestURI());
        LOG.trace(getBeanName() + ":handleRequestInternal - protocol  = " + request.getProtocol());
        LOG.trace(getBeanName() + ":handleRequestInternal - secure  = " + request.isSecure());

        // dump all the http headers and their values
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                LOG.trace(getBeanName() + ":handleRequestInternal - " + headerName + " = "
                        + request.getHeader(headerName));
            }
        }

        if (request.getQueryString() != null) {
            LOG.trace(getBeanName() + ":handleRequestInternal - queryString  = " + request.getQueryString());
        }
    }

    long currentTime = System.currentTimeMillis();

    // give the response a Date header with the current time
    response.setDateHeader(DATE_HDR, currentTime);

    // assign the Server header this container's info
    response.setHeader(SERVER_HDR, getServerInfo());

    // determine the HTTP protocol version being used by the client
    // default version will be 0
    int protocolVersion = 0;
    try {
        protocolVersion = Integer
                .parseInt(request.getProtocol().split(FORWARD_SLASH_STR)[1].split(ESC_DOT_STR)[1]);
    } catch (Exception exc) {
        LOG.warn(getBeanName() + ": handleRequestInternal - unable to get http protocol "
                + "version, stack trace follows: ");
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
    }

    LOG.trace(getBeanName() + ":handleRequestInternal - using this " + "protocol version: " + protocolVersion);

    /*
     * Ok, the request first needs to run the security gauntlet
     * 
     * We do not want to send any error messages back to the client that
     * would give it a hint that we're invoking SQL statements. This is a
     * countermeasure for SQL injection probes.
     */

    // see if this RDB is restricting user agents and if so, validate user
    // agent
    if ((getAllowedAgents() != null && !getAllowedAgents().isEmpty())
            || (getNotAllowedAgents() != null && !getNotAllowedAgents().isEmpty())) {

        String userAgent = request.getHeader(USER_AGENT_HDR);

        if (userAgent != null && userAgent.length() > 0) {
            LOG.debug(
                    getBeanName() + ": handleRequestInternal - validating this " + "user agent: " + userAgent);

            // Convert to lower case as allowed agents have been
            // converted to lower case as well
            userAgent = userAgent.toLowerCase();

            boolean allow = false;
            if (getAllowedAgents() != null && !getAllowedAgents().isEmpty()) {
                for (String agent : getAllowedAgents()) {
                    LOG.trace(getBeanName() + ": handleRequestInternal - comparing to this "
                            + "allowed agent : " + agent);
                    if (userAgent.indexOf(agent) >= 0) {
                        LOG.trace(getBeanName() + ": handleRequestInternal - this allowed agent "
                                + "was found: " + agent);
                        allow = true;
                        break;
                    }
                }
            } else {
                allow = true;
                for (String agent : getNotAllowedAgents()) {
                    LOG.trace(getBeanName() + ": handleRequestInternal - comparing to this "
                            + "non-allowed agent : " + agent);
                    if (userAgent.indexOf(agent) >= 0) {
                        LOG.trace(getBeanName() + ": handleRequestInternal - this non-allowed "
                                + "agent was found: " + agent);
                        allow = false;
                        break;
                    }
                }
            }
            if (!allow) {
                response.sendError(SC_UNAUTHORIZED, "ERROR, user agent " + "is not authorized");
                LOG.error(getBeanName() + ": handleRequestInternal - ERROR, user agent is " + "not authorized");
                return null;
            }
        } else {
            response.sendError(SC_UNAUTHORIZED,
                    "ERROR, user agent info " + "was not received and is required!");
            LOG.error(getBeanName() + ": handleRequestInternal - ERROR, user agent header "
                    + "is required but was not provided by the client");
            return null;
        }
    }

    // we do not support chunked transfer encoding, which is a http
    // 1.1 feature.
    if (request.getHeader(TRANSFER_ENCODING_HDR) != null
            && request.getHeader(TRANSFER_ENCODING_HDR).equalsIgnoreCase(CHUNKED)) {
        response.sendError(SC_BAD_REQUEST, "Chunked tranfer encoding is not " + "supported");
        return null;
    }

    /*
     * isSecure returns a boolean indicating whether this request was made
     * using a secure channel, such as HTTPS. so, if the channel must be
     * secure, but it is not, then throw an exception and return an error.
     */
    if (isSecure() && !request.isSecure()) {
        response.sendError(SC_UNAUTHORIZED, "ERROR, channel is not secure");
        LOG.error(getBeanName() + ": handleRequestInternal - ERROR, channel is not secure");
        return null;
    }

    /*
     * getUserPrincipal() returns a java.security.Principal containing the
     * name of the user making this request, else it returns null if the
     * user has not been authenticated. so, if it is mandated that the user
     * be authenticated, but has not been authenticated, then throw an
     * exception and return an error
     */
    if (isAuthenticated() && request.getUserPrincipal() == null) {
        response.sendError(SC_UNAUTHORIZED, "ERROR, user is not authenticated");
        LOG.error(getBeanName() + ": handleRequestInternal - ERROR, user is not authenticated");
        return null;
    }

    /*
     * Check for valid method - the only supported http methods are GET,
     * POST, PUT, and DELETE. Here are some good descriptions regarding the
     * methods and their use with respect to this servlet.
     * 
     * The GET method is used for projecting data from the DB. So it maps to
     * a select statement.
     * 
     * The PUT and POST methods are used for inserting or updating an entity
     * in the DB. So they map to either an update or insert.
     * 
     * The DELETE is used for removing one or more entities from the DB. So
     * it maps to a delete.
     * 
     * The bean must be assigned at least one of the methods to service
     */
    Method method = null;
    try {
        method = Enum.valueOf(Method.class, request.getMethod().toUpperCase());
        LOG.debug(getBeanName() + ": handleRequestInternal - processing this method: " + method.toString());
    } catch (IllegalArgumentException e) {
        LOG.error(getBeanName() + ":handleRequestInternal - This method is not allowed [" + request.getMethod()
                + "]");
        response.setHeader("Allow", allowedMethodsRsp);
        response.sendError(SC_METHOD_NOT_ALLOWED, "This method is not allowed [" + request.getMethod() + "]");
        return null;
    }

    // do some more method validation; i.e., make sure requested method has
    // been assigned a SQL statement
    //
    // TODO: we may be able to remove this block of code
    String s1 = null;
    if (method.isGet() && sqlStmnts4Get == null || method.isPost() && sqlStmnts4Post == null
            || method.isPut() && sqlStmnts4Put == null || method.isDelete() && sqlStmnts4Delete == null) {
        response.setHeader("Allow", allowedMethodsRsp);
        s1 = "HTTP method [" + method + "] is not supported";
        response.sendError(SC_METHOD_NOT_ALLOWED, s1);
        LOG.error(getBeanName() + ":handleRequestInternal - " + s1);
        return null;
    }

    // If the client has specified an 'Accept' header field, then determine
    // if it is willing or capable of accepting JSON or anything (*/*)
    //
    // TODO: what about the client accepting urlencoded strings??
    s1 = request.getHeader(ACCEPT_HDR);
    if (s1 != null && s1.length() > 0) {
        LOG.debug(getBeanName() + ":handleRequestInternal - client-specified media "
                + "type in accept header = " + s1);
        // parse the accept header's content
        String[] mediaTypes = s1.trim().split(COMMA_STR);
        boolean match = false;
        for (String mediaType : mediaTypes) {
            mediaType = mediaType.trim().toLowerCase();
            if (mediaType.startsWith(anyContentType) || mediaType.startsWith(jsonContentType)) {
                match = true;
                break;
            }
        }
        if (!match) {
            LOG.error(getBeanName() + ":handleRequestInternal - client-specified media type of '" + s1
                    + "' does not include '" + "'" + jsonContentType);
            response.sendError(SC_NOT_ACCEPTABLE, "client-specified media " + "type of '" + s1
                    + "' does not include '" + "'" + jsonContentType);
            return null;
        }
    }

    // pick up the corresponding list of SQL statements for this request
    List<SqlStmnt> sqlStmnts = null;
    switch (method) {
    case GET:
        sqlStmnts = getSqlStmnts4Get();
        break;
    case DELETE:
        sqlStmnts = getSqlStmnts4Delete();
        break;
    case PUT:
        sqlStmnts = getSqlStmnts4Put();
        break;
    case POST:
        sqlStmnts = getSqlStmnts4Post();
        break;
    default:
        response.sendError(SC_METHOD_NOT_ALLOWED, "ERROR, unsupported method type: " + method);
        LOG.error(getBeanName() + ": handleRequestInternal - ERROR, encountered unknown " + "method type: "
                + method);
        return null;
    }

    // ~~~~~~ EXTRACT PARAMERTERS, IF ANY ~~~~~~~~~~~

    // GETs with entity bodies are illegal
    if (method.isGet() && request.getContentLength() > 0) {
        response.sendError(SC_BAD_REQUEST,
                "Client has issued a malformed or illegal request; " + "GET cannot include entity body");
        return null;
    }

    // the DELETE method also cannot include an entity body; however, the
    // servlet containers already ignore them. so no need to check for that

    // see if json object arrived
    boolean jsonObjectPresent = (method.isPost() || method.isPut())
            && (request.getContentLength() > 0 && request.getContentType().equalsIgnoreCase(jsonContentType));

    LOG.debug(getBeanName() + ": jsonObjectPresent = " + jsonObjectPresent);

    // see if this is a PUT with entity. we've learned that for PUTs,
    // getParameterMap does not work the same across all servlet containers.
    // so we need take care of this ourselves
    boolean putWithBodyPresent = (method.isPut()) && (request.getContentLength() > 0
            && request.getContentType().equalsIgnoreCase(urlEncodedContentType));

    LOG.debug(getBeanName() + ": putWithBodyPresent = " + putWithBodyPresent);

    // collect incoming parameters and place them in a common bucket
    //
    // ~~~~ ALL PARAMETER KEY NAMES MUST BE FORCED TO LOWER CASE ~~~
    //
    List<Map<String, String>> cParams = new ArrayList<Map<String, String>>();

    // first, get the incoming query or form parameters (if any); we will
    // assume that each key has only one parameter. in other words,
    // we're not dealing with drop-down boxes or things similar
    if (!putWithBodyPresent && !jsonObjectPresent) {
        Map<String, String[]> qParams = request.getParameterMap();
        if (qParams != null && !qParams.isEmpty()) {
            Map<String, String> qMap = new HashMap<String, String>();
            for (String key : qParams.keySet()) {
                qMap.put(key.toLowerCase(), qParams.get(key)[0]);
            }
            if (!qMap.isEmpty()) {
                cParams.add(qMap);
                LOG.debug(getBeanName() + ": query params = " + qMap.toString());
            }
        }
    }

    // a put with entity body arrived, so get the parameters from the
    // body and place them in the common bucket
    else if (putWithBodyPresent) {

        try {
            Map<String, String> putParams = null;
            // parseUrlEncoded will force keys to lower case
            putParams = Utils.parseUrlEncoded(request.getInputStream());
            if (putParams != null && !putParams.isEmpty()) {
                cParams.add(putParams);
            }
        } catch (Exception exc) {
            LOG.error(getBeanName() + ": ERROR, caught this " + "exception while parsing urlencoded string: "
                    + exc.toString());
            LOG.error(getBeanName() + ": exception stack trace follows:");
            dumpStackTrace(exc.getStackTrace());
            if (exc.getCause() != null) {
                LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
                LOG.error(getBeanName() + ": causing exception stack trace follows:");
                dumpStackTrace(exc.getCause().getStackTrace());
            }
            response.sendError(SC_BAD_REQUEST, "urlencoded string parsing error: " + exc.getMessage());
            return null;
        }
    }

    // ok, a json object arrived, so get parameters defined in that object
    // and place them in the common bucket
    else {
        // its a json object, so parse it to extract params from it
        try {
            List<Map<String, String>> jParams = null;
            // parseJson will ensure that all passed-in JSON objects have
            // the same set of identical keys
            jParams = Utils.parseJson(request.getInputStream());
            if (jParams != null && !jParams.isEmpty()) {
                // if we also got query params then ensure they have the
                // same set of keys as the json params. why anyone would
                // ever do this is beyond me, but I'll leave it in for now
                if (!cParams.isEmpty()) {
                    Map<String, String> cMap = cParams.get(0);
                    Map<String, String> jMap = jParams.get(0);
                    for (String key : cMap.keySet()) {
                        if (jMap.get(key) == null) {
                            String eStr = getBeanName() + ": ERROR, json "
                                    + "object key set does not match query " + "param key set";
                            LOG.error(eStr);
                            response.sendError(SC_BAD_REQUEST, eStr);
                            return null;
                        }
                    }
                    // place the passed in query params in the jParams
                    // bucket
                    jParams.add(cMap);
                }
                // assign the jParams bucket to the common bucket
                cParams = jParams;
            }
        } catch (Exception exc) {
            LOG.error(getBeanName() + ": ERROR, caught this " + "exception while parsing json object: "
                    + exc.toString());
            LOG.error(getBeanName() + ": exception stack trace follows:");
            dumpStackTrace(exc.getStackTrace());
            if (exc.getCause() != null) {
                LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
                LOG.error(getBeanName() + ": causing exception stack trace follows:");
                dumpStackTrace(exc.getCause().getStackTrace());
            }
            response.sendError(SC_BAD_REQUEST, "json parsing error: " + exc.getMessage());
            return null;
        }
    }

    // if trace is on, dump the params (if any) to the log
    if (LOG.isDebugEnabled()) {
        if (!cParams.isEmpty()) {
            for (int i = 0; i < cParams.size(); i++) {
                LOG.debug(getBeanName() + ": handleRequestInternal - received these params: "
                        + cParams.get(i).toString());
            }
        } else {
            LOG.debug(getBeanName() + ": handleRequestInternal - did not receive any params");
        }
    }

    // ensure none of the params' values have been black listed
    if (!cParams.isEmpty() && getBlackList().length() > 0) {
        char[] bl = getBlackList().toCharArray();
        for (int i = 0; i < cParams.size(); i++) {
            for (String value : cParams.get(i).values()) {
                if (Utils.isOnBlackList(value, bl)) {
                    response.sendError(SC_BAD_REQUEST,
                            "encountered black listed character in this param " + "value: " + value);
                    LOG.error(getBeanName() + "handleRequestInternal - encountered black listed "
                            + "character in this param value: " + value);
                    return null;
                }

            }
        }
    }

    // find the proper SQL statement based on the incoming parameters' (if
    // any) keys
    SqlStmnt sqlStmnt = null;
    try {
        // getMatch will try and find a match, even if no params were
        // provided.
        // @formatter:off
        sqlStmnt = (cParams.isEmpty()) ? SqlStmnt.getMatch(sqlStmnts, null)
                : SqlStmnt.getMatch(sqlStmnts, cParams.get(0).keySet());
        // @formatter:on

        if (sqlStmnt == null && !cParams.isEmpty()) {
            LOG.error(getBeanName() + ":ERROR, unable to find sql " + "statement with this incoming param set: "
                    + cParams.toString());
            response.sendError(SC_INTERNAL_SERVER_ERROR, "internal server error: mapping error");
            return null;
        } else if (sqlStmnt == null) {
            LOG.warn(getBeanName() + ": warning, unable to find sql "
                    + "statement on first pass, will use extra path info");
        } else {
            LOG.debug(getBeanName() + ": handleRequestInternal - matching sql stmt = " + sqlStmnt.toString());
        }
    } catch (Exception exc) {
        LOG.error(getBeanName() + ":ERROR, caught this exception " + "while mapping sql to params: "
                + exc.toString());
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
        if (exc.getCause() != null) {
            LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
            LOG.error(getBeanName() + ": causing exception stack trace follows:");
            dumpStackTrace(exc.getCause().getStackTrace());
        }
        response.sendError(SC_INTERNAL_SERVER_ERROR, "mapping error");
        return null;
    }

    // if getMatch could not find a match - perhaps input params were not
    // provided - then use the URI's 'extended path' information as an input
    // param
    if (sqlStmnt == null) {
        LOG.debug(getBeanName() + ": invoking getExtraPathInfo");
        String[] xtraPathInfo = Utils.getExtraPathInfo(request.getPathInfo());
        if (xtraPathInfo != null && xtraPathInfo.length >= 2) {
            LOG.debug(getBeanName() + ": extra path key:value = " + xtraPathInfo[0] + ":" + xtraPathInfo[1]);
        } else {
            LOG.error(getBeanName() + ":ERROR, getExtraPathInfo failed to find info");
            response.sendError(SC_INTERNAL_SERVER_ERROR, "internal server error: mapping error");
            return null;
        }
        // put the xtra path info in the common param bucket and try again
        cParams.clear();
        Map<String, String> xMap = new HashMap<String, String>();
        xMap.put(xtraPathInfo[0], xtraPathInfo[1]);
        cParams.add(xMap);
        // try again with the extra path info
        sqlStmnt = SqlStmnt.getMatch(sqlStmnts, xMap.keySet());
        if (sqlStmnt == null) {
            LOG.error(getBeanName() + ":ERROR, unable to find sql " + "statement with this xtra path info: "
                    + cParams.toString());
            response.sendError(SC_NOT_FOUND, "internal server error: mapping error");
            return null;
        }
    }

    // if we've gotten this far, we've gotten past the security gauntlet and
    // we have a SQL statement to work with.
    SqlResult sqlResult = null;
    try {
        // get the output stream
        OutputStream os = response.getOutputStream();

        // FIRE IN THE DB HOLE :)
        if ((sqlResult = sqlStmnt.execute(cParams)) == null) {
            // execute will have logged the necessary debug/error info
            response.sendError(SC_INTERNAL_SERVER_ERROR);
            return null;
        }

        // execute went through ok, lets see how to respond
        switch (method) {
        case GET:
            // if a resultset was returned, then set the content type,
            // convert it to json, and write it out
            List<Map<String, Object>> listMap = sqlResult.getResultSet();
            if (listMap != null) {
                // tell the client the content type
                response.setContentType(rspJsonContentType);
                String jsonOutput = Utils.generateJson(sqlResult.getResultSet());
                LOG.trace(getBeanName() + ": returning this payload - " + jsonOutput);
                os.write(jsonOutput.getBytes());

                // ensure that only the client can cache the data and tell
                // the client how long the data can remain active
                response.setHeader(CACHE_CNTRL_HDR,
                        (getCacheControl() != null) ? getCacheControl() : DFLT_CACHE_CNTRL_STR);
                response.setHeader(PRAGMA_HDR, PRAGMA_NO_CACHE_STR);
                response.setDateHeader(EXPIRES_HDR, currentTime + (getExpires() * 1000));
            } else {
                LOG.debug(getBeanName() + ": NOT returning json message");
            }
            response.setStatus(SC_OK);
            break;
        case DELETE:
            // a DELETE should not send back an entity body
            response.setStatus(SC_NO_CONTENT);
            break;
        case PUT:
            /*
             * PUTs are idempotent; therefore, they must provide ALL the
             * properties that pertain to the resource/entity that they are
             * creating or updating. Updates cannot be partial updates; they
             * must be full updates. A PUT is issued by a client that knows
             * the identifier (in our case, primary key) of the
             * resource/entity. Therefore, we do not have to send back a
             * Location header in response to a PUT that has created a
             * resource.
             */
            if (sqlStmnt.isInsert()) {
                response.setStatus(SC_CREATED);
            } else {
                response.setStatus(SC_OK);
            }
            break;
        case POST:
            /*
             * A POST is not idempotent; therefore, it can be used to
             * perform a 'partial' update, as well as a full create. When
             * creating a resource via POST, the client does not know the
             * primary key, and it assumes it will be auto-generated;
             * therefore, a Location header with auto-generated key must be
             * returned to client.
             */
            if (sqlStmnt.isInsert()) {
                response.setStatus(SC_CREATED);
                // we need to return the new key, but only if it was not a
                // batch insert. the new key should be returned via the
                // location header

                // check if a key holder exists; if not, then table was not
                // configured with auto-generated key.
                String locationPath = request.getRequestURL().toString();
                if (sqlResult.getKeyHolder() != null) {
                    // key holder exists, check and see if a key is
                    // present
                    if (sqlResult.getKeyHolder().getKey() != null) {
                        String id = sqlResult.getKeyHolder().getKey().toString();
                        LOG.debug(getBeanName() + ": getKey() returns " + id);
                        locationPath += ("/" + id);
                        LOG.debug(getBeanName() + ": locationPath = " + locationPath);
                        response.setHeader(LOCATION_HDR, locationPath);
                    }
                    // no key, check for multiple keys
                    // TODO: should we send back all keys?
                    else if (sqlResult.getKeyHolder().getKeys() != null) {
                        Map<String, Object> keyMap = sqlResult.getKeyHolder().getKeys();
                        LOG.debug(getBeanName() + ": getKeys() returns " + keyMap);
                    }
                    // maybe map of keys?
                    // TODO: should we send back all keys?
                    else if (sqlResult.getKeyHolder().getKeyList() != null) {
                        for (Map<String, Object> map : sqlResult.getKeyHolder().getKeyList()) {
                            LOG.debug(getBeanName() + ": Map from getKeyList(): " + map);
                        }
                    }
                } else {
                    // if it was not an insert, then it was an update.
                    LOG.debug(getBeanName() + ": key holder was not returned for the insert");
                }
            } else {
                // it was not an insert, so just send back an OK for the
                // update
                response.setStatus(SC_OK);
            }
            break;
        default:
            response.setStatus(SC_OK);
            break;
        }
    } catch (JsonProcessingException exc) {
        LOG.error(getBeanName() + ":ERROR, caught this " + "JsonProcessingException while trying to gen json "
                + "message: " + exc.toString());
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
        if (exc.getCause() != null) {
            LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
            LOG.error(getBeanName() + ": causing exception stack trace follows:");
            dumpStackTrace(exc.getCause().getStackTrace());
        }
        response.sendError(SC_INTERNAL_SERVER_ERROR, "parsing error");
        return null;
    } catch (Exception exc) {
        LOG.error(getBeanName() + ":ERROR, caught this " + "Exception while trying to gen json " + "message: "
                + exc.toString());
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
        if (exc.getCause() != null) {
            LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
            LOG.error(getBeanName() + ": causing exception stack trace follows:");
            dumpStackTrace(exc.getCause().getStackTrace());
        }
        response.sendError(SC_INTERNAL_SERVER_ERROR, "parsing error");
        return null;

    } finally {
        if (sqlResult != null) {
            SqlResult.enqueue(sqlResult);
        }
    }

    // must return null, because we're not using views!
    return null;
}

From source file:de.innovationgate.wgpublisher.WGPDispatcher.java

public static String getPublisherURL(javax.servlet.http.HttpServletRequest request, boolean absolute) {

    if (absolute) {
        String protocol = request.getProtocol().substring(0, request.getProtocol().indexOf("/")).toLowerCase();
        if (protocol.equals("http") && request.isSecure()) {
            protocol = "https";
        }//w  w  w.  j  a  v a  2 s.c o  m

        int port = request.getServerPort();
        if (port != -1) {
            if (protocol.equals("http") && port == 80) {
                port = -1;
            } else if (protocol.equals("https") && port == 443) {
                port = -1;
            }
        }

        return protocol + "://" + request.getServerName() + (port != -1 ? ":" + port : "")
                + request.getContextPath();
    } else {
        return request.getContextPath();
    }

}

From source file:axiom.servlet.AbstractServletClient.java

void sendRedirect(HttpServletRequest req, HttpServletResponse res, String url) {
    String location = url;//from   w ww  .  j  a v a 2 s.co  m

    if (url.indexOf("://") == -1) {
        // need to transform a relative URL into an absolute one
        String scheme = req.getScheme();
        StringBuffer loc = new StringBuffer(scheme);

        loc.append("://");
        String hostname = req.getServerName();
        boolean forwarded = false;
        if (req.getHeader("X-Forwarded-Host") != null) {
            hostname = req.getHeader("X-Forwarded-Host");
            forwarded = true;
        }
        loc.append(hostname);

        int p = (!forwarded) ? req.getServerPort() : 80;

        // check if we need to include server port
        if ((p > 0) && (("http".equals(scheme) && (p != 80)) || ("https".equals(scheme) && (p != 443)))) {
            loc.append(":");
            loc.append(p);
        }

        if (!url.startsWith("/")) {
            String requri = req.getRequestURI();
            int lastSlash = requri.lastIndexOf("/");

            if (lastSlash == (requri.length() - 1)) {
                loc.append(requri);
            } else if (lastSlash > -1) {
                loc.append(requri.substring(0, lastSlash + 1));
            } else {
                loc.append("/");
            }
        }

        loc.append(url);
        location = loc.toString();
    }

    // send status code 303 for HTTP 1.1, 302 otherwise
    if (isOneDotOne(req.getProtocol())) {
        res.setStatus(HttpServletResponse.SC_SEE_OTHER);
    } else {
        res.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    }

    res.setContentType("text/html");
    res.setHeader("Location", location);
}

From source file:es.juntadeandalucia.mapea.proxy.ProxyRedirect.java

/***************************************************************************
 * Process the HTTP Get request/*w w  w. j  a v  a  2s .  c  o  m*/
 ***************************************************************************/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    String serverUrl = request.getParameter("url");
    // manages a get request if it's the geoprint or getcapabilities operation
    boolean isGeoprint = serverUrl.toLowerCase().contains("mapeaop=geoprint");
    boolean isGetCapabilities = serverUrl.toLowerCase().contains("getcapabilities");
    boolean isGetFeatureInfo = serverUrl.toLowerCase().contains("wmsinfo");
    if (isGeoprint || isGetCapabilities || isGetFeatureInfo) {
        String strErrorMessage = "";
        serverUrl = checkTypeRequest(serverUrl);
        if (!serverUrl.equals("ERROR")) {
            // removes mapeaop parameter
            String url = serverUrl.replaceAll("\\&?\\??mapeaop=geoprint", "");
            url = serverUrl.replaceAll("\\&?\\??mapeaop=getcapabilities", "");
            url = serverUrl.replaceAll("\\&?\\??mapeaop=wmsinfo", "");
            HttpClient client = new HttpClient();
            GetMethod httpget = null;
            try {
                httpget = new GetMethod(url);
                HttpClientParams params = client.getParams();
                params.setIntParameter(HttpClientParams.MAX_REDIRECTS, numMaxRedirects);
                client.executeMethod(httpget);
                // REDIRECTS MANAGEMENT
                if (httpget.getStatusCode() == HttpStatus.SC_OK) {
                    // PATH_SECURITY_PROXY - AG
                    Header[] respHeaders = httpget.getResponseHeaders();
                    int compSize = httpget.getResponseBody().length;
                    ArrayList<Header> headerList = new ArrayList<Header>(Arrays.asList(respHeaders));
                    String headersString = headerList.toString();
                    boolean checkedContent = checkContent(headersString, compSize, serverUrl);
                    // FIN_PATH_SECURITY_PROXY
                    if (checkedContent) {
                        if (request.getProtocol().compareTo("HTTP/1.0") == 0) {
                            response.setHeader("Pragma", "no-cache");
                        } else if (request.getProtocol().compareTo("HTTP/1.1") == 0) {
                            response.setHeader("Cache-Control", "no-cache");
                        }
                        response.setDateHeader("Expires", -1);
                        // set content-type headers
                        if (isGeoprint) {
                            response.setContentType("application/json");
                        } else if (isGetCapabilities) {
                            response.setContentType("text/xml");
                        }
                        /*
                         * checks if it has requested an getfeatureinfo to modify the response content
                         * type.
                         */
                        String requesteredUrl = request.getParameter("url");
                        if (GETINFO_PLAIN_REGEX.matcher(requesteredUrl).matches()) {
                            response.setContentType("text/plain");
                        } else if (GETINFO_GML_REGEX.matcher(requesteredUrl).matches()) {
                            response.setContentType("application/gml+xml");
                        } else if (GETINFO_HTML_REGEX.matcher(requesteredUrl).matches()) {
                            response.setContentType("text/html");
                        }
                        InputStream st = httpget.getResponseBodyAsStream();
                        ServletOutputStream sos = response.getOutputStream();
                        IOUtils.copy(st, sos);
                    } else {
                        strErrorMessage += errorType;
                        log.error(strErrorMessage);
                    }
                } else {
                    strErrorMessage = "Unexpected failure: " + httpget.getStatusLine().toString();
                    log.error(strErrorMessage);
                }
                httpget.releaseConnection();
            } catch (Exception e) {
                log.error("Error al tratar el contenido de la peticion: " + e.getMessage(), e);
            } finally {
                if (httpget != null) {
                    httpget.releaseConnection();
                }
            }
        } else {
            // String errorXML = strErrorMessage;
            String errorXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><error><descripcion>Error en el parametro url de entrada</descripcion></error>";
            response.setContentType("text/xml");
            try {
                PrintWriter out = response.getWriter();
                out.print(errorXML);
                response.flushBuffer();
            } catch (Exception e) {
                log.error(e);
            }
        }
    } else {
        doPost(request, response);
    }
}

From source file:ro.raisercostin.web.DebuggingFilter.java

public String debug(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response,
        DebuggingPrinter debuggingPrinter, boolean debugAll, boolean debugRequest) {
    final JspFactory jspFactory = JspFactory.getDefaultFactory();
    HttpSession session = request.getSession();
    debuggingPrinter.addHeader();// w  ww .j a  v  a 2s  . c o  m
    debuggingPrinter.addSection("Request Parameters");
    for (Iterator iterator = request.getParameterMap().entrySet().iterator(); iterator.hasNext();) {
        Map.Entry<String, Object> parameter = (Map.Entry<String, Object>) iterator.next();
        addRow(debuggingPrinter, parameter.getKey(),
                StringUtils.arrayToCommaDelimitedString((Object[]) parameter.getValue()));
    }
    debuggingPrinter.endSection();

    if (debugRequest) {
        debuggingPrinter.addSection("Request Header");
        for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
            String parameterName = (String) e.nextElement();
            addRow(debuggingPrinter, parameterName,
                    debuggingPrinter.transform(request.getHeader(parameterName)));
        }
        debuggingPrinter.endSection();

        debuggingPrinter.addSection("Request Attributes");
        java.util.Enumeration en = request.getAttributeNames();
        while (en.hasMoreElements()) {
            String attrName = (String) en.nextElement();
            try {
                addRow(debuggingPrinter, split(attrName, 50), toString2(request.getAttribute(attrName), 120));
            } catch (Exception e) {
                addRow(debuggingPrinter, split(attrName, 50), toString(e, 120));
            }

        }
        debuggingPrinter.endSection();

        debuggingPrinter.addSection("Session Attributes");
        en = session.getAttributeNames();
        while (en.hasMoreElements()) {
            String attrName = (String) en.nextElement();
            try {
                addRow(debuggingPrinter, split(attrName, 50), toString2(session.getAttribute(attrName), 120));
            } catch (Exception e) {
                addRow(debuggingPrinter, split(attrName, 50), toString(e, 120));
            }
        }
        debuggingPrinter.endSection();

        debuggingPrinter.addSection("Request Info");
        addRow(debuggingPrinter, "AuthType", request.getAuthType());
        addRow(debuggingPrinter, "ContextPath", request.getContextPath());
        addRow(debuggingPrinter, "Method", request.getMethod());
        addRow(debuggingPrinter, "PathInfo", request.getPathInfo());
        addRow(debuggingPrinter, "PathTranslated", request.getPathTranslated());
        addRow(debuggingPrinter, "Protocol", request.getProtocol());
        addRow(debuggingPrinter, "QueryString", request.getQueryString());
        addRow(debuggingPrinter, "RemoteAddr", request.getRemoteAddr());
        addRow(debuggingPrinter, "RemoteUser", request.getRemoteUser());
        addRow(debuggingPrinter, "RequestedSessionId", request.getRequestedSessionId());
        addRow(debuggingPrinter, "RequestURI", request.getRequestURI());
        addRow(debuggingPrinter, "RequestURL", request.getRequestURL().toString());
        addRow(debuggingPrinter, "ServletPath", request.getServletPath());
        addRow(debuggingPrinter, "Scheme", request.getScheme());
        addRow(debuggingPrinter, "ServletPath", request.getServletPath());
    }
    if (debugAll) {
        debuggingPrinter.addSection("Server");
        addRow(debuggingPrinter, "Server Info", servletContext.getServerInfo());
        addRow(debuggingPrinter, "Servlet Engine Version",
                servletContext.getMajorVersion() + "." + servletContext.getMinorVersion());
        addRow(debuggingPrinter, "JSP Version", jspFactory.getEngineInfo().getSpecificationVersion());
        debuggingPrinter.endSection();

        debuggingPrinter.addSection("JVM Properties");
        for (Enumeration e = System.getProperties().propertyNames(); e.hasMoreElements();) {
            String parameterName = (String) e.nextElement();
            addRow(debuggingPrinter, parameterName,
                    debuggingPrinter.transform(System.getProperty(parameterName)));
        }
        debuggingPrinter.endSection();

        debuggingPrinter.addSection("Environment");
        for (Map.Entry<String, String> property : System.getenv().entrySet()) {
            addRow(debuggingPrinter, property.getKey(), debuggingPrinter.transform(property.getValue()));
        }
        debuggingPrinter.endSection();

        debuggingPrinter.addSection("Debugger Provided by");
        addRow(debuggingPrinter, "provided by", "raisercostin");
        debuggingPrinter.addRow("source",
                "<a target='_blank' href='http://code.google.com/p/raisercostin/wiki/DebuggingFilter'>http://code.google.com/p/raisercostin/wiki/DebuggingFilter</a>");
        addRow(debuggingPrinter, "version", "1.0");
        addRow(debuggingPrinter, "timestamp", "2008.June.14");
        addRow(debuggingPrinter, "license",
                "<a target='_blank' href='http://www.apache.org/licenses/LICENSE-2.0.html'>Apache License 2.0</a>");
        debuggingPrinter.endSection();
    }
    debuggingPrinter.addFooter();
    return debuggingPrinter.getString();
}

From source file:org.sakaiproject.entitybroker.util.http.EntityHttpServletRequest.java

/**
 * Set all the values from a request on this request object and set this request
 * as the one which the values were copied from
 * @param req any request//from  w ww  .ja v  a 2s  . co m
 */
public void setRequestValues(HttpServletRequest req) {
    if (req == null) {
        throw new IllegalArgumentException("request cannot be null");
    }
    // get the collections of values out
    Enumeration<String> attribNames = req.getAttributeNames();
    while (attribNames.hasMoreElements()) {
        String name = (String) attribNames.nextElement();
        Object obj = req.getAttribute(name);
        if (obj != null) {
            attributes.put(name, obj);
        }
    }
    Cookie[] ck = req.getCookies();
    if (ck != null) {
        for (int i = 0; i < ck.length; i++) {
            cookies.add(ck[i]);
        }
    }
    Enumeration<String> headerNames = req.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        Enumeration<String> henum = req.getHeaders(name);
        Vector<String> v = new Vector<String>(1);
        while (henum.hasMoreElements()) {
            String h = henum.nextElement();
            v.add(h);
        }
    }
    for (Entry<String, String[]> entry : (Set<Entry<String, String[]>>) req.getParameterMap().entrySet()) {
        parameters.put(entry.getKey(), entry.getValue());
    }
    // get the basic values out
    this.locale = req.getLocale();
    this.method = req.getMethod();
    this.contentType = req.getContentType();
    this.characterEncoding = req.getCharacterEncoding() == null ? "UTF-8" : req.getCharacterEncoding();
    this.contentLength = req.getContentLength();

    this.contextPath = req.getContextPath();
    this.pathInfo = req.getPathInfo();
    this.queryString = req.getQueryString();
    this.requestURI = req.getRequestURI();
    this.servletPath = req.getServletPath();

    this.scheme = req.getScheme();
    this.protocol = req.getProtocol();
    this.serverName = req.getServerName();
    this.serverPort = req.getServerPort();
    this.remoteAddr = req.getRemoteAddr();
    this.remoteHost = req.getRemoteHost();

    this.realDispatcher = true;
}

From source file:com.icesoft.faces.webapp.http.servlet.ServletEnvironmentRequest.java

public ServletEnvironmentRequest(Object request, HttpSession session, Authorization authorization) {
    HttpServletRequest initialRequest = (HttpServletRequest) request;
    this.session = session;
    this.authorization = authorization;
    //Copy common data
    authType = initialRequest.getAuthType();
    contextPath = initialRequest.getContextPath();
    remoteUser = initialRequest.getRemoteUser();
    userPrincipal = initialRequest.getUserPrincipal();
    requestedSessionId = initialRequest.getRequestedSessionId();
    requestedSessionIdValid = initialRequest.isRequestedSessionIdValid();

    attributes = new HashMap();
    Enumeration attributeNames = initialRequest.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
        String name = (String) attributeNames.nextElement();
        Object attribute = initialRequest.getAttribute(name);
        if ((null != name) && (null != attribute)) {
            attributes.put(name, attribute);
        }//from  w w  w. ja v  a2  s .com
    }

    // Warning:  For some reason, the various javax.include.* attributes are
    // not available via the getAttributeNames() call.  This may be limited
    // to a Liferay issue but when the MainPortlet dispatches the call to
    // the MainServlet, all of the javax.include.* attributes can be
    // retrieved using this.request.getAttribute() but they do NOT appear in
    // the Enumeration of names returned by getAttributeNames().  So here
    // we manually add them to our map to ensure we can find them later.
    String[] incAttrKeys = Constants.INC_CONSTANTS;
    for (int index = 0; index < incAttrKeys.length; index++) {
        String incAttrKey = incAttrKeys[index];
        Object incAttrVal = initialRequest.getAttribute(incAttrKey);
        if (incAttrVal != null) {
            attributes.put(incAttrKey, initialRequest.getAttribute(incAttrKey));
        }
    }

    headers = new HashMap();
    Enumeration headerNames = initialRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = (String) headerNames.nextElement();
        Enumeration values = initialRequest.getHeaders(name);
        headers.put(name, Collections.list(values));
    }

    parameters = new HashMap();
    Enumeration parameterNames = initialRequest.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String name = (String) parameterNames.nextElement();
        parameters.put(name, initialRequest.getParameterValues(name));
    }

    scheme = initialRequest.getScheme();
    serverName = initialRequest.getServerName();
    serverPort = initialRequest.getServerPort();
    secure = initialRequest.isSecure();

    //Copy servlet specific data
    cookies = initialRequest.getCookies();
    method = initialRequest.getMethod();
    pathInfo = initialRequest.getPathInfo();
    pathTranslated = initialRequest.getPathTranslated();
    queryString = initialRequest.getQueryString();
    requestURI = initialRequest.getRequestURI();
    try {
        requestURL = initialRequest.getRequestURL();
    } catch (NullPointerException e) {
        //TODO remove this catch block when GlassFish bug is addressed
        if (log.isErrorEnabled()) {
            log.error("Null Protocol Scheme in request", e);
        }
        HttpServletRequest req = initialRequest;
        requestURL = new StringBuffer(
                "http://" + req.getServerName() + ":" + req.getServerPort() + req.getRequestURI());
    }
    servletPath = initialRequest.getServletPath();
    servletSession = initialRequest.getSession();
    isRequestedSessionIdFromCookie = initialRequest.isRequestedSessionIdFromCookie();
    isRequestedSessionIdFromURL = initialRequest.isRequestedSessionIdFromURL();
    characterEncoding = initialRequest.getCharacterEncoding();
    contentLength = initialRequest.getContentLength();
    contentType = initialRequest.getContentType();
    protocol = initialRequest.getProtocol();
    remoteAddr = initialRequest.getRemoteAddr();
    remoteHost = initialRequest.getRemoteHost();
    initializeServlet2point4Properties(initialRequest);
}

From source file:net.lightbody.bmp.proxy.jetty.servlet.Dump.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setAttribute("Dump", this);
    request.setCharacterEncoding("ISO_8859_1");
    getServletContext().setAttribute("Dump", this);

    String info = request.getPathInfo();
    if (info != null && info.endsWith("Exception")) {
        try {/*from   w  w  w  .j a  va  2s.  c o m*/
            throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance());
        } catch (Throwable th) {
            throw new ServletException(th);
        }
    }

    String redirect = request.getParameter("redirect");
    if (redirect != null && redirect.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendRedirect(redirect);
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String error = request.getParameter("error");
    if (error != null && error.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendError(Integer.parseInt(error));
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String length = request.getParameter("length");
    if (length != null && length.length() > 0) {
        response.setContentLength(Integer.parseInt(length));
    }

    String buffer = request.getParameter("buffer");
    if (buffer != null && buffer.length() > 0)
        response.setBufferSize(Integer.parseInt(buffer));

    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html");

    if (info != null && info.indexOf("Locale/") >= 0) {
        try {
            String locale_name = info.substring(info.indexOf("Locale/") + 7);
            Field f = java.util.Locale.class.getField(locale_name);
            response.setLocale((Locale) f.get(null));
        } catch (Exception e) {
            LogSupport.ignore(log, e);
            response.setLocale(Locale.getDefault());
        }
    }

    String cn = request.getParameter("cookie");
    String cv = request.getParameter("value");
    String v = request.getParameter("version");
    if (cn != null && cv != null) {
        Cookie cookie = new Cookie(cn, cv);
        cookie.setComment("Cookie from dump servlet");
        if (v != null) {
            cookie.setMaxAge(300);
            cookie.setPath("/");
            cookie.setVersion(Integer.parseInt(v));
        }
        response.addCookie(cookie);
    }

    String pi = request.getPathInfo();
    if (pi != null && pi.startsWith("/ex")) {
        OutputStream out = response.getOutputStream();
        out.write("</H1>This text should be reset</H1>".getBytes());
        if ("/ex0".equals(pi))
            throw new ServletException("test ex0", new Throwable());
        if ("/ex1".equals(pi))
            throw new IOException("test ex1");
        if ("/ex2".equals(pi))
            throw new UnavailableException("test ex2");
        if ("/ex3".equals(pi))
            throw new HttpException(501);
    }

    PrintWriter pout = response.getWriter();
    Page page = null;

    try {
        page = new Page();
        page.title("Dump Servlet");

        page.add(new Heading(1, "Dump Servlet"));
        Table table = new Table(0).cellPadding(0).cellSpacing(0);
        page.add(table);
        table.newRow();
        table.addHeading("getMethod:&nbsp;").cell().right();
        table.addCell("" + request.getMethod());
        table.newRow();
        table.addHeading("getContentLength:&nbsp;").cell().right();
        table.addCell(Integer.toString(request.getContentLength()));
        table.newRow();
        table.addHeading("getContentType:&nbsp;").cell().right();
        table.addCell("" + request.getContentType());
        table.newRow();
        table.addHeading("getCharacterEncoding:&nbsp;").cell().right();
        table.addCell("" + request.getCharacterEncoding());
        table.newRow();
        table.addHeading("getRequestURI:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURI());
        table.newRow();
        table.addHeading("getRequestURL:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURL());
        table.newRow();
        table.addHeading("getContextPath:&nbsp;").cell().right();
        table.addCell("" + request.getContextPath());
        table.newRow();
        table.addHeading("getServletPath:&nbsp;").cell().right();
        table.addCell("" + request.getServletPath());
        table.newRow();
        table.addHeading("getPathInfo:&nbsp;").cell().right();
        table.addCell("" + request.getPathInfo());
        table.newRow();
        table.addHeading("getPathTranslated:&nbsp;").cell().right();
        table.addCell("" + request.getPathTranslated());
        table.newRow();
        table.addHeading("getQueryString:&nbsp;").cell().right();
        table.addCell("" + request.getQueryString());

        table.newRow();
        table.addHeading("getProtocol:&nbsp;").cell().right();
        table.addCell("" + request.getProtocol());
        table.newRow();
        table.addHeading("getScheme:&nbsp;").cell().right();
        table.addCell("" + request.getScheme());
        table.newRow();
        table.addHeading("getServerName:&nbsp;").cell().right();
        table.addCell("" + request.getServerName());
        table.newRow();
        table.addHeading("getServerPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getServerPort()));
        table.newRow();
        table.addHeading("getLocalName:&nbsp;").cell().right();
        table.addCell("" + request.getLocalName());
        table.newRow();
        table.addHeading("getLocalAddr:&nbsp;").cell().right();
        table.addCell("" + request.getLocalAddr());
        table.newRow();
        table.addHeading("getLocalPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getLocalPort()));
        table.newRow();
        table.addHeading("getRemoteUser:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteUser());
        table.newRow();
        table.addHeading("getRemoteAddr:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteAddr());
        table.newRow();
        table.addHeading("getRemoteHost:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteHost());
        table.newRow();
        table.addHeading("getRemotePort:&nbsp;").cell().right();
        table.addCell("" + request.getRemotePort());
        table.newRow();
        table.addHeading("getRequestedSessionId:&nbsp;").cell().right();
        table.addCell("" + request.getRequestedSessionId());
        table.newRow();
        table.addHeading("isSecure():&nbsp;").cell().right();
        table.addCell("" + request.isSecure());

        table.newRow();
        table.addHeading("isUserInRole(admin):&nbsp;").cell().right();
        table.addCell("" + request.isUserInRole("admin"));

        table.newRow();
        table.addHeading("getLocale:&nbsp;").cell().right();
        table.addCell("" + request.getLocale());

        Enumeration locales = request.getLocales();
        while (locales.hasMoreElements()) {
            table.newRow();
            table.addHeading("getLocales:&nbsp;").cell().right();
            table.addCell(locales.nextElement());
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers")
                .attribute("COLSPAN", "2").left();
        Enumeration h = request.getHeaderNames();
        String name;
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();

            Enumeration h2 = request.getHeaders(name);
            while (h2.hasMoreElements()) {
                String hv = (String) h2.nextElement();
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().right();
                table.addCell(hv);
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters")
                .attribute("COLSPAN", "2").left();
        h = request.getParameterNames();
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().right();
            table.addCell(request.getParameter(name));
            String[] values = request.getParameterValues(name);
            if (values == null) {
                table.newRow();
                table.addHeading(name + " Values:&nbsp;").cell().right();
                table.addCell("NULL!!!!!!!!!");
            } else if (values.length > 1) {
                for (int i = 0; i < values.length; i++) {
                    table.newRow();
                    table.addHeading(name + "[" + i + "]:&nbsp;").cell().right();
                    table.addCell(values[i]);
                }
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left();
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            Cookie cookie = cookies[i];

            table.newRow();
            table.addHeading(cookie.getName() + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell(cookie.getValue());
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes")
                .attribute("COLSPAN", "2").left();
        Enumeration a = request.getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>");
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>");
        }

        if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data")
                && request.getContentLength() < 1000000) {
            MultiPartRequest multi = new MultiPartRequest(request);
            String[] parts = multi.getPartNames();

            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content")
                    .attribute("COLSPAN", "2").left();
            for (int p = 0; p < parts.length; p++) {
                name = parts[p];
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
                table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>");
            }
        }

        String res = request.getParameter("resource");
        if (res != null && res.length() > 0) {
            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res)
                    .attribute("COLSPAN", "2").left();

            table.newRow();
            table.addHeading("this.getClass():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getResource(res));

            table.newRow();
            table.addHeading("this.getClass().getClassLoader():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getClassLoader().getResource(res));

            table.newRow();
            table.addHeading("Thread.currentThread().getContextClassLoader():&nbsp;").cell().right();
            table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res));

            table.newRow();
            table.addHeading("getServletContext():&nbsp;").cell().right();
            try {
                table.addCell("" + getServletContext().getResource(res));
            } catch (Exception e) {
                table.addCell("" + e);
            }
        }

        /* ------------------------------------------------------------ */
        page.add(Break.para);
        page.add(new Heading(1, "Request Wrappers"));
        ServletRequest rw = request;
        int w = 0;
        while (rw != null) {
            page.add((w++) + ": " + rw.getClass().getName() + "<br/>");
            if (rw instanceof HttpServletRequestWrapper)
                rw = ((HttpServletRequestWrapper) rw).getRequest();
            else if (rw instanceof ServletRequestWrapper)
                rw = ((ServletRequestWrapper) rw).getRequest();
            else
                rw = null;
        }

        page.add(Break.para);
        page.add(new Heading(1, "International Characters"));
        page.add("Directly encoced:  Drst<br/>");
        page.add("HTML reference: D&uuml;rst<br/>");
        page.add("Decimal (252) 8859-1: D&#252;rst<br/>");
        page.add("Hex (xFC) 8859-1: D&#xFC;rst<br/>");
        page.add(
                "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>");
        page.add(Break.para);
        page.add(new Heading(1, "Form to generate GET content"));
        TableForm tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("GET");
        tf.addTextField("TextField", "TextField", 20, "value");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(Break.para);
        page.add(new Heading(1, "Form to generate POST content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("TextField", "TextField", 20, "value");
        Select select = tf.addSelect("Select", "Select", true, 3);
        select.add("ValueA");
        select.add("ValueB1,ValueB2");
        select.add("ValueC");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(new Heading(1, "Form to upload content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.attribute("enctype", "multipart/form-data");
        tf.addFileField("file", "file");
        tf.addButton("Upload", "Upload");
        page.add(tf);

        page.add(new Heading(1, "Form to get Resource"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("resource", "resource", 20, "");
        tf.addButton("Action", "getResource");
        page.add(tf);

    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
    }

    page.write(pout);

    String data = request.getParameter("data");
    if (data != null && data.length() > 0) {
        int d = Integer.parseInt(data);
        while (d > 0) {
            pout.println("1234567890123456789012345678901234567890123456789\n");
            d = d - 50;

        }
    }

    pout.close();

    if (pi != null) {
        if ("/ex4".equals(pi))
            throw new ServletException("test ex4", new Throwable());
        if ("/ex5".equals(pi))
            throw new IOException("test ex5");
        if ("/ex6".equals(pi))
            throw new UnavailableException("test ex6");
        if ("/ex7".equals(pi))
            throw new HttpException(501);
    }

    request.getInputStream().close();

}