Example usage for javax.servlet.http HttpServletRequest getAttribute

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

Introduction

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

Prototype

public Object getAttribute(String name);

Source Link

Document

Returns the value of the named attribute as an Object, or null if no attribute of the given name exists.

Usage

From source file:com.hihsoft.baseclass.web.controller.BaseController.java

public static <T> T getOrCreateRequestAttribute(HttpServletRequest request, String key, Class<T> clazz) {
    Object value = request.getAttribute(key);
    if (value == null) {
        try {//  ww  w  .j a v a  2  s  . co  m
            value = clazz.newInstance();
        } catch (Exception e) {
            ReflectionUtils.handleReflectionException(e);
        }
        request.setAttribute(key, value);
    }
    return clazz.cast(value);
}

From source file:com.redhat.rhn.frontend.taglibs.list.ListTagUtil.java

private static String makeNonPagedLink(HttpServletRequest request, String listName) {
    String url = (String) request.getAttribute("parentUrl");
    String queryString = request.getQueryString();
    if (queryString != null && queryString.length() > 0) {
        url += "?";
        for (StringTokenizer strtok = new StringTokenizer(queryString, "&"); strtok.hasMoreTokens();) {
            String token = strtok.nextToken();
            if (token.indexOf(listName) > -1 && token.indexOf("_page=") > -1) {
                continue;
            }/*ww  w  . j  av a  2  s .c o  m*/
            if (url.endsWith("?")) {
                url += token;
            } else {
                url = url + "&" + token;
            }
        }
    }
    return url;
}

From source file:cn.bc.web.util.WebUtils.java

/**
 * ???
 * /*from w  w  w  . j a v a  2s  . c om*/
 * <pre>
 * http://www.demo.com/demo/test.htm  -->  /demo/test.htm</span>
 * </pre>
 * 
 * @param request
 * @return ?/demo/test.htm
 */
public static String getResourcePath(HttpServletRequest request) {
    // Adapted from VelocityViewServlet.handleRequest() method:

    // If we get here from RequestDispatcher.include(), getServletPath()
    // will return the original (wrong) URI requested. The following
    // special attribute holds the correct path. See section 8.3 of the
    // Servlet 2.3 specification.

    String path = (String) request.getAttribute("javax.servlet.include.servlet_path");

    // Also take into account the PathInfo stated on
    // SRV.4.4 Request Path Elements.
    String info = (String) request.getAttribute("javax.servlet.include.path_info");

    if (path == null) {
        path = request.getServletPath();
        info = request.getPathInfo();
    }

    if (info != null) {
        path += info;
    }

    return path;
}

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

