Example usage for org.springframework.web.context.request WebRequest getAttribute

List of usage examples for org.springframework.web.context.request WebRequest getAttribute

Introduction

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

Prototype

@Nullable
Object getAttribute(String name, int scope);

Source Link

Document

Return the value for the scoped attribute of the given name, if any.

Usage

From source file:org.broadleafcommerce.profile.web.core.security.CustomerStateRequestProcessor.java

/**
 * Returns the anonymous customer that was saved in session. This first checks for a full customer in session (meaning
 * that the customer has not already been persisted) and returns that. If there is no full customer in session (and
 * there is instead just an anonymous customer ID) then this will look up the customer from the database using that and
 * return it./*ww  w . j  a  v  a  2  s.c om*/
 * 
 * @param request the current request
 * @return the anonymous customer in session or null if there is no anonymous customer represented in session
 * @see {@link #getAnonymousCustomerSessionAttributeName()} 
 * @see {@link #getAnonymousCustomerIdSessionAttributeName()}
 */
public Customer getAnonymousCustomer(WebRequest request) {
    if (BLCRequestUtils.isOKtoUseSession(request)) {
        Customer anonymousCustomer = (Customer) request.getAttribute(getAnonymousCustomerSessionAttributeName(),
                WebRequest.SCOPE_GLOBAL_SESSION);
        if (anonymousCustomer == null) {
            //Customer is not in session, see if we have just a customer ID in session (the anonymous customer might have
            //already been persisted)
            Long customerId = (Long) request.getAttribute(getAnonymousCustomerIdSessionAttributeName(),
                    WebRequest.SCOPE_GLOBAL_SESSION);
            if (customerId != null) {
                //we have a customer ID in session, look up the customer from the database to ensure we have an up-to-date
                //customer to store in CustomerState
                anonymousCustomer = customerService.readCustomerById(customerId);
            }
        }
        return anonymousCustomer;
    }
    return null;
}

From source file:org.cloudfoundry.identity.uaa.oauth.AccessController.java

@RequestMapping("/oauth/error")
public String handleError(WebRequest request, Map<String, Object> model) throws Exception {
    // There is already an error entry in the model
    Object object = request.getAttribute("error", RequestAttributes.SCOPE_REQUEST);
    if (object != null) {
        model.put("error", object);
    }//  w w w. j av a 2s.co m
    return "access_confirmation_error";
}

From source file:org.encuestame.oauth1.support.OAuth1RequestFlow.java

/**
 * Extract request token./*  w w w.ja v a 2  s .  c  o m*/
 * @param request
 * @return
 */
private OAuth1Token extractCachedRequestToken(WebRequest request) {
    OAuth1Token requestToken = (OAuth1Token) request.getAttribute(OAuthUtils.OAUTH_TOKEN_ATTRIBUTE,
            WebRequest.SCOPE_SESSION);
    request.removeAttribute(OAuthUtils.OAUTH_TOKEN_ATTRIBUTE, WebRequest.SCOPE_SESSION);
    log.debug("requestToken " + requestToken.toString());
    return requestToken;
}

From source file:org.focusns.web.portal.Portal.java

@RequestMapping("/portal")
public String doRender(@RequestParam(required = false) String mode,
        @RequestParam(required = false) String projectCode, @RequestParam String path, WebRequest webRequest)
        throws Exception {
    ///* w w w .  j  a va2s.  c om*/
    String categoryCode = null;
    // export project
    if (StringUtils.hasText(projectCode)) {
        Project project = projectService.getProject(projectCode);
        if (project != null) {
            ProjectCategory projectCategory = categoryService.getCategory(project.getCategoryId());
            categoryCode = projectCategory.getCode();
            //
            webRequest.setAttribute("project", project, WebRequest.SCOPE_REQUEST);
            webRequest.setAttribute(Project.KEY, project, WebRequest.SCOPE_REQUEST);
            webRequest.setAttribute("projectCategory", projectCategory, WebRequest.SCOPE_REQUEST);
            webRequest.setAttribute(ProjectCategory.KEY, projectCategory, WebRequest.SCOPE_REQUEST);
            // export feature
            String featureCode = webRequest.getParameter("featureCode");
            if (StringUtils.hasText(featureCode)) {
                ProjectFeature projectFeature = featureService.getProjectFeature(project.getId(), featureCode);
                webRequest.setAttribute("projectFeature", projectFeature, WebRequest.SCOPE_REQUEST);
                webRequest.setAttribute(ProjectFeature.KEY, projectFeature, WebRequest.SCOPE_REQUEST);
            }
        }
    }
    // export ProjectUser
    ProjectUser projectUser = (ProjectUser) webRequest.getAttribute(ProjectUser.KEY, WebRequest.SCOPE_SESSION);
    if (projectUser != null) {
        webRequest.setAttribute("user", projectUser, WebRequest.SCOPE_REQUEST);
        webRequest.setAttribute(ProjectUser.KEY, projectUser, WebRequest.SCOPE_REQUEST);
    }
    //
    PageConfig pageConfig = resolvePage(path, mode, categoryCode);
    Assert.notNull(pageConfig, String.format("Page %s not found!", path));
    //
    processPageConfig(pageConfig, webRequest);
    //
    webRequest.setAttribute("pageConfig", pageConfig, WebRequest.SCOPE_REQUEST);
    //
    return "viewName";
}

From source file:org.openmrs.web.controller.LoginController.java

/**
 * Generates an appropriate alert message and send it to users with the system developer role
 *
 * @param webRequest the {@link WebRequest} object
 * @param model the {@link ModelMap} object
 * @return the view name// w  w w  .  j  a va2 s .c  om
 */
@RequestMapping(LOGIN_FORM)
public String handleRequest(WebRequest webRequest, ModelMap model) {
    boolean failedPrivilegeCheck = false;
    Object attributeValue = webRequest.getAttribute(WebConstants.INSUFFICIENT_PRIVILEGES,
            WebRequest.SCOPE_SESSION);
    if (attributeValue != null) {
        if (Boolean.valueOf(attributeValue.toString().trim())) {
            failedPrivilegeCheck = true;
        }
        webRequest.removeAttribute(WebConstants.INSUFFICIENT_PRIVILEGES, WebRequest.SCOPE_SESSION);
    }

    //If there is a currently logged in user and they failed a privilege check, else go to login in page
    if (Context.getAuthenticatedUser() != null && failedPrivilegeCheck) {
        model.addAttribute("foundMissingPrivileges", true);
        webRequest.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.insufficientPrivileges",
                WebRequest.SCOPE_SESSION);

        String deniedPage = null;
        String requiredPrivileges = null;
        String exceptionMsg = null;
        String refererUrl = null;
        if (webRequest.getAttribute(WebConstants.DENIED_PAGE, WebRequest.SCOPE_SESSION) != null) {
            String deniedPageTemp = webRequest.getAttribute(WebConstants.DENIED_PAGE, WebRequest.SCOPE_SESSION)
                    .toString();
            webRequest.removeAttribute(WebConstants.DENIED_PAGE, WebRequest.SCOPE_SESSION);
            if (StringUtils.isNotBlank(deniedPageTemp)) {
                deniedPage = deniedPageTemp;
            }

        }
        if (webRequest.getAttribute(WebConstants.REQUIRED_PRIVILEGES, WebRequest.SCOPE_SESSION) != null) {
            String requiredPrivilegesTemp = webRequest
                    .getAttribute(WebConstants.REQUIRED_PRIVILEGES, WebRequest.SCOPE_SESSION).toString();
            webRequest.removeAttribute(WebConstants.REQUIRED_PRIVILEGES, WebRequest.SCOPE_SESSION);
            if (StringUtils.isNotBlank(requiredPrivilegesTemp)) {
                requiredPrivileges = requiredPrivilegesTemp;
            }
        }
        if (webRequest.getAttribute(WebConstants.UNCAUGHT_EXCEPTION_MESSAGE,
                WebRequest.SCOPE_SESSION) != null) {
            String exceptionMsgTemp = webRequest
                    .getAttribute(WebConstants.UNCAUGHT_EXCEPTION_MESSAGE, WebRequest.SCOPE_SESSION).toString();
            webRequest.removeAttribute(WebConstants.UNCAUGHT_EXCEPTION_MESSAGE, WebRequest.SCOPE_SESSION);
            if (StringUtils.isNotBlank(exceptionMsgTemp)) {
                exceptionMsg = exceptionMsgTemp;
            }
        }
        if (webRequest.getAttribute(WebConstants.REFERER_URL, WebRequest.SCOPE_SESSION) != null) {
            String refererUrlTemp = webRequest.getAttribute(WebConstants.REFERER_URL, WebRequest.SCOPE_SESSION)
                    .toString();
            webRequest.removeAttribute(WebConstants.REFERER_URL, WebRequest.SCOPE_SESSION);
            if (StringUtils.isNotBlank(refererUrlTemp) && !refererUrlTemp.contains("login.")) {
                refererUrl = refererUrlTemp;
            }
        }

        String alertMessage = null;
        if (requiredPrivileges != null && deniedPage != null) {
            alertMessage = Context.getMessageSourceService()
                    .getMessage("general.alert.requestPrivilegesForPage", new String[] {
                            Context.getAuthenticatedUser().getUsername(), requiredPrivileges, deniedPage },
                            null);
        } else if (exceptionMsg != null && deniedPage != null) {
            alertMessage = Context.getMessageSourceService().getMessage(
                    "general.alert.privilegesForPageOnException",
                    new String[] { exceptionMsg, Context.getAuthenticatedUser().getUsername(), deniedPage },
                    null);
        } else if (deniedPage != null) {
            alertMessage = Context.getMessageSourceService().getMessage(
                    "general.alert.requestUnKnownPrivilegesForPage",
                    new String[] { Context.getAuthenticatedUser().getUsername(), deniedPage }, null);
        } else if (requiredPrivileges != null) {
            alertMessage = Context.getMessageSourceService().getMessage("general.alert.requestPrivileges",
                    new String[] { Context.getAuthenticatedUser().getUsername(), requiredPrivileges }, null);
        } else if (exceptionMsg != null) {
            alertMessage = Context.getMessageSourceService().getMessage("general.alert.requestPrivileges",
                    new String[] { Context.getAuthenticatedUser().getUsername(), exceptionMsg }, null);
        }

        String reason = null;
        if (requiredPrivileges != null) {
            reason = Context.getMessageSourceService().getMessage("error.privilegesRequired",
                    new Object[] { requiredPrivileges }, null);
        } else if (exceptionMsg != null) {
            reason = exceptionMsg;
        } else {
            reason = Context.getMessageSourceService().getMessage("error.extraPrivilegesRequired");
        }

        //else we don't know both the page and privileges required, and there 
        //was no exception message that might contain the required privilege

        //will be sending the alert via ajax, so we need to escape js special chars
        model.put("alertMessage", JavaScriptUtils.javaScriptEscape(alertMessage));
        model.put("reason", reason);
        model.put("refererUrl", refererUrl);
    }

    return "/module/legacyui" + LOGIN_FORM;
}

From source file:org.sparkcommerce.core.web.order.security.CartStateRequestProcessor.java

@Override
public void process(WebRequest request) {
    Customer customer = CustomerState.getCustomer();

    if (customer == null) {
        LOG.warn(//from   ww w .  ja  va  2  s.c o  m
                "No customer was found on the current request, no cart will be added to the current request. Ensure that the"
                        + " blCustomerStateFilter occurs prior to the blCartStateFilter");
        return;
    }

    Order cart = getOverrideCart(request);

    if (cart == null && mergeCartNeeded(customer, request)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Merge cart required, calling mergeCart " + customer.getId());
        }
        cart = mergeCart(customer, request);
    } else if (cart == null) {
        cart = orderService.findCartForCustomer(customer);
    }

    if (cart == null) {
        cart = orderService.getNullOrder();
    } else {
        updateCartService.updateAndValidateCart(cart);
    }

    request.setAttribute(cartRequestAttributeName, cart, WebRequest.SCOPE_REQUEST);

    // Setup cart for content rule processing
    @SuppressWarnings("unchecked")
    Map<String, Object> ruleMap = (Map<String, Object>) request.getAttribute(SC_RULE_MAP_PARAM,
            WebRequest.SCOPE_REQUEST);
    if (ruleMap == null) {
        ruleMap = new HashMap<String, Object>();
    }
    ruleMap.put("order", cart);

    // Leaving the following line in for backwards compatibility, but all rules should use order as the 
    // variable name.
    ruleMap.put("cart", cart);
    request.setAttribute(SC_RULE_MAP_PARAM, ruleMap, WebRequest.SCOPE_REQUEST);

}

