Example usage for org.springframework.web.context.request RequestContextHolder currentRequestAttributes

List of usage examples for org.springframework.web.context.request RequestContextHolder currentRequestAttributes

Introduction

In this page you can find the example usage for org.springframework.web.context.request RequestContextHolder currentRequestAttributes.

Prototype

public static RequestAttributes currentRequestAttributes() throws IllegalStateException 

Source Link

Document

Return the RequestAttributes currently bound to the thread.

Usage

From source file:net.shopxx.service.impl.MerchantServiceImpl.java

@Transactional(readOnly = true)
public String getCurrentUsername() {
    RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
    if (requestAttributes != null) {
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        Principal principal = (Principal) request.getSession().getAttribute(Merchant.PRINCIPAL_ATTRIBUTE_NAME);
        if (principal != null) {
            return principal.getUsername();
        }//from   w w w  .j  av  a 2  s .  c om
    }
    return null;
}

From source file:com.dp2345.service.impl.ShopServiceImpl.java

/**
 * ???//from w  w  w  .  j  a  v a  2  s  .  com
 */
@Transactional(readOnly = true)
public String getCurrentUsername() {
    RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
    if (requestAttributes != null) {
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        Principal principal = (Principal) request.getSession().getAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME);
        if (principal != null) {
            return principal.getUsername();
        }
    }
    return null;
}

From source file:au.org.intersect.dms.webapp.controller.LocationController.java

private List<LocationConnectForm> getCurrentConnections() {
    List<LocationConnectForm> connections = (List<LocationConnectForm>) RequestContextHolder
            .currentRequestAttributes().getAttribute(CONNECTIONS, RequestAttributes.SCOPE_SESSION);
    if (connections == null) {
        connections = new LinkedList<LocationConnectForm>();
    }/*from   ww  w  . j a  v  a 2 s. com*/
    return connections;
}

From source file:org.jahia.modules.spamfiltering.rules.SpamFilteringRuleService.java

/**
 * Verifies the content of the node with anti-spam service and applies spam filtering (by assigning a special mixin).
 * //from w  w  w  . j av  a2s. c o m
 * @param nodeFact
 *            the node which content should be checked
 * @param maxSpamCount the number of maximum spams tolerated before the user is locked and his session is killed.
 * @param drools
 *            the rule engine helper class
 * @throws RepositoryException
 *             in case of an error
 */
public void checkForSpam(AddedNodeFact nodeFact, Integer maxSpamCount, KnowledgeHelper drools)
        throws RepositoryException {
    if (logger.isDebugEnabled()) {
        logger.debug("Checking content of the node {} for spam", nodeFact.getPath());
    }

    try {
        User user = (User) drools.getWorkingMemory().getGlobal("user");

        HttpServletRequest httpServletRequest = spamFilter.getHttpServletRequest();

        if (httpServletRequest == null) {
            // we didn't manage to get the request from our own filter, try to access it through Spring MVC's
            // framework
            RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
            if (requestAttributes != null && requestAttributes instanceof ServletRequestAttributes) {
                ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
                httpServletRequest = servletRequestAttributes.getRequest();
            }
        }

        boolean isSpam = false;
        JCRNodeWrapper node = nodeFact.getNode();
        String text = getTextContent(node);
        if (StringUtils.isNotEmpty(text)) {
            isSpam = spamFilteringService.isSpam(text, node, httpServletRequest);
        }

        if (isSpam) {
            if (!node.isNodeType(SPAM_DETECTED_MIXIN)) {
                // is detected as spam -> add mixin
                node.getSession().checkout(node);
                node.addMixin(SPAM_DETECTED_MIXIN);
            }
            if (maxSpamCount != null && httpServletRequest != null) {
                HttpSession httpSession = httpServletRequest.getSession(false);
                JahiaUser jahiaUser = user.getJahiaUser();
                if (httpSession != null && !"guest".equals(jahiaUser.getName())) {
                    String spamSessionsValue = jahiaUser.getProperty(SPAM_SESSIONS_PROPERTY_NAME);
                    List<String> spamSessions = new ArrayList<String>();
                    if (spamSessionsValue != null) {
                        spamSessions.addAll(Arrays.asList(spamSessionsValue.split(",")));
                    }

                    spamSessions.add(httpSession.getId());

                    if (spamSessions.size() >= maxSpamCount) {
                        logger.info("Maximum number of spam count reached (" + maxSpamCount
                                + "), locking user account and killing session...");
                        logger.info("Marking session " + httpSession.getId()
                                + " as invalid and will be killed on next access.");
                        spamFilter.addSessionToKill(httpSession.getId());
                        // add code to lock account
                        logger.info("Locking account " + jahiaUser + "...");
                        jahiaUser.setProperty("j:accountLocked", "true");
                        if (sendSpamNotificationEmails) {
                            logger.info("Sending account lock notification to administrator...");
                            sendAccountLockNotification(node, jahiaUser, httpServletRequest);
                        }
                        // we clear the session list to avoid it growing to big
                        spamSessions.clear();
                    } else {
                        logger.info("User " + jahiaUser + " has sent " + spamSessions.size() + " spam so far.");
                    }

                    if (spamSessions.size() > 0) {
                        jahiaUser.setProperty(SPAM_SESSIONS_PROPERTY_NAME, StringUtils.join(spamSessions, ","));
                    } else {
                        jahiaUser.removeProperty(SPAM_SESSIONS_PROPERTY_NAME);
                    }

                }
            }
        } else if (node.isNodeType(SPAM_DETECTED_MIXIN)) {
            // no longer spam -> remove mixin
            node.getSession().checkout(node);
            node.removeMixin(SPAM_DETECTED_MIXIN);
        }
        logger.info("Content of the node {} is{} detected as spam", node.getPath(), !isSpam ? " not" : "");
    } catch (Exception e) {
        logger.warn("Unable to check the content of the node " + nodeFact.getPath() + " for spam. Cause: "
                + e.getMessage(), e);
    }
}