public static UserInfo getUserName(final HttpServletRequest request) {
    UserInfo result = null;// ww  w .j a  v a  2  s.  co 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:com.ibm.jaggr.core.test.TestUtils.java

public static HttpServletRequest createMockRequest(IAggregator aggregator,
        final Map<String, Object> requestAttributes, final Map<String, String[]> requestParameters,
        final Cookie[] cookies, final Map<String, String> headers) {
    HttpServletRequest mockRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    if (requestAttributes != null) {
        requestAttributes.put(IAggregator.AGGREGATOR_REQATTRNAME, aggregator);
        EasyMock.expect(mockRequest.getAttribute((String) EasyMock.anyObject()))
                .andAnswer(new IAnswer<Object>() {
                    public Object answer() throws Throwable {
                        return requestAttributes.get((String) EasyMock.getCurrentArguments()[0]);
                    }// www.j a v  a 2 s.  c o m
                }).anyTimes();
        mockRequest.setAttribute((String) EasyMock.anyObject(), EasyMock.anyObject());
        EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
            public Object answer() throws Throwable {
                String name = (String) EasyMock.getCurrentArguments()[0];
                Object value = EasyMock.getCurrentArguments()[1];
                requestAttributes.put(name, value);
                return null;
            }
        }).anyTimes();
        mockRequest.removeAttribute((String) EasyMock.anyObject());
        EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
            public Object answer() throws Throwable {
                String name = (String) EasyMock.getCurrentArguments()[0];
                requestAttributes.remove(name);
                return null;
            }
        }).anyTimes();
    } else {
        EasyMock.expect(mockRequest.getAttribute(IAggregator.AGGREGATOR_REQATTRNAME)).andReturn(aggregator)
                .anyTimes();
    }
    if (requestParameters != null) {
        EasyMock.expect(mockRequest.getParameter((String) EasyMock.anyObject()))
                .andAnswer(new IAnswer<String>() {
                    public String answer() throws Throwable {
                        String[] ary = requestParameters.get((String) EasyMock.getCurrentArguments()[0]);
                        return ary != null && ary.length > 0 ? ary[0] : null;
                    }
                }).anyTimes();
        EasyMock.expect(mockRequest.getParameterMap()).andAnswer(new IAnswer<Map<String, String[]>>() {
            @Override
            public Map<String, String[]> answer() throws Throwable {
                return requestParameters;
            }
        }).anyTimes();
    }
    if (cookies != null) {
        EasyMock.expect(mockRequest.getCookies()).andAnswer(new IAnswer<Cookie[]>() {
            public Cookie[] answer() throws Throwable {
                return cookies;
            }
        }).anyTimes();
    }
    if (headers != null) {
        EasyMock.expect(mockRequest.getHeader((String) EasyMock.anyObject())).andAnswer(new IAnswer<String>() {
            public String answer() throws Throwable {
                return headers.get((String) EasyMock.getCurrentArguments()[0]);
            }
        }).anyTimes();
    }
    return mockRequest;
}

From source file:com.lily.dap.web.util.Struts2Utils.java

/**
 * Gets an attribute as a boolean./*w  w w  .ja va  2  s .c o  m*/
 * 
 * @param request
 *            The HttpServletRequest object, known as "request" in a JSP
 *            page.
 * @param name
 *            The name of the attribute you want to get
 * @return True if the value of the attribute is "true", false otherwise.
 */
public static boolean getBooleanAttribute(String name) {
    HttpServletRequest request = getRequest();

    String temp = (String) request.getAttribute(name);
    if (temp != null && temp.equals("true")) {
        return true;
    } else {
        return false;
    }
}

From source file:org.itracker.web.util.LoginUtilities.java

/**
 * Get a locale from request// w ww. j  av  a 2  s  . co m
 * <p/>
 * <p>
 * TODO the order of retrieving locale from request should be:
 * <ol>
 * <li>request-attribute Constants.LOCALE_KEY</li>
 * <li>request-param 'loc'</li>
 * <li>session attribute <code>Constants.LOCALE_KEY</code></li>
 * <li>cookie 'loc'</li>
 * <li>request.getLocale()/request.getLocales()</li>
 * <li>ITrackerResources.DEFAULT_LOCALE</li>
 * </ol>
 * </p>
 */
