Example usage for javax.servlet.http HttpServletRequest getAttributeNames

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

Introduction

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

Prototype

public Enumeration<String> getAttributeNames();

Source Link

Document

Returns an Enumeration containing the names of the attributes available to this request.

Usage

From source file:org.sakaiproject.portal.util.ErrorReporter.java

@SuppressWarnings("rawtypes")
private String requestDisplay(HttpServletRequest request) {
    ResourceBundle rb = rbDefault;
    StringBuilder sb = new StringBuilder();
    try {//  w  ww. j  a v a 2  s . c  o  m
        sb.append(rb.getString("bugreport.request")).append("\n");
        sb.append(rb.getString("bugreport.request.authtype")).append(request.getAuthType()).append("\n");
        sb.append(rb.getString("bugreport.request.charencoding")).append(request.getCharacterEncoding())
                .append("\n");
        sb.append(rb.getString("bugreport.request.contentlength")).append(request.getContentLength())
                .append("\n");
        sb.append(rb.getString("bugreport.request.contenttype")).append(request.getContentType()).append("\n");
        sb.append(rb.getString("bugreport.request.contextpath")).append(request.getContextPath()).append("\n");
        sb.append(rb.getString("bugreport.request.localaddr")).append(request.getLocalAddr()).append("\n");
        sb.append(rb.getString("bugreport.request.localname")).append(request.getLocalName()).append("\n");
        sb.append(rb.getString("bugreport.request.localport")).append(request.getLocalPort()).append("\n");
        sb.append(rb.getString("bugreport.request.method")).append(request.getMethod()).append("\n");
        sb.append(rb.getString("bugreport.request.pathinfo")).append(request.getPathInfo()).append("\n");
        sb.append(rb.getString("bugreport.request.protocol")).append(request.getProtocol()).append("\n");
        sb.append(rb.getString("bugreport.request.querystring")).append(request.getQueryString()).append("\n");
        sb.append(rb.getString("bugreport.request.remoteaddr")).append(request.getRemoteAddr()).append("\n");
        sb.append(rb.getString("bugreport.request.remotehost")).append(request.getRemoteHost()).append("\n");
        sb.append(rb.getString("bugreport.request.remoteport")).append(request.getRemotePort()).append("\n");
        sb.append(rb.getString("bugreport.request.requesturl")).append(request.getRequestURL()).append("\n");
        sb.append(rb.getString("bugreport.request.scheme")).append(request.getScheme()).append("\n");
        sb.append(rb.getString("bugreport.request.servername")).append(request.getServerName()).append("\n");
        sb.append(rb.getString("bugreport.request.headers")).append("\n");
        for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
            String headerName = (String) e.nextElement();
            boolean censor = (censoredHeaders.get(headerName) != null);
            for (Enumeration he = request.getHeaders(headerName); he.hasMoreElements();) {
                String headerValue = (String) he.nextElement();
                sb.append(rb.getString("bugreport.request.header")).append(headerName).append(":")
                        .append(censor ? "---censored---" : headerValue).append("\n");
            }
        }
        sb.append(rb.getString("bugreport.request.parameters")).append("\n");
        for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {

            String parameterName = (String) e.nextElement();
            boolean censor = (censoredParameters.get(parameterName) != null);
            String[] paramvalues = request.getParameterValues(parameterName);
            for (int i = 0; i < paramvalues.length; i++) {
                sb.append(rb.getString("bugreport.request.parameter")).append(parameterName).append(":")
                        .append(i).append(":").append(censor ? "----censored----" : paramvalues[i])
                        .append("\n");
            }
        }
        sb.append(rb.getString("bugreport.request.attributes")).append("\n");
        for (Enumeration e = request.getAttributeNames(); e.hasMoreElements();) {
            String attributeName = (String) e.nextElement();
            Object attribute = request.getAttribute(attributeName);
            boolean censor = (censoredAttributes.get(attributeName) != null);
            sb.append(rb.getString("bugreport.request.attribute")).append(attributeName).append(":")
                    .append(censor ? "----censored----" : attribute).append("\n");
        }
        HttpSession session = request.getSession(false);
        if (session != null) {
            DateFormat serverLocaleDateFormat = DateFormat.getDateInstance(DateFormat.FULL,
                    Locale.getDefault());
            sb.append(rb.getString("bugreport.session")).append("\n");
            sb.append(rb.getString("bugreport.session.creation")).append(session.getCreationTime())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.lastaccess")).append(session.getLastAccessedTime())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.creationdatetime"))
                    .append(serverLocaleDateFormat.format(session.getCreationTime())).append("\n");
            sb.append(rb.getString("bugreport.session.lastaccessdatetime"))
                    .append(serverLocaleDateFormat.format(session.getLastAccessedTime())).append("\n");
            sb.append(rb.getString("bugreport.session.maxinactive")).append(session.getMaxInactiveInterval())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.attributes")).append("\n");
            for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) {
                String attributeName = (String) e.nextElement();
                Object attribute = session.getAttribute(attributeName);
                boolean censor = (censoredAttributes.get(attributeName) != null);
                sb.append(rb.getString("bugreport.session.attribute")).append(attributeName).append(":")
                        .append(censor ? "----censored----" : attribute).append("\n");
            }

        }
    } catch (Exception ex) {
        M_log.error("Failed to generate request display", ex);
        sb.append("Error " + ex.getMessage());
    }

    return sb.toString();
}

From source file:org.motrice.bpm.hippo.util.ServletUserNameUtil.java

