Example usage for org.springframework.web.bind ServletRequestUtils getStringParameters

List of usage examples for org.springframework.web.bind ServletRequestUtils getStringParameters

Introduction

In this page you can find the example usage for org.springframework.web.bind ServletRequestUtils getStringParameters.

Prototype

public static String[] getStringParameters(ServletRequest request, String name) 

Source Link

Document

Get an array of String parameters, return an empty array if not found.

Usage

From source file:psiprobe.controllers.sessions.ExpireSessionsController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    for (String sidWebApp : ServletRequestUtils.getStringParameters(request, "sid_webapp")) {
        if (sidWebApp != null) {
            String[] ss = sidWebApp.split(";");
            if (ss.length == 2) {
                String sessionId = ss[0];
                String appName = ss[1];
                Context context = getContainerWrapper().getTomcatContainer().findContext(appName);
                if (context != null) {
                    Manager manager = context.getManager();
                    Session session = manager.findSession(sessionId);
                    if (session != null && session.isValid()) {
                        session.expire();
                    }/*from  w w w .j av a 2 s .  c o  m*/
                } else {
                    return new ModelAndView("errors/paramerror");
                }
            } else {
                return new ModelAndView("errors/paramerror");
            }
        }
    }
    return new ModelAndView(new InternalResourceView(getViewName()));
}

From source file:com.googlecode.psiprobe.controllers.sessions.ExpireSessionsController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String[] sidWebApps = ServletRequestUtils.getStringParameters(request, "sid_webapp");
    for (int i = 0; i < sidWebApps.length; i++) {
        if (sidWebApps[i] != null) {
            String[] ss = sidWebApps[i].split(";");
            if (ss.length == 2) {
                String sessionId = ss[0];
                String appName = ss[1];
                Context context = getContainerWrapper().getTomcatContainer().findContext(appName);
                if (context != null) {
                    Manager manager = context.getManager();
                    Session session = manager.findSession(sessionId);
                    if (session != null && session.isValid()) {
                        session.expire();
                    }//from   ww  w  . java  2s  .  co  m
                } else {
                    return new ModelAndView("errors/paramerror");
                }
            } else {
                return new ModelAndView("errors/paramerror");
            }
        }
    }
    return new ModelAndView(new InternalResourceView(getViewName()));
}

From source file:net.testdriven.psiprobe.controllers.sessions.ExpireSessionsController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String[] sidWebApps = ServletRequestUtils.getStringParameters(request, "sid_webapp");
    for (String sidWebApp : sidWebApps) {
        if (sidWebApp != null) {
            String[] ss = sidWebApp.split(";");
            if (ss.length == 2) {
                String sessionId = ss[0];
                String appName = ss[1];
                Context context = getContainerWrapper().getTomcatContainer().findContext(appName);
                if (context != null) {
                    Manager manager = context.getManager();
                    Session session = manager.findSession(sessionId);
                    if (session != null && session.isValid()) {
                        session.expire();
                    }//from  w  w  w  .  ja  va 2 s  . c om
                } else {
                    return new ModelAndView("errors/paramerror");
                }
            } else {
                return new ModelAndView("errors/paramerror");
            }
        }
    }
    return new ModelAndView(new InternalResourceView(getViewName()));
}

From source file:org.openmrs.web.controller.user.RoleListController.java

/**
 * The onSubmit function receives the form/command object that was modified by the input form
 * and saves it to the db//  ww  w  .  ja va 2  s.c  o m
 *
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    HttpSession httpSession = request.getSession();

    String view = getFormView();
    if (Context.isAuthenticated()) {
        StringBuilder success = new StringBuilder();
        StringBuilder error = new StringBuilder();

        MessageSourceAccessor msa = getMessageSourceAccessor();

        String[] roleList = ServletRequestUtils.getStringParameters(request, "roleId");
        if (roleList.length > 0) {
            UserService us = Context.getUserService();

            String deleted = msa.getMessage("general.deleted");
            String notDeleted = msa.getMessage("Role.cannot.delete");
            String notDeletedWithChild = msa.getMessage("Role.cannot.delete.with.child");
            for (String p : roleList) {
                //TODO convenience method deleteRole(String) ??
                try {
                    us.purgeRole(us.getRole(p));
                    if (!success.toString().isEmpty()) {
                        success.append("<br/>");
                    }
                    success.append(p).append(" ").append(deleted);
                } catch (DataIntegrityViolationException e) {
                    handleRoleIntegrityException(e, error, notDeleted, p);
                } catch (CannotDeleteRoleWithChildrenException e) {
                    handleRoleIntegrityException(e, error, notDeletedWithChild, p);
                } catch (APIException e) {
                    handleRoleIntegrityException(e, error, notDeleted, p);
                }
            }
        } else {
            error.append(msa.getMessage("Role.select"));
        }

        view = getSuccessView();
        if (!success.toString().isEmpty()) {
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, success.toString());
        }
        if (!error.toString().isEmpty()) {
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, error.toString());
        }
    }

    return new ModelAndView(new RedirectView(view));
}

From source file:org.openmrs.module.sync.web.controller.MaintenanceController.java

/**
 * @see org.springframework.web.servlet.mvc.SimpleFormController#processFormSubmission(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 *//*ww w  .  j a v a 2s . c om*/