@SuppressWarnings("unchecked")
public static Locale getCurrentLocale(HttpServletRequest request) {
    Locale requestLocale = null;
    HttpSession session = request.getSession(true);
    try {

        requestLocale = (Locale) request.getAttribute(Constants.LOCALE_KEY);

        if (logger.isDebugEnabled()) {
            logger.debug("getCurrentLocale: request-attribute was {}", requestLocale);
        }

        if (null == requestLocale) {
            // get locale from request param
            String loc = request.getParameter("loc");
            if (null != loc && loc.trim().length() > 1) {
                requestLocale = ITrackerResources.getLocale(loc);
            }

            logger.debug("getCurrentLocale: request-parameter was {}", loc);

        }

        if (null == requestLocale) {
            // get it from the session
            requestLocale = (Locale) session.getAttribute(Constants.LOCALE_KEY);
            //            if (logger.isDebugEnabled()) {
            //               logger.debug("getCurrentLocale: session-attribute was "
            //                     + requestLocale);
            //            }
        }

        if (null == requestLocale) {
            ResourceBundle bundle = ITrackerResources.getBundle(request.getLocale());
            if (logger.isDebugEnabled()) {
                logger.debug("getCurrentLocale: trying request header locale " + request.getLocale());
            }
            if (bundle.getLocale().getLanguage().equals(request.getLocale().getLanguage())) {
                requestLocale = request.getLocale();
                if (logger.isDebugEnabled()) {
                    logger.debug("getCurrentLocale: request-locale was " + requestLocale);
                }
            }
        }

        // is there no way to detect supported locales of current
        // installation?

        if (null == requestLocale) {
            Enumeration<Locale> locales = (Enumeration<Locale>) request.getLocales();
            ResourceBundle bundle;
            Locale locale;
            while (locales.hasMoreElements()) {
                locale = locales.nextElement();
                bundle = ITrackerResources.getBundle(locale);

                logger.debug("getCurrentLocale: request-locales processing {}, bundle: {}", locale, bundle);

                if (bundle.getLocale().getLanguage().equals(locale.getLanguage())) {
                    requestLocale = locale;

                    logger.debug("getCurrentLocale: request-locales locale was {}", requestLocale);

                }
            }
        }

    } finally {
        if (null == requestLocale) {
            // fall back to default locale
            requestLocale = ITrackerResources.getLocale();

            logger.debug("getCurrentLocale: fallback default locale was {}", requestLocale);

        }
        session.setAttribute(Constants.LOCALE_KEY, requestLocale);
        request.setAttribute(Constants.LOCALE_KEY, requestLocale);
        request.setAttribute("currLocale", requestLocale);

        logger.debug("getCurrentLocale: request and session was setup with {}", requestLocale);

    }

    return requestLocale;
}

From source file:com.lily.dap.web.util.Struts2Utils.java

/**
 * Gets a parameter as a string./* ww  w. ja  va 2s.  c o  m*/
 * 
 * @param request
 *            The HttpServletRequest object, known as "request" in a JSP
 *            page.
 * @param name
 *            The name of the parameter you want to get
 * @param emptyStringsOK
 *            Return the parameter values even if it is an empty string.
 * @return The value of the parameter or null if the parameter was not
 *         found.
 */
public static String getAttribute(String name, boolean emptyStringsOK) {
    HttpServletRequest request = getRequest();

    String temp = (String) request.getAttribute(name);
    if (temp != null) {
        if (temp.equals("") && !emptyStringsOK) {
            return null;
        } else {
            return temp;
        }
    } else {
        return null;
    }
}

From source file:com.lily.dap.web.util.Struts2Utils.java

/**
 * Gets an attribute as a int.//from  w ww  .  j  ava 2s. co m
 * 
 * @param request
 *            The HttpServletRequest object, known as "request" in a JSP
 *            page.
 * @param name
 *            The name of the attribute you want to get
 * @return The int value of the attribute or the default value if the
 *         attribute is not found or is a zero length string.
 */
public static int getIntAttribute(String name, int defaultNum) {
    HttpServletRequest request = getRequest();

    String temp = (String) request.getAttribute(name);
    if (temp != null && !temp.equals("")) {
        int num = defaultNum;
        try {
            num = Integer.parseInt(temp.trim());
        } catch (Exception ignored) {
        }
        return num;
    } else {
        return defaultNum;
    }
}

From source file:com.lily.dap.web.util.Struts2Utils.java

/**
 * Gets an attribute as a long./*from   www .j a v a 2  s .  co  m*/
 * 
 * @param request
 *            The HttpServletRequest object, known as "request" in a JSP
 *            page.
 * @param name
 *            The name of the attribute you want to get
 * @return The long value of the attribute or the default value if the
 *         attribute is not found or is a zero length string.
 */
public static long getLongAttribute(String name, long defaultNum) {
    HttpServletRequest request = getRequest();

    String temp = (String) request.getAttribute(name);
    if (temp != null && !temp.equals("")) {
        long num = defaultNum;
        try {
            num = Long.parseLong(temp.trim());
        } catch (Exception ignored) {
        }
        return num;
    } else {
        return defaultNum;
    }
}