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:com.glaf.report.web.springmvc.MxReportController.java

@ResponseBody
@RequestMapping("/xls")
public void xls(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String reportId = request.getParameter("reportId");
    if (StringUtils.isNotEmpty(reportId)) {
        LoginContext loginContext = RequestUtils.getLoginContext(request);

        Map<String, Object> params = RequestUtils.getParameterMap(request);

        java.util.Enumeration<?> e = request.getAttributeNames();
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            params.put(name, request.getAttribute(name));
        }/* www  . ja  v  a2 s .  com*/

        Workbook wb = JxlsReportContainer.getContainer().execute(reportId, loginContext.getActorId(), params);
        if (wb != null) {
            String contentDisposition = "attachment;filename=\"export.xls\"";
            response.setHeader("Content-Transfer-Encoding", "base64");
            response.setHeader("Content-Disposition", contentDisposition);
            response.setContentType("application/octet-stream");
            java.io.OutputStream outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
            outputStream = null;
            wb = null;
        }
    }
}

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

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

    attributes = new HashMap();
    Enumeration attributeNames = initialRequest.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
        String name = (String) attributeNames.nextElement();
        Object attribute = initialRequest.getAttribute(name);
        if ((null != name) && (null != attribute)) {
            attributes.put(name, attribute);
        }//from   w ww . jav a 2  s  . c o  m
    }

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

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

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

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

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

