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

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

Introduction

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

Prototype

@Nullable
String getParameter(String paramName);

Source Link

Document

Return the request parameter of the given name, or null if none.

Usage

From source file:edu.jhuapl.openessence.controller.ReportController.java

@RequestMapping("/chartJson")
public @ResponseBody Map<String, Object> chartJson(WebRequest request, HttpServletRequest servletRequest,
        @RequestParam("dsId") JdbcOeDataSource ds, ChartModel chartModel) throws ErrorMessageException {

    log.info(LogStatements.GRAPHING.getLoggingStmt() + request.getUserPrincipal().getName());

    final List<Filter> filters = new Filters().getFilters(request.getParameterMap(), ds, null, 0, null, 0);
    final List<Dimension> results = ControllerUtils.getResultDimensionsByIds(ds,
            request.getParameterValues("results"));

    Dimension filterDimension = null;
    if (results.get(0).getFilterBeanId() != null && results.get(0).getFilterBeanId().length() > 0) {
        filterDimension = ds.getFilterDimension(results.get(0).getFilterBeanId());
    }/* w  w  w. ja v  a  2 s .c o m*/
    // if not provided, use the result dimension
    // it means name and id columns are same...
    if (filterDimension != null) {
        results.add(results.size(), filterDimension);
    }

    // Subset of results, should check
    final List<Dimension> charts = ControllerUtils.getResultDimensionsByIds(ds,
            request.getParameterValues("charts"));

    final List<Dimension> accumulations = ControllerUtils.getAccumulationsByIds(ds,
            request.getParameterValues("accumId"));

    final List<OrderByFilter> sorts = new ArrayList<OrderByFilter>();
    try {
        sorts.addAll(Sorters.getSorters(request.getParameterMap()));
    } catch (Exception e) {
        log.warn("Unable to get sorters, using default ordering");
    }

    // TODO put this on ChartModel
    //default to white allows clean copy paste of charts from browser
    Color backgroundColor = Color.WHITE;

    String bgParam = request.getParameter("backgroundColor");
    if (bgParam != null && !"".equals(bgParam)) {
        if ("transparent".equalsIgnoreCase(bgParam)) {
            backgroundColor = new Color(255, 255, 255, 0);
        } else {
            backgroundColor = ControllerUtils.getColorsFromHex(Color.WHITE, bgParam)[0];
        }
    }

    String graphBarUrl = request.getContextPath() + servletRequest.getServletPath() + "/report/graphBar";
    graphBarUrl = appendGraphFontParam(ds, graphBarUrl);

    String graphPieUrl = request.getContextPath() + servletRequest.getServletPath() + "/report/graphPie";
    graphPieUrl = appendGraphFontParam(ds, graphPieUrl);

    // TODO eliminate all the nesting in response and just use accumulation and chartID properties
    Map<String, Object> response = new HashMap<String, Object>();
    Map<String, Object> graphs = new HashMap<String, Object>();
    response.put("graphs", graphs);

    String clientTimezone = null;
    String timezoneEnabledString = messageSource.getMessage(TIMEZONE_ENABLED, "false");
    if (timezoneEnabledString.equalsIgnoreCase("true")) {
        clientTimezone = ControllerUtils.getRequestTimezoneAsHourMinuteString(request);
    }
    Collection<Record> records = new DetailsQuery().performDetailsQuery(ds, results, accumulations, filters,
            sorts, false, clientTimezone);
    final List<Filter> graphFilters = new Filters().getFilters(request.getParameterMap(), ds, null, 0, null, 0,
            false);
    //for each requested accumulation go through each requested result and create a chart
    for (Dimension accumulation : accumulations) {
        Map<String, Object> accumulationMap = new HashMap<String, Object>();
        // Create charts for dimensions (subset of results)
        for (Dimension chart : charts) {
            DefaultGraphData data = new DefaultGraphData();
            data.setGraphTitle(chartModel.getTitle());
            data.setGraphHeight(chartModel.getHeight());
            data.setGraphWidth(chartModel.getWidth());
            data.setShowLegend(chartModel.isLegend());
            data.setBackgroundColor(backgroundColor);
            data.setShowGraphLabels(chartModel.isShowGraphLabels());
            data.setLabelBackgroundColor(backgroundColor);
            data.setPlotHorizontal(chartModel.isPlotHorizontal());
            data.setNoDataMessage(chartModel.getNoDataMessage());
            data.setTitleFont(new Font("Arial", Font.BOLD, 12));

            GraphObject graph = createGraph(ds, request.getUserPrincipal().getName(), records, chart,
                    filterDimension, accumulation, data, chartModel, graphFilters);
            String graphURL = "";
            if (BAR.equalsIgnoreCase(chartModel.getType())) {
                graphURL = graphBarUrl;
            } else if (PIE.equalsIgnoreCase(chartModel.getType())) {
                graphURL = graphPieUrl;
            }
            graphURL = appendUrlParameter(graphURL, "graphDataId", graph.getGraphDataId());

            chartModel.setImageUrl(graphURL);
            chartModel.setImageMap(graph.getImageMap());
            chartModel.setImageMapName(graph.getImageMapName());

            accumulationMap.put(chart.getId(), chartModel);
        }
        graphs.put(accumulation.getId(), accumulationMap);
    }

    log.info(String.format("Chart JSON Details query for %s", request.getUserPrincipal().getName()));

    return response;
}

From source file:org.openmrs.web.controller.patient.ShortPatientFormController.java

/**
 * Creates a map of string of the form 3b, 3a and the actual person Relationships
 * /*from   w w w.j  a v a2  s .c o  m*/
 * @param result
 * @param person the patient/person whose relationships to return
 * @param request the webRequest Object
 * @return map of strings matched against actual relationships
 */