public static UserInfo getUserName(final HttpServletRequest request) {
    UserInfo result = null;//from   w ww . j a  v a2 s  . c  o m

    /*
     * log.error("ServletUserNameUtil:error");
     * log.warn("ServletUserNameUtil:warn");
     * log.info("ServletUserNameUtil:info");
     * log.debug("ServletUserNameUtil:debug");
     * log.trace("ServletUserNameUtil:trace");
     */
    checkEngine();
    // / trying shibboleth
    String Shib_Identity_Provider = (String) request.getAttribute("Shib-Identity-Provider");
    log.info("request.getAttribute(Shib-Identity-Provider) = " + Shib_Identity_Provider);
    String Shib_Application_ID = (String) request.getAttribute("Shib-Application-ID");
    log.info("request.getAttribute(Shib-Application-ID) = " + Shib_Application_ID);
    // log.info("request.getHeader(Shib-Identity-Provider)  = "
    // + request.getHeader("Shib-Identity-Provider"));
    if ((Shib_Identity_Provider != null) && (Shib_Application_ID.equals("default"))) {
        // the names of the attributes are set in attribute-*.xml files in
        // /etc/shibboleth for the SP
        // Different IdPs might privide different attributes, it probable
        // makes sence
        // to make the mapping in the attribute-*.xml to the same attribute name for the different IdPs.
        String Subject_SerialNumber = (String) request.getAttribute("Subject_SerialNumber");
        // String gn = (String) request.getAttribute("GivenName");
        String gn = getAttributeShibboleth("GivenName", request);
        String sn = getAttributeShibboleth("Subject_Surname", request);
        //String sn_id = (String) request.getAttribute("sn_id");
        String sn_id = null;
        String cn = getAttributeShibboleth("Subject_CommonName", request);
        log.info("Subject_SerialNumber = " + Subject_SerialNumber + " gn = " + gn + " sn = " + sn + " cn = "
                + cn);
        result = engine.getUserBySerial(Subject_SerialNumber, gn, sn, sn_id, cn);
    }

    if ((Shib_Identity_Provider != null) && (Shib_Application_ID.equals("internal"))) {
        // the names of the attributes are set in attribute-*.xml files in
        // /etc/shibboleth for the SP
        // Different IdPs might privide different attributes, it probable
        // makes sence
        // to make the mapping in the attribute-*.xml to the same attribute name for the different IdPs.
        String cn = getAttributeShibboleth("Subject_CommonName", request);
        log.info(" cn = " + cn);
        String userBaseDn = ConfigUtil.getConfigProperties().getProperty("userDirectoryService.userBaseDn");
        String baseDn = ConfigUtil.getConfigProperties().getProperty("userDirectoryService.baseDn");
        // String dn ="cn="+cn+",ou=Personal,ou=Organisation,ou=Malmo,dc=adm,dc=malmo,dc=se" ; // NOTE  
        String dn = "cn=" + cn + "," + userBaseDn + "," + baseDn; // 
        log.info(" dn = " + dn);
        // log.info("Subject_SerialNumber = " + Subject_SerialNumber + " gn = "
        //          + gn + " sn = " + sn + " cn = " + cn);
        result = engine.getUserByDn(dn);
    }

    if (result == null) {

        log.info("Trying openAM");
        // OPEN AM
        String dn = request.getHeader("x-ipl-dn");
        String ser = request.getHeader("x-ipl-ser");
        String certificateSubject = request.getHeader("x-ipl-cer-sub");

        if (dn == null) {
            if (ser != null) {
                result = engine.getUserBySerial(ser, certificateSubject);
            }
        } else {
            if (ser == null) {
                result = engine.getUserByDn(dn);
            } else {
                log.debug("Only one of header x-ipl-dn and x-ipl-ser should be used");
                log.debug("x-ipl-dn=[  {} ]", dn);
                log.debug("x-ipl-ser=[  {} ]", ser);

                /**
                 * TODO workaround to detect by path komin/extern
                 */
                String pathInfo = request.getPathInfo();
                if (pathInfo != null && pathInfo.indexOf("komin") > 0) {
                    result = engine.getUserByDn(dn);
                } else {
                    result = engine.getUserBySerial(ser, certificateSubject);
                }

            }
        }

        if (result == null) {

            log.info("userName header not found, get user principal instead");
            log.info("Only one of header x-ipl-dn and x-ipl-ser should be used");
            log.info("x-ipl-dn=[{} ]", dn);
            log.info("x-ipl-ser=[{}  ]", ser);
            log.info("x-ipl-cer-sub=[{}]", certificateSubject);

            Principal principal = request.getUserPrincipal();
            if (principal != null) {
                String hippoDn = "CN=" + principal.getName()
                        + ",OU=Personal,OU=Organisation,OU=Hippo Internal User,DC=adm,DC=inherit,DC=se";
                result = engine.getUserByDn(hippoDn);
                // "CN=tesetj,OU=Personal,OU=Organisation,OU=Malmo,DC=adm,DC=malmo,DC=se"

            }

        }

        log.info("Render page with userInfo=[ {} ]", result);

        Enumeration attributes = request.getAttributeNames();
        while (attributes.hasMoreElements()) {
            String attr_name = (String) attributes.nextElement();
            Object attr_val = request.getAttribute(attr_name);
            log.info(attr_name + " = " + attr_val);

        }
    }
    log.info("request.getAttribute(GivenName) = {} ", getAttributeShibboleth("GivenName", request));
    log.info("request.getAttribute(sn_id) = {} ", getAttributeShibboleth("sn_id", request));
    log.info("request.getAttribute(SecurityLevelDescription) = {} ",
            getAttributeShibboleth("SecurityLevelDescription", request));
    log.info("request.getAttribute(Subject_CountryName) = {} ",
            getAttributeShibboleth("Subject_CountryName", request));
    log.info("request.getAttribute(Subject_CommonName) = {} ",
            getAttributeShibboleth("Subject_CommonName", request));
    log.info("request.getAttribute(CertificateSerialNumber) = {} ",
            getAttributeShibboleth("CertificateSerialNumber", request));
    log.info("request.getAttribute(dateOfBirth) = {} ", getAttributeShibboleth("dateOfBirth", request));
    log.info("request.getAttribute(Subject_OrganisationName) = {} ",
            getAttributeShibboleth("Subject_OrganisationName", request));
    log.info("request.getAttribute(Issuer_OrganizationName) = {} ",
            getAttributeShibboleth("Issuer_OrganizationName", request));
    log.info("request.getAttribute(sn_type) = {} ", getAttributeShibboleth("sn_type", request));
    log.info("request.getAttribute(Subject_Surname) = {} ", getAttributeShibboleth("Subject_Surname", request));
    log.info("request.getAttribute(Subject_SerialNumber) = {} ",
            getAttributeShibboleth("Subject_SerialNumber", request));
    log.info("request.getAttribute(Gender) = ", getAttributeShibboleth("Gender", request));
    log.info("request.getAttribute(ValidationOcspResponse, request) = {} ",
            getAttributeShibboleth("ValidationOcspResponse", request));
    log.info("request.getAttribute(SecurityLevel) = {} ", getAttributeShibboleth("SecurityLevel", request));
    log.info("request.getAttribute(Issuer_CommonName) = {} ",
            getAttributeShibboleth("Issuer_CommonName", request));
    log.info("request.getAttribute(age) = {} ", getAttributeShibboleth("age", request));
    log.info("request.getAttribute(affiliation) = {} ", getAttributeShibboleth("affiliation", request));
    log.info("request.getAttribute(entitlement) = {} ", getAttributeShibboleth("entitlement", request));
    log.info("request.getAttribute(eppn) = {} ", getAttributeShibboleth("eppn", request));
    log.info("request.getAttribute(persistent-id) = {} ", getAttributeShibboleth("persistent-id", request));
    log.info("request.getAttribute(telephoneNumber) = {} ", getAttributeShibboleth("telephoneNumber", request));
    log.info("request.getAttribute(unscoped-affiliation) = {} ",
            getAttributeShibboleth("unscoped-affiliation", request));
    return result;
}