From source file:org.apache.hadoop.fs.webdav.WebdavServlet.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.info("/--------------------------------------------------");
    log.debug(request.getMethod() + " " + request.getRequestURL().toString());
    log.info(request.getMethod() + " " + request.getRequestURL().toString());
    log.info(request.getMethod() + " " + request.getRequestURI().toString());

    log.info("  RemoteHost: " + request.getRemoteHost());
    log.info("| ATTRIBUTES: ");
    Enumeration e1 = request.getAttributeNames();
    while (e1.hasMoreElements()) {
        String name = (String) e1.nextElement();
        log.info("|| " + name + ": ");
    }//from w w  w  .  j  av a 2s.  c om

    log.info("| PARAMETERS: ");
    Enumeration e2 = request.getParameterNames();
    while (e2.hasMoreElements()) {
        String name = (String) e2.nextElement();
        log.info("|| " + name + ": ");
    }

    log.info("HEADERS: ");
    Enumeration e6 = request.getHeaderNames();
    while (e6.hasMoreElements()) {
        String name = (String) e6.nextElement();
        log.info("-- " + name + ": " + request.getHeader(name));
    }
    log.info("RemoteUser: " + request.getRemoteUser());
    log.info("AuthType: " + request.getAuthType());

    currentUserName = request.getRemoteUser();

    String roles = "";
    if (currentUserRoles != null) {
        for (String roleName : currentUserRoles) {
            roles += roleName + ", ";
        }
        if (roles.length() > 2) {
            roles = roles.substring(0, roles.length() - 2);
        }
    }
    log.debug("Roles: " + roles);

    try {
        super.service(request, response);
    } catch (Exception e) {
        if (e.getCause() instanceof AccessControlException) {
            log.info("EXCEPTION: Can't access to resource. You don't have permissions.");
            MultiStatusResponse msr = new MultiStatusResponse(request.getRequestURL().toString(), 401,
                    "Can't access to resource. You don't have permissions.");

            MultiStatus ms = new MultiStatus();
            ms.addResponse(msr);

            WebdavResponse webdavResponse = new WebdavResponseImpl(response);
            webdavResponse.sendMultiStatus(ms);
        } else
            new WebdavResponseImpl(response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    log.info("\\--------------------------------------------------");
}

From source file:org.wso2.carbon.identity.authenticator.saml2.sso.ui.SSOAssertionConsumerService.java

/**
 * Handle SAML Responses and authenticate.
 *
 * @param req        HttpServletRequest//from ww w .  j a v a 2  s.co  m
 * @param resp       HttpServletResponse
 * @param samlObject SAML Response object
 * @throws ServletException  Error when redirecting
 * @throws IOException       Error when redirecting
 */
private void handleSAMLResponses(HttpServletRequest req, HttpServletResponse resp, XMLObject samlObject)
        throws ServletException, IOException, SAML2SSOUIAuthenticatorException {
    Response samlResponse;
    samlResponse = (Response) samlObject;
    List<Assertion> assertions = samlResponse.getAssertions();
    Assertion assertion = null;
    if (assertions != null && assertions.size() > 0) {
        assertion = assertions.get(0);
    }

    if (assertion == null) {

        // This condition would succeed if Passive Login Request was sent because SP session has timed out
        if (samlResponse.getStatus() != null && samlResponse.getStatus().getStatusCode() != null
                && samlResponse.getStatus().getStatusCode().getValue()
                        .equals("urn:oasis:names:tc:SAML:2.0:status:Responder")
                && samlResponse.getStatus().getStatusCode().getStatusCode() != null
                && samlResponse.getStatus().getStatusCode().getStatusCode().getValue()
                        .equals("urn:oasis:names:tc:SAML:2.0:status:NoPassive")) {

            RequestDispatcher requestDispatcher = req.getRequestDispatcher("/carbon/admin/login.jsp");
            requestDispatcher.forward(req, resp);
            return;

        }

        if (samlResponse.getStatus() != null && samlResponse.getStatus().getStatusMessage() != null) {
            log.error(samlResponse.getStatus().getStatusMessage().getMessage());
        } else {
            log.error("SAML Assertion not found in the Response.");
        }
        throw new SAML2SSOUIAuthenticatorException("SAML Authentication Failed.");
    }

    // Get the subject name from the Response Object and forward it to login_action.jsp
    String username = null;
    if (assertion.getSubject() != null && assertion.getSubject().getNameID() != null) {
        username = Util.getUsernameFromResponse(samlResponse);
    }

    if (log.isDebugEnabled()) {
        log.debug("A username is extracted from the response. : " + username);
    }

    if (username == null) {
        log.error("SAMLResponse does not contain the name of the subject");
        throw new SAML2SSOUIAuthenticatorException("SAMLResponse does not contain the name of the subject");
    }

    String relayState = req.getParameter(SAMLConstants.RELAY_STATE);
    boolean isFederated = false;

    if (relayState != null) {
        FederatedSSOToken federatedSSOToken = org.wso2.carbon.identity.authenticator.saml2.sso.common.SSOSessionManager
                .getFederatedToken(relayState);
        if (federatedSSOToken != null) {
            isFederated = true;
            HttpServletRequest fedRequest = federatedSSOToken.getHttpServletRequest();

            String samlRequest = fedRequest.getParameter("SAMLRequest");
            String authMode = SAMLConstants.AuthnModes.USERNAME_PASSWORD;
            String fedRelayState = fedRequest.getParameter(SAMLConstants.RELAY_STATE);
            String rpSessionId = fedRequest.getParameter(MultitenantConstants.SSO_AUTH_SESSION_ID);

            Enumeration<String> e = fedRequest.getAttributeNames();

            while (e.hasMoreElements()) {
                String name = e.nextElement();
                req.setAttribute(name, fedRequest.getAttribute(name));
            }

            Cookie[] cookies = fedRequest.getCookies();

            if (cookies != null) {
                for (int i = 0; i < cookies.length; i++) {
                    resp.addCookie(cookies[i]);
                }
            }

            HttpSession session = fedRequest.getSession();

            // Use sessionID as the tokenID, if cookie is not set.
            String ssoTokenID = session.getId();
            Cookie tokenCookie = getSSOTokenCookie(fedRequest);
            if (tokenCookie != null) {
                ssoTokenID = tokenCookie.getValue();
            }

            handleFederatedSAMLRequest(req, resp, ssoTokenID, samlRequest, fedRelayState, authMode,
                    assertion.getSubject(), rpSessionId);
        }
    }

    if (!isFederated) {
        // Set the SAML2 Response as a HTTP Attribute, so it is not required to build the
        // assertion again.
        req.setAttribute(SAML2SSOAuthenticatorConstants.HTTP_ATTR_SAML2_RESP_TOKEN, samlResponse);

        String sessionIndex = null;
        List<AuthnStatement> authnStatements = assertion.getAuthnStatements();
        if (authnStatements != null && authnStatements.size() > 0) {
            // There can be only one authentication stmt inside the SAML assertion of a SAML Response
            AuthnStatement authStmt = authnStatements.get(0);
            sessionIndex = authStmt.getSessionIndex();
        }

        String url = req.getRequestURI();
        url = url.replace("acs",
                "carbon/admin/login_action.jsp?username=" + URLEncoder.encode(username, "UTF-8"));

        if (sessionIndex != null) {
            url += "&" + SAML2SSOAuthenticatorConstants.IDP_SESSION_INDEX + "="
                    + URLEncoder.encode(sessionIndex, "UTF-8");
        }

        if (log.isDebugEnabled()) {
            log.debug("Forwarding to path : " + url);
        }

        RequestDispatcher reqDispatcher = req.getRequestDispatcher(url);
        req.getSession().setAttribute("CarbonAuthenticator", new SAML2SSOUIAuthenticator());
        reqDispatcher.forward(req, resp);
    }
}

From source file:es.sm2.openppm.front.servlets.AbstractGenericServlet.java

/**
 * Add information to plugin/*from  w  w  w.  java2  s .co  m*/
 *
 * @param req
 * @param operationPlugin
 */
@SuppressWarnings("rawtypes")
protected void setInformationPlugin(HttpServletRequest req, OperationPlugin operationPlugin) {

    // Request attributes
    //
    Hashtable<String, Object> attributes = new Hashtable<String, Object>();

    for (Enumeration e = req.getAttributeNames(); e.hasMoreElements();) {

        String attName = (String) e.nextElement();

        attributes.put(attName, req.getAttribute(attName));
    }

    operationPlugin.setAttributes(attributes);

    // Request parameters
    //
    Hashtable<String, Object> parameters = new Hashtable<String, Object>();

    for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) {

        String attName = (String) e.nextElement();

        parameters.put(attName, req.getParameter(attName));
    }

    operationPlugin.setParameters(parameters);

    // Request session attributes
    //
    Hashtable<String, Object> sessionAttributes = new Hashtable<String, Object>();

    for (Enumeration e = req.getSession().getAttributeNames(); e.hasMoreElements();) {

        String attName = (String) e.nextElement();

        sessionAttributes.put(attName, req.getSession().getAttribute(attName));
    }

    operationPlugin.setSessionAttributes(sessionAttributes);

    // Resource boundle
    operationPlugin.setResourceBundle(getResourceBundle(req));
}

