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.kuali.kra.web.filter.RequestLoggingFilter.java

/**
 * Constructs a log message that displays attribute information belonging to the given
 * {@link HttpServletRequest} instance. 
 *
 * @param request/* ww  w .ja  v  a 2s .  co m*/
 * @return Log message
 */
private String getRequestAttributesMessage(HttpServletRequest request) {
    StringBuilder retval = new StringBuilder();
    for (Enumeration<String> attributeNames = request.getAttributeNames(); attributeNames.hasMoreElements();) {
        String attributeName = attributeNames.nextElement();
        retval.append(attributeName).append(": ").append(request.getAttribute(attributeName)).append("\n")
                .toString();
    }

    return retval.toString();
}

From source file:org.talframework.tal.aspects.loggers.http.DefaultRequestLogger.java

/**
 * Helper to log out the request attributes at trace level
 * /*  w w  w .j  av  a  2s .  c  o m*/
 * @param req The request
 * @param logger The logger
 */
@SuppressWarnings("unchecked")
private void logRequestAttributes(HttpServletRequest req, Log logger) {
    StringBuilder buf = new StringBuilder();
    buf.append("Request Attributes: ");
    buf.append("\n\t**** Request Attributes ****");
    Enumeration e = req.getAttributeNames();
    while (e.hasMoreElements()) {
        String k = (String) e.nextElement();
        buf.append("\n\t").append(k).append("=").append(LoggerHelper.getValue(req.getAttribute(k)));
    }
    buf.append("\n\t**** End Request Attrobites ****");
    logger.trace(buf.toString());
}

From source file:rapture.server.web.servlet.BaseReflexScriptPageServlet.java

private Map<String, Object> getHeaderAttributes(HttpServletRequest req) {
    Map<String, Object> variables = new HashMap<String, Object>();
    Enumeration<String> vars = req.getAttributeNames();
    while (vars.hasMoreElements()) {
        String attrName = vars.nextElement();
        variables.put(attrName, req.getAttribute(attrName));
    }/*  ww w .j  a  va 2s . co m*/
    return variables;
}

From source file:org.frat.common.security.authc.SessionTimeoutAuthenticationFilter.java

@Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
        ServletResponse response) throws Exception { // NOSONAR
    HttpServletRequest req = (HttpServletRequest) request;
    LOGGER.info("{} login complete, session ID: {} ", subject.getPrincipal(), subject.getSession().getId());
    StringBuilder sb = new StringBuilder();
    Enumeration<?> attriNames = req.getAttributeNames();
    while (attriNames.hasMoreElements()) {
        String attriName = (String) attriNames.nextElement();
        sb.append("[").append(attriName).append("=").append(req.getAttribute(attriName)).append("]");
    }/*  w  ww . j  av a2 s.c om*/
    LOGGER.info("session attributes: {}", sb);
    return super.onLoginSuccess(token, subject, request, response);
}

From source file:org.sakaiproject.vm.VelocityServlet.java

/**
 * <p>/*from  w  ww.ja v  a2 s. co  m*/
 * main routine to handle a request. Called by VelocityServlet, your responsibility as programmer is to simply return a valid Template
 * </p>
 * 
 * @param ctx
 *        a Velocity Context object to be filled with data. Will be used for rendering this template
 * @return Template to be used for request
 */
public Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context ctx) {
    // Note: Velocity doesn't like dots in the context names, so we change them to '_'

    // load the context with attributes
    Enumeration e = request.getAttributeNames();
    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        String vName = escapeVmName(name);
        Object value = request.getAttribute(name);

        ctx.put(vName, value);
        // log("--> context (attribute): " + vName + " = " + value);
    }

    // if the javax.servlet.include.servlet_path attribute exists, use this value as the template
    String templatePath = (String) request.getAttribute("javax.servlet.include.servlet_path");

    // if not there, try our special include
    if (templatePath == null) {
        templatePath = (String) request.getAttribute("sakai.vm.path");
    }

    // if not there, use the servletpath
    if (templatePath == null) {
        templatePath = request.getServletPath();
    }

    Template template = null;
    try {
        // log("--> template path: " + templatePath);
        template = getTemplate(templatePath);
    } catch (ParseErrorException ex) {
        log("Exception reading vm template: " + templatePath + " " + ex);
    } catch (ResourceNotFoundException ex) {
        log("Exception reading vm template: " + templatePath + " " + ex);
    } catch (Exception ex) {
        log("Exception reading vm template: " + templatePath + " " + ex);
    }

    return template;

}

From source file:org.apache.openaz.xacml.rest.XACMLRest.java

/**
 * Helper routine to dump the HTTP servlet request being serviced. Primarily for debugging.
 *
 * @param request - Servlet request (from a POST/GET/PUT/etc.)
 *///from  w  w w.j ava2s  .  c  om
