Example usage for javax.servlet.http HttpServletRequest getParameterValues

List of usage examples for javax.servlet.http HttpServletRequest getParameterValues

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getParameterValues.

Prototype

public String[] getParameterValues(String name);

Source Link

Document

Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist.

Usage

From source file:org.oscarehr.web.OcanReportingAction.java

public ActionForward generateIndividualNeedRatingOverTimeReport(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {
    String clientId = request.getParameter("client");
    String[] assessments = request.getParameterValues("assessment");
    String needsMet = request.getParameter("needs_met");
    String needsUnmet = request.getParameter("needs_unmet");
    String needsNo = request.getParameter("needs_no");
    String needsUnknown = request.getParameter("needs_unknown");

    logger.debug("Generate Individual Needs Rating over Time Report");
    logger.debug("clientId=" + clientId);
    for (int x = 0; x < assessments.length; x++)
        logger.debug("assessment=" + assessments[x]);
    logger.debug("needsMet=" + needsMet);
    logger.debug("needsUnmet=" + needsUnmet);
    logger.debug("needsNo=" + needsNo);
    logger.debug("needsUnknown=" + needsUnknown);

    //bean which will feed our generator
    OcanIndividualNeedsOverTimeBean bean = new OcanIndividualNeedsOverTimeBean();
    bean.setConsumerName(/*from w w w  . jav  a 2s.  c om*/
            demographicDao.getClientByDemographicNo(Integer.parseInt(clientId)).getFormattedName());
    bean.setStaffName(LoggedInInfo.loggedInInfo.get().loggedInProvider.getFormattedName());
    bean.setReportDate(new Date());
    bean.setShowUnmetNeeds(needsUnmet != null);
    bean.setShowMetNeeds(needsMet != null);
    bean.setShowNoNeeds(needsNo != null);
    bean.setShowUnknownNeeds(needsUnknown != null);

    //list of charts
    List<IndividualNeedsOverTimeChartBean> results = new ArrayList<IndividualNeedsOverTimeChartBean>();

    for (int x = 0; x < assessments.length; x++) {
        Integer formId = Integer.valueOf(assessments[x].split(";")[0]);

        //get the latest form for the assessment
        OcanStaffForm ocanForm = ocanStaffFormDao.find(formId);
        //get data fields
        List<OcanStaffFormData> ocanFormData = ocanStaffFormDataDao.findByForm(ocanForm.getId());
        //convert to map
        Map<String, OcanStaffFormData> ocanFormDataMap = new HashMap<String, OcanStaffFormData>();
        for (OcanStaffFormData tmp : ocanFormData) {
            ocanFormDataMap.put(tmp.getQuestion(), tmp);
        }
        //create and initialize map of counts
        Map<String, Integer> needsCountMap = new HashMap<String, Integer>();
        needsCountMap.put("unmet", 0);
        needsCountMap.put("met", 0);
        needsCountMap.put("no", 0);
        needsCountMap.put("unknown", 0);
        needsCountMap.put("clientUnmet", 0);
        needsCountMap.put("clientMet", 0);
        needsCountMap.put("clientNo", 0);
        needsCountMap.put("clientUnknown", 0);

        for (int i = 1; i <= 24; i++) {
            addToNeedCount_Client(needsCountMap, "client_" + i + "_1", ocanFormDataMap);
        }

        for (int i = 1; i <= 24; i++) {
            addToNeedCount_Staff(needsCountMap, i + "_1", ocanFormDataMap);
        }

        IndividualNeedsOverTimeChartBean chartBean = new IndividualNeedsOverTimeChartBean(ocanForm,
                needsCountMap, assessments[x].split(";")[1]);
        results.add(chartBean);
    }

    if (bean.isShowUnmetNeeds()) {
        bean.setUnmetNeedsChart(generateChart("Number of Unmet Needs over Time (Consumer and Staff)", "unmet",
                "clientUnmet", results));
    }

    if (bean.isShowMetNeeds()) {
        bean.setMetNeedsChart(generateChart("Number of Met Needs over Time (Consumer and Staff)", "met",
                "clientMet", results));
    }

    if (bean.isShowNoNeeds()) {
        bean.setNoNeedsChart(
                generateChart("Number of No Needs over Time (Consumer and Staff)", "no", "clientNo", results));
    }
    if (bean.isShowUnknownNeeds()) {
        bean.setUnknownNeedsChart(generateChart("Number of Unknown Needs over Time (Consumer and Staff)",
                "unknown", "clientUnknown", results));
    }

    IndividualNeedRatingOverTimeReportGenerator reportGen = new IndividualNeedRatingOverTimeReportGenerator();
    reportGen.setReportBean(bean);

    try {
        response.setContentType("application/pdf");
        response.setHeader("content-disposition", "inline; filename=\"IndividualNeedRatingOverTime.pdf\"");
        reportGen.generateReport(response.getOutputStream());
    } catch (Exception e) {
        logger.error("error", e);
    }

    return null;
}

From source file:compare.handler.get.CompareGetHandler.java

/**
 * Format the requested URN version as HTML
 * @param request the original http request
 * @param response the response to write to
 * @param urn the original request urn//from ww  w  .j a  v  a2s . c o m
 * @throws CompareException if the response could not be written
 */
protected void handleGetVersion(HttpServletRequest request, HttpServletResponse response, String urn)
        throws CompareException, CalliopeException {
    String version1 = request.getParameter(Params.VERSION1);
    if (version1 == null) {
        try {
            response.getWriter().println("<p>version1 parameter required</p>");
        } catch (Exception e) {
            throw new CompareException(e);
        }
    } else {
        String selectedVersions = request.getParameter(Params.SELECTED_VERSIONS);
        //System.out.println("version1="+version1);
        EcdosisVersion corTex = doGetResourceVersion(Database.CORTEX, urn, version1);
        // 1. get corcodes and styles
        String[] corCodes = request.getParameterValues(Params.CORCODE);
        String[] styles = request.getParameterValues(Params.STYLE);
        HashSet<String> styleSet = new HashSet<String>();
        for (int i = 0; i < styles.length; i++)
            styleSet.add(styles[i]);
        try {
            for (int i = 0; i < corCodes.length; i++) {
                String ccResource = Utils.canonisePath(urn, corCodes[i]);
                EcdosisVersion ev = doGetResourceVersion(Database.CORCODE, ccResource, version1);
                Comment comment = new Comment();
                comment.addText("version-length: " + ev.getVersionLength());
                response.setCharacterEncoding("UTF-8");
                response.getWriter().println(comment.toString());
                styleSet.add(ev.getStyle());
                corCodes[i] = ev.getVersionString();
            }
        } catch (Exception e) {
            // this won't ever happen because UTF-8 is always supported
            throw new CompareException(e);
        }
        // 2. add mergeids if needed
        if (selectedVersions != null && selectedVersions.length() > 0) {
            corCodes = addMergeIds(corCodes, corTex.getMVD(), version1, selectedVersions);
            styleSet.add("diffs/default");
        }
        // 3. recompute styles array (docids)
        styles = new String[styleSet.size()];
        styleSet.toArray(styles);
        // 4. convert style names to actual corforms
        styles = fetchStyles(styles);
        // 5. call the native library to format it
        JSONResponse html = new JSONResponse(JSONResponse.HTML);
        String text = corTex.getVersionString();
        int res = new AeseFormatter().format(text, corCodes, styles, html);
        if (res == 0)
            throw new CompareException("formatting failed");
        else {
            response.setContentType("text/html;charset=UTF-8");
            try {
                Comment comment = new Comment();
                comment.addText("styles: ");
                for (int i = 0; i < styles.length; i++)
                    comment.addText(styles[i]);
                response.getWriter().println(comment.toString());
                response.getWriter().println(html.getBody());
            } catch (Exception e) {
                throw new CompareException(e);
            }
        }
    }
}

From source file:org.oscarehr.web.OcanReportingAction.java

public ActionForward generateSummaryOfActionsAndCommentsReport(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {
    String clientId = request.getParameter("client");
    String[] assessments = request.getParameterValues("assessment");
    String[] domains = request.getParameterValues("domains");
    String comments = request.getParameter("comments");

    logger.debug("Generate Summary Of Actions and Comments Report");
    logger.debug("clientId=" + clientId);
    for (int x = 0; x < assessments.length; x++)
        logger.debug("assessment=" + assessments[x]);
    for (int x = 0; x < domains.length; x++)
        logger.debug("domain=" + domains[x]);
    logger.debug("comments=" + comments);

    SummaryOfActionsAndCommentsReportBean reportBean = new SummaryOfActionsAndCommentsReportBean();

    //loop through the selected domains, figure out which category it goes into (using
    //current OCAN). Create a SummaryOfActionsAndCommentsDomainBean, and put it into the
    //right need category of the report bean

    String currentOcanFormId = assessments[assessments.length - 1].split(";")[0];
    OcanStaffForm ocanForm = ocanStaffFormDao.find(Integer.parseInt(currentOcanFormId));
    List<OcanStaffFormData> ocanFormData = ocanStaffFormDataDao.findByForm(ocanForm.getId());
    Map<String, OcanStaffFormData> ocanFormDataMap = new HashMap<String, OcanStaffFormData>();
    for (OcanStaffFormData tmp : ocanFormData) {
        ocanFormDataMap.put(tmp.getQuestion(), tmp);
    }//ww  w  . j  a v  a2  s. co  m

    for (int x = 0; x < domains.length; x++) {
        SummaryOfActionsAndCommentsDomainBean domainBean = new SummaryOfActionsAndCommentsDomainBean();
        String domainId = domains[x].split(";")[0];
        String domainName = domains[x].split(";")[1];

        OcanStaffFormData staffFormData = ocanFormDataMap.get(domainId + "_1");
        OcanStaffFormData consumerFormData = ocanFormDataMap.get("client_" + domainId + "_1");
        String staffValue = (staffFormData == null) ? null : staffFormData.getAnswer();
        String consumerValue = (consumerFormData == null) ? null : consumerFormData.getAnswer();
        String needCategory = this.determineBestNeed(staffValue, consumerValue);
        domainBean.setDomainId(domainId);
        domainBean.setDomainName(domainName);
        if (needCategory.equals("unmet")) {
            reportBean.getUnmetNeeds().add(domainBean);
        } else if (needCategory.equals("met")) {
            reportBean.getMetNeeds().add(domainBean);
        } else if (needCategory.equals("no")) {
            reportBean.getNoNeeds().add(domainBean);
        } else {
            reportBean.getUnknown().add(domainBean);
        }
    }

    //we need to pre-load all the OCANs..or else we will be constantly getting it from db.
    List<CachedOcanFormAndData> ocanFormAndDataList = new ArrayList<CachedOcanFormAndData>();
    for (int x = 0; x < assessments.length; x++) {
        Integer formId = Integer.valueOf(assessments[x].split(";")[0]);

        //get the latest form for the assessment
        ocanForm = ocanStaffFormDao.find(formId);
        //get data fields
        ocanFormData = ocanStaffFormDataDao.findByForm(ocanForm.getId());
        //convert to map
        ocanFormDataMap = new HashMap<String, OcanStaffFormData>();
        for (OcanStaffFormData tmp : ocanFormData) {
            ocanFormDataMap.put(tmp.getQuestion(), tmp);
        }
        ocanFormAndDataList.add(0, new CachedOcanFormAndData(ocanForm, ocanFormDataMap));
    }
    //Collections.reverse(ocanFormAndDataList);

    //we now know which domain goes in which category. now we will go through each domain
    //bean, and populate with OCAN data.
    boolean includeComments = (comments != null && comments.equals("comments")) ? true : false;
    for (SummaryOfActionsAndCommentsDomainBean domainBean : reportBean.getUnmetNeeds()) {
        populateOcansIntoDomain(ocanFormAndDataList, domainBean, domainBean.getOcanBeans(), includeComments,
                assessments);
    }
    for (SummaryOfActionsAndCommentsDomainBean domainBean : reportBean.getMetNeeds()) {
        populateOcansIntoDomain(ocanFormAndDataList, domainBean, domainBean.getOcanBeans(), includeComments,
                assessments);
    }
    for (SummaryOfActionsAndCommentsDomainBean domainBean : reportBean.getNoNeeds()) {
        populateOcansIntoDomain(ocanFormAndDataList, domainBean, domainBean.getOcanBeans(), includeComments,
                assessments);
    }
    for (SummaryOfActionsAndCommentsDomainBean domainBean : reportBean.getUnknown()) {
        populateOcansIntoDomain(ocanFormAndDataList, domainBean, domainBean.getOcanBeans(), includeComments,
                assessments);
    }

    SummaryOfActionsAndCommentsReportGenerator reportGen = new SummaryOfActionsAndCommentsReportGenerator();
    reportGen.setReportBean(reportBean);
    reportGen.setConsumerName(
            demographicDao.getClientByDemographicNo(Integer.parseInt(clientId)).getFormattedName());
    reportGen.setStaffName(LoggedInInfo.loggedInInfo.get().loggedInProvider.getFormattedName());
    reportGen.setReportDate(new Date());
    reportGen.setIncludeComments(includeComments);

    try {
        response.setContentType("application/pdf");
        response.setHeader("content-disposition", "inline; filename=\"SummaryOfActionsAndComments.pdf\"");
        reportGen.generateReport(response.getOutputStream());
    } catch (Exception e) {
        logger.error("error", e);
    }

    return null;
}

From source file:mx.edu.um.mateo.general.web.UsuarioController.java

@Transactional
@RequestMapping(value = "/crea", method = RequestMethod.POST)
public String crea(HttpServletRequest request, HttpServletResponse response, @Valid Usuario usuario,
        BindingResult bindingResult, Errors errors, Model modelo, RedirectAttributes redirectAttributes,
        @RequestParam Boolean enviaCorreo) {
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }//from  w w  w . j  ava2 s.  c om
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");
        List<Rol> roles = obtieneRoles();
        modelo.addAttribute("roles", roles);
        return "admin/usuario/nuevo";
    }

    String password = null;
    try {
        log.debug("Evaluando roles {}", request.getParameterValues("roles"));
        String[] roles = request.getParameterValues("roles");
        if (roles == null || roles.length == 0) {
            log.debug("Asignando ROLE_USER por defecto");
            roles = new String[] { "ROLE_USER" };
        }
        Long almacenId = (Long) request.getSession().getAttribute("almacenId");
        password = KeyGenerators.string().generateKey();
        usuario.setPassword(password);
        usuario = usuarioDao.crea(usuario, almacenId, roles);

        if (enviaCorreo) {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(usuario.getCorreo());
            helper.setSubject(messageSource.getMessage("envia.correo.password.titulo.message", new String[] {},
                    request.getLocale()));
            helper.setText(messageSource.getMessage("envia.correo.password.contenido.message",
                    new String[] { usuario.getNombre(), usuario.getUsername(), password }, request.getLocale()),
                    true);
            mailSender.send(message);
        }

    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear al usuario", e);
        errors.rejectValue("username", "campo.duplicado.message", new String[] { "username" }, null);
        List<Rol> roles = obtieneRoles();
        modelo.addAttribute("roles", roles);
        return "admin/usuario/nuevo";
    } catch (MessagingException e) {
        log.error("No se pudo enviar la contrasena por correo", e);

        redirectAttributes.addFlashAttribute("message", "usuario.creado.sin.correo.message");
        redirectAttributes.addFlashAttribute("messageAttrs", new String[] { usuario.getUsername(), password });

        return "redirect:/admin/usuario/ver/" + usuario.getId();
    }

    redirectAttributes.addFlashAttribute("message", "usuario.creado.message");
    redirectAttributes.addFlashAttribute("messageAttrs", new String[] { usuario.getUsername() });

    return "redirect:/admin/usuario/ver/" + usuario.getId();
}