From source file:org.sparkcommerce.core.web.order.security.CartStateRequestProcessor.java

public Order getOverrideCart(WebRequest request) {
    Long orderId = null;/*from  w w w  .  j ava  2 s . c  om*/
    if (SCRequestUtils.isOKtoUseSession(request)) {
        orderId = (Long) request.getAttribute(OVERRIDE_CART_ATTR_NAME, WebRequest.SCOPE_GLOBAL_SESSION);
    }
    Order cart = null;
    if (orderId != null) {
        cart = orderService.findOrderById(orderId);

        if (cart == null || cart.getStatus().equals(OrderStatus.SUBMITTED)
                || cart.getStatus().equals(OrderStatus.CANCELLED)) {
            return null;
        }
    }

    return cart;
}

From source file:org.sparkcommerce.openadmin.web.filter.SparkAdminRequestProcessor.java

protected void prepareSandBox(WebRequest request, SparkRequestContext brc) {
    AdminUser adminUser = adminRemoteSecurityService.getPersistentAdminUser();
    if (adminUser == null) {
        //clear any sandbox
        if (SCRequestUtils.isOKtoUseSession(request)) {
            request.removeAttribute(SparkSandBoxResolver.SANDBOX_ID_VAR, WebRequest.SCOPE_GLOBAL_SESSION);
        }/*from   www.j av  a2  s.  c o  m*/
    } else {
        SandBox sandBox = null;
        if (StringUtils.isNotBlank(request.getParameter(SANDBOX_REQ_PARAM))) {
            Long sandBoxId = Long.parseLong(request.getParameter(SANDBOX_REQ_PARAM));
            sandBox = sandBoxService.retrieveUserSandBoxForParent(adminUser.getId(), sandBoxId);
            if (sandBox == null) {
                SandBox approvalOrUserSandBox = sandBoxService.retrieveSandBoxById(sandBoxId);
                if (approvalOrUserSandBox.getSandBoxType().equals(SandBoxType.USER)) {
                    sandBox = approvalOrUserSandBox;
                } else {
                    sandBox = sandBoxService.createUserSandBox(adminUser.getId(), approvalOrUserSandBox);
                }
            }
        }

        if (sandBox == null) {
            Long previouslySetSandBoxId = null;
            if (SCRequestUtils.isOKtoUseSession(request)) {
                previouslySetSandBoxId = (Long) request.getAttribute(SparkSandBoxResolver.SANDBOX_ID_VAR,
                        WebRequest.SCOPE_GLOBAL_SESSION);
            }
            if (previouslySetSandBoxId != null) {
                sandBox = sandBoxService.retrieveSandBoxById(previouslySetSandBoxId);
            }
        }

        if (sandBox == null) {
            List<SandBox> defaultSandBoxes = sandBoxService.retrieveSandBoxesByType(SandBoxType.DEFAULT);
            if (defaultSandBoxes.size() > 1) {
                throw new IllegalStateException("Only one sandbox should be configured as default");
            }

            SandBox defaultSandBox;
            if (defaultSandBoxes.size() == 1) {
                defaultSandBox = defaultSandBoxes.get(0);
            } else {
                defaultSandBox = sandBoxService.createDefaultSandBox();
            }

            sandBox = sandBoxService.retrieveUserSandBoxForParent(adminUser.getId(), defaultSandBox.getId());
            if (sandBox == null) {
                sandBox = sandBoxService.createUserSandBox(adminUser.getId(), defaultSandBox);
            }
        }

        // If the user just changed sandboxes, we want to update the database record.
        Long previouslySetSandBoxId = null;
        if (SCRequestUtils.isOKtoUseSession(request)) {
            previouslySetSandBoxId = (Long) request.getAttribute(SparkSandBoxResolver.SANDBOX_ID_VAR,
                    WebRequest.SCOPE_GLOBAL_SESSION);
        }
        if (previouslySetSandBoxId != null && !sandBox.getId().equals(previouslySetSandBoxId)) {
            adminUser.setLastUsedSandBoxId(sandBox.getId());
            adminUser = adminSecurityService.saveAdminUser(adminUser);
        }

        if (SCRequestUtils.isOKtoUseSession(request)) {
            request.setAttribute(SparkSandBoxResolver.SANDBOX_ID_VAR, sandBox.getId(),
                    WebRequest.SCOPE_GLOBAL_SESSION);
        }
        brc.setSandBox(sandBox);
        brc.getAdditionalProperties().put("adminUser", adminUser);
    }
}