public static void dumpRequest(HttpServletRequest request) {
    if (logger.isDebugEnabled()) {
        // special-case for receiving heartbeat - don't need to repeatedly output all of the information
        // in multiple lines
        if (request.getMethod().equals("GET") && "hb".equals(request.getParameter("type"))) {
            logger.debug("GET type=hb : heartbeat received");
            return;
        }
        logger.debug(request.getMethod() + ":" + request.getRemoteAddr() + " " + request.getRemoteHost() + " "
                + request.getRemotePort());
        logger.debug(request.getLocalAddr() + " " + request.getLocalName() + " " + request.getLocalPort());
        Enumeration<String> en = request.getHeaderNames();
        logger.debug("Headers:");
        while (en.hasMoreElements()) {
            String element = en.nextElement();
            Enumeration<String> values = request.getHeaders(element);
            while (values.hasMoreElements()) {
                String value = values.nextElement();
                logger.debug(element + ":" + value);
            }
        }
        logger.debug("Attributes:");
        en = request.getAttributeNames();
        while (en.hasMoreElements()) {
            String element = en.nextElement();
            logger.debug(element + ":" + request.getAttribute(element));
        }
        logger.debug("ContextPath: " + request.getContextPath());
        if (request.getMethod().equals("PUT") || request.getMethod().equals("POST")) {
            // POST and PUT are allowed to have parameters in the content, but in our usage the parameters
            // are always in the Query string.
            // More importantly, there are cases where the POST and PUT content is NOT parameters (e.g. it
            // might contain a Policy file).
            // Unfortunately the request.getParameterMap method reads the content to see if there are any
            // parameters,
            // and once the content is read it cannot be read again.
            // Thus for PUT and POST we must avoid reading the content here so that the main code can read
            // it.
            logger.debug("Query String:" + request.getQueryString());
            try {
                if (request.getInputStream() == null) {
                    logger.debug("Content: No content inputStream");
                } else {
                    logger.debug("Content available: " + request.getInputStream().available());
                }
            } catch (Exception e) {
                logger.debug("Content: inputStream exception: " + e.getMessage() + ";  (May not be relevant)");
            }
        } else {
            logger.debug("Parameters:");
            Map<String, String[]> params = request.getParameterMap();
            Set<String> keys = params.keySet();
            for (String key : keys) {
                String[] values = params.get(key);
                logger.debug(key + "(" + values.length + "): " + (values.length > 0 ? values[0] : ""));
            }
        }
        logger.debug("Request URL:" + request.getRequestURL());
    }
}

From source file:org.topazproject.ambra.auth.web.UsernameReplacementWithGuidFilter.java

private void dumpRequest(final HttpServletRequest request, final String prefix) {
    log.debug(prefix + "----------------" + System.currentTimeMillis());
    log.debug("url:" + request.getRequestURL());
    log.debug("query string:" + request.getQueryString());

    log.debug("Request Attributes:");
    final Enumeration attribs = request.getAttributeNames();
    while (attribs.hasMoreElements()) {
        final String attribName = (String) attribs.nextElement();
        log.debug(attribName + ":" + request.getAttribute(attribName).toString());
    }//from   ww  w.  j  a v a  2s  .com

    log.debug("Request Parameters:");
    final Enumeration params = request.getParameterNames();
    while (params.hasMoreElements()) {
        final String paramName = (String) params.nextElement();
        log.debug(paramName + ":" + Arrays.toString(request.getParameterValues(paramName)));
    }
}

From source file:com.qwazr.library.freemarker.FreeMarkerTool.java

public void template(final String templatePath, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, TemplateException {
    final Map<String, Object> variables = new HashMap<>();
    variables.put("request", request);
    variables.put("session", request.getSession());
    final Enumeration<String> attrNames = request.getAttributeNames();
    if (attrNames != null) {
        while (attrNames.hasMoreElements()) {
            final String attrName = attrNames.nextElement();
            variables.put(attrName, request.getAttribute(attrName));
        }/*  w  ww.j a va2  s  .  co  m*/
    }
    template(templatePath, variables, response);
}

From source file:net.solarnetwork.web.support.JSONView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    PropertyEditorRegistrar registrar = this.propertyEditorRegistrar;
    Enumeration<String> attrEnum = request.getAttributeNames();
    while (attrEnum.hasMoreElements()) {
        String key = attrEnum.nextElement();
        Object val = request.getAttribute(key);
        if (val instanceof PropertyEditorRegistrar) {
            registrar = (PropertyEditorRegistrar) val;
            break;
        }//w w  w . j  a v  a2s .c  o  m
    }

    response.setCharacterEncoding(UTF8_CHAR_ENCODING);
    response.setContentType(getContentType());
    Writer writer = response.getWriter();
    if (this.includeParentheses) {
        writer.write('(');
    }
    JsonGenerator json = new JsonFactory().createGenerator(writer);
    json.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
    if (indentAmount > 0) {
        json.useDefaultPrettyPrinter();
    }
    json.writeStartObject();
    for (String key : model.keySet()) {
        Object val = model.get(key);
        writeJsonValue(json, key, val, registrar);
    }
    json.writeEndObject();
    json.close();
    if (this.includeParentheses) {
        writer.write(')');
    }
}