From source file:com.expressflow.servlets.ExecProcessServlet.java

private void performRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html");

    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    if (user != null) {
        StringBuilder sb = new StringBuilder(request.getRequestURI());
        String processID = sb.substring(6, sb.length());
        if (processID != null) {
            try {
                // TaskQueues do not support UserService functions...
                // Add the process to the flow-processing queue
                TaskOptions taskOptions = TaskOptions.Builder.withUrl("/_ah/queue/flowprocessor");

                Enumeration parameterNames = request.getParameterNames();
                while (parameterNames.hasMoreElements()) {
                    String parameterName = (String) parameterNames.nextElement();
                    String[] paramValues = request.getParameterValues(parameterName);
                    if (paramValues.length == 1) {
                        taskOptions.param(parameterName, paramValues[0]);
                    } else {
                        System.err.print(parameterName + " has more values?!");
                    }/*from w ww .java  2  s .co  m*/
                }

                //                  Map<String, String[]> parameterMap = request.getParameterMap();
                //                  for (Map.Entry<String, String[]> parameter : parameterMap.entrySet()) {
                //                     for(String value : parameter.getValue()){
                //                        taskOptions.param(parameter.getKey(), value);
                //                     }
                //                  }

                Queue queue = QueueFactory.getQueue("flowprocessor");
                queue.add(taskOptions.param("key", processID));

            } catch (Exception e) {
                log.info(e.getMessage());
            }
        }
    } else {
        response.sendRedirect(response.encodeRedirectURL(userService.createLoginURL(request.getRequestURI())));
    }
}