@Override
protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response,
        Object command, BindException errors) throws Exception {
    TaskDefinition task = (TaskDefinition) command;
    Map<String, String> properties = new HashMap<String, String>();
    String[] names = ServletRequestUtils.getStringParameters(request, "propertyName");
    String[] values = ServletRequestUtils.getStringParameters(request, "propertyValue");
    if (names != null) {
        for (int x = 0; x < names.length; x++) {
            if (names[x].length() > 0)
                properties.put(names[x], values[x]);
        }
    }
    task.setProperties(properties);

    task.setStartTimePattern(SchedulerFormController.DEFAULT_DATE_PATTERN);
    // if the user selected a different repeat interval unit, fix repeatInterval
    String units = request.getParameter("repeatIntervalUnits");
    Long interval = task.getRepeatInterval();

    if ("minutes".equals(units)) {
        interval = interval * 60;
    } else if ("hours".equals(units)) {
        interval = interval * 60 * 60;
    } else if ("days".equals(units)) {
        interval = interval * 60 * 60 * 24;
    }

    task.setRepeatInterval(interval);

    return super.processFormSubmission(request, response, command, errors);
}

From source file:com.netease.channel.util.ServletUtils.java

/**
 * Get an array of String parameters, return an empty array if not found.
 *
 * @param request/* w  w  w . j a  v a  2 s.c  om*/
 *            current HTTP request
 * @param name
 *            the name of the parameter with multiple possible values
 */
public static String[] getStrs(ServletRequest request, String name) {
    return ServletRequestUtils.getStringParameters(request, name);
}

From source file:org.openmrs.module.restrictbyuser.web.controller.RestrictByUserFormController.java

/**
 * The onSubmit function receives the form/command object that was modified
 * by the input form and saves it to the db
 * //from w w  w  .  j a  v  a  2s.c  o  m
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    HttpSession httpSession = request.getSession();
    MessageSourceAccessor msa = getMessageSourceAccessor();
    String userId = request.getParameter("userId");
    String view = getSuccessView();

    if (Context.isAuthenticated()
            && Context.getAuthenticatedUser().hasPrivilege(ModConstants.MANAGE_USER_RESTRICTIONS)) {
        String patientId = ServletRequestUtils.getStringParameter(request, "patientId");

        /* Assign proxy privileges needed for the operations */
        try {
            Context.addProxyPrivilege(PrivilegeConstants.VIEW_USERS);
            Context.addProxyPrivilege(PrivilegeConstants.EDIT_USERS);

            if (StringUtils.hasText(userId)) {
                UserService us = Context.getService(UserService.class);
                PatientService ps = Context.getPatientService();
                String message = "";
                String success = "";
                String error = "";

                User u = (User) us.getUser(Integer.parseInt(userId));
                String remove = request.getParameter("remove");

                /* Remove patients in the list */
                if (remove != null) {
                    String[] patientList = ServletRequestUtils.getStringParameters(request, "patientId");
                    if (patientList.length > 0) {
                        for (String p : patientList) {
                            u.removePatient(ps.getPatient(Integer.parseInt(p)));
                        }
                        message = WebConstants.OPENMRS_MSG_ATTR;
                        success = msa.getMessage("restrictbyuser.form.success.remove");
                    } else {
                        message = WebConstants.OPENMRS_ERROR_ATTR;
                        error = msa.getMessage("restrictbyuser.form.error.noPatient");
                    }
                    /* If a valid patient is selected, add it to the object */
                } else if (patientId != "") {
                    Patient p = ps.getPatient(Integer.parseInt(patientId));
                    if (u.getPatients().contains(p)) {
                        message = WebConstants.OPENMRS_ERROR_ATTR;
                        error = msa.getMessage("restrictbyuser.form.error.duplicate");
                    } else {
                        u.addPatient(ps.getPatient(Integer.parseInt(patientId)));
                        message = WebConstants.OPENMRS_MSG_ATTR;
                        success = msa.getMessage("restrictbyuser.form.success.add");
                    }
                    /*
                     * If an invalide patient is selected, set display error
                     * message
                     */
                } else if (patientId == "") {
                    error = msa.getMessage("restrictbyuser.form.error.invalidPatient");
                }

                /* Dispaly error message and save changes */
                if (message == WebConstants.OPENMRS_ERROR_ATTR) {
                    httpSession.setAttribute(message, error);
                } else {
                    u = (User) us.saveUser(u, null);
                    httpSession.setAttribute(message, success);
                }
            } else {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                        msa.getMessage("restrictbyuser.form.error"));
            }
        } finally {
            Context.removeProxyPrivilege(PrivilegeConstants.VIEW_USERS);
            Context.removeProxyPrivilege(PrivilegeConstants.EDIT_USERS);
        }

    }

    return new ModelAndView(new RedirectView(view + "?userId=" + request.getParameter("userId")));
}