From source file:org.sakaiproject.dav.DavServlet.java

/**
 * Show HTTP header information.//w  ww .  ja va2 s. c  o  m
 */
@SuppressWarnings("unchecked")
protected void showRequestInfo(HttpServletRequest req) {

    if (M_log.isDebugEnabled())
        M_log.debug("DefaultServlet Request Info");

    // Show generic info
    if (M_log.isDebugEnabled())
        M_log.debug("Encoding : " + req.getCharacterEncoding());
    if (M_log.isDebugEnabled())
        M_log.debug("Length : " + req.getContentLength());
    if (M_log.isDebugEnabled())
        M_log.debug("Type : " + req.getContentType());

    if (M_log.isDebugEnabled())
        M_log.debug("Parameters");

    Enumeration parameters = req.getParameterNames();

    while (parameters.hasMoreElements()) {
        String paramName = (String) parameters.nextElement();
        String[] values = req.getParameterValues(paramName);
        System.out.print(paramName + " : ");
        for (int i = 0; i < values.length; i++) {
            System.out.print(values[i] + ", ");
        }
    }

    if (M_log.isDebugEnabled())
        M_log.debug("Protocol : " + req.getProtocol());
    if (M_log.isDebugEnabled())
        M_log.debug("Address : " + req.getRemoteAddr());
    if (M_log.isDebugEnabled())
        M_log.debug("Host : " + req.getRemoteHost());
    if (M_log.isDebugEnabled())
        M_log.debug("Scheme : " + req.getScheme());
    if (M_log.isDebugEnabled())
        M_log.debug("Server Name : " + req.getServerName());
    if (M_log.isDebugEnabled())
        M_log.debug("Server Port : " + req.getServerPort());

    if (M_log.isDebugEnabled())
        M_log.debug("Attributes");

    Enumeration attributes = req.getAttributeNames();

    while (attributes.hasMoreElements()) {
        String attributeName = (String) attributes.nextElement();
        System.out.print(attributeName + " : ");
        if (M_log.isDebugEnabled())
            M_log.debug(req.getAttribute(attributeName).toString());
    }

    // Show HTTP info
    if (M_log.isDebugEnabled())
        M_log.debug("HTTP Header Info");

    if (M_log.isDebugEnabled())
        M_log.debug("Authentication Type : " + req.getAuthType());
    if (M_log.isDebugEnabled())
        M_log.debug("HTTP Method : " + req.getMethod());
    if (M_log.isDebugEnabled())
        M_log.debug("Path Info : " + req.getPathInfo());
    if (M_log.isDebugEnabled())
        M_log.debug("Path translated : " + req.getPathTranslated());
    if (M_log.isDebugEnabled())
        M_log.debug("Query string : " + req.getQueryString());
    if (M_log.isDebugEnabled())
        M_log.debug("Remote user : " + req.getRemoteUser());
    if (M_log.isDebugEnabled())
        M_log.debug("Requested session id : " + req.getRequestedSessionId());
    if (M_log.isDebugEnabled())
        M_log.debug("Request URI : " + req.getRequestURI());
    if (M_log.isDebugEnabled())
        M_log.debug("Context path : " + req.getContextPath());
    if (M_log.isDebugEnabled())
        M_log.debug("Servlet path : " + req.getServletPath());
    if (M_log.isDebugEnabled())
        M_log.debug("User principal : " + req.getUserPrincipal());
    if (M_log.isDebugEnabled())
        M_log.debug("Headers : ");

    Enumeration headers = req.getHeaderNames();

    while (headers.hasMoreElements()) {
        String headerName = (String) headers.nextElement();
        System.out.print(headerName + " : ");
        if (M_log.isDebugEnabled())
            M_log.debug(req.getHeader(headerName));
    }
}

From source file:org.intermine.web.struts.QueryBuilderConstraintAction.java