From source file:com.attribyte.essem.model.StoredGraph.java

/**
 * Parses the components of a graph from request parameters.
 * @param request The request.//from w  w  w  . j a v  a2s  .  c  o m
 * @param app The application name to use (overrides any parameter).
 * @return A parsed graph builder with all parameters set, or null if key is invalid.
 */
public static StoredGraph.Builder parseGraph(final HttpServletRequest request, String app) {
    if (app == null) {
        app = request.getParameter("app");
        if (app == null)
            app = request.getParameter("application");
    }
    MetricKey key = MetricKey.parseKey(request, app);
    if (!key.isValidIdentifier()) {
        return null;
    }

    StoredGraph.Builder graphBuilder = new StoredGraph.Builder();
    graphBuilder.setMetricKey(key);
    graphBuilder.setRangeName(request.getParameter("range"));

    String startTimestampStr = Strings.nullToEmpty(request.getParameter("startTimestamp"));
    if (!startTimestampStr.isEmpty()) {
        graphBuilder.setStartTimestamp(Long.parseLong(startTimestampStr));
    }

    String endTimestampStr = Strings.nullToEmpty(request.getParameter("endTimestamp"));
    if (!endTimestampStr.isEmpty()) {
        graphBuilder.setEndTimestamp(Long.parseLong(endTimestampStr));
    }

    graphBuilder.setDownsampleFn(request.getParameter("downsampleFn"));
    graphBuilder.setRateUnit(request.getParameter("rateUnit"));
    graphBuilder.setTitle(toValidIdentifier(request.getParameter("title")));
    graphBuilder.setDescription(toValidIdentifier(request.getParameter("description")));
    graphBuilder.setXLabel(toValidIdentifier(request.getParameter("xLabel")));
    graphBuilder.setYLabel(toValidIdentifier(request.getParameter("yLabel")));

    String[] tags = request.getParameterValues("tag");
    if (tags != null && tags.length > 0) {
        graphBuilder.setTags(ImmutableSet.copyOf(tags));
    } else if (request.getParameter("tagString") != null) {
        for (String tag : Util.csvSplitter.split(request.getParameter("tagString"))) {
            graphBuilder.addTag(toValidIdentifier(tag));
        }
    }

    return graphBuilder;
}