From source file:org.opentaps.common.util.UtilCommon.java

/**
 * Checks if a request has an error set.
 * @param request a <code>HttpServletRequest</code> value
 * @return a <code>Boolean</code> value
 */// ww  w.ja  va 2 s  .  c  om
@SuppressWarnings("unchecked")
public static Boolean hasError(HttpServletRequest request) {
    Enumeration<String> attrs = request.getAttributeNames();
    while (attrs.hasMoreElements()) {
        String a = attrs.nextElement();
        if ("_ERROR_MESSAGE_LIST_".equals(a) || "_ERROR_MESSAGE_".equals(a) || "opentapsErrors".equals(a)) {
            return true;
        }
    }
    return false;
}

From source file:org.dataone.proto.trove.mn.rest.base.AbstractWebController.java

protected void debugRequest(HttpServletRequest request) {
    /*     see values with just a plain old request object being sent through */
    logger.debug("request RequestURL: " + request.getRequestURL());
    logger.debug("request RequestURI: " + request.getRequestURI());
    logger.debug("request PathInfo: " + request.getPathInfo());
    logger.debug("request PathTranslated: " + request.getPathTranslated());
    logger.debug("request QueryString: " + request.getQueryString());
    logger.debug("request ContextPath: " + request.getContextPath());
    logger.debug("request ServletPath: " + request.getServletPath());
    logger.debug("request toString:" + request.toString());
    Enumeration<String> attributeNames = request.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
        String attributeName = attributeNames.nextElement();
        logger.debug("request " + attributeName + ": " + request.getAttribute(attributeName));
    }/*  w w  w .j  a v  a 2  s . c  o m*/
    /*      values of proxyServletWrapper request object to be sent through */
    logger.info("");

    /*      uncomment to see what the parameters of servlet passed in are  */
    Map<String, String[]> parameterMap = request.getParameterMap();

    for (Object key : parameterMap.keySet()) {
        String[] values = parameterMap.get((String) key);
        for (int i = 0; i < values.length; ++i) {
            logger.info("request ParameterMap: " + (String) key + " = " + values[i]);
        }

    }
    logger.debug("");

}

From source file:com.cws.us.pws.controllers.ServicesController.java

