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:architecture.user.security.authentication.impl.DefaultAuthenticationProvider.java

protected String getLocalName() {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
            .getRequest();
    return request.getLocalName();
}

From source file:com.hack23.cia.web.impl.ui.application.views.user.home.pagemode.UserHomeOverviewPageModContentFactoryImpl.java

@Secured({ "ROLE_USER", "ROLE_ADMIN" })
@Override// w w  w.ja  v  a  2s .c  om
public Layout createContent(final String parameters, final MenuBar menuBar, final Panel panel) {
    final VerticalLayout panelContent = createPanelContent();

    final String pageId = getPageId(parameters);

    userHomeMenuItemFactory.createUserHomeMenuBar(menuBar, pageId);

    LabelFactory.createHeader2Label(panelContent, OVERVIEW);

    final Button logoutButton = new Button(LOGOUT, FontAwesome.SIGN_OUT);

    final LogoutRequest logoutRequest = new LogoutRequest();
    logoutRequest.setSessionId(RequestContextHolder.currentRequestAttributes().getSessionId());
    logoutButton.addClickListener(new LogoutClickListener(logoutRequest, getApplicationManager()));

    panelContent.addComponent(logoutButton);

    final DataContainer<UserAccount, Long> dataContainer = getApplicationManager()
            .getDataContainer(UserAccount.class);

    final Long userIdFromSecurityContext = UserContextUtil.getUserInternalIdFromSecurityContext();

    if (userIdFromSecurityContext == null) {
        UI.getCurrent().getNavigator().navigateTo(CommonsViews.MAIN_VIEW_NAME);
    } else {

        final UserAccount userAccount = dataContainer.load(userIdFromSecurityContext);

        getFormFactory().addFormPanelTextFields(panelContent, new BeanItem<>(userAccount), UserAccount.class,
                Arrays.asList(
                        new String[] { "username", "createdDate", "email", "country", "numberOfVisits" }));

        final DataContainer<ApplicationActionEvent, Long> eventDataContainer = getApplicationManager()
                .getDataContainer(ApplicationActionEvent.class);

        final BeanItemContainer<ApplicationActionEvent> politicianDocumentDataSource = new BeanItemContainer<>(
                ApplicationActionEvent.class,
                eventDataContainer.findOrderedListByProperty(ApplicationActionEvent_.userId,
                        userAccount.getUserId(), ApplicationActionEvent_.createdDate));

        getGridFactory().createBasicBeanItemGrid(panelContent, politicianDocumentDataSource,
                "ApplicationActionEvent",
                new String[] { "hjid", "createdDate", "eventGroup", "applicationOperation", "actionName",
                        "page", "pageMode", "elementId", "applicationMessage", "errorMessage",
                        "modelObjectVersion" },
                new String[] { "hjid", "userId", "sessionId", "modelObjectId", "modelObjectVersion" },
                new PageItemPropertyClickListener(AdminViews.ADMIN_APPLICATIONS_EVENTS_VIEW_NAME, "hjid"), null,
                null);

        panelContent.setExpandRatio(logoutButton, ContentRatio.SMALL);

    }

    panel.setCaption(USERHOME);

    getPageActionEventHelper().createPageEvent(ViewAction.VISIT_USER_HOME_VIEW, ApplicationEventGroup.USER,
            NAME, parameters, pageId);

    return panelContent;

}

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

@Override
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
    String authenticationKey = authenticationKeyGenerator.extractKey(authentication);
    String userLogin = authentication.getName();

    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    Locale locale = restAuthUtils.extractLocaleFromRequestHeader(request);
    String refreshTokenValue = token.getRefreshToken() != null ? token.getRefreshToken().getValue() : null;
    serverTokenStore.storeAccessToken(token.getValue(), serializeAccessToken(token), authenticationKey,
            serializeAuthentication(authentication), token.getExpiration(), userLogin, locale,
            refreshTokenValue);/*w  w w  .  ja  v a 2  s  . c  om*/
    processSession(authentication, token.getValue());
    log.info("REST API access token stored: [{}] {}", authentication.getPrincipal(), token.getValue());
}

From source file:com.bisone.saiku.security.replace.SessionService.java