@ModelAttribute("relationshipsMap")
private Map<String, Relationship> getRelationshipsMap(
        @RequestParam(value = "patientId", required = false) Integer patientId, WebRequest request) {
    Map<String, Relationship> relationshipMap = new LinkedHashMap<String, Relationship>();

    if (patientId == null) {
        return relationshipMap;
    }

    Person person = Context.getPersonService().getPerson(patientId);
    if (person == null) {
        throw new IllegalArgumentException("Patient does not exist: " + patientId);
    }

    // Check if relationships must be shown
    String showRelationships = Context.getAdministrationService()
            .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_NEWPATIENTFORM_SHOW_RELATIONSHIPS, "false");

    if ("false".equals(showRelationships)) {
        return relationshipMap;
    }

    // gp is in the form "3a, 7b, 4a"
    String relationshipsString = Context.getAdministrationService()
            .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_NEWPATIENTFORM_RELATIONSHIPS, "");
    relationshipsString = relationshipsString.trim();
    if (relationshipsString.length() > 0) {
        String[] showRelations = relationshipsString.split(",");
        // iterate over strings like "3a"
        for (String showRelation : showRelations) {
            showRelation = showRelation.trim();

            boolean aIsToB = true;
            if (showRelation.endsWith("b")) {
                aIsToB = false;
            }

            // trim out the trailing a or b char
            String showRelationId = showRelation.replace("a", "");
            showRelationId = showRelationId.replace("b", "");

            RelationshipType relationshipType = Context.getPersonService()
                    .getRelationshipType(Integer.valueOf(showRelationId));

            // flag to know if we need to create a stub relationship
            boolean relationshipFound = false;

            if (person.getPersonId() != null) {
                if (aIsToB) {
                    List<Relationship> relationships = Context.getPersonService().getRelationships(null, person,
                            relationshipType);
                    if (relationships.size() > 0) {
                        relationshipMap.put(showRelation, relationships.get(0));
                        relationshipFound = true;
                    }
                } else {
                    List<Relationship> relationships = Context.getPersonService().getRelationships(person, null,
                            relationshipType);
                    if (relationships.size() > 0) {
                        relationshipMap.put(showRelation, relationships.get(0));
                        relationshipFound = true;
                    }
                }
            }

            // if no relationship was found, create a stub one now
            if (!relationshipFound) {
                Relationship relationshipStub = new Relationship();
                relationshipStub.setRelationshipType(relationshipType);
                if (aIsToB) {
                    relationshipStub.setPersonB(person);
                } else {
                    relationshipStub.setPersonA(person);
                }

                relationshipMap.put(showRelation, relationshipStub);
            }

            // check the request to see if a parameter exists in there
            // that matches to the user desired relation. Overwrite
            // any previous data if found
            String submittedPersonId = request.getParameter(showRelation);
            if (submittedPersonId != null && submittedPersonId.length() > 0) {
                Person submittedPerson = Context.getPersonService()
                        .getPerson(Integer.valueOf(submittedPersonId));
                if (aIsToB) {
                    relationshipMap.get(showRelation).setPersonA(submittedPerson);
                } else {
                    relationshipMap.get(showRelation).setPersonB(submittedPerson);
                }
            }
        }
    }

    return relationshipMap;
}

From source file:org.openmrs.web.controller.patient.ShortPatientFormController.java

/**
 * Processes the death information for a deceased patient and save it to the database
 * /*from w w  w .  j a  v  a  2 s  . c  o  m*/
 * @param patientModel the modelObject containing the patient info collected from the form
 *            fields
 * @param request webRequest object
 */
private void saveDeathInfo(ShortPatientModel patientModel, WebRequest request) {
    // update the death reason
    if (patientModel.getPatient().getDead()) {
        log.debug("Patient is dead, so let's make sure there's an Obs for it");
        // need to make sure there is an Obs that represents the
        // patient's cause of death, if applicable

        String codProp = Context.getAdministrationService().getGlobalProperty("concept.causeOfDeath");
        Concept causeOfDeath = Context.getConceptService().getConcept(codProp);

        if (causeOfDeath != null) {
            List<Obs> obssDeath = Context.getObsService()
                    .getObservationsByPersonAndConcept(patientModel.getPatient(), causeOfDeath);
            if (obssDeath != null) {
                if (obssDeath.size() > 1) {
                    log.warn("Multiple causes of death (" + obssDeath.size() + ")?  Shouldn't be...");
                } else {
                    Obs obsDeath = null;
                    if (obssDeath.size() == 1) {
                        // already has a cause of death - let's edit
                        // it.
                        log.debug("Already has a cause of death, so changing it");

                        obsDeath = obssDeath.iterator().next();

                    } else {
                        // no cause of death obs yet, so let's make
                        // one
                        log.debug("No cause of death yet, let's create one.");

                        obsDeath = new Obs();
                        obsDeath.setPerson(patientModel.getPatient());
                        obsDeath.setConcept(causeOfDeath);
                    }

                    // put the right concept and (maybe) text in this obs
                    Concept currCause = patientModel.getPatient().getCauseOfDeath();
                    if (currCause == null) {
                        // set to NONE
                        log.debug("Current cause is null, attempting to set to NONE");
                        String noneConcept = Context.getAdministrationService()
                                .getGlobalProperty("concept.none");
                        currCause = Context.getConceptService().getConcept(noneConcept);
                    }

                    if (currCause != null) {
                        log.debug("Current cause is not null, setting to value_coded");
                        obsDeath.setValueCoded(currCause);
                        obsDeath.setValueCodedName(currCause.getName());

                        Date dateDeath = patientModel.getPatient().getDeathDate();
                        if (dateDeath == null) {
                            dateDeath = new Date();
                        }
                        obsDeath.setObsDatetime(dateDeath);

                        // check if this is an "other" concept - if
                        // so, then we need to add value_text
                        String otherConcept = Context.getAdministrationService()
                                .getGlobalProperty("concept.otherNonCoded");
                        Concept conceptOther = Context.getConceptService().getConcept(otherConcept);
                        if (conceptOther != null) {
                            if (conceptOther.equals(currCause)) {
                                // seems like this is an other
                                // concept - let's try to get the
                                // "other" field info
                                String otherInfo = request.getParameter("patient.causeOfDeath_other");
                                if (otherInfo == null) {
                                    otherInfo = "";
                                }
                                log.debug("Setting value_text as " + otherInfo);
                                obsDeath.setValueText(otherInfo);

                            } else {
                                log.debug("New concept is NOT the OTHER concept, so setting to blank");
                                obsDeath.setValueText("");
                            }
                        } else {
                            log.debug("Don't seem to know about an OTHER concept, so deleting value_text");
                            obsDeath.setValueText("");
                        }

                        if (StringUtils.isBlank(obsDeath.getVoidReason())) {
                            obsDeath.setVoidReason(Context.getMessageSourceService()
                                    .getMessage("general.default.changeReason"));
                        }
                        Context.getObsService().saveObs(obsDeath, obsDeath.getVoidReason());
                    } else {
                        log.debug("Current cause is still null - aborting mission");
                    }
                }
            }
        } else {
            log.debug(
                    "Cause of death is null - should not have gotten here without throwing an error on the form.");
        }
    }

}

