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

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

Introduction

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

Prototype

void setAttribute(String name, Object value, int scope);

Source Link

Document

Set the value for the scoped attribute of the given name, replacing an existing value (if any).

Usage

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 {
    ///*from  w w w  .  jav  a  2s.c  o  m*/
    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.module.dhisreport.web.controller.ReportController.java

@RequestMapping(value = "/module/dhisreport/executeReport", method = RequestMethod.POST)
public String executeReport(ModelMap model,
        @RequestParam(value = "reportDefinition_id", required = true) Integer reportDefinition_id,
        @RequestParam(value = "location", required = false) String OU_Code,
        @RequestParam(value = "resultDestination", required = true) String destination,
        @RequestParam(value = "date", required = true) String dateStr,
        @RequestParam(value = "frequency", required = true) String freq,
        @RequestParam(value = "prior", required = true) String prior, WebRequest webRequest,
        HttpServletRequest request) throws Exception {
    DHIS2ReportingService service = Context.getService(DHIS2ReportingService.class);
    Period period = null;//w  w  w.  j  av a2s.  c  o  m
    //System.out.println( "freeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" + freq );
    //System.out.println( "dasdasssssssssssssssssssss" + dateStr );

    if (freq.equalsIgnoreCase("monthly")) {
        if (dateStr.length() > 7)
            dateStr = replacedateStrMonth(dateStr);
        dateStr = dateStr.concat("-01");
        try {
            //System.out.println( "helloooooooooo1=====" + dateStr );
            period = new MonthlyPeriod(new SimpleDateFormat("yyyy-MM-dd").parse(dateStr));
            // System.out.println( "helloooooooooo2=====" + period );
        } catch (ParseException pex) {
            log.error("Cannot convert passed string to date... Please check dateFormat", pex);
            webRequest.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                    Context.getMessageSourceService().getMessage("Date Parsing Error"),
                    WebRequest.SCOPE_SESSION);
            return null;
        }
    }
    if (freq.equalsIgnoreCase("weekly")) {
        try {
            String finalweek = "";
            String[] modify_week = dateStr.split("W");
            Integer weekvalue = Integer.parseInt(dateStr.substring(dateStr.indexOf('W') + 1)) + 1;
            if (weekvalue > 9) {
                weekvalue = weekvalue == 54 ? 53 : weekvalue;
                finalweek = modify_week[0].concat("W" + weekvalue.toString());
            } else {
                finalweek = modify_week[0].concat("W0" + weekvalue.toString());
            }

            period = new WeeklyPeriod(new SimpleDateFormat("yyyy-'W'ww").parse(finalweek));
        } catch (ParseException ex) {
            log.error("Cannot convert passed string to date... Please check dateFormat", ex);
            webRequest.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                    Context.getMessageSourceService().getMessage("Date Parsing Error"),
                    WebRequest.SCOPE_SESSION);
            return null;
        }
    }
    if (freq.equalsIgnoreCase("daily")) {

        webRequest.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                Context.getMessageSourceService().getMessage("dhisreport.dateFormatError"),
                WebRequest.SCOPE_SESSION);
        return null;

    }

    // Get Location by OrgUnit Code
    //Location location = service.getLocationByOU_Code( OU_Code );
    // System.out.println( "helloooooooooo3=====" + period );
    List<DataValueSet> dvsList = new ArrayList<DataValueSet>();
    List<Location> locationList = new ArrayList<Location>();
    List<Location> locationListFinal = new ArrayList<Location>();
    //locationList.add( location );
    //locationList.add( service.getLocationByOU_Code( "Gahombo" ) );
    locationList.addAll(Context.getLocationService().getAllLocations());

    //remove locations without Organization Unit codes
    for (Location l : locationList) {
        for (LocationAttribute la : l.getActiveAttributes()) {
            if (la.getAttributeType().getName().equals("CODE")) {
                //System.out.println( "Name-----" + la.getAttributeType().getName() + "Value---" + la.getValue() );
                if (!la.getValue().toString().isEmpty() && la.getValue().toString() != null) {
                    locationListFinal.add(l);
                    break;
                }

            }

        }
    }

    Map<String, Map> desetList = new HashMap<String, Map>();
    List<AggregatedResultSet> aggregatedList = new ArrayList<AggregatedResultSet>();
    if (locationListFinal.isEmpty() && !locationList.isEmpty()) {
        log.error("Location attribute CODE not set");
        request.getSession().setAttribute("errorMessage",
                "Please set location attribute CODE to generate results.");
        String referer = webRequest.getHeader("Referer");
        return "redirect:" + referer;
    }

    boolean priority = false;
    if (prior.equals("report")) {
        priority = true;
    }

    for (Location l : locationListFinal) {
        AggregatedResultSet agrs = new AggregatedResultSet();
        DataValueSet dvs = service.evaluateReportDefinition(service.getReportDefinition(reportDefinition_id),
                period, l, priority);
        for (LocationAttribute la : l.getActiveAttributes()) {
            if (la.getAttributeType().getName().equals("CODE"))
                dvs.setOrgUnit(la.getValue().toString());
        }
        // Set OrgUnit code into DataValueSet

        List<DataValue> datavalue = dvs.getDataValues();
        Map<DataElement, String> deset = new HashMap<DataElement, String>();
        for (DataValue dv : datavalue) {

            DataElement detrmp = service.getDataElementByCode(dv.getDataElement());
            // System.out.println( detrmp.getName() + detrmp.getCode() );
            deset.put(detrmp, dv.getValue());
        }
        agrs.setDataValueSet(dvs);
        agrs.setDataElementMap(deset);
        AdxType adxType = getAdxType(dvs, dateStr);

        if (destination.equals("post")) {
            ImportSummaries importSummaries = Context.getService(DHIS2ReportingService.class)
                    .postAdxReport(adxType);
            agrs.setImportSummaries(importSummaries);
        }
        aggregatedList.add(agrs);
    }

    org.openmrs.module.reporting.report.definition.ReportDefinition rrd = Context
            .getService(ReportDefinitionService.class)
            .getDefinitionByUuid(service.getReportDefinition(reportDefinition_id).getReportingReportId());

    Map<String, Object> param = new HashMap<String, Object>();
    param.put("startDate", period.getStartDate());
    param.put("endDate", period.getEndDate());
    if (rrd != null) {
        ReportRequest rq = new ReportRequest();
        rq.setReportDefinition(
                new Mapped<org.openmrs.module.reporting.report.definition.ReportDefinition>(rrd, param));
        rq.setRenderingMode(new RenderingMode(new DefaultWebRenderer(), "Web", null, 100));
        Report report = Context.getService(ReportService.class).runReport(rq);
        model.addAttribute("resultUuid", rq.getUuid());
    } else {
        model.addAttribute("resultUuid", null);
    }
    model.addAttribute("user", Context.getAuthenticatedUser());
    model.addAttribute("aggregatedList", aggregatedList);
    return null;
}

