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

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

Introduction

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

Prototype

@Nullable
public static RequestAttributes getRequestAttributes() 

Source Link

Document

Return the RequestAttributes currently bound to the thread.

Usage

From source file:com.emaxcore.emaxdata.common.web.Servlets.java

/**
 * ??//from   w w w.  jav a2s  .  c  om
 * @return
 */
public static HttpServletRequest getRequest() {
    try {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    } catch (Exception e) {
        logger.warn(e + "");
        return null;
    }
}

From source file:org.jasig.portlet.calendar.adapter.exchange.ExchangeCredentialsInitializationService.java

public void initialize(PortletRequest request) {

    Object credentials;//from   w  ww. java 2 s .  c  o m
    PortletPreferences prefs = request.getPreferences();

    // 1. Exchange Impersonation
    if (usesExchangeImpersonation(request)) {
        String exchangeImpersonationUsername = prefs.getValue(PREFS_IMPERSONATION_USERNAME, "");
        String exchangeImpersonationPassword = prefs.getValue(PREFS_IMPERSONATION_PASSWORD, "");

        //do not fill in the domain field else authentication fails with a 503, service not available response
        credentials = new NTCredentials(exchangeImpersonationUsername, exchangeImpersonationPassword,
                "paramDoesNotSeemToMatter", "");
        logger.debug("Creating Exchange Impersonation credentials for EWS call");
    } else {

        // Get the password from the UserInfo map.
        @SuppressWarnings("unchecked")
        Map<String, String> userInfo = (Map<String, String>) request.getAttribute(PortletRequest.USER_INFO);
        String password = userInfo.get(passwordAttribute);
        if (password == null) {
            throw new CalendarException(
                    "Required user attribute password is null. Insure user-attribute password"
                            + " is enabled in portlet.xml and CAS ClearPass is configured properly");
        }

        // 2. If the domain is specified, return NT credentials from the username, password, and domain.
        String ntDomain = getNtlmDomain(request);
        if (StringUtils.isNotBlank(ntDomain)) {
            String username = userInfo.get(usernameAttribute);
            credentials = createNTCredentials(ntDomain, username, password);
            logger.debug("Creating NT credentials for {}", username);
        } else {
            // 3. Otherwise construct credentials from the email address and password for Office365 integration.
            String emailAddress = userInfo.get(this.mailAttribute);
            if (emailAddress == null) {
                throw new CalendarException(
                        "Required user attribute email address is null. Insure user-attribute mail"
                                + " is enabled in portlet.xml and populated via LDAP or other approach");
            }
            credentials = new UsernamePasswordCredentials(emailAddress, password);
            logger.debug("Creating simple username/password credentials for {}", emailAddress);

        }
    }

    // cache the credentials object to this thread
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes == null) {
        requestAttributes = new PortletRequestAttributes(request);
        RequestContextHolder.setRequestAttributes(requestAttributes);
    }
    requestAttributes.setAttribute(ExchangeWsCredentialsProvider.EXCHANGE_CREDENTIALS_ATTRIBUTE, credentials,
            RequestAttributes.SCOPE_SESSION);
}

From source file:aode.lx.service.impl.BaseServiceImpl.java

@Override
public Page<T> searchPaginated(Map<String, SearchFilter> additionalFilters) {
    RequestAttributes ar = RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = ((ServletRequestAttributes) ar).getRequest();
    PageRequest pageRequest = PageRequestBulider.getPageRequest(request);
    Map<String, SearchFilter> filters = SearchFilter.parse(request);
    addAdditionalFilters(filters, additionalFilters);
    Specification<T> spec = DynamicSpecifications.bySearchFilter(filters.values(), this.entityClass);
    Page<T> page = null;//from w w  w.  ja v  a 2 s .  c  o  m
    page = this.getRepository().findAll(spec, pageRequest);
    return page;
}

From source file:org.magnum.dataup.VideoSvcCtrl.java

/**
 * Helps the helper method for getting the url of a video by
 * generating the urlbase for a local server
 *//*from w ww .ja va 2  s .  co  m*/
public String getUrlBaseForLocalServer() {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
            .getRequest();
    String base = "http://" + request.getServerName()
            + ((request.getServerPort() != 80) ? ":" + request.getServerPort() : "");
    return base;
}

From source file:org.gooru.insights.api.security.MethodAuthorizationAspect.java

