Example usage for javax.servlet.http HttpServletRequest getSession

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

Introduction

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

Prototype

public HttpSession getSession();

Source Link

Document

Returns the current session associated with this request, or if the request does not have a session, creates one.

Usage

From source file:com.mnt.base.web.DigestAuthenticator.java

public static boolean authenticate(HttpServletRequest req, HttpServletResponse resp) {

    boolean result = false;

    HttpSession session = req.getSession();

    if (session != null) {

        result = session.getAttribute(AUTHENTICATED_FLAG_KEY) != null;

        if (!result) {

            session.setMaxInactiveInterval(60);

            Map<String, Object> authInfoMap = CommonUtil.uncheckedMapCast(session.getAttribute(AUTH_INFO_MAP));

            if (authInfoMap == null) {
                authInfoMap = new HashMap<String, Object>();
                session.setAttribute(AUTH_INFO_MAP, authInfoMap);
            }//from  w  w w  .  j a  v a  2  s.com

            String authentication = req.getHeader("Authorization");

            if (CommonUtil.isEmpty(authentication) || !authentication.startsWith("Digest ")) {

                postAuthRequired(req, resp, authInfoMap);

            } else {
                result = authenticate(req.getMethod(), authentication, authInfoMap);

                if (result) {

                    if (authProvider != null) {
                        try {
                            authProvider.authenticated(authUser.get(), true);
                        } catch (Exception e) {
                            log.error("error while invoke the authProvider.authenticated: " + authUser.get(),
                                    e);
                        }
                    }
                    session.setAttribute(AUTHENTICATED_FLAG_KEY, true);
                    session.removeAttribute(AUTH_INFO_MAP);
                    authInfoMap.clear();
                    authInfoMap = null;

                    session.setMaxInactiveInterval(1800);
                } else {
                    authProvider.authenticated(authUser.get(), false);
                    authInfoMap.clear();
                    postAuthRequired(req, resp, authInfoMap);
                }
            }
        }
    } else {
        System.err.println("Just support session available authentication.");
    }

    return result;
}

From source file:org.apache.ofbiz.passport.event.LinkedInEvents.java

/**
 * Parse LinkedIn login response and login the user if possible.
 * //from  ww w.ja va2 s .  com
 * @return 
 */