From source file:org.openmrs.module.reporting.web.controller.ScriptedCompositionPatientDataDefinitionController.java

/**
 * Copies the composition patient data definition with the given uuid into another one with the
 * same parameters and contained definitions, but blank name/description and composition string
 * /*  w ww.j a va  2 s.c  o m*/
 * @param uuid
 * @return
 */
@RequestMapping("/module/reporting/definition/scriptedCompositionPatientDataDefinitionClone")
public String cloneDefinition(WebRequest request, @RequestParam("name") String name,
        @RequestParam(value = "description", required = false) String description,
        @RequestParam("copyFromUuid") String copyFromUuid) {
    PatientDataDefinition def = Context.getService(PatientDataService.class).getDefinitionByUuid(copyFromUuid);
    ScriptedCompositionPatientDataDefinition from = (ScriptedCompositionPatientDataDefinition) def;

    ScriptedCompositionPatientDataDefinition clone = new ScriptedCompositionPatientDataDefinition();
    clone.setName(name);
    clone.setDescription(description);
    clone.setParameters(from.getParameters());
    clone.setContainedDataDefinitions(from.getContainedDataDefinitions());
    clone.setScriptCode(from.getScriptCode());
    clone.setScriptType(from.getScriptType());
    Context.getService(PatientDataService.class).saveDefinition(clone);
    request.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Saved as a new copy", WebRequest.SCOPE_SESSION);
    return "redirect:scriptedCompositionPatientDataDefinition.form?uuid=" + clone.getUuid();
}