From source file:no.dusken.aranea.web.control.RssCacheController.java

/**
 * If urls contain links these will be used, else feeds defined in the context is used.
 * numberOfEntries can also be set through the request else the value set in context is used
 *///from www .java2  s  .co m
public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws ServletRequestBindingException {
    Map<String, Object> map = new HashMap<String, Object>();
    String[] urls = ServletRequestUtils.getStringParameters(request, "url");

    int numOfEntriesFromrequest = ServletRequestUtils.getIntParameter(request, "numberOfEntries", 0);
    if (numOfEntriesFromrequest != 0) {
        map.put("numberOfEntries", numOfEntriesFromrequest);
    } else {
        map.put("numberOfEntries", numberOfEntries);
    }

    Map<String, SyndFeed> feedMap = new HashMap<String, SyndFeed>();
    if (urls.length != 0) {
        for (String f : urls) {
            SyndFeed feed = loadOrGetFromCache(f, numberOfEntries);
            feedMap.put(feed.getTitle(), feed);
        }
    } else {
        for (String f : feeds.keySet()) {
            feedMap.put(f, loadOrGetFromCache(feeds.get(f), numberOfEntries));
        }
    }

    map.put("feeds", feedMap);
    return new ModelAndView("no/dusken/aranea/base/web/rss/view", map);
}

From source file:org.openmrs.web.controller.visit.VisitFormController.java

/**
 * Processes requests to save/update a visit
 *
 * @param request the {@link WebRequest} object
 * @param visit the visit object to save/update
 * @param result the {@link BindingResult} object
 * @param model the {@link ModelMap} object
 * @return the url to forward/redirect to
 *///  w  ww  . ja  va 2  s . co m
@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.POST, value = VISIT_FORM_URL)
public String saveVisit(HttpServletRequest request, @ModelAttribute("visit") Visit visit, BindingResult result,
        ModelMap model) {
    String[] ids = ServletRequestUtils.getStringParameters(request, "encounterIds");
    List<Integer> encounterIds = new ArrayList<Integer>();
    EncounterService es = Context.getEncounterService();
    List<Encounter> encountersToSave = new ArrayList<Encounter>();
    if (!ArrayUtils.isEmpty(ids)) {
        for (String id : ids) {
            if (StringUtils.hasText(id)) {
                encounterIds.add(Integer.valueOf(id));
            }
        }
        //validate that the encounters
        List<Encounter> visitEncounters = (List<Encounter>) model.get("visitEncounters");
        for (Encounter e : visitEncounters) {
            if (!encounterIds.contains(e.getEncounterId())) {
                //this encounter was removed in the UI, remove it from this visit
                e.setVisit(null);
                validateEncounter(e, result);
                if (result.hasErrors()) {
                    addEncounterAndObservationCounts(visit, encounterIds, model);
                    return VISIT_FORM;
                }

                encountersToSave.add(e);
            } else {
                //this is an already added encounter
                encounterIds.remove(e.getEncounterId());
            }
        }

        //the remaining encounterIds are for the newly added ones, validate and associate them to this visit
        for (Integer encounterId : encounterIds) {
            Encounter e = es.getEncounter(encounterId);
            if (e != null) {
                e.setVisit(visit);
                validateEncounter(e, result);
                if (result.hasErrors()) {
                    addEncounterAndObservationCounts(visit, encounterIds, model);
                    return VISIT_FORM;
                }

                encountersToSave.add(e);
            }
        }
    }

    // manually handle the attribute parameters
    List<VisitAttributeType> attributeTypes = (List<VisitAttributeType>) model.get("attributeTypes");

    WebAttributeUtil.handleSubmittedAttributesForType(visit, result, VisitAttribute.class, request,
            attributeTypes);
    new VisitValidator().validate(visit, result);
    if (!result.hasErrors()) {
        try {
            Context.getVisitService().saveVisit(visit);
            if (log.isDebugEnabled()) {
                log.debug("Saved visit: " + visit.toString());
            }
            request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Visit.saved");

            for (Encounter encounter : encountersToSave) {
                es.saveEncounter(encounter);
            }

            return "redirect:" + "/patientDashboard.form?patientId=" + visit.getPatient().getPatientId();
        } catch (APIException e) {
            log.warn("Error while saving visit(s)", e);
            request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Visit.save.error");
        }
    }

    addEncounterAndObservationCounts(visit, encounterIds, model);
    return VISIT_FORM;
}