/**
 * Method called when user has finished updating a constraint.
 *
 * @param mapping The ActionMapping used to select this instance
 * @param form The optional ActionForm bean for this request (if any)
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 * @return an ActionForward object defining where control goes next
 * @exception Exception if the application business logic throws an exception
 *//*w w w .  j a v a 2  s  .  co  m*/
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        @SuppressWarnings("unused") HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();
    //to prevent submit twice
    if (!isTokenValid(request)) {
        return mapping.findForward("query");
    }
    resetToken(request);
    PathQuery query = SessionMethods.getQuery(session);
    QueryBuilderConstraintForm constraintForm = (QueryBuilderConstraintForm) form;

    Path path = query.makePath(constraintForm.getPath());
    String rootPath = null;
    if (path.endIsAttribute()) {
        rootPath = path.getPrefix().toStringNoConstraints();
    } else {
        rootPath = path.toStringNoConstraints();
    }

    String joinType = constraintForm.getJoinType();

    String editingConstraintCode = constraintForm.getEditingConstraintCode();

    boolean constrainToAnAttribute = request.getParameter("attribute") != null;
    boolean constrainToABag = request.getParameter("bag") != null;
    boolean constrainToALoop = request.getParameter("loop") != null;
    boolean constrainToASubclass = request.getParameter("subclass") != null;
    boolean constrainToNull = request.getParameter("nullnotnull") != null;
    boolean editingTemplateConstraintParams = request.getParameter("template") != null;

    // Select the join style for the path in the query
    // If we set an outer join, then we need to take care of the consequences, like order by
    // and loop constraints
    if ((!StringUtils.isEmpty(joinType)) && (rootPath.contains("."))) {
        if ("outer".equals(joinType)) {
            query.setOuterJoinStatus(rootPath, OuterJoinStatus.OUTER);
            List<String> messages = query.fixUpForJoinStyle();
            for (String message : messages) {
                SessionMethods.recordMessage(message, session);
            }
        } else {
            query.setOuterJoinStatus(rootPath, null);
        }
    }

    PathConstraint oldConstraint = null;
    if (!StringUtils.isBlank(editingConstraintCode)) {
        oldConstraint = query.getConstraintForCode(editingConstraintCode);

        if (query instanceof TemplateQuery) {
            TemplateQuery template = (TemplateQuery) query;
            if (editingTemplateConstraintParams) {
                // We're just updating template settings
                template.setEditable(oldConstraint, constraintForm.isEditable());
                template.setConstraintDescription(oldConstraint, constraintForm.getTemplateLabel());

                String switchable = constraintForm.getSwitchable();
                if ("on".equals(switchable)) {
                    template.setSwitchOffAbility(oldConstraint, SwitchOffAbility.ON);
                } else if ("off".equals(switchable)) {
                    template.setSwitchOffAbility(oldConstraint, SwitchOffAbility.OFF);
                } else {
                    template.setSwitchOffAbility(oldConstraint, SwitchOffAbility.LOCKED);
                }
                constraintForm.reset(mapping, request);
                return mapping.findForward("query");
            }
        }
    }

    PathConstraint newConstraint = null;
    if (constrainToAnAttribute) {
        ConstraintOp constraintOp = ConstraintOp
                .getOpForIndex(Integer.valueOf(constraintForm.getAttributeOp()));
        String constraintValue = constraintForm.getAttributeValue();
        if (ConstraintOp.LOOKUP.equals(constraintOp)) {
            newConstraint = new PathConstraintLookup(constraintForm.getPath(), constraintValue,
                    constraintForm.getExtraValue());
        } else if (PathConstraintMultiValue.VALID_OPS.contains(constraintOp)) {
            String multiValues = constraintForm.getMultiValueAttribute();
            newConstraint = new PathConstraintMultiValue(constraintForm.getPath(), constraintOp,
                    Arrays.asList(multiValues.split(",")));
        } else {
            newConstraint = new PathConstraintAttribute(constraintForm.getPath(), constraintOp,
                    constraintValue);
        }
    } else if (constrainToABag) {
        ConstraintOp constraintOp = ConstraintOp.getOpForIndex(Integer.valueOf(constraintForm.getBagOp()));
        String constraintValue = constraintForm.getBagValue();
        // Note, we constrain the parent if the path is an attribute
        Path path1 = query.makePath(constraintForm.getPath());
        if (path1.endIsAttribute()) {
            path1 = path1.getPrefix();
        }
        newConstraint = new PathConstraintBag(path1.getNoConstraintsString(), constraintOp, constraintValue);
    } else if (constrainToALoop) {
        ConstraintOp constraintOp = ConstraintOp
                .getOpForIndex(Integer.valueOf(constraintForm.getLoopQueryOp()));
        String constraintValue = constraintForm.getLoopQueryValue();
        // Here, we trust the the jsp has already prevented us from creating a loop over an
        // outer join boundary.
        newConstraint = new PathConstraintLoop(constraintForm.getPath(), constraintOp, constraintValue);
    } else if (constrainToASubclass) {
        newConstraint = new PathConstraintSubclass(constraintForm.getPath(), constraintForm.getSubclassValue());
    } else if (constrainToNull) {
        if ("NotNULL".equals(constraintForm.getNullConstraint())) {
            newConstraint = Constraints.isNotNull(constraintForm.getPath());
        } else {
            newConstraint = Constraints.isNull(constraintForm.getPath());
        }
        // TODO: It doesn't make much sense to have a null constraint as the root of an outer
        // join group, but because the default join style is inner, we'll let the user shoot
        // themselves in the foot if they really know how to.
    } else if (constraintForm.getUseJoin() != null) {
        // already dealt with that
    } else {
        StringBuilder sb = new StringBuilder("attributes = {");
        boolean needComma = false;
        Enumeration<String> attNames = request.getAttributeNames();
        while (attNames.hasMoreElements()) {
            if (needComma) {
                sb.append(", ");
            }
            needComma = true;
            String attName = attNames.nextElement();
            sb.append(attName).append(" = ").append(request.getAttribute(attName));
        }
        sb.append("}, parameters = {");
        needComma = false;
        for (Map.Entry<String, String[]> param : ((Map<String, String[]>) request.getParameterMap())
                .entrySet()) {
            if (needComma) {
                sb.append(", ");
            }
            needComma = true;
            sb.append(param.getKey()).append(" = [");
            boolean needComma2 = false;
            for (String val : param.getValue()) {
                if (needComma2) {
                    sb.append(", ");
                }
                sb.append(val);
            }
            sb.append("]");
        }
        sb.append("}");
        throw new IllegalArgumentException("Unrecognised action: " + sb);
    }
    if (newConstraint != null) {
        if (oldConstraint != null) {
            // subclass constraints don't have a code but all other constraint types do
            if (oldConstraint instanceof PathConstraintSubclass
                    || newConstraint instanceof PathConstraintSubclass) {
                query.removeConstraint(oldConstraint);
                query.addConstraint(newConstraint);
            } else {
                query.replaceConstraint(oldConstraint, newConstraint);
            }
        } else {
            query.addConstraint(newConstraint);
        }
        if (query instanceof TemplateQuery && !(newConstraint instanceof PathConstraintSubclass)
                && !(newConstraint instanceof PathConstraintLoop)) {
            ((TemplateQuery) query).setEditable(newConstraint, true);
        }
    }

    constraintForm.reset(mapping, request);

    return mapping.findForward("query");
}