private boolean hasApiOperationsAuthority(AuthorizeOperations authorizeOperations, ProceedingJoinPoint pjp) {

    HttpServletRequest request = null;//  ww w  . j a v  a2s  . c  o m
    HttpSession session = null;
    String sessionToken = null;
    Map<String, Boolean> validStatus = new HashMap<String, Boolean>();
    validStatus.put(PROCEED, false);
    if (RequestContextHolder.getRequestAttributes() != null) {
        request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        session = request.getSession(true);
        sessionToken = RequestUtils.getSessionToken(request);
    }
    if (sessionToken != null) {
        String address = endPoint.getColumnByName(ApiConstants.CONSTANT_VALUE).getStringValue()
                + "/v2/user/token/" + sessionToken + "?sessionToken=" + sessionToken;
        ClientResource client = new ClientResource(address);
        Form headers = (Form) client.getRequestAttributes().get("org.restlet.http.headers");
        if (headers == null) {
            headers = new Form();
        }
        headers.add(ApiConstants.GOORU_SESSION_TOKEN, sessionToken);
        client.getRequestAttributes().put("org.restlet.http.headers", headers);
        if (client.getStatus().isSuccess()) {
            try {
                Representation representation = client.get();
                JsonRepresentation jsonRepresentation = new JsonRepresentation(representation);
                JSONObject jsonObj = jsonRepresentation.getJsonObject();
                User user = new User();
                user.setFirstName(jsonObj.getString(ApiConstants.FIRST_NAME));
                user.setLastName(jsonObj.getString(ApiConstants.LAST_NAME));
                user.setEmailId(jsonObj.getString(ApiConstants.EMAIL_ID));
                user.setGooruUId(jsonObj.getString(ApiConstants.GOORU_U_ID));
                if (hasGooruAdminAuthority(authorizeOperations, jsonObj)
                        || hasAuthority(authorizeOperations, jsonObj, request)) {
                    session.setAttribute(ApiConstants.SESSION_TOKEN, sessionToken);
                    return true;
                }
            } catch (Exception e) {
                throw new AccessDeniedException("Invalid sessionToken!");
            }
        } else {
            throw new AccessDeniedException("Invalid sessionToken!");
        }
    } else {
        InsightsLogger.debug("session token is null");
        throw new AccessDeniedException("sessionToken can not be NULL!");
    }
    return false;
}

From source file:org.magnum.dataup.VideoController.java

private String getUrlBaseForLocalServer() {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
            .getRequest();//  ww  w. j a v a2  s  .  c  o  m
    InetAddress IP = null;
    try {
        IP = getLocalHostLANAddress();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    System.out.println("IP of my system is := " + IP.getHostAddress());
    String base = "http://" + IP.getHostAddress()
            + ((request.getServerPort() != 80) ? ":" + request.getServerPort() : "");
    System.out.println("dataUrl is :" + base);
    return base;
}

From source file:aode.lx.service.impl.BaseServiceImpl.java

@Override
public Page<T> searchPaginated(Map<String, SearchFilter> additionalFilters, Pageable pageable) {
    RequestAttributes ar = RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = ((ServletRequestAttributes) ar).getRequest();
    Map<String, SearchFilter> filters = SearchFilter.parse(request);
    addAdditionalFilters(filters, additionalFilters);
    Specification<T> spec = DynamicSpecifications.bySearchFilter(filters.values(), this.entityClass);
    Page<T> page = null;//  w ww .java 2  s  .com
    page = this.getRepository().findAll(spec, pageable);
    return page;
}

From source file:org.gooru.insights.security.MethodAuthorizationAspect.java

public Map<String, Boolean> hasRedisOperations(AuthorizeOperations authorizeOperations,
        ProceedingJoinPoint pjp) {/* ww  w. j a v  a  2  s .c  om*/

    HttpServletRequest request = null;
    HttpSession session = null;
    String sessionToken = null;
    Map<String, Boolean> validStatus = new HashMap<String, Boolean>();
    validStatus.put(APIConstants.PROCEED, false);
    validStatus.put(DO_API, false);
    if (RequestContextHolder.getRequestAttributes() != null) {
        request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        session = request.getSession(true);
    }
    sessionToken = getSessionToken(request);
    if (sessionToken != null && !sessionToken.isEmpty()) {
        try {
            String result = redisService.getDirectValue(GOORU_PREFIX + sessionToken);
            if (result == null || result.isEmpty()) {
                InsightsLogger.error(ASPECT,
                        ErrorConstants.IS_NULL.replace(ErrorConstants.REPLACER, ErrorConstants.REDIS_DATA)
                                + GOORU_PREFIX + sessionToken);
                validStatus.put(DO_API, true);
                return validStatus;
            }
            JSONObject jsonObject = new JSONObject(result);
            jsonObject = new JSONObject(jsonObject.getString(APIConstants.USER_TOKEN));
            jsonObject = new JSONObject(jsonObject.getString(APIConstants.USER));
            User user = new User();
            user.setFirstName(jsonObject.getString(APIConstants.FIRST_NAME));
            user.setLastName(jsonObject.getString(APIConstants.LAST_NAME));
            user.setEmailId(jsonObject.getJSONArray(APIConstants.IDENTITIES).getJSONObject(0)
                    .getString(APIConstants.EXTERNAL_ID));
            user.setGooruUId(jsonObject.getString(APIConstants.PARTY_UID));
            if (hasGooruAdminAuthority(authorizeOperations, jsonObject)) {
                session.setAttribute(APIConstants.SESSION_TOKEN, sessionToken);
                validStatus.put(APIConstants.PROCEED, true);
                return validStatus;
            }
            if (hasAuthority(authorizeOperations, jsonObject)) {
                session.setAttribute(APIConstants.SESSION_TOKEN, sessionToken);
                validStatus.put(APIConstants.PROCEED, true);
                return validStatus;
            }
        } catch (Exception e) {
            InsightsLogger.error(ASPECT,
                    ErrorConstants.EXCEPTION_IN.replace(ErrorConstants.REPLACER, ErrorConstants.REDIS), e);
            validStatus.put(DO_API, true);
            return validStatus;
        }
    } else {
        throw new AccessDeniedException(
                MessageHandler.getMessage(ErrorConstants.E102, new String[] { APIConstants.SESSION_TOKEN }));
    }
    return validStatus;
}