private void createSession(Authentication auth, String username, String password) {

    if (auth == null || !auth.isAuthenticated()) {
        return;//from  w ww  .j  a v a 2s .  com
    }

    boolean isAnonymousUser = (auth instanceof AnonymousAuthenticationToken);
    Object p = auth.getPrincipal();
    String authUser = getUsername(p);
    boolean isAnonymous = (isAnonymousUser || StringUtils.equals("anonymousUser", authUser));
    boolean isAnonOk = (!isAnonymous || (isAnonymous && anonymous));

    if (isAnonOk && auth.isAuthenticated() && p != null && !sessionHolder.containsKey(p)) {
        Map<String, Object> session = new HashMap<String, Object>();

        if (isAnonymous) {
            log.debug("Creating Session for Anonymous User");
        }

        if (StringUtils.isNotBlank(username)) {
            session.put("username", username);
        } else {
            session.put("username", authUser);
        }
        if (StringUtils.isNotBlank(password)) {
            session.put("password", password);
        }
        session.put("sessionid", UUID.randomUUID().toString());
        session.put("authid", RequestContextHolder.currentRequestAttributes().getSessionId());
        List<String> roles = new ArrayList<String>();
        for (GrantedAuthority ga : SecurityContextHolder.getContext().getAuthentication().getAuthorities()) {
            roles.add(ga.getAuthority());
        }
        session.put("roles", roles);

        sessionHolder.put(p, session);
    }

}

From source file:org.grails.plugins.zkui.metaclass.RedirectDynamicMethod.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*from ww w  . j  av  a 2 s.  c o m*/
public Object invoke(Object target, String methodName, Object[] arguments) {
    if (arguments.length == 0) {
        throw new MissingMethodException(METHOD_SIGNATURE, target.getClass(), arguments);
    }

    Map argMap = arguments[0] instanceof Map ? (Map) arguments[0] : Collections.EMPTY_MAP;
    if (argMap.isEmpty()) {
        throw new MissingMethodException(METHOD_SIGNATURE, target.getClass(), arguments);
    }

    GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.currentRequestAttributes();

    HttpServletRequest request = webRequest.getCurrentRequest();
    if (request.getAttribute(GRAILS_REDIRECT_ISSUED) != null) {
        throw new CannotRedirectException(
                "Cannot issue a redirect(..) here. A previous call to redirect(..) has already redirected the response.");
    }

    HttpServletResponse response = webRequest.getCurrentResponse();
    if (response.isCommitted()) {
        throw new CannotRedirectException(
                "Cannot issue a redirect(..) here. The response has already been committed either by another redirect or by directly writing to the response.");
    }

    Object uri = argMap.get(ARGUMENT_URI);
    String url = argMap.containsKey(ARGUMENT_URL) ? argMap.get(ARGUMENT_URL).toString() : null;
    String actualUri;
    if (uri != null) {
        GrailsApplicationAttributes attrs = webRequest.getAttributes();
        actualUri = attrs.getApplicationUri(request) + uri.toString();
    } else if (url != null) {
        actualUri = url;
    } else {
        if (argMap.get(ARGUMENT_ACTION) == null || argMap.get(ARGUMENT_CONTROLLER) == null) {
            throw new CannotRedirectException(
                    "redirect required attribute [controller] or attribute [action] is missing");
        }
        String actionName = argMap.get(ARGUMENT_ACTION).toString();
        String controllerName = argMap.get(ARGUMENT_CONTROLLER).toString();
        controllerName = controllerName != null ? controllerName : webRequest.getControllerName();

        Map params = (Map) argMap.get(ARGUMENT_PARAMS);
        if (params == null) {
            params = new HashMap();
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Dynamic method [redirect] looking up URL mapping for controller [" + controllerName
                    + "] and action [" + actionName + "] and params [" + params + "] with [" + urlMappingsHolder
                    + "]");
        }

        Object id = argMap.get(ARGUMENT_ID);
        try {
            if (id != null) {
                params.put(ARGUMENT_ID, id);
            }

            UrlCreator urlMapping = urlMappingsHolder.getReverseMapping(controllerName, actionName, params);
            if (urlMapping == null && LOG.isDebugEnabled()) {
                LOG.debug("Dynamic method [redirect] no URL mapping found for params [" + params + "]");
            }

            String frag = argMap.get(ARGUMENT_FRAGMENT) != null ? argMap.get(ARGUMENT_FRAGMENT).toString()
                    : null;
            actualUri = urlMapping.createURL(controllerName, actionName, params, request.getCharacterEncoding(),
                    frag);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Dynamic method [redirect] mapped to URL [" + actualUri + "]");
            }
        } finally {
            if (id != null) {
                params.remove(ARGUMENT_ID);
            }
        }
    }

    return redirectResponse(actualUri, request, response);
}

From source file:eu.supersede.fe.security.SecurityConfiguration.java