From source file:au.org.intersect.dms.webapp.controller.LocationController.java

private void updateCurrectConnections(List<LocationConnectForm> connections) {
    RequestContextHolder.currentRequestAttributes().setAttribute(CONNECTIONS, connections,
            RequestAttributes.SCOPE_SESSION);
}

From source file:de.metas.ui.web.login.LoginRestController.java

private static void destroySession(final Login loginService, final MSession session) {
    if (session != null) {
        session.logout();/*from   ww  w  .j  a  v  a  2  s  .  c  o  m*/
    }

    if (loginService != null) {
        loginService.getCtx().resetAD_Session_ID();
    }

    //
    // Destroy http session
    final ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    final HttpSession httpSession = servletRequestAttributes.getRequest().getSession(false);
    if (httpSession != null) {
        httpSession.invalidate();
    }
}

From source file:org.freeeed.search.web.solr.SolrSearchService.java

/**
 * /*from  w  w w .  ja  v  a  2  s  .  com*/
 * Do the actual HTTP requst to Solr and execute the given query.
 * 
 * @param query
 * @param from
 * @param rows
 * @return
 */
private String searchSolr(String query, int from, int rows, String defaultField, boolean highlight,
        String fields) {

    HttpServletRequest curRequest = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
            .getRequest();
    HttpSession session = curRequest.getSession();
    SolrSessionObject solrSession = (SolrSessionObject) session
            .getAttribute(WebConstants.WEB_SESSION_SOLR_OBJECT);
    if (solrSession == null || solrSession.getSelectedCase() == null) {
        return null;
    }

    String solrCore = solrSession.getSelectedCase().getSolrSourceCore();

    if (defaultField == null) {
        defaultField = "gl-search-field";
    }

    try {
        String encodedQuery = URLEncoder.encode(query, "UTF-8");
        String urlStr = configuration.getSolrEndpoint() + "/solr/" + solrCore + "/select/?q=" + encodedQuery
                + "&start=" + from + "&rows=" + rows + "&df=" + defaultField + "&hl=" + highlight;
        if (fields != null) {
            urlStr += "&fl=" + fields;
        }

        URL url = new URL(urlStr);

        log.debug("Will execute: " + url.toString());

        URLConnection conn = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        StringBuffer resultBuff = new StringBuffer();

        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            resultBuff.append(inputLine).append("\n");
        }

        in.close();

        return resultBuff.toString();
    } catch (Exception e) {
        log.error("Problem accessing Solr: ", e);
    }

    return null;
}

From source file:com.haulmont.restapi.auth.ClientProxyTokenStore.java

/**
 * Tries to find the session associated with the given {@code authentication}. If the session id is in the store and
 * exists then it is set to the {@link SecurityContext}. If the session id is not in the store or the session with
 * the id doesn't exist in the middleware, then the trusted login attempt is performed.
 *//* www.  j  a  v  a  2 s . c  om*/
protected void processSession(OAuth2Authentication authentication, String tokenValue) {
    RestUserSessionInfo sessionInfo = serverTokenStore.getSessionInfoByTokenValue(tokenValue);
    UUID sessionId = sessionInfo != null ? sessionInfo.getId() : null;
    if (sessionId == null) {
        @SuppressWarnings("unchecked")
        Map<String, String> userAuthenticationDetails = (Map<String, String>) authentication
                .getUserAuthentication().getDetails();
        //sessionId parameter was put in the CubaUserAuthenticationProvider
        String sessionIdStr = userAuthenticationDetails.get("sessionId");
        if (!Strings.isNullOrEmpty(sessionIdStr)) {
            sessionId = UUID.fromString(sessionIdStr);
        }
    }

    UserSession session = null;
    if (sessionId != null) {
        try {
            session = trustedClientService.findSession(restApiConfig.getTrustedClientPassword(), sessionId);
        } catch (LoginException e) {
            throw new RuntimeException("Unable to login with trusted client password");
        }
    }

    if (session == null) {
        @SuppressWarnings("unchecked")
        Map<String, String> userAuthenticationDetails = (Map<String, String>) authentication
                .getUserAuthentication().getDetails();
        String username = userAuthenticationDetails.get("username");
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                    .currentRequestAttributes();
            Locale locale = sessionInfo != null ? sessionInfo.getLocale() : null;
            TrustedClientCredentials credentials = new TrustedClientCredentials(username,
                    restApiConfig.getTrustedClientPassword(), locale);
            credentials.setClientType(ClientType.REST_API);
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                credentials.setIpAddress(request.getRemoteAddr());
                credentials.setClientInfo(makeClientInfo(request.getHeader(HttpHeaders.USER_AGENT)));
            } else {
                credentials.setClientInfo(makeClientInfo(""));
            }

            //if locale was not determined then use the user locale
            if (locale == null) {
                credentials.setOverrideLocale(false);
            }

            session = authenticationService.login(credentials).getSession();
        } catch (LoginException e) {
            throw new OAuth2Exception("Cannot login to the middleware");
        }
    }

    if (session != null) {
        serverTokenStore.putSessionInfo(tokenValue, new RestUserSessionInfo(session));
        AppContext.setSecurityContext(new SecurityContext(session));
    }
}

From source file:com.launchkey.example.springmvc.AuthManager.java

private String getSessionId() {
    return RequestContextHolder.currentRequestAttributes().getSessionId();
}

From source file:com.archsystemsinc.ipms.sec.webapp.controller.ActionItemController.java

public static HttpSession getSession() {
    final ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    return attr.getRequest().getSession(true); // true == allow create
}