From source file:org.springframework.data.neo4j.web.support.OpenSessionInViewInterceptor.java

@Override
public void preHandle(WebRequest request) throws DataAccessException {
    String participateAttributeName = getParticipateAttributeName();

    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    if (asyncManager.hasConcurrentResult()) {
        if (applyCallableInterceptor(asyncManager, participateAttributeName)) {
            return;
        }//from  w w  w  .j  a v a2 s.  c  om
    }

    if (TransactionSynchronizationManager.hasResource(getSessionFactory())) {
        // Do not modify the Session: just mark the request accordingly.
        Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
        int newCount = (count != null ? count + 1 : 1);
        request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
    } else {
        logger.debug("Opening Neo4j OGM Session in OpenSessionInViewInterceptor");
        Session session = sessionFactory.openSession();
        SessionHolder sessionHolder = new SessionHolder(session);
        TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder);

        AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(getSessionFactory(), sessionHolder);
        asyncManager.registerCallableInterceptor(participateAttributeName, interceptor);
        asyncManager.registerDeferredResultInterceptor(participateAttributeName, interceptor);
    }
}

From source file:org.springframework.data.neo4j.web.support.OpenSessionInViewInterceptor.java

private boolean decrementParticipateCount(WebRequest request) {
    String participateAttributeName = getParticipateAttributeName();
    Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
    if (count == null) {
        return false;
    }//from   w w w . j  a  va2s  . c  o  m
    // Do not modify the Session: just clear the marker.
    if (count > 1) {
        request.setAttribute(participateAttributeName, count - 1, WebRequest.SCOPE_REQUEST);
    } else {
        request.removeAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
    }
    return true;
}