@Bean
AuthenticationProvider customAuthenticationProvider() {
    return new AuthenticationProvider() {
        private final Logger log = LoggerFactory.getLogger(this.getClass());

        @Override//from   ww w  . j av  a 2  s .  co  m
        @Transactional
        public Authentication authenticate(Authentication auth) throws AuthenticationException {
            String username = (String) auth.getPrincipal();
            String password = (String) auth.getCredentials();

            ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder
                    .currentRequestAttributes();
            HttpServletRequest req = attr.getRequest();
            String tenantId = req.getHeader("TenantId");

            if (tenantId == null) {
                log.error("Tenant provided");
                throw new BadCredentialsException("Invalid login request: missing tenant");
            }

            AuthorizationToken token = getAuthToken(username, password, tenantId);
            User user = users.findByUsername(username);

            if (user == null) {
                log.error("Username not found in Database");
                throw new BadCredentialsException("Invalid login request: user " + username + " not found");
            }

            // get authorities from profiles
            List<Profile> profiles = user.getProfiles();
            String[] authorities = new String[profiles.size()];

            for (int i = 0; i < profiles.size(); i++) {
                authorities[i] = "ROLE_" + profiles.get(i).getName();
            }

            log.debug("User has " + authorities.length + " authorities");

            List<GrantedAuthority> permissions = AuthorityUtils.createAuthorityList(authorities);
            DatabaseUser dbUser = new DatabaseUser(user.getUserId(),
                    user.getFirstName() + " " + user.getLastName(), user.getEmail(), password, token, true,
                    true, true, true, permissions, user.getLocale());

            return new UsernamePasswordAuthenticationToken(dbUser, password, permissions);// AUTHORITIES
        }

        private AuthorizationToken getAuthToken(String username, String password, String tenantId) {
            AuthorizationToken token = null;

            if (AUTH_MANAGER_ENABLED) {
                try {
                    token = proxy.getIFAuthenticationManager(tenantId).getAuthorizationToken(username, password,
                            tenantId);
                } catch (HttpClientErrorException e) {
                    log.error("Invalid username and password.");
                } catch (NullPointerException e1) {
                    log.error("Authorization token is null, check your if.properties file in the conf/ folder");
                } catch (Exception e2) {
                    e2.printStackTrace();
                }

                if (token == null || token.getAccessToken() == null) {
                    log.error("Supersede integration token is null");
                    throw new BadCredentialsException(
                            "Invalid login request: authentication manager token is null");
                }
            } else {
                log.warn("IF Authentication Manager disable, user token is NULL");
            }

            return token;
        }

        @Override
        @SuppressWarnings("rawtypes")
        public boolean supports(Class authentication) {
            return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
        }
    };
}

From source file:com.jaspersoft.jasperserver.remote.settings.DateTimeSettingsProvider.java

private File getSettingsFile(String path) {
    ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    HttpServletRequest request = attr.getRequest();
    ServletContext servletContext = request.getSession().getServletContext();
    String realPath = servletContext.getRealPath(path);

    return new File(realPath);
}

From source file:com.autentia.wuija.widget.ChangePasswordCtrl.java

public int getMaximumValidityPeriodOnDays() {
    FacesRequestAttributes attr = (FacesRequestAttributes) RequestContextHolder.currentRequestAttributes();
    return ((Integer) attr.getAttribute("MAXIMUM_VALIDITY_PERIOD", RequestAttributes.SCOPE_SESSION)).intValue();
}

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

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

    if (DEBUG) {//from  w  ww .j av a 2 s  .c o m
        DEBUGGER.debug(methodName);
    }

    ModelAndView mView = new ModelAndView();

    final ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    final HttpServletRequest hRequest = requestAttributes.getRequest();
    final HttpSession hSession = hRequest.getSession();
    final String lang = hRequest.getParameter(Constants.PARAMETER_LANG);

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

        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);
        }
    }

    try {
        ProductRequest productRequest = new ProductRequest();
        productRequest.setIsFeatured(true);
        productRequest.setLang((StringUtils.isBlank(lang)) ? "en" : lang);

        if (DEBUG) {
            DEBUGGER.debug("ProductRequest: {}", productRequest);
        }

        ProductResponse productResponse = this.productRefSvc.getFeaturedProducts(productRequest);

        if (DEBUG) {
            DEBUGGER.debug("ProductResponse: {}", productResponse);
        }

        if (productResponse.getRequestStatus() == CoreServicesStatus.SUCCESS) {
            List<Product> featuredProducts = productResponse.getProductList();

            if (DEBUG) {
                DEBUGGER.debug("List<Product>: {}", featuredProducts);
            }

            mView.addObject("featuredProducts", featuredProducts);
        }

        mView.addObject("command", new Product());
        mView.setViewName(this.defaultPage);
    } catch (ProductRequestException prx) {
        ERROR_RECORDER.error(prx.getMessage(), prx);

        mView = new ModelAndView(new RedirectView());
        mView.setViewName(this.appConfig.getErrorResponsePage());
    }

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

    return mView;
}