From source file:org.openmrs.module.personalhr.web.controller.PhrUserFormController.java

/**
 * @should work for an example// w w  w. ja v a2s  .  c o m
 */
@RequestMapping(value = "/phr/user.form", method = RequestMethod.POST)
public String handleSubmission(final WebRequest request, final HttpSession httpSession, final ModelMap model,
        @RequestParam(required = false, value = "action") final String action,
        @RequestParam(required = false, value = "userFormPassword") String password,
        @RequestParam(required = false, value = "secretQuestion") final String secretQuestion,
        @RequestParam(required = false, value = "secretAnswer") final String secretAnswer,
        @RequestParam(required = false, value = "confirm") String confirm,
        @RequestParam(required = false, value = "forcePassword") final Boolean forcePassword,
        @RequestParam(required = false, value = "roleStrings") final String[] roles,
        @RequestParam(required = false, value = "createNewPerson") final String createNewPerson,
        @RequestParam(required = false, value = "sharingToken") String sharingToken,
        @ModelAttribute("user") final User user, final BindingResult errors) {

    if (sharingToken == null) {
        sharingToken = (String) model.get("sharingToken");
    }

    log.debug("Entering PhrUserFormController:handleSubmission..." + sharingToken);
    //add temporary privileges
    boolean isTemporary = false;
    boolean isAdministrator = false;
    if (!Context.isAuthenticated()) {
        Context.authenticate("temporary", "Temporary8");
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
        Context.addProxyPrivilege("PHR Restricted Patient Access");
        isTemporary = true;
        log.debug("Added proxy privileges!");
    } else {
        if (PhrService.PhrBasicRole.PHR_ADMINISTRATOR.getValue()
                .equals(PersonalhrUtil.getService().getPhrRole(Context.getAuthenticatedUser()))) {
            isAdministrator = true;
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_DELETE_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_PURGE_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
        }
    }

    try {
        final UserService us = Context.getUserService();
        final MessageSourceService mss = Context.getMessageSourceService();

        if (mss.getMessage("User.assumeIdentity").equals(action)) {
            Context.becomeUser(user.getSystemId());
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.assumeIdentity.success");
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, user.getPersonName());
            return "redirect:/phr/index.htm";

        } else if (mss.getMessage("User.delete").equals(action)) {
            try {
                Context.getUserService().purgeUser(user);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.delete.success");
                return "redirect:/phr/user.list";
            } catch (final Exception ex) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "User.delete.failure");
                log.error("Failed to delete user", ex);
                return "redirect:/phr/user.form?userId=" + request.getParameter("userId");
            }

        } else if (mss.getMessage("User.retire").equals(action)) {
            final String retireReason = request.getParameter("retireReason");
            if (!(StringUtils.hasText(retireReason))) {
                errors.rejectValue("retireReason", "User.disableReason.empty");
                return showForm(user.getUserId(), createNewPerson, sharingToken, user, model, httpSession);
            } else {
                us.retireUser(user, retireReason);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.retiredMessage");
            }

        } else if (mss.getMessage("User.unRetire").equals(action)) {
            us.unretireUser(user);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.unRetiredMessage");
        } else {
            // check if username is already in the database
            if (us.hasDuplicateUsername(user)) {
                errors.rejectValue("username", "error.username.taken");
            }

            // check if password and password confirm are identical
            if ((password == null) || password.equals("XXXXXXXXXXXXXXX")) {
                password = "";
            }
            if ((confirm == null) || confirm.equals("XXXXXXXXXXXXXXX")) {
                confirm = "";
            }

            if (!password.equals(confirm)) {
                errors.reject("error.password.match");
            }

            if ((password.length() == 0) && isNewUser(user)) {
                errors.reject("error.password.weak");
            }

            //check password strength
            if (password.length() > 0) {
                try {
                    OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId());
                } catch (final PasswordException e) {
                    errors.reject(e.getMessage());
                }
            }

            final Set<Role> newRoles = new HashSet<Role>();
            if (roles != null) {
                for (final String r : roles) {
                    // Make sure that if we already have a detached instance of this role in the
                    // user's roles, that we don't fetch a second copy of that same role from
                    // the database, or else hibernate will throw a NonUniqueObjectException.
                    Role role = null;
                    if (user.getRoles() != null) {
                        for (final Role test : user.getRoles()) {
                            if (test.getRole().equals(r)) {
                                role = test;
                            }
                        }
                    }
                    if (role == null) {
                        role = us.getRole(r);
                        user.addRole(role);
                    }
                    newRoles.add(role);
                }
            } else {
                final Role role = us.getRole("PHR Restricted User");
                newRoles.add(role);
                user.addRole(role);
                log.debug("Added PHR Restricted User role only: " + role);
            }

            if (user.getRoles() == null) {
                newRoles.clear();
            } else {
                user.getRoles().retainAll(newRoles);
            }

            final String[] keys = request.getParameterValues("property");
            final String[] values = request.getParameterValues("value");

            if ((keys != null) && (values != null)) {
                for (int x = 0; x < keys.length; x++) {
                    final String key = keys[x];
                    final String val = values[x];
                    user.setUserProperty(key, val);
                }
            }

            new UserProperties(user.getUserProperties()).setSupposedToChangePassword(forcePassword);

            final UserValidator uv = new UserValidator();
            uv.validate(user, errors);

            if (errors.hasErrors()) {
                log.debug("errors validating user: " + errors.getErrorCount() + errors.toString());
                return showForm(user.getUserId(), createNewPerson, sharingToken, user, model, httpSession);
            }

            String emailEntered = request.getParameter("9");

            if (isNewUser(user) && !isAdministrator) {
                log.debug("Saving new user " + user.getUsername() + ", sharingToken=" + sharingToken);
                final PhrSharingToken token = Context.getService(PhrSharingTokenService.class)
                        .getSharingToken(sharingToken);

                //check token existence and name matching
                if (token == null || token.getExpireDate().before(new Date())) {
                    httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                            "Failed to register without a valid sharing token");
                    log.error("Failed to register without a valid sharing token");
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null,
                            httpSession.getId(), null,
                            "error=Failed to register without a valid sharing token; user_name="
                                    + user.getName());

                    if (isTemporary) {
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
                        Context.removeProxyPrivilege("PHR Restricted Patient Access");
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
                        Context.logout();
                        log.debug("Removed proxy privileges!");
                    }
                    return "redirect:/phr/index.htm?noredirect=true";
                } else if ((token != null) && (token.getRelatedPerson() != null)) {
                    httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                            "Failed to register with a used sharing token");
                    log.error("Failed to register with a used sharing token");
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null,
                            httpSession.getId(), null,
                            "error=Failed to register with a used sharing token; user_name=" + user.getName()
                                    + "; sharingToken=" + token);
                    if (isTemporary) {
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
                        Context.removeProxyPrivilege("PHR Restricted Patient Access");
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
                        Context.logout();
                        log.debug("Removed proxy privileges!");
                    }

                    return "redirect:/phr/index.htm?noredirect=true";
                } else if (emailEntered != null
                        && token.getRelatedPersonEmail().equalsIgnoreCase(emailEntered)) {
                    // look for person attributes (including email entered) in the request and save to user
                    for (final PersonAttributeType type : Context.getPersonService()
                            .getPersonAttributeTypes(PERSON_TYPE.PATIENT, ATTR_VIEW_TYPE.VIEWING)) {
                        final String paramName = type.getPersonAttributeTypeId().toString();
                        final String value = request.getParameter(paramName);

                        this.log.debug("paramName=" + paramName);

                        // if there is an error displaying the attribute, the value will be null
                        if (value != null) {
                            final PersonAttribute attribute = new PersonAttribute(type, value);
                            try {
                                final Object hydratedObject = attribute.getHydratedObject();
                                if ((hydratedObject == null) || "".equals(hydratedObject.toString())) {
                                    // if null is returned, the value should be blanked out
                                    attribute.setValue("");
                                } else if (hydratedObject instanceof Attributable) {
                                    attribute.setValue(((Attributable) hydratedObject).serialize());
                                } else if (!hydratedObject.getClass().getName().equals(type.getFormat())) {
                                    // if the classes doesn't match the format, the hydration failed somehow
                                    // TODO change the PersonAttribute.getHydratedObject() to not swallow all errors?
                                    throw new APIException();
                                }
                            } catch (final APIException e) {
                                errors.rejectValue("attributeMap[" + type.getName() + "]",
                                        "Invalid value for " + type.getName() + ": '" + value + "'");
                                this.log.warn("Got an invalid value: " + value
                                        + " while setting personAttributeType id #" + paramName, e);

                                // setting the value to empty so that the user can reset the value to something else
                                attribute.setValue("");

                            }
                            user.getPerson().addAttribute(attribute);
                        }
                    }

                    //create a new user by self registration
                    us.saveUser(user, password);

                    //update sharing token
                    token.setRelatedPerson(user.getPerson());
                    token.setChangedBy(user);
                    final Date date = new Date();
                    token.setDateChanged(date);
                    token.setActivateDate(date);
                    Context.getService(PhrSharingTokenService.class).savePhrSharingToken(token);
                    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "personalhr.user.signed.up");
                    log.debug("New self-registered user created: " + user.getUsername());
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), user,
                            httpSession.getId(), null, "info=New self-registered user created; user_name="
                                    + user.getName() + "; sharingToken=" + token);

                    //save email to messaging service
                    Integer addressId = saveEmail(user.getPerson(), emailEntered);

                    //set default messaging alert address
                    boolean shouldAlert = true;
                    PersonalhrUtil.setMessagingAlertSettings(user.getPerson(), shouldAlert, addressId);

                    //send email notification

                    // TODO get the deployUrl from the request object; also bad to inject /openmrs/ ...
                    final String deployUrl = Context.getRuntimeProperties().getProperty("deployment.url");//"https://65.111.248.164:8443/"; //"172.30.201.24";

                    final String url = deployUrl + "/openmrs/phr/index.htm";
                    final String passwordOption = Context.getAdministrationService()
                            .getGlobalProperty("personalhr.show.password");

                    String notification = NOTIFICATION_TEMPLATE;
                    notification = notification.replaceAll("OPENMRS_PHR_RELATED_PERSON",
                            user.getPerson().getGivenName());
                    notification = notification.replaceAll("OPENMRS_USERNAME", user.getUsername());
                    notification = notification.replaceAll("OPENMRS_PASSWORD",
                            showPassword(password, passwordOption));
                    notification = notification.replaceAll("OPENMRS_URL", url);

                    PersonalhrUtil.sendEmail(emailEntered, notification);
                } else {
                    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                            "Failed to create new user due to email mismatch: " + emailEntered);
                    log.debug("Failed to create new user due to email mismatch: "
                            + token.getRelatedPersonEmail() + " vs " + emailEntered);
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null,
                            httpSession.getId(), null,
                            "info=Failed to create new user due to email mismatch: "
                                    + token.getRelatedPersonEmail() + "vs " + emailEntered + "; sharingToken="
                                    + token);
                }
            } else if (isNewUser(user) && isAdministrator) {
                //create a new user by PHR Administrator
                us.saveUser(user, password);
            } else {
                //modify an exiting user
                us.saveUser(user, null);

                if (!password.equals("") && Context.hasPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS)) {
                    if (log.isDebugEnabled()) {
                        log.debug("calling changePassword for user " + user + " by user "
                                + Context.getAuthenticatedUser());
                    }
                    us.changePassword(user, password);
                }
                log.debug("Existing user " + user.getUsername() + " changed by user "
                        + Context.getAuthenticatedUser().getUsername());
                PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_UPDATE, new Date(),
                        Context.getAuthenticatedUser(), httpSession.getId(), null,
                        "info=Existing user updated; user_name=" + user.getName());
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved");
            }

            if (StringUtils.hasLength(secretQuestion) && StringUtils.hasLength(secretAnswer)) {
                us.changeQuestionAnswer(user, secretQuestion, secretAnswer);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved");
            }
        }
    } finally {
        //remove temporary privileges
        if (isTemporary) {
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
            Context.removeProxyPrivilege("PHR Restricted Patient Access");
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
            Context.logout();
            log.debug("Removed proxy privileges for self registration!");
        } else if (isAdministrator) {
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_DELETE_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_PURGE_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
            log.debug("Removed proxy privileges for PHR Administrator!");
        }
    }
    return "redirect:/phr/index.htm?noredirect=true";
}