From source file:org.opensubsystems.core.util.servlet.WebUtils.java

/**
 * Create debug string containing all parameter names and their values from
 * the request, all attributes, all cookies and other data characterizing the
 * request./*  ww  w .j  av a2s  .  c  o  m*/
 *
 * @param  hsrqRequest - the servlet request.
 * @return String - debug string containing all parameter names and their
 *                  values from the request
 */
public static String debug(HttpServletRequest hsrqRequest) {
    Enumeration enumNames;
    Enumeration enumValues;
    Iterator iterValues;
    String strName;
    String[] arValues;
    Cookie[] arCookies;
    int iIndex;
    Map<String, String[]> mpParamMap;
    StringBuilder sbfReturn = new StringBuilder();

    sbfReturn.append("HttpServletRequest=[");
    sbfReturn.append("\nRemoteAddress=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteAddr()));
    sbfReturn.append(";");
    sbfReturn.append("\nRemotePort=");
    sbfReturn.append(hsrqRequest.getRemotePort());
    sbfReturn.append(";");
    sbfReturn.append("\nRemoteHost=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteHost()));
    sbfReturn.append(";");
    sbfReturn.append("\nRemoteUser=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteUser()));
    sbfReturn.append(";");
    sbfReturn.append("\nFullURL=");
    sbfReturn.append(getFullRequestURL(hsrqRequest));
    sbfReturn.append(";");
    sbfReturn.append("\nContextPath=");
    sbfReturn.append(hsrqRequest.getContextPath());
    sbfReturn.append(";");
    sbfReturn.append("\nServletPath=");
    sbfReturn.append(hsrqRequest.getServletPath());
    sbfReturn.append(";");
    sbfReturn.append("\nPathInfo =");
    sbfReturn.append(hsrqRequest.getPathInfo());
    sbfReturn.append(";");
    sbfReturn.append("\nRequestURI=");
    sbfReturn.append(hsrqRequest.getRequestURI());
    sbfReturn.append(";");
    sbfReturn.append("\nRequestURL=");
    sbfReturn.append(hsrqRequest.getRequestURL());
    sbfReturn.append(";");
    sbfReturn.append("\nMethod=");
    sbfReturn.append(hsrqRequest.getMethod());
    sbfReturn.append(";");
    sbfReturn.append("\nAuthenticationType=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getAuthType()));
    sbfReturn.append(";");
    sbfReturn.append("\nCharacterEncoding=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getCharacterEncoding()));
    sbfReturn.append(";");
    sbfReturn.append("\nContentType=");
    sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getContentType()));
    sbfReturn.append(";");
    sbfReturn.append("\nMultiPart=");
    sbfReturn.append(ServletFileUpload.isMultipartContent(hsrqRequest));
    sbfReturn.append(";");

    // Parameters ////////////////////////////////////////////////////////////

    try {
        Map.Entry<String, String[]> entry;

        // Use getParameterMap rather than request.getParameterNames since it 
        // correctly handles multipart requests
        mpParamMap = WebParamUtils.getParameterMap("WebUtils: ", hsrqRequest);
        for (iterValues = mpParamMap.entrySet().iterator(); iterValues.hasNext();) {
            entry = (Map.Entry<String, String[]>) iterValues.next();
            strName = entry.getKey();
            arValues = entry.getValue();
            sbfReturn.append("\nParam=");
            sbfReturn.append(strName);
            sbfReturn.append(" values=");
            for (iIndex = 0; iIndex < arValues.length; iIndex++) {
                sbfReturn.append(arValues[iIndex]);
                if (iIndex < (arValues.length - 1)) {
                    sbfReturn.append(";");
                }
            }
            if (iterValues.hasNext()) {
                sbfReturn.append(";");
            }
        }
    } catch (OSSInvalidDataException ex) {
        sbfReturn.append("<Cannot access parameter map of the request>");
        s_logger.log(Level.SEVERE, "Cannot access parameter map of the request", ex);
    }

    // Uploaded files ////////////////////////////////////////////////////////

    if (ServletFileUpload.isMultipartContent(hsrqRequest)) {
        try {
            FileItem item;
            Map<String, FileItem> mpFiles;
            TwoElementStruct<Map<String, Object>, Map<String, FileItem>> params;

            params = WebParamUtils.getMultipartParameters("WebUtils: ", hsrqRequest);
            mpFiles = params.getSecond();

            for (iterValues = mpFiles.values().iterator(); iterValues.hasNext();) {
                item = (FileItem) iterValues.next();
                sbfReturn.append("\nUpload=");
                sbfReturn.append(item.getName());
                sbfReturn.append(" field=");
                sbfReturn.append(item.getFieldName());
                sbfReturn.append(" contentType=");
                sbfReturn.append(item.getContentType());
                sbfReturn.append(" isInMemory=");
                sbfReturn.append(item.isInMemory());
                sbfReturn.append(" sizeInBytes=");
                sbfReturn.append(item.getSize());
                if (iterValues.hasNext()) {
                    sbfReturn.append(";");
                }
            }
        } catch (OSSInvalidDataException ex) {
            sbfReturn.append("<Cannot access list of multipart parameters>");
            s_logger.log(Level.SEVERE, "Cannot access list of multipart parameters", ex);
        }
    }

    // Headers ///////////////////////////////////////////////////////////////

    for (enumNames = hsrqRequest.getHeaderNames(); enumNames.hasMoreElements();) {
        strName = (String) enumNames.nextElement();
        sbfReturn.append("\nHeader=");
        sbfReturn.append(strName);
        sbfReturn.append(" values=");
        for (enumValues = hsrqRequest.getHeaders(strName); enumValues.hasMoreElements();) {
            sbfReturn.append(enumValues.nextElement());
            if (enumValues.hasMoreElements()) {
                sbfReturn.append(";");
            }
        }
        if (enumNames.hasMoreElements()) {
            sbfReturn.append(";");
        }
    }

    // Cookies ///////////////////////////////////////////////////////////////

    arCookies = hsrqRequest.getCookies();
    if (arCookies != null) {
        Cookie cookie;

        for (iIndex = 0; iIndex < arCookies.length; iIndex++) {
            cookie = arCookies[iIndex];
            sbfReturn.append("\nCookie=");
            sbfReturn.append(cookie.getName());
            sbfReturn.append(" path=");
            sbfReturn.append(cookie.getPath());
            sbfReturn.append(" path=");
            sbfReturn.append(cookie.getDomain());
            sbfReturn.append(" maxage=");
            sbfReturn.append(cookie.getMaxAge());
            sbfReturn.append(" version=");
            sbfReturn.append(cookie.getVersion());
            sbfReturn.append(" secure=");
            sbfReturn.append(cookie.getSecure());
            sbfReturn.append(" value=");
            sbfReturn.append(cookie.getValue());
            sbfReturn.append(" comment=");
            sbfReturn.append(StringUtils.valueIfNotNull(cookie.getComment()));
            if (iIndex < (arCookies.length - 1)) {
                sbfReturn.append(";");
            }
        }
    }
    if (enumNames.hasMoreElements()) {
        sbfReturn.append(";");
    }

    // Attributes ////////////////////////////////////////////////////////////

    for (enumNames = hsrqRequest.getAttributeNames(); enumNames.hasMoreElements();) {
        strName = (String) enumNames.nextElement();
        sbfReturn.append("\nAttribute=");
        sbfReturn.append(strName);
        sbfReturn.append(" value=");
        sbfReturn.append(hsrqRequest.getAttribute(strName));
        if (enumNames.hasMoreElements()) {
            sbfReturn.append(";");
        }
    }

    // Content ///////////////////////////////////////////////////////////////

    sbfReturn.append("\nContent=");
    try {
        sbfReturn.append(StringUtils.convertStreamToString(hsrqRequest.getInputStream(), true));
    } catch (IOException ex) {
        sbfReturn.append("<Cannot access input stream of the request>");
        s_logger.log(Level.SEVERE, "Cannot access input stream of the request", ex);
    }
    sbfReturn.append(";");

    return sbfReturn.toString();
}

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  ww  .  ja  v a 2 s .  com*/
            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();

}

From source file:org.openqa.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 ww .j a va2 s  .co 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();

}

From source file:org.protorabbit.servlet.ProtoRabbitServlet.java

@SuppressWarnings("unchecked")
@Override/*from   w  ww .j a v a2 s .co m*/
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    WebContext wc = null;
    int bytesServed = 0;
    long iStartTime = System.currentTimeMillis();
    String path = req.getServletPath();
    String pathInfo = req.getPathInfo();
    String clientId = req.getRemoteAddr();
    try {

        String command = req.getParameter("command");
        if (command != null) {
            if ("ping".equals(command)) {
                resp.setHeader("pragma", "NO-CACHE");
                resp.setHeader("Cache-Control", "no-cache");
                resp.getWriter().write((new Date()).getTime() + "");
                return;
            } else if ("timeshift".equals(command)) {
                long clientTime = Long.parseLong(req.getParameter("clientTime"));
                resp.setHeader("pragma", "NO-CACHE");
                resp.setHeader("Cache-Control", "no-cache");
                long timeShift = ((new Date()).getTime() - clientTime);
                resp.getWriter().write("timeshift=" + timeShift + ";");
                return;
            } else if ("episodesync".equals(command)) {
                long startTime = Long.parseLong(req.getParameter("timestamp"));
                long transitTime = Long.parseLong(req.getParameter("transitTime"));
                Episode e = jcfg.getEpisodeManager().getEpisode(clientId, startTime);
                if (e == null) {
                    return;
                }
                e.setTransitTime(transitTime);
                Mark m = e.getMark("transit_to");
                long transitStartTime = m.getStartTime();
                long now = (new Date()).getTime();
                long duration = (now - (transitStartTime + transitTime));
                // add the page load directly following the start time  (add 1 to always make sure it is after transit time)
                e.addMark(new Mark("page_load", transitStartTime + transitTime + 1));
                Measure m1 = new Measure("transit_to", transitTime);
                // include transit time for this request and intial page load
                Measure m2 = new Measure("page_load", (duration + transitTime));
                e.addMeasure("transit_to", m1);
                e.addMeasure("page_load", m2);
                // now - duration is assumed transit time to offset call to this command
                resp.getWriter().write("var t_firstbyte=new Number(new Date());"
                        + "window.postMessage(\"EPISODES:mark:firstbyte:\" + t_firstbyte, \"*\");");
                return;
            } else if ("stats".equals(command)) {

                Map<String, Object> stats = new HashMap<String, Object>();
                stats.put("cachedResources", jcfg.getCombinedResourceManager().getResources());
                stats.put("templates", jcfg.getTemplates());
                stats.put("includeFiles", jcfg.getIncludeFiles());
                if (json == null) {
                    SerializationFactory factory = new SerializationFactory();
                    json = factory.getInstance();
                }
                resp.setHeader("pragma", "NO-CACHE");
                resp.setHeader("Cache-Control", "no-cache");
                Object jo = json.serialize(stats);
                resp.getWriter().write(jo.toString());
                return;
            } else if ("recordProfile".equals(command)) {

                long startTime = Long.parseLong(req.getParameter("timestamp"));
                long timeshift = Long.parseLong(req.getParameter("timeshift"));
                long timestamp = (new Date()).getTime();
                long duration = timestamp - startTime;
                Episode e = jcfg.getEpisodeManager().getEpisode(clientId, startTime);
                if (e == null) {
                    getLogger().severe("Unable to find episode " + startTime
                            + " to recourd data into with client " + clientId);
                    return;
                }
                e.setTimeshift(timeshift);
                // make sure to account for transit time
                Measure m = new Measure("full_request", duration - e.getTransitTime());
                e.addMeasure("full_request", m);
                String data = req.getParameter("data");
                JSONObject jo = null;
                try {
                    jo = new JSONObject(data);
                    jcfg.getEpisodeManager().updateEpisode(clientId, startTime, jo);
                } catch (JSONException ex) {
                    ex.printStackTrace();
                }
                resp.getWriter().write("ok");
                return;
            } else if ("episodes".equals(command)) {
                if (json == null) {
                    SerializationFactory factory = new SerializationFactory();
                    json = factory.getInstance();
                }
                Object data = null;
                data = jcfg.getEpisodeManager().getEpisodes();
                resp.setHeader("pragma", "NO-CACHE");
                resp.setHeader("Cache-Control", "no-cache");
                Object jo = json.serialize(data);
                resp.getWriter().write(jo.toString());
                return;
            } else if ("version".equals(command)) {
                resp.getWriter().write(version);
                return;
            } else if ("resetProfiles".equals(command)) {
                jcfg.getEpisodeManager().reset();
                resp.getWriter().write("profiles reset");
                return;
            } else if ("startProfiling".equals(command)) {
                jcfg.setProfile(true);
                resp.getWriter().write("profiling enabled");
                return;
            } else if ("stopProfiling".equals(command)) {
                jcfg.setProfile(false);
                resp.getWriter().write("profiling disabled");
                return;
            }
        } else if (pathInfo != null) {
            for (String t : writeHeaders) {
                if (pathInfo.endsWith(t)) {
                    writeHeaders(req, resp, pathInfo);
                    return;
                }
            }
        }

        // check for updates to the templates.json file
        if (isDevMode) {
            updateConfig();
        }
        boolean canGzip = false;
        // check if client supports gzip
        Enumeration<String> hnum = req.getHeaders("Accept-Encoding");
        while (hnum.hasMoreElements()) {
            String acceptType = hnum.nextElement();
            if (acceptType != null && acceptType.indexOf("gzip") != -1) {
                canGzip = true;
                break;
            }
        }
        wc = new WebContext(jcfg, ctx, req, resp);
        wc.setAttribute(Config.START_TIME, new Long(new Date().getTime()));
        String id = req.getParameter("resourceid");
        if (id != null) {
            processResourceRequest(id, wc, req, resp, canGzip);
            return;
        }

        if (("/" + serviceURI).equals(path)) {
            path = req.getPathInfo();
        }
        int lastSep = -1;
        if (path != null) {
            lastSep = path.lastIndexOf("/");
        }
        String namespace = null;
        if (lastSep != -1 && lastSep < path.length() - 1) {
            int nextDot = path.indexOf(".", lastSep + 1);
            int lastSlash = path.lastIndexOf("/");
            if (nextDot != -1) {
                id = path.substring(lastSep + 1, nextDot);
            } else {
                if (lastSlash != -1 && lastSlash < path.length()) {
                    id = path.substring(lastSlash + 1);
                }
            }
            if (lastSlash != -1 && lastSlash < path.length()) {
                namespace = path.substring(0, lastSlash);
            }
        }
        ITemplate t = null;

        if (id != null) {
            t = jcfg.getTemplate(id, wc);

            if (jcfg.profile()) {
                long timestamp = (new Date()).getTime();
                Episode e = new Episode(timestamp);
                e.setUserAgent(req.getHeader("user-agent"));
                e.setClientId(clientId);
                e.setUri(id);
                e.addMark(new Mark("full_request", timestamp));
                e.addMark(new Mark("server_render", timestamp));
                wc.setAttribute(Config.EPISODE, e);
                wc.setAttribute(Config.DEFAULT_EPISODE_PROCESS, new Boolean(true));
                jcfg.getEpisodeManager().addEpisode(e);
            }
        }
        // make sure that if a namespace is required that is is used to access the template. Also account for "" which can 
        // result from the namespace.
        boolean namespaceOk = true;
        if (t != null && t.getURINamespace(wc) != null) {
            if (namespace == null || (namespace != null && "".equals(namespace))
                    || !t.getURINamespace(wc).startsWith(namespace)) {
                namespaceOk = false;
                getLogger().warning(
                        "request for template " + id + " without matching namespace " + t.getURINamespace(wc));
            }
        }

        if (id == null || t == null || !namespaceOk) {
            getLogger().warning("template " + id + " requested but not found.");
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        // set the template engine
        IEngine renderEngine = null;
        if (t.getTemplateURI(wc).getFullURI().endsWith(".st")) {
            renderEngine = new StringTemplateEngine();
            // build up a list of the session/reqeust attributes for string tempalte
            Map<String, Object> sessionMap = new HashMap<String, Object>();
            HttpSession hs = req.getSession();
            Enumeration en = hs.getAttributeNames();
            while (en.hasMoreElements()) {
                String key = (String) en.nextElement();
                sessionMap.put(key, hs.getAttribute(key));
            }
            Map<String, Object> requestMap = new HashMap<String, Object>();
            Enumeration ren = req.getAttributeNames();
            while (ren.hasMoreElements()) {
                String key = (String) en.nextElement();
                requestMap.put(key, req.getAttribute(key));
            }
            wc.setAttribute("session", sessionMap);
            req.getSession().setAttribute("protorabbitVersion", version);
            req.getSession().setAttribute("protorabbitBuildDate", buildDate);
            wc.setAttribute("request", requestMap);
        } else {
            renderEngine = engine;
        }
        // buffer the output stream
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        ICacheable tr = t.getTemplateResource();
        resp.setHeader("Content-Type", "text/html");
        if (jcfg.profile()) {
            resp.setHeader("pragma", "NO-CACHE");
            resp.setHeader("Cache-Control", "no-cache");
        }

        // get the initial content or get the content if it is expired
        if ((t.getTimeout(wc) != null && (t.getTimeout(wc) > 0)
                && ((tr == null || tr.getCacheContext().isExpired()) || t.requiresRefresh(wc) || jcfg.profile()
                        || t.hasUserAgentPropertyDependencies(wc)))) {
            if (canGzip && t.gzipTemplate(wc) != null && t.gzipTemplate(wc) == true) {
                resp.setHeader("Vary", "Accept-Encoding");
                resp.setHeader("Content-Encoding", "gzip");
            }
            // headers after this point do not get written
            renderEngine.renderTemplate(id, wc, bos);

            String content = bos.toString(jcfg.getEncoding());
            String hash = IOUtil.generateHash(content);
            ICacheable cr = new CacheableResource("text/html", t.getTimeout(wc), hash);

            if (!jcfg.profile()) {
                resp.setHeader("ETag", cr.getContentHash());
            }
            cr.setContent(new StringBuffer(content));
            t.setTemplateResource(cr);

            if (canGzip && t.gzipTemplate(wc) != null && t.gzipTemplate(wc) == true) {
                byte[] bytes = cr.getGZippedContent();
                cr.incrementGzipAccessCount();
                resp.setContentLength(bytes.length);
                OutputStream out = resp.getOutputStream();
                if (bytes != null) {
                    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
                    bytesServed = bytes.length;
                    IOUtil.writeBinaryResource(bis, out);
                }
            } else {
                OutputStream out = resp.getOutputStream();
                byte[] bytes = cr.getContent().toString().getBytes();
                cr.incrementAccessCount();
                resp.setContentLength(bytes.length);
                bytesServed = bytes.length;
                if (bytes != null) {
                    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
                    IOUtil.writeBinaryResource(bis, out);
                }
            }

            // write out content / gzip or otherwise from the cache
        } else if (t.getTimeout(wc) != null && t.getTimeout(wc) > 0 && tr != null) {

            // if the client has the same resource as the one on the server return a 304
            // get the If-None-Match header
            String etag = tr.getContentHash();

            String ifNoneMatch = req.getHeader("If-None-Match");
            if (etag != null && ifNoneMatch != null && ifNoneMatch.equals(etag)) {
                resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                if (jcfg.profile()) {
                    profile(wc);
                }
                return;
            }

            resp.setContentType(tr.getContentType());
            if (!jcfg.profile()) {
                resp.setHeader("ETag", etag);
                resp.setHeader("Expires", tr.getCacheContext().getExpires());
                resp.setHeader("Cache-Control", "public,max-age=" + tr.getCacheContext().getMaxAge());
            }

            if (canGzip && t.gzipTemplate(wc) != null && t.gzipTemplate(wc) == true) {

                OutputStream out = resp.getOutputStream();
                resp.setHeader("Content-Encoding", "gzip");
                resp.setHeader("Vary", "Accept-Encoding");

                tr.incrementGzipAccessCount();
                byte[] bytes = tr.getGZippedContent();

                if (bytes != null) {
                    resp.setContentLength(bytes.length);
                    bytesServed = bytes.length;
                    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
                    IOUtil.writeBinaryResource(bis, out);
                }
            } else {

                OutputStream out = resp.getOutputStream();
                tr.incrementAccessCount();
                byte[] bytes = tr.getContent().toString().getBytes();
                resp.setContentLength(bytes.length);
                if (bytes != null) {
                    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
                    bytesServed = bytes.length;
                    IOUtil.writeBinaryResource(bis, out);
                }
            }

        } else {
            OutputStream out = resp.getOutputStream();
            //  t.getTemplateResource().incrementAccessCount();
            renderEngine.renderTemplate(id, wc, bos);
            bytesServed = bos.size();
            out.write(bos.toByteArray());
        }
        // increment the total template accesses
        if (t != null) {
            t.incrementAccessCount();
        }
        if (jcfg.profile()) {
            profile(wc);
        }

    } catch (java.net.SocketException jos) {
        logger.warning("Got broken pipe. Ignoring...");
        return;
    } finally {
        if (wc != null) {
            wc.destroy();
        }
    }

    long endTime = System.currentTimeMillis();
    // add more stats stuff
    IStat stat = new StatsItem();
    stat.setTimestamp(System.currentTimeMillis());
    stat.setPath(path);
    stat.setPathInfo(pathInfo);
    stat.setRemoteClient(cg.getClientId(req));
    stat.setType(StatsItem.types.VIEW);
    stat.setRequestURI(req.getRequestURI());
    stat.setProcessTime(new Long(endTime - iStartTime));
    stat.setContentLength(new Long(bytesServed));
    stat.setContentType("text/html");
    statsManager.add(stat);

}