From source file:org.openmrs.module.reporting.web.datasets.LogicDataSetEditor.java

@RequestMapping("/module/reporting/datasets/logicDataSetEditorSave")
public String saveLogicDataset(ModelMap model, @RequestParam(required = false, value = "uuid") String uuid,
        @RequestParam(required = false, value = "name") String name,
        @RequestParam(required = false, value = "description") String description, WebRequest request) {
    DataSetDefinitionService svc = Context.getService(DataSetDefinitionService.class);
    LogicDataSetDefinition definition = uuid == null ? new LogicDataSetDefinition()
            : (LogicDataSetDefinition) svc.getDefinition(uuid, LogicDataSetDefinition.class);

    definition.setName(name);/*from w w w. j a  va2s . co m*/
    definition.setDescription(description);

    definition.clearColumns();
    int numColumns = request.getParameterValues("columnLogic").length;
    for (int i = 0; i < numColumns; ++i) {
        String columnName = request.getParameterValues("columnName")[i];
        String columnLabel = request.getParameterValues("columnLabel")[i];
        String columnLogic = request.getParameterValues("columnLogic")[i];
        String columnFormat = request.getParameterValues("columnFormat")[i];
        if (!StringUtils.isBlank(columnName) && !StringUtils.isBlank(columnLogic))
            definition.addColumn(columnName, columnLabel, columnLogic, columnFormat);
    }

    try {
        boolean foundInvalidExpression = false;
        ArrayList<String> invalidTokens = null;
        //validate each logic expression
        for (Column col : definition.getColumns()) {
            if (!LogicUtil.isValidLogicExpression(col.getLogic())) {
                foundInvalidExpression = true;
                if (invalidTokens == null)
                    invalidTokens = new ArrayList<String>();
                invalidTokens.add(col.getLogic());
            }
        }

        if (foundInvalidExpression) {
            String dynamicText = (invalidTokens.size() == 1) ? "value is" : "values are";
            request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "The following logic expression "
                    + dynamicText + " invalid: " + StringUtils.join(invalidTokens, ", "),
                    WebRequest.SCOPE_SESSION);
        } else
            svc.saveDefinition(definition);

    } catch (LogicException e) {
        request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, e.getMessage(), WebRequest.SCOPE_SESSION);
        log.error(e.getMessage(), e);
    }

    return "redirect:logicDataSetEditor.form?uuid=" + definition.getUuid();
}

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/*ww w .  j  av  a 2 s  .  com*/
 */
@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   w w w  .  j a  v a 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

/**
 * Looks up the anonymous customer and merges that cart with the cart from the given logged in <b>customer</b>. This
 * will also remove the customer from session after it has finished since it is no longer needed
 *//*from  w w  w  . j  a v  a2s  .  com*/
public Order mergeCart(Customer customer, WebRequest request) {
    Customer anonymousCustomer = customerStateRequestProcessor.getAnonymousCustomer(request);
    MergeCartResponse mergeCartResponse;
    try {
        Order cart = orderService.findCartForCustomer(anonymousCustomer);
        mergeCartResponse = mergeCartService.mergeCart(customer, cart);
    } catch (PricingException e) {
        throw new RuntimeException(e);
    } catch (RemoveFromCartException e) {
        throw new RuntimeException(e);
    }

    if (SCRequestUtils.isOKtoUseSession(request)) {
        // The anonymous customer from session is no longer needed; it can be safely removed
        request.removeAttribute(CustomerStateRequestProcessor.getAnonymousCustomerSessionAttributeName(),
                WebRequest.SCOPE_GLOBAL_SESSION);
        request.removeAttribute(CustomerStateRequestProcessor.getAnonymousCustomerIdSessionAttributeName(),
                WebRequest.SCOPE_GLOBAL_SESSION);

        request.setAttribute(mergeCartResponseKey, mergeCartResponse, WebRequest.SCOPE_GLOBAL_SESSION);
    }
    return mergeCartResponse.getOrder();
}

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);
        }//w  ww  . j  a  va  2 s.  co 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;
        }// ww  w. j  a  v a2  s  .c  o  m
    }

    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  va  2s . co 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;
}