From source file:com.seajas.search.attender.controller.ProfileController.java

/**
 * Render the submit action in the same way as a regular page view is rendered.
 * /*  w w w  . j  a va2s.c  o  m*/
 * @param command
 * @param result
 * @param model
 * @param request
 * @return String
 * @throws Exception
 */
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("profileCommand") final ProfileCommand command,
        final BindingResult result, final ModelMap model, final WebRequest request) throws Exception {
    // Collect and set the subscribers by the individual values

    List<String> subscriberEmails = new ArrayList<String>();
    List<String> subscriberEmailLanguages = new ArrayList<String>();
    List<String> subscriberTimeZones = new ArrayList<String>();
    List<String> subscriberTypes = new ArrayList<String>();
    List<String> subscriberDays = new ArrayList<String>();
    List<String> subscriberHours = new ArrayList<String>();
    List<String> subscriberMinutes = new ArrayList<String>();
    List<String> subscriberIntervals = new ArrayList<String>();
    List<String> subscriberMaximums = new ArrayList<String>();
    List<String> subscriberUniqueIds = new ArrayList<String>();
    List<String> subscriberConfirmations = new ArrayList<String>();
    List<String> subscriberLastNotifications = new ArrayList<String>();

    if (request.getParameterValues("subscriberEmails") != null)
        for (String subscriberEmail : request.getParameterValues("subscriberEmails"))
            subscriberEmails.add(subscriberEmail);

    command.setSubscriberEmails(subscriberEmails);

    if (request.getParameterValues("subscriberEmailLanguages") != null)
        for (String subscriberEmailLanguage : request.getParameterValues("subscriberEmailLanguages"))
            subscriberEmailLanguages.add(subscriberEmailLanguage);

    command.setSubscriberEmailLanguages(subscriberEmailLanguages);

    if (request.getParameterValues("subscriberTimeZones") != null)
        for (String subscriberTimeZone : request.getParameterValues("subscriberTimeZones"))
            subscriberTimeZones.add(subscriberTimeZone);

    command.setSubscriberTimeZones(subscriberTimeZones);

    if (request.getParameterValues("subscriberNotificationTypes") != null)
        for (String subscriberType : request.getParameterValues("subscriberNotificationTypes"))
            subscriberTypes.add(subscriberType);

    command.setSubscriberTypes(subscriberTypes);

    if (request.getParameterValues("subscriberNotificationDays") != null)
        for (String subscriberDay : request.getParameterValues("subscriberNotificationDays"))
            subscriberDays.add(subscriberDay);

    command.setSubscriberDays(subscriberDays);

    if (request.getParameterValues("subscriberNotificationHours") != null)
        for (String subscriberHour : request.getParameterValues("subscriberNotificationHours"))
            subscriberHours.add(subscriberHour);

    command.setSubscriberHours(subscriberHours);

    if (request.getParameterValues("subscriberNotificationMinutes") != null)
        for (String subscriberMinute : request.getParameterValues("subscriberNotificationMinutes"))
            subscriberMinutes.add(subscriberMinute);

    command.setSubscriberMinutes(subscriberMinutes);

    if (request.getParameterValues("subscriberNotificationIntervals") != null)
        for (String subscriberInterval : request.getParameterValues("subscriberNotificationIntervals"))
            subscriberIntervals.add(StringUtils.isEmpty(subscriberInterval) ? "-1" : subscriberInterval);

    command.setSubscriberIntervals(subscriberIntervals);

    if (request.getParameterValues("subscriberNotificationMaximums") != null)
        for (String subscriberMaximum : request.getParameterValues("subscriberNotificationMaximums"))
            subscriberMaximums.add(StringUtils.isEmpty(subscriberMaximum) ? "-1" : subscriberMaximum);

    command.setSubscriberMaximums(subscriberMaximums);

    if (request.getParameterValues("subscriberNotificationUniqueIds") != null)
        for (String subscriberUniqueId : request.getParameterValues("subscriberNotificationUniqueIds"))
            subscriberUniqueIds.add(subscriberUniqueId);

    command.setSubscriberUniqueIds(subscriberUniqueIds);

    if (request.getParameterValues("subscriberNotificationConfirmations") != null)
        for (String subscriberConfirmation : request.getParameterValues("subscriberNotificationConfirmations"))
            subscriberConfirmations.add(subscriberConfirmation);

    command.setSubscriberConfirmations(subscriberConfirmations);

    if (request.getParameterValues("subscriberNotificationLastNotifications") != null)
        for (String subscriberLastNotification : request
                .getParameterValues("subscriberNotificationLastNotifications"))
            subscriberLastNotifications.add(subscriberLastNotification);

    command.setSubscriberLastNotifications(subscriberLastNotifications);

    // Collect and set the parameters

    if (request.getParameterValues("searchParameterFormat") != null)
        command.setSearchParameterFormat(request.getParameterValues("searchParameterFormat")[0]);
    if (request.getParameterValues("searchParameterLanguage") != null)
        command.setSearchParameterLanguage(request.getParameterValues("searchParameterLanguage")[0]);
    if (request.getParameterValues("searchParameterAuthor") != null
            && !StringUtils.isEmpty(request.getParameterValues("searchParameterLanguage")[0]))
        command.setSearchParameterAuthor(request.getParameterValues("searchParameterAuthor")[0]);
    if (request.getParameterValues("searchParameterType") != null
            && !StringUtils.isEmpty(request.getParameterValues("searchParameterType")[0]))
        command.setSearchParameterType(request.getParameterValues("searchParameterType")[0]);
    if (request.getParameterValues("searchParameterGeo") != null
            && !StringUtils.isEmpty(request.getParameterValues("searchParameterGeo")[0]))
        command.setSearchParameterGeo(request.getParameterValues("searchParameterGeo")[0]);

    // Collect and set the taxonomy identifiers

    List<String> taxonomyIdentifiersCommand = new ArrayList<String>();

    if (request.getParameterValues("taxonomyIdentifiersList") != null)
        for (String taxonomyIdentifier : request.getParameterValues("taxonomyIdentifiersList")[0].trim()
                .split(" "))
            if (!StringUtils.isBlank(taxonomyIdentifier))
                taxonomyIdentifiersCommand.add(taxonomyIdentifier.trim());

    command.setTaxonomyIdentifiers(taxonomyIdentifiersCommand);

    // Update the enabled attribute

    if (request.getParameter("isEnabled") == null)
        command.setIsEnabled(false);

    validator.validate(command, result);

    if (!result.hasErrors()) {
        // Any search parameter validation errors should have been caught by the validator

        Map<String, String> searchParameters = new HashMap<String, String>();

        if (!StringUtils.isEmpty(command.getSearchParameterFormat()))
            searchParameters.put("dcterms_format", command.getSearchParameterFormat());
        if (!StringUtils.isEmpty(command.getSearchParameterLanguage()))
            searchParameters.put("dcterms_language", command.getSearchParameterLanguage());
        if (!StringUtils.isEmpty(command.getSearchParameterAuthor()))
            searchParameters.put("dcterms_author", command.getSearchParameterAuthor());
        if (!StringUtils.isEmpty(command.getSearchParameterType()))
            searchParameters.put("dcterms_type", command.getSearchParameterType());
        if (!StringUtils.isEmpty(command.getSearchParameterGeo()))
            searchParameters.put("geo_total", command.getSearchParameterGeo());

        // Any number formatting exceptions should have been caught by the validator

        List<Integer> taxonomyIdentifiers = new ArrayList<Integer>();

        for (String taxonomyIdentifier : command.getTaxonomyIdentifiers()) {
            Integer identifier = Integer.parseInt(taxonomyIdentifier);

            logger.info("Profile will be narrowed down by taxonomy identifiers - adding " + identifier);

            taxonomyIdentifiers.add(identifier);
        }

        // Any length inconsistencies should have been intercepted by the validator

        List<ProfileSubscriber> subscribers = new ArrayList<ProfileSubscriber>();

        if (!command.getAction().equals("delete"))
            for (int i = 0; i < subscriberEmails.size(); i++)
                if (!StringUtils.isEmpty(subscriberEmails.get(i))) {
                    Long subscriberLastNotification = null;
                    String uniqueId = null;

                    if (!StringUtils.isEmpty(subscriberLastNotifications.get(i)))
                        try {
                            subscriberLastNotification = Long.valueOf(subscriberLastNotifications.get(i));
                        } catch (NumberFormatException e) {
                            // Do nothing, if it's simply incorrect
                        }
                    if (!StringUtils.isEmpty(subscriberUniqueIds.get(i))
                            && subscriberUniqueIds.get(i).length() > 10)
                        uniqueId = subscriberUniqueIds.get(i);

                    subscribers.add(new ProfileSubscriber(subscriberEmails.get(i),
                            subscriberEmailLanguages.get(i), Boolean.valueOf(subscriberConfirmations.get(i)),
                            uniqueId, subscriberTimeZones.get(i),
                            NotificationType.valueOf(subscriberTypes.get(i)),
                            Integer.valueOf(subscriberDays.get(i)), Integer.valueOf(subscriberHours.get(i)),
                            Integer.valueOf(subscriberMinutes.get(i)),
                            Integer.valueOf(subscriberIntervals.get(i)),
                            Integer.valueOf(subscriberMaximums.get(i)),
                            subscriberLastNotification != null && subscriberLastNotification > 0
                                    ? new Date(subscriberLastNotification)
                                    : null));
                }

        if (command.getAction().equals("add"))
            attenderService.addProfile(command.getQuery(), command.getIsEnabled(), subscribers,
                    searchParameters, taxonomyIdentifiers);
        else if (command.getAction().equals("edit"))
            attenderService.modifyProfile(command.getId(), command.getQuery(), command.getIsEnabled(),
                    subscribers, searchParameters, taxonomyIdentifiers);
        else if (command.getAction().equals("delete"))
            attenderService.deleteProfile(command.getId());

        // Re-populate the data

        model.put("data", populateData());

        command.clear();
    }

    return "profiles";
}