@RequestMapping(value = "/default", method = RequestMethod.GET)
public final ModelAndView showDefaultPage() {
    final String methodName = ServicesController.CNAME + "#showDefaultPage()";

    if (DEBUG) {//from ww  w  .  j a  v  a2s  .c om
        DEBUGGER.debug(methodName);
    }

    ModelAndView mView = new ModelAndView();

    final ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    final HttpServletRequest hRequest = requestAttributes.getRequest();
    final HttpSession hSession = hRequest.getSession();

    if (DEBUG) {
        DEBUGGER.debug("ServletRequestAttributes: {}", requestAttributes);
        DEBUGGER.debug("HttpServletRequest: {}", hRequest);
        DEBUGGER.debug("HttpSession: {}", hSession);

        DEBUGGER.debug("Dumping session content:");
        @SuppressWarnings("unchecked")
        Enumeration<String> sessionEnumeration = hSession.getAttributeNames();

        while (sessionEnumeration.hasMoreElements()) {
            String sessionElement = sessionEnumeration.nextElement();
            Object sessionValue = hSession.getAttribute(sessionElement);

            DEBUGGER.debug("Attribute: " + sessionElement + "; Value: " + sessionValue);
        }

        DEBUGGER.debug("Dumping request content:");
        @SuppressWarnings("unchecked")
        Enumeration<String> requestEnumeration = hRequest.getAttributeNames();

        while (requestEnumeration.hasMoreElements()) {
            String requestElement = requestEnumeration.nextElement();
            Object requestValue = hRequest.getAttribute(requestElement);

            DEBUGGER.debug("Attribute: " + requestElement + "; Value: " + requestValue);
        }

        DEBUGGER.debug("Dumping request parameters:");
        @SuppressWarnings("unchecked")
        Enumeration<String> paramsEnumeration = hRequest.getParameterNames();

        while (paramsEnumeration.hasMoreElements()) {
            String requestElement = paramsEnumeration.nextElement();
            Object requestValue = hRequest.getParameter(requestElement);

            DEBUGGER.debug("Parameter: " + requestElement + "; Value: " + requestValue);
        }
    }

    mView.setViewName(this.defaultPage);

    if (DEBUG) {
        DEBUGGER.debug("ModelAndView: {}", mView);
    }

    return mView;
}

From source file:es.sm2.openppm.front.servlets.AbstractGenericServlet.java

/**
 * Add information to plugin//from   w  ww. j a v a 2 s . c o  m
 *
 * @param req
 * @param genericAction
 */
protected void setInformationPlugin(HttpServletRequest req, GenericAction genericAction) {

    // Set multipart fields
    genericAction.setMultipartFields(getMultipartFields());

    // Request attributes
    //
    Hashtable<String, Object> attributes = new Hashtable<String, Object>();

    for (Enumeration e = req.getAttributeNames(); e.hasMoreElements();) {

        String attName = (String) e.nextElement();

        attributes.put(attName, req.getAttribute(attName));
    }

    genericAction.setAttributes(attributes);

    // Request parameters
    //
    Hashtable<String, Object> parameters = new Hashtable<String, Object>();

    for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) {

        String attName = (String) e.nextElement();

        parameters.put(attName, req.getParameter(attName));
    }

    genericAction.setParameters(parameters);

    // Request session attributes
    //
    Hashtable<String, Object> sessionAttributes = new Hashtable<String, Object>();

    for (Enumeration e = req.getSession().getAttributeNames(); e.hasMoreElements();) {

        String attName = (String) e.nextElement();

        sessionAttributes.put(attName, req.getSession().getAttribute(attName));
    }

    genericAction.setSessionAttributes(sessionAttributes);

    // Resource boundle
    genericAction.setResourceBundle(getResourceBundle(req));
}

From source file:org.jasig.cas.support.pac4j.web.flow.ClientBackChannelAction.java

private void log(HttpServletRequest request) {

    logger.debug("=========================================================");
    logger.debug("ClientBackChannelAction.doExecute: ");
    logger.debug("request.method: " + request.getMethod());
    logger.debug("request.requestURI: " + request.getRequestURI());
    logger.debug("request.queryString: " + request.getQueryString());
    logger.debug("request. host port remoteaddress: " + request.getRemoteHost() + " " + request.getRemotePort()
            + " " + request.getRemoteAddr());
    logger.debug("request. parameter:");
    Enumeration enParams = request.getParameterNames();
    while (enParams.hasMoreElements()) {
        String paramName = (String) enParams.nextElement();
        logger.debug(paramName + ": " + request.getParameter(paramName));
    }//from  w  w w . ja  va 2  s.  co m

    logger.debug("request. attribute:");
    Enumeration enParams2 = request.getAttributeNames();
    while (enParams2.hasMoreElements()) {
        String paramName2 = (String) enParams2.nextElement();
        logger.debug(paramName2 + ": " + request.getAttribute(paramName2));
    }
    logger.debug("=========================================================");
}