From source file:nl.surfnet.coin.teams.control.AddExternalGroupController.java

@RequestMapping(value = "/doaddexternalgroup.shtml", method = RequestMethod.POST)
public RedirectView addExternalGroups(@ModelAttribute(TokenUtil.TOKENCHECK) String sessionToken,
        @ModelAttribute("team") Team team, @RequestParam String token, ModelMap modelMap, SessionStatus status,
        HttpServletRequest request) throws UnsupportedEncodingException {

    TokenUtil.checkTokens(sessionToken, token, status);
    Person person = (Person) request.getSession().getAttribute(LoginInterceptor.PERSON_SESSION_KEY);
    String personId = person.getId();
    if (!controllerUtil.hasUserAdministrativePrivileges(person, team.getId())) {
        throw new RuntimeException("Requester (" + person.getId()
                + ") is not member or does not have the correct " + "privileges to add external groups");
    }//from   ww  w  .  j  a v  a  2  s .c o  m

    final List<ExternalGroup> myExternalGroups = getExternalGroups(personId, request);
    Map<String, ExternalGroup> map = new HashMap<String, ExternalGroup>();
    for (ExternalGroup e : myExternalGroups) {
        map.put(e.getIdentifier(), e);
    }
    final String[] chosenGroups = request.getParameterValues(EXTERNAL_GROUPS_SESSION_KEY);

    List<TeamExternalGroup> teamExternalGroups = new ArrayList<TeamExternalGroup>();
    for (String identifier : chosenGroups) {
        TeamExternalGroup t = new TeamExternalGroup();
        t.setGrouperTeamId(team.getId());
        ExternalGroup externalGroup = map.get(identifier);
        t.setExternalGroup(externalGroup);
        teamExternalGroups.add(t);
        teamExternalGroupDao.saveOrUpdate(t);
        AuditLog.log("User {} added external group to team {}: {}", personId, team, externalGroup);
    }

    request.getSession().removeAttribute(EXTERNAL_GROUPS_SESSION_KEY);
    status.setComplete();
    modelMap.clear();
    return new RedirectView("detailteam.shtml?team=" + URLEncoder.encode(team.getId(), UTF_8) + "&view="
            + ViewUtil.getView(request), false, true, false);
}