From source file:org.broadleafcommerce.common.web.BroadleafRequestProcessor.java

@Override
public void process(WebRequest request) {
    BroadleafRequestContext brc = new BroadleafRequestContext();
    brc.getAdditionalProperties().putAll(entityExtensionManagers);

    Site site = siteResolver.resolveSite(request);

    brc.setSite(site);//from ww  w.  j a v a2  s .  co m
    brc.setWebRequest(request);
    if (site == null) {
        brc.setIgnoreSite(true);
    }
    brc.setAdmin(false);

    if (siteStrictValidateProductionChanges) {
        brc.setValidateProductionChangesState(ValidateProductionChangesState.SITE);
    } else {
        brc.setValidateProductionChangesState(ValidateProductionChangesState.UNDEFINED);
    }

    BroadleafRequestContext.setBroadleafRequestContext(brc);

    Locale locale = localeResolver.resolveLocale(request);
    brc.setLocale(locale);
    TimeZone timeZone = broadleafTimeZoneResolver.resolveTimeZone(request);
    BroadleafRequestedCurrencyDto currencyDto = currencyResolver.resolveCurrency(request);
    // Assumes BroadleafProcess
    RequestDTO requestDTO = (RequestDTO) request.getAttribute(REQUEST_DTO_PARAM_NAME, WebRequest.SCOPE_REQUEST);
    if (requestDTO == null) {
        requestDTO = new RequestDTOImpl(request);
    }

    SandBox currentSandbox = sandboxResolver.resolveSandBox(request, site);

    // When a user elects to switch his sandbox, we want to invalidate the current session. We'll then redirect the 
    // user to the current URL so that the configured filters trigger again appropriately.
    Boolean reprocessRequest = (Boolean) request.getAttribute(BroadleafRequestProcessor.REPROCESS_PARAM_NAME,
            WebRequest.SCOPE_REQUEST);
    if (reprocessRequest != null && reprocessRequest) {
        LOG.debug("Reprocessing request");
        if (request instanceof ServletWebRequest) {
            HttpServletRequest hsr = ((ServletWebRequest) request).getRequest();

            clearBroadleafSessionAttrs(request);

            StringBuffer url = hsr.getRequestURL();
            if (hsr.getQueryString() != null) {
                url.append('?').append(hsr.getQueryString());
            }
            try {
                ((ServletWebRequest) request).getResponse().sendRedirect(url.toString());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            throw new HaltFilterChainException("Reprocess required, redirecting user");
        }
    }

    if (currentSandbox != null) {
        SandBoxContext previewSandBoxContext = new SandBoxContext();
        previewSandBoxContext.setSandBoxId(currentSandbox.getId());
        previewSandBoxContext.setPreviewMode(true);
        SandBoxContext.setSandBoxContext(previewSandBoxContext);
    }
    if (currencyDto != null) {
        brc.setBroadleafCurrency(currencyDto.getCurrencyToUse());
        brc.setRequestedBroadleafCurrency(currencyDto.getRequestedCurrency());
    }

    brc.setSandBox(currentSandbox);
    brc.setDeployBehavior(deployBehaviorUtil.isProductionSandBoxMode() ? DeployBehavior.CLONE_PARENT
            : DeployBehavior.OVERWRITE_PARENT);

    // Note that this must happen after the request context is set up as resolving a theme is dependent on site
    Theme theme = themeResolver.resolveTheme(request);
    brc.setTheme(theme);

    brc.setMessageSource(messageSource);
    brc.setTimeZone(timeZone);
    brc.setRequestDTO(requestDTO);
    Map<String, Object> ruleMap = (Map<String, Object>) request.getAttribute("blRuleMap",
            WebRequest.SCOPE_REQUEST);
    if (ruleMap == null) {
        LOG.trace("Creating ruleMap and adding in Locale.");
        ruleMap = new HashMap<String, Object>();
        request.setAttribute("blRuleMap", ruleMap, WebRequest.SCOPE_REQUEST);
    } else {
        LOG.trace("Using pre-existing ruleMap - added by non standard BLC process.");
    }
    ruleMap.put("locale", locale);

    String adminUserId = request.getParameter(BroadleafRequestFilter.ADMIN_USER_ID_PARAM_NAME);
    if (StringUtils.isNotBlank(adminUserId)) {
        //TODO: Add token logic to secure the admin user id
        brc.setAdminUserId(Long.parseLong(adminUserId));
    }

}

From source file:org.broadleafcommerce.common.web.BroadleafSandBoxResolverImpl.java

@Override
public SandBox resolveSandBox(WebRequest request, Site site) {
    Long previousSandBoxId = null;
    if (BLCRequestUtils.isOKtoUseSession(request)) {
        previousSandBoxId = (Long) request.getAttribute(SANDBOX_ID_VAR, WebRequest.SCOPE_GLOBAL_SESSION);
    }//www  .  j ava  2s .  c  o m
    SandBox currentSandbox = null;
    if (!sandBoxPreviewEnabled) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Sandbox preview disabled. Setting sandbox to production");
        }
        request.setAttribute(SANDBOX_VAR, currentSandbox, WebRequest.SCOPE_REQUEST);
    } else if (crossAppAuthService != null && !crossAppAuthService.isAuthedFromAdmin()) {
        if (LOG.isInfoEnabled()) {
            LOG.info("Sandbox preview attempted without authentication");
        }
        request.setAttribute(SANDBOX_VAR, currentSandbox, WebRequest.SCOPE_REQUEST);
    } else if (crossAppAuthService != null && crossAppAuthService.hasCsrPermission()) {
        if (LOG.isInfoEnabled()) {
            LOG.info("Sandbox preview attempted in CSR mode");
        }
        request.setAttribute(SANDBOX_VAR, currentSandbox, WebRequest.SCOPE_REQUEST);
    } else {
        Long sandboxId = null;
        // Clear the sandBox - second parameter is to support legacy implementations.
        if ((request.getParameter("blClearSandBox") == null)
                && (request.getParameter("blSandboxDateTimeRibbonProduction") == null)) {
            sandboxId = lookupSandboxId(request);
        } else {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Removing sandbox from session.");
            }
            if (BLCRequestUtils.isOKtoUseSession(request)) {
                request.removeAttribute(SANDBOX_DATE_TIME_VAR, WebRequest.SCOPE_GLOBAL_SESSION);
                request.removeAttribute(SANDBOX_ID_VAR, WebRequest.SCOPE_GLOBAL_SESSION);
            }
            SystemTime.resetLocalTimeSource();
        }
        if (sandboxId != null) {
            if (previousSandBoxId != null && !previousSandBoxId.equals(sandboxId)) {
                request.setAttribute(BroadleafRequestProcessor.REPROCESS_PARAM_NAME, true,
                        WebRequest.SCOPE_REQUEST);
            }

            currentSandbox = sandBoxDao.retrieve(sandboxId);
            request.setAttribute(SANDBOX_VAR, currentSandbox, WebRequest.SCOPE_REQUEST);
            if (currentSandbox != null && !SandBoxType.PRODUCTION.equals(currentSandbox.getSandBoxType())) {
                setContentTime(request);
            }
        }

        //            if (currentSandbox == null && site != null) {
        //                currentSandbox = site.getProductionSandbox();
        //            }
    }

    if (LOG.isTraceEnabled()) {
        if (currentSandbox != null) {
            LOG.trace("Serving request using sandbox: " + currentSandbox);
        } else {
            LOG.trace("Serving request without a sandbox.");
        }
    }

    Date currentSystemDateTime = SystemTime.asDate(true);
    Calendar sandboxDateTimeCalendar = Calendar.getInstance();
    sandboxDateTimeCalendar.setTime(currentSystemDateTime);
    request.setAttribute(SANDBOX_DISPLAY_DATE_TIME_DATE_PARAM,
            CONTENT_DATE_DISPLAY_FORMATTER.format(currentSystemDateTime), WebRequest.SCOPE_REQUEST);
    request.setAttribute(SANDBOX_DISPLAY_DATE_TIME_HOURS_PARAM,
            CONTENT_DATE_DISPLAY_HOURS_FORMATTER.format(currentSystemDateTime), WebRequest.SCOPE_REQUEST);
    request.setAttribute(SANDBOX_DISPLAY_DATE_TIME_MINUTES_PARAM,
            CONTENT_DATE_DISPLAY_MINUTES_FORMATTER.format(currentSystemDateTime), WebRequest.SCOPE_REQUEST);
    request.setAttribute(SANDBOX_DISPLAY_DATE_TIME_AMPM_PARAM, sandboxDateTimeCalendar.get(Calendar.AM_PM),
            WebRequest.SCOPE_REQUEST);
    return currentSandbox;
}