public static String parseLinkedInResponse(HttpServletRequest request, HttpServletResponse response) {
    String authorizationCode = request.getParameter(PassportUtil.COMMON_CODE);
    String state = request.getParameter(PassportUtil.COMMON_STATE);
    if (!state.equals(request.getSession().getAttribute(SESSION_LINKEDIN_STATE))) {
        String errMsg = UtilProperties.getMessage(resource, "LinkedInFailedToMatchState",
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    if (UtilValidate.isEmpty(authorizationCode)) {
        String error = request.getParameter(PassportUtil.COMMON_ERROR);
        String errorDescpriton = request.getParameter(PassportUtil.COMMON_ERROR_DESCRIPTION);
        String errMsg = null;
        try {
            errMsg = UtilProperties.getMessage(resource, "FailedToGetLinkedInAuthorizationCode",
                    UtilMisc.toMap(PassportUtil.COMMON_ERROR, error, PassportUtil.COMMON_ERROR_DESCRIPTION,
                            URLDecoder.decode(errorDescpriton, "UTF-8")),
                    UtilHttp.getLocale(request));
        } catch (UnsupportedEncodingException e) {
            errMsg = UtilProperties.getMessage(resource, "GetLinkedInAuthorizationCodeError",
                    UtilHttp.getLocale(request));
        }
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    // Debug.logInfo("LinkedIn authorization code: " + authorizationCode, module);

    GenericValue oauth2LinkedIn = getOAuth2LinkedInConfig(request);
    if (UtilValidate.isEmpty(oauth2LinkedIn)) {
        String errMsg = UtilProperties.getMessage(resource, "GetOAuth2LinkedInConfigError",
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    String clientId = oauth2LinkedIn.getString(PassportUtil.ApiKeyLabel);
    String secret = oauth2LinkedIn.getString(PassportUtil.SecretKeyLabel);
    String returnURI = oauth2LinkedIn.getString(envPrefix + PassportUtil.ReturnUrlLabel);

    // Grant token from authorization code and oauth2 token
    // Use the authorization code to obtain an access token
    String accessToken = null;

    try {
        URI uri = new URIBuilder().setScheme(TokenEndpoint.substring(0, TokenEndpoint.indexOf(":")))
                .setHost(TokenEndpoint.substring(TokenEndpoint.indexOf(":") + 3)).setPath(TokenServiceUri)
                .setParameter("client_id", clientId).setParameter("client_secret", secret)
                .setParameter("grant_type", "authorization_code").setParameter("code", authorizationCode)
                .setParameter("redirect_uri", returnURI).build();
        HttpPost postMethod = new HttpPost(uri);
        CloseableHttpClient jsonClient = HttpClients.custom().build();
        // Debug.logInfo("LinkedIn get access token query string: " + postMethod.getURI(), module);
        postMethod.setConfig(PassportUtil.StandardRequestConfig);
        CloseableHttpResponse postResponse = jsonClient.execute(postMethod);
        String responseString = new BasicResponseHandler().handleResponse(postResponse);
        // Debug.logInfo("LinkedIn get access token response code: " + postResponse.getStatusLine().getStatusCode(), module);
        // Debug.logInfo("LinkedIn get access token response content: " + responseString, module);
        if (postResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // Debug.logInfo("Json Response from LinkedIn: " + responseString, module);
            JSON jsonObject = JSON.from(responseString);
            JSONToMap jsonMap = new JSONToMap();
            Map<String, Object> userMap = jsonMap.convert(jsonObject);
            accessToken = (String) userMap.get("access_token");
            // Debug.logInfo("Generated Access Token : " + accessToken, module);
        } else {
            String errMsg = UtilProperties.getMessage(resource, "GetOAuth2LinkedInAccessTokenError",
                    UtilMisc.toMap("error", responseString), UtilHttp.getLocale(request));
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
    } catch (UnsupportedEncodingException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    } catch (IOException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    } catch (ConversionException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    } catch (URISyntaxException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    }

    // Get User Profile
    HttpGet getMethod = new HttpGet(TokenEndpoint + UserApiUri + "?oauth2_access_token=" + accessToken);
    Document userInfo = null;
    try {
        userInfo = LinkedInAuthenticator.getUserInfo(getMethod, UtilHttp.getLocale(request));
    } catch (IOException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    } catch (AuthenticatorException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    } catch (SAXException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    } catch (ParserConfigurationException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    } finally {
        getMethod.releaseConnection();
    }
    // Debug.logInfo("LinkedIn User Info:" + userInfo, module);

    // Store the user info and check login the user
    return checkLoginLinkedInUser(request, userInfo, accessToken);
}

From source file:com.krawler.esp.handlers.AuthHandler.java

public static Integer getPerms(HttpServletRequest request, String keyName) throws SessionExpiredException {
    long perl = 0;
    int per = 0;/*from  w  w  w.  j a  v a  2 s  . c o  m*/

    try {
        if (request.getSession().getAttribute(keyName) != null) {
            perl = (Long) request.getSession().getAttribute(keyName);
        }
        per = (int) perl;
        //  per = Integer.parseInt(perm);
    } catch (Exception e) {
        per = 0;
    }
    return per;
}

From source file:com.huateng.ebank.business.common.GlobalInfo.java

public static GlobalInfo getFromRequest2(HttpServletRequest request) throws CommonException {
    HttpSession httpSession = request.getSession();
    GlobalInfo globalInfo = (GlobalInfo) httpSession.getAttribute(GlobalInfo.KEY_GLOBAL_INFO);

    if (log.isDebugEnabled()) {
        log.debug("session id = " + httpSession.getId());
    }//ww  w.  j  a v  a 2  s  .  co  m

    if (null != globalInfo) {
        setCurrentInstance(globalInfo);
        String sessionId = httpSession.getId();
        globalInfo.setSessionId(sessionId);
    }
    return globalInfo;
}

From source file:com.huateng.ebank.business.common.GlobalInfo.java

public static GlobalInfo getFromRequest(HttpServletRequest request) throws CommonException {
    HttpSession httpSession = request.getSession();
    GlobalInfo globalInfo = (GlobalInfo) httpSession.getAttribute(GlobalInfo.KEY_GLOBAL_INFO);

    if (log.isDebugEnabled()) {
        log.debug("session id = " + httpSession.getId());
    }/*from  w w  w .j  ava  2 s.  c o m*/

    if (null != globalInfo) {
        setCurrentInstance(globalInfo);
        String oldSessionId = globalInfo.getSessionId();
        String sessionId = httpSession.getId();
        if (!sessionId.equals(oldSessionId)) {
            ExceptionUtil.throwCommonException("???, ?.",
                    ErrorCode.ERROR_CODE_TLRNO_SESSION_BINDED);
        }
        globalInfo.setSessionId(sessionId);
    }
    return globalInfo;
}

From source file:com.krawler.esp.handlers.AuthHandler.java

public static String getSubDomain(HttpServletRequest request) throws SessionExpiredException {
    String subdomain = "";
    Session session = null;//w  w w  . j a v a2  s  .c o m
    String companyid = NullCheckAndThrow(request.getSession().getAttribute("companyid"),
            SessionExpiredException.USERID_NULL);
    try {
        session = HibernateUtil.getCurrentSession();
        Company company = (Company) session.get(Company.class, companyid);
        subdomain = company.getSubDomain();
    } catch (Exception e) {
        HibernateUtil.closeSession(session);
    }

    return subdomain;
}

From source file:fr.paris.lutece.plugins.search.solr.web.SolrSearchApp.java

/**
 * Return the model used during the last search
 *
 * @param request The HTTP request./*from w ww  .  j  a v a  2  s .c  o m*/
 * @return the model used during the last search
 * @deprecated model is not stored in session anymore
 */
@Deprecated
public static Map<String, Object> getLastSearchModel(HttpServletRequest request) {
    AppLogService
            .error("calling deprecated code : SolrSearchApp.getLastSearchModel( HttpServletRequest request )");
    return (Map<String, Object>) request.getSession().getAttribute(PARAMETER_PREVIOUS_SEARCH);
}

From source file:com.buession.cas.web.utils.CaptchaUtils.java

/**
 * ???/*from w ww .  j av  a 2s . c om*/
 * 
 * @param request
 *        HttpServletRequest
 * @param captchaProducer
 *        ?????
 * @param validateCode
 *        ????
 * @return ???
 */
public static boolean validate(final HttpServletRequest request, final Config config,
        final String validateCode) {
    if (validateCode == null || validateCode.length() == 0) {
        return false;
    }

    Cookie cookies[] = request.getCookies();
    if (cookies == null || cookies.length == 0) {
        return false;
    }

    String captchaCookieName = CaptchaUtils.getCaptchaCookieName(config);
    for (int i = 0; i < cookies.length; i++) {
        Cookie cookie = cookies[i];

        if (captchaCookieName.equals(cookie.getName()) == true) {
            mcrypt.setSalt(request.getSession().getId());
            return mcrypt.encode(validateCode).equalsIgnoreCase(cookie.getValue());
        }
    }

    return false;
}

From source file:ispyb.client.common.util.FileUtil.java

public static boolean isJpgThumbForImage(Integer imageId, HttpServletRequest request) throws Exception {

    boolean isJpg = false;

    Integer proposalId = (Integer) request.getSession().getAttribute(Constants.PROPOSAL_ID);
    if (proposalId == null) {
        proposalId = new Integer(request.getParameter(Constants.PROPOSAL_ID));
    }/*w w  w. j  av a  2s .  c o  m*/

    Ejb3ServiceLocator ejb3ServiceLocator = Ejb3ServiceLocator.getInstance();
    Image3Service imageService = (Image3Service) ejb3ServiceLocator.getLocalService(Image3Service.class);
    // two variables to guarantee the user fecths only its own images
    List<Image3VO> imageFetchedList = imageService.findByImageIdAndProposalId(imageId, proposalId);

    if (imageFetchedList.size() == 1) {

        Image3VO imgValue = imageFetchedList.get(0);

        String sourceFileName = imgValue.getJpegThumbnailFileFullPath();
        sourceFileName = PathUtils.FitPathToOS(sourceFileName);

        isJpg = FileUtil.fileExists(sourceFileName);
    }

    return isJpg;

}

From source file:org.codehaus.groovy.grails.plugins.springsecurity.AuthorizeTools.java

/**
 * Check if the request was triggered by an Ajax call.
 * @param request the request/*from w  w  w  .j a  v a 2s  .  co  m*/
 * @return <code>true</code> if Ajax
 */
public static boolean isAjax(final HttpServletRequest request) {

    // look for an ajax=true parameter
    if ("true".equals(request.getParameter("ajax"))) {
        return true;
    }

    // check the current request's headers
    if (request.getHeader(_ajaxHeaderName) != null) {
        return true;
    }

    // check the SavedRequest's headers
    SavedRequest savedRequest = (SavedRequest) request.getSession()
            .getAttribute(AbstractProcessingFilter.SPRING_SECURITY_SAVED_REQUEST_KEY);
    if (savedRequest != null) {
        return savedRequest.getHeaderValues(_ajaxHeaderName).hasNext();
    }

    return false;
}