From source file:org.openmrs.web.controller.encounter.EncounterFormController.java

/**
 * @see org.springframework.web.servlet.mvc.SimpleFormController#processFormSubmission(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 *///from  w  w  w . ja  va 2s  .c  o  m
@Override
protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse reponse,
        Object obj, BindException errors) throws Exception {

    Encounter encounter = (Encounter) obj;

    try {
        if (Context.isAuthenticated()) {
            Context.addProxyPrivilege(PrivilegeConstants.GET_USERS);
            Context.addProxyPrivilege(PrivilegeConstants.GET_PATIENTS);

            if (encounter.getEncounterId() == null && StringUtils.hasText(request.getParameter("patientId"))) {
                encounter.setPatient(Context.getPatientService()
                        .getPatient(Integer.valueOf(request.getParameter("patientId"))));
            }
            if (encounter.isVoided()) {
                ValidationUtils.rejectIfEmptyOrWhitespace(errors, "voidReason", "error.null");
            }

            String[] providerIdsArray = ServletRequestUtils.getStringParameters(request, "providerIds");
            if (ArrayUtils.isEmpty(providerIdsArray)) {
                errors.reject("Encounter.provider.atleastOneProviderRequired");
            }

            String[] roleIdsArray = ServletRequestUtils.getStringParameters(request, "encounterRoleIds");

            ProviderService ps = Context.getProviderService();
            EncounterService es = Context.getEncounterService();
            if (providerIdsArray != null && roleIdsArray != null) {
                //list to store role provider mappings to be used below to detect removed providers
                List<String> unremovedRoleAndProviders = new ArrayList<String>();
                for (int i = 0; i < providerIdsArray.length; i++) {
                    if (StringUtils.hasText(providerIdsArray[i]) && StringUtils.hasText(roleIdsArray[i])) {
                        unremovedRoleAndProviders.add(roleIdsArray[i] + "-" + providerIdsArray[i]);
                        Provider provider = ps.getProvider(Integer.valueOf(providerIdsArray[i]));
                        EncounterRole encounterRole = es.getEncounterRole(Integer.valueOf(roleIdsArray[i]));
                        //if this is an existing provider, don't create a new one to avoid losing existing
                        //details like dateCreated, creator, uuid etc in the encounter_provider table
                        if (encounter.getProvidersByRole(encounterRole).contains(provider)) {
                            continue;
                        }

                        //this is a new provider
                        encounter.addProvider(encounterRole, provider);
                    }
                }
                //Get rid of the removed ones
                for (Map.Entry<EncounterRole, Set<Provider>> entry : encounter.getProvidersByRoles()
                        .entrySet()) {
                    for (Provider p : entry.getValue()) {
                        if (!unremovedRoleAndProviders
                                .contains(entry.getKey().getEncounterRoleId() + "-" + p.getProviderId())) {
                            encounter.removeProvider(entry.getKey(), p);
                        }
                    }
                }
            }

            ValidationUtils.invokeValidator(new EncounterValidator(), encounter, errors);
        }
    } finally {
        Context.removeProxyPrivilege(PrivilegeConstants.GET_USERS);
        Context.removeProxyPrivilege(PrivilegeConstants.GET_PATIENTS);
    }

    return super.processFormSubmission(request, reponse, encounter, errors);
}