From source file:org.broadleafcommerce.common.web.BroadleafSandBoxResolverImpl.java

/**
 * If another filter has already set the language as a request attribute, that will be honored.
 * Otherwise, the request parameter is checked followed by the session attribute.
 *
 * @param request//ww w .  j av a 2  s  .  c  o  m
 * @return
 */
private Long lookupSandboxId(WebRequest request) {
    String sandboxIdStr = request.getParameter(SANDBOX_ID_VAR);
    Long sandboxId = null;

    if (sandboxIdStr != null) {
        try {
            sandboxId = Long.valueOf(sandboxIdStr);
            if (LOG.isTraceEnabled()) {
                LOG.trace("SandboxId found on request " + sandboxId);
            }
        } catch (NumberFormatException nfe) {
            LOG.warn("blcSandboxId parameter could not be converted into a Long", nfe);
        }
    }

    if (BLCRequestUtils.isOKtoUseSession(request)) {
        if (sandboxId == null) {
            // check the session            
            sandboxId = (Long) request.getAttribute(SANDBOX_ID_VAR, WebRequest.SCOPE_GLOBAL_SESSION);

            if (LOG.isTraceEnabled()) {
                if (sandboxId != null) {
                    LOG.trace("SandboxId found in session " + sandboxId);
                }
            }
        } else {
            request.setAttribute(SANDBOX_ID_VAR, sandboxId, WebRequest.SCOPE_GLOBAL_SESSION);
        }
    }
    return sandboxId;
}