From source file:com.swiftcorp.portal.question.web.QuestionDispatchAction.java

public ActionForward addQuestionnaire(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SystemException, BusinessRuleViolationException, Exception {
    log.info("addQuestionnaire() : Enter");
    HttpSession session = request.getSession();
    String[] checkbox = (String[]) request.getParameterValues("checkgroup");

    return promptQuestionnaireSerialList(mapping, form, request, response);
}

From source file:ke.co.tawi.babblesms.server.servlet.accountmngmt.EditContact.java

/**
 *
 * @param request/*w  w w.j a  va 2s . c  o m*/
 * @param response
 * @throws ServletException, IOException
 */

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession(true);

    String username = (String) session.getAttribute(SessionConstants.ACCOUNT_SIGN_IN_KEY);
    if (StringUtils.isEmpty(username)) {
        response.sendRedirect("../index.jsp");
    }
    Account account = new Account();

    Element element;
    if ((element = accountCache.get(username)) != null) {
        account = (Account) element.getObjectValue();
    }
    String contactname = request.getParameter("name").trim();
    String contactstatusuuid = request.getParameter("statusuuid").trim();
    String description = request.getParameter("description").trim();

    String[] groupArray = request.getParameterValues("groupselected[]");
    String cuuid = request.getParameter("uuid").trim();
    String[] phonenumArray = request.getParameterValues("phone1[]");

    String[] emailArray = request.getParameterValues("email[]");
    String[] networkArray = request.getParameterValues("network[]");

    if (contactname.equals("") || phonenumArray.equals("")) {
        session.setAttribute("fail", ERROR_NO_NAME);
    }

    else {

        boolean Contact = saveContact(cuuid, contactname, description, account);
        boolean Phone = savePhone(phonenumArray, networkArray, cuuid, contactstatusuuid);
        boolean Email = saveEmail(cuuid, emailArray);
        boolean Group = saveGroup(account, groupArray);

        if (Contact == true && Phone == true && Email == true && Group == true) {
            session.setAttribute("success", "Saved Successfully!!");

        } else {
            session.setAttribute("fail", "An Error occurred, Please try Again!!");
        }
    }

    response.sendRedirect("contact.jsp");
}