From source file:org.wso2.carbon.identity.oidc.dcr.factory.OIDCRegistrationRequestFactoryTest.java

@Test(dataProvider = "OIDCRequestBuilderCreationData")
public void testCreate(String request, String sectorIdUrl, String subjectType, String tokenSignAlg,
        String tokenEncrAlg, String tokenEncrEnc, String userInfoRespSignAlg, String userInfoRespEncrAlg,
        String userInfoRespEnceEnc, String reqObjSignAlg, String reqObjEncrAlg, String reqObjEncrEnc,
        String tokenEPAuthSignAlg, String defaultMaxAge, String requireAuthTime, String defaultAcrValues,
        String initLoginUrl, List<String> requestUris) throws Exception {
    HttpServletRequest mockRequest = mock(HttpServletRequest.class);
    HttpServletResponse mockResponse = mock(HttpServletResponse.class);
    when(mockRequest.getReader()).thenReturn(new BufferedReader(new StringReader(request)));
    when(mockRequest.getHeaderNames()).thenReturn(Collections.<String>emptyEnumeration());
    when(mockRequest.getAttributeNames()).thenReturn(Collections.<String>emptyEnumeration());

    OIDCRegistrationRequest.OIDCRegistrationRequestBuilder requestBuilder = testedRegistrationRequestFactory
            .create(mockRequest, mockResponse);
    RegistrationRequest registrationRequest = requestBuilder.build();
    RegistrationRequestProfile requestProfile = registrationRequest.getRegistrationRequestProfile();
    assertTrue(requestProfile instanceof OIDCRegistrationRequestProfile,
            "Request profile should be an instance " + "of OIDCRegistrationRequestProfile");
    OIDCRegistrationRequestProfile oidcRegRequestProfile = (OIDCRegistrationRequestProfile) requestProfile;

    assertEquals(requestBuilder.getRequest(), mockRequest, "Builder should have the provided request.");
    assertEquals(requestBuilder.getResponse(), mockResponse, "Builder should have the provided response.");
    assertEquals(oidcRegRequestProfile.getSectorIdentifierUri(), sectorIdUrl, "Invalid Sector Id URL");
    assertEquals(oidcRegRequestProfile.getSubjectType(), subjectType, "Invalid subject type");
    assertEquals(oidcRegRequestProfile.getIdTokenSignedResponseAlg(), tokenSignAlg,
            "Invalid token sign " + "algorithm");
    assertEquals(oidcRegRequestProfile.getIdTokenEncryptedResponseAlg(), tokenEncrAlg,
            "Invalid token encryption" + " alg");
    assertEquals(oidcRegRequestProfile.getIdTokenEncryptedResponseEnc(), tokenEncrEnc,
            "Invalid token encryption" + " enc");
    assertEquals(oidcRegRequestProfile.getUserinfoSignedResponseAlg(), userInfoRespSignAlg,
            "Invalid userinfo " + "response sign alg");
    assertEquals(oidcRegRequestProfile.getUserinfoencryptedResponseAlg(), userInfoRespEncrAlg,
            "Invalid userinfo " + "response encr alg");
    assertEquals(oidcRegRequestProfile.getUserinfoEncryptedResponseEnc(), userInfoRespEnceEnc,
            "Invalid userinfo " + "response encr enc");
    assertEquals(oidcRegRequestProfile.getRequestObjectSigningAlg(), reqObjSignAlg,
            "Invalid request obj sign " + "alg");
    assertEquals(oidcRegRequestProfile.getRequestObjectEncryptionAlg(), reqObjEncrAlg,
            "Invalid request obj encr" + " alg");
    assertEquals(oidcRegRequestProfile.getRequestObjectEncryptionEnc(), reqObjEncrEnc,
            "Invalid request obj encr" + " enc");
    assertEquals(oidcRegRequestProfile.getTokenEndpointAuthSigningAlg(), tokenEPAuthSignAlg,
            "Invalid token " + "endpoint auth response alg.");
    assertEquals(oidcRegRequestProfile.getDefaultMaxAge(), defaultMaxAge, "Invalid default max age");
    assertEquals(oidcRegRequestProfile.getRequireAuthTime(), requireAuthTime, "Invalid require auth time");
    assertEquals(oidcRegRequestProfile.getDefaultAcrValues(), defaultAcrValues, "Invalid default acr values");
    assertEquals(oidcRegRequestProfile.getInitiateLoginUri(), initLoginUrl, "Invalid initiate login uri");
    assertTrue(CollectionUtils.isEqualCollection(oidcRegRequestProfile.getRequestUris(), requestUris),
            "Invalid " + "request URLs ");
}