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:com.manydesigns.elements.fields.search.SelectSearchField.java

public void readFromRequest(HttpServletRequest req) {
    Object[] values = req.getParameterValues(inputName);
    if (values == null) {
        return;//from   w  w  w. j a  v  a2 s  .c  om
    } else if (values.length == 1 && VALUE_NOT_SET.equals(values[0])) {
        notSet = true;
    } else if (SearchDisplayMode.AUTOCOMPLETE == displayMode) {
        String stringValue = values[0].toString();
        boolean search;
        Object value;
        String userValue = req.getParameter(autocompleteInputName);
        if (StringUtils.isEmpty(stringValue)) {
            search = true;
            value = null;
        } else {
            value = OgnlUtils.convertValue(stringValue, accessor.getType());
            String label = selectionModel.getOption(selectionModelIndex, value, true);
            search = userValue != null && !StringUtils.equals(userValue, label);
        }
        if (search) {
            value = null;
            //Attempt to find the value among the options
            Map<Object, SelectionModel.Option> options = selectionModel.getOptions(selectionModelIndex);
            boolean found = false;
            for (SelectionModel.Option option : options.values()) {
                if (ObjectUtils.equals(userValue, option.label)) {
                    found = true;
                    value = option.value;
                }
            }
            if (!found) {
                return;
            }
        }
        selectionModel.setValue(selectionModelIndex, value);
    } else {
        Object[] castedValues = new Object[values.length];
        for (int i = 0; i < values.length; i++) {
            if (!StringUtils.isEmpty((String) values[i])) {
                castedValues[i] = OgnlUtils.convertValueQuietly(values[i], accessor.getType());
            }
        }
        selectionModel.setValue(selectionModelIndex, castedValues);
    }
}

From source file:com.neu.edu.servlet.CSVController.java

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    ModelAndView mv = new ModelAndView();
    String action = request.getParameter("action");
    if (action.equals("insert")) {

        int result = salesorderDAO.addToDb(request);

        if (result > 0) {
            // RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/views/addBooksSuccess.jsp");
            //rd.forward(request, response);
            String SalesOrderIDlist[] = request.getParameterValues("SalesOrderID");

            HttpSession session = request.getSession();
            session.setAttribute("count2", SalesOrderIDlist.length);
            mv.addObject("count2", SalesOrderIDlist.length);
            mv.setViewName("index");
        }//from www.j a v a2  s  .c o m

    } else {

        ArrayList<SalesOrder> retVal = salesorderDAO.getAllOrders();

        mv.addObject("retVal", retVal);
        mv.setViewName("index");

    }
    return mv;
}

From source file:com.searchbox.framework.web.SearchboxController.java

@ModelAttribute("conditions")
public Set<AbstractSearchCondition> getSearchConditions(HttpServletRequest request) {
    // Fetch all search Conditions within HTTP params
    Set<AbstractSearchCondition> conditions = new HashSet<AbstractSearchCondition>();
    for (String param : conversionService.getSearchConditionParams()) {
        if (request.getParameterValues(param) != null) {
            LOGGER.info("Parsing condition {} from params", param);
            for (String value : request.getParameterValues(param)) {
                if (value != null && !value.isEmpty()) {
                    try {
                        AbstractSearchCondition cond = (AbstractSearchCondition) conversionService
                                .convert(value, conversionService.getSearchConditionClass(param));
                        conditions.add(cond);
                    } catch (Exception e) {
                        LOGGER.error("Could not convert " + value, e);
                    }/*w  w  w. ja v a2 s .c  o m*/
                }
            }
        }
    }
    return conditions;
}

From source file:com.mtgi.analytics.servlet.ServletRequestBehaviorTrackingAdapter.java

protected String getEventName(HttpServletRequest request) {
    //use the request path as an event name, excluding proto, host, and query string.
    String eventName = request.getRequestURI();
    //optionally use important parameters as part of the event name
    if (nameParameters != null) {
        char sep = '?';
        StringBuffer buf = new StringBuffer(eventName);
        for (String name : this.nameParameters) {
            String[] values = request.getParameterValues(name);
            if (values != null) {
                for (String v : values) {
                    buf.append(sep).append(name).append('=').append(v);
                    sep = '&';
                }/*w ww . j a  v a2 s.c  om*/
            }
        }
        eventName = buf.toString();
    }

    return eventName;
}

From source file:org.esgf.globusonline.GOauthView1Controller.java

@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.POST)
public ModelAndView doPost(final HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //grab the dataset name, file names and urls from the query string
    String dataset_name = request.getParameter("id");
    String[] file_names = request.getParameterValues("child_id");
    String[] file_urls = request.getParameterValues("child_url");
    String esg_user = "";
    String esg_password = "";
    //String e;/*from   w w w .j  a v a 2 s .  c o  m*/
    //grab the credential string
    String credential = request.getParameter("credential");
    System.out.println("Starting GlobusOnline workflow");
    //System.out.println("\n\n\n\t\tGO Credential " + credential + "\n\n\n");

    StringBuffer currentURL = request.getRequestURL();
    String currentURI = request.getRequestURI();
    //System.out.println("current URL is: " + currentURL);
    //System.out.println("current URI is: " + currentURI);
    //System.out.println("index is: " + currentURL.lastIndexOf(currentURI));
    String BaseURL = currentURL.substring(0, currentURL.lastIndexOf(currentURI));
    //System.out.println("BaseURL string is: " + BaseURL );

    //Instantiate model object:
    Map<String, Object> model = new HashMap<String, Object>();

    //Bail out if no gsiftp URLs are in file_names
    if (file_names != null) {
        for (int i = 0; i < file_names.length; i++) {
            if (!(file_urls[i] == null) && (file_urls[i].contains("gsiftp"))) {
                break;
            } else {
                model.put(GOFORMVIEW_ERROR, "error");
                String error_msg = "Selected dataset " + dataset_name
                        + " contains no GridFTP URLS, and cannot be transferred with this transfer method.";
                model.put(GOFORMVIEW_ERROR_MSG, error_msg);
                return new ModelAndView("goauthview3", model);
            }
        }
    } else {
        System.out.println("file_urls itself was null\n");
        model.put(GOFORMVIEW_ERROR, "error");
        String error_msg = "Selected dataset(s) " + dataset_name
                + " contain no GridFTP URLS, and cannot be transferred with this transfer method.";
        model.put(GOFORMVIEW_ERROR_MSG, error_msg);
        return new ModelAndView("goauthview3", model);
    }
    //Create a session if it doesn't already exist, so we can save state.
    HttpSession session = request.getSession(true);
    if (session.isNew() == false) {
        session.invalidate();
        session = request.getSession(true);
    }

    //System.out.println("Auth1, session id is:" + session.getId());

    session.setAttribute("fileUrls", file_urls);
    session.setAttribute("fileNames", file_names);
    session.setAttribute("datasetName", dataset_name);
    session.setAttribute("baseurl", BaseURL);
    if (!(credential == null)) {
        session.setAttribute("usercertificatefile", credential);
    }

    Cookie[] cookies = request.getCookies();
    String openId = "";

    for (int i = 0; i < cookies.length; i++) {
        if (cookies[i].getName().equals("esgf.idp.cookie")) {
            openId = cookies[i].getValue();
        }
    }

    LOG.debug("Got User OpenID: " + openId);
    // Create the client
    Properties GOProperties = getGOProperties();
    String PortalID = (String) GOProperties.getProperty("GOesgfPortalID", "bogususer");
    String PortalPass = (String) GOProperties.getProperty("GOesgfPortalPassword", "boguspassword");

    String loginUri = "";
    try {
        GoauthClient cli = new GoauthClient("nexus.api.globusonline.org", "globusonline.org", PortalID,
                PortalPass);
        cli.setIgnoreCertErrors(true);

        // Redirect the user agent to the globusonline log in page
        loginUri = cli.getLoginUrl(response.encodeURL(BaseURL + "/esgf-web-fe/goauthview2"));

    } catch (NexusClientException e) {
        System.out.println("ERROR:  GOesgfPortalID and/or GOesgfPortalPassword wrong or not set.");
        //            e.printStackTrace();
        model.put(GOFORMVIEW_ERROR, "error");
        String error_msg = "GlobusOnline Configuration file not found. Please create /esg/config/globusonline.properties and populate it with GOesgfPortalID and GOesgfPortalPassword";
        model.put(GOFORMVIEW_ERROR_MSG, error_msg);
        return new ModelAndView("goauthview3", model);
    }
    String myproxyServerStr = null;

    return new ModelAndView("redirect:" + loginUri, model);
}

From source file:org.openmrs.module.conceptsearch.web.controller.ConceptNameTagListController.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  . ja v  a2s  .  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()) {
        String success = "";
        String error = "";

        MessageSourceAccessor msa = getMessageSourceAccessor();

        String[] conceptNameTagList = request.getParameterValues("conceptNameTagId");
        if (conceptNameTagList != null) {
            ConceptService cs = Context.getConceptService();
            ConceptSearchService css = (ConceptSearchService) Context.getService(ConceptSearchService.class);

            String deleted = msa.getMessage("general.deleted");
            String notDeleted = msa.getMessage("ConceptNameTag.cannot.delete");
            for (String nameTag : conceptNameTagList) {
                try {
                    css.purgeConceptNameTag(cs.getConceptNameTag(Integer.valueOf(nameTag)));
                    if (!success.equals(""))
                        success += "<br/>";
                    success += nameTag + " " + deleted;
                } catch (DataIntegrityViolationException e) {
                    error = handleConceptNameTagIntegrityException(e, error, notDeleted);
                } catch (APIException e) {
                    error = handleConceptNameTagIntegrityException(e, error, notDeleted);
                }
            }
        } else
            error = msa.getMessage("ConceptNameTag.select");

        view = getSuccessView();
        if (!success.equals(""))
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, success);
        if (!error.equals(""))
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, error);
    }

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

From source file:RegistrationServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    JSONObject json = new JSONObject();

    Enumeration paramNames = request.getParameterNames();
    String params[] = new String[3];
    int i = 0;/* ww  w. j  a  v  a2 s . co  m*/
    while (paramNames.hasMoreElements()) {
        String paramName = (String) paramNames.nextElement();
        //System.out.println("ParamName : " +paramName);

        String[] paramValues = request.getParameterValues(paramName);
        params[i] = paramValues[0];
        //System.out.println("ParamValue : " +params[i]);

        i++;
    }

    DatabaseHandler db = new DatabaseHandler();

    conn = db.makeConnection();
    try {
        stmt = conn.createStatement();

        //params[0]=password,params[1]=name,params[2]=email
        String query = "INSERT INTO user (name,email,password) VALUES (\"" + params[1] + "\",\"" + params[2]
                + "\",\"" + params[0] + "\")";
        //System.out.println(query);

        int updatedRows = stmt.executeUpdate(query);
        if (updatedRows == 1) {
            json.put("reply", "done");
        } else {
            json.put("reply", "undone");
        }

    } catch (SQLException ex) {
        Logger.getLogger(RegistrationServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    //System.out.println(updatedRows);
    //System.out.println(json);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json.toString());

    //closing mysql connection (now done in DatanaseHandler class)
    db.closeAllConnections(conn, stmt);

}

From source file:br.org.indt.ndg.servlets.OpenRosaManagement.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    m_openRosaBD.setPortAndAddress(SystemProperties.getServerAddress());

    String action = request.getParameter(ACTION_PARAM);

    if (SET_AVAILABLE_FOR_USER.equals(action)) {
        String selectedImei = request.getParameter(SELECTED_IMEI_PARAM);
        String[] selectedSurveyIds = request.getParameterValues(SELECTED_SURVEY_ID_PARAM);
        if (selectedImei != null && selectedSurveyIds != null) {
            log.info("IMEI: " + selectedImei);
            for (int i = 0; i < selectedSurveyIds.length; i++) {
                log.info("Survey id:" + selectedSurveyIds[i]);
            }/*from   www  . j  a  va 2 s  .c  om*/
        }
        boolean result = m_openRosaBD.makeSurveysAvailableForImei(selectedImei, selectedSurveyIds);
        request.setAttribute(RESULT_ATTR, result);
        dispatchSurveysForUserSelectionPage(request, response);
    } else if (EXPORT_RESULTS_FOR_USER.equals(action)) {
        ServletOutputStream outputStream = null;
        FileInputStream fileInputStream = null;
        DataInputStream dataInputStream = null;
        File file = null;
        try {
            String zipFilename = m_openRosaBD.exportZippedResultsForUser("223344556677");
            file = new File(zipFilename);
            int length = 0;
            outputStream = response.getOutputStream();
            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType("application/octet-stream");

            response.setContentType(mimetype);
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "attachment; filename=\"" + zipFilename + "\"");

            byte[] bbuf = new byte[1024];
            fileInputStream = new FileInputStream(file);
            dataInputStream = new DataInputStream(fileInputStream);

            while ((dataInputStream != null) && ((length = dataInputStream.read(bbuf)) != -1)) {
                outputStream.write(bbuf, 0, length);
            }
            outputStream.flush();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (fileInputStream != null)
                    fileInputStream.close();
                if (dataInputStream != null)
                    dataInputStream.close();
                if (fileInputStream != null)
                    fileInputStream.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            file.delete();
        }
    }
}

From source file:com.virtusa.akura.attendance.controller.SpecialEventsAttendanceController.java

/**
 * method to save or update Special Events Attendance object.
 * //from   w ww.j a  v a2s .com
 * @param request Http request.
 * @param map model map to set data.
 * @return String value of jsp page to direct.
 * @throws AkuraAppException throw exception if occur.
 */

@RequestMapping(method = RequestMethod.POST, value = SAVEORUPDATE_SPECIAL_EVENTS_ATTENDANCE_HTM)
public String saveorupdateSpecialAttendance(HttpServletRequest request, ModelMap map) throws AkuraAppException {

    String[] studentID = request.getParameterValues(STUDENT_ID_LIST);
    int participationId = Integer.parseInt(request.getParameter(SELECTED_PARTICIPANT));

    List<SpecialEventsAttendance> specialEventsAttendances = dailyAttendanceService
            .getSpecialEventAttandanceList(participationId);
    List<String> pastAttendanceList = new ArrayList<String>();
    // get the present students id list
    for (SpecialEventsAttendance specialEventsAttendancesList : specialEventsAttendances) {
        pastAttendanceList.add(String.valueOf(specialEventsAttendancesList.getStudentId()));
    }
    try {
        if (studentID != null) {

            @SuppressWarnings("unchecked")
            // get the absent student list
            List<String> toBeRomoved = ListUtils.subtract((pastAttendanceList), Arrays.asList(studentID));

            @SuppressWarnings("unchecked")
            // get the present student list
            List<String> toBeAdd = ListUtils.subtract(Arrays.asList(studentID), pastAttendanceList);

            // add present students
            if (!toBeAdd.isEmpty()) {

                addSpecialEventAttendance(participationId, toBeAdd);
            }
            // remove absent students
            if (!toBeRomoved.isEmpty()) {

                deleteSpecialEventAttendance(participationId, toBeRomoved);
            }

            return searchSpecialEventsAttendance(request, map);
        } else if (studentID == null && (!specialEventsAttendances.isEmpty())) {

            deleteSpecialEventAttendance(participationId, pastAttendanceList);

            return searchSpecialEventsAttendance(request, map);
        }

    } catch (AkuraAppException e) {
        if (e.getCause() instanceof DataIntegrityViolationException) {
            String message = new ErrorMsgLoader().getErrorMessage(ATTENDANCE_SAVE_FAIL);

            map.addAttribute(MESSAGE, message);
            return ATTENDANCE_SPECIAL_EVENTS_ATTENDANCE;
        } else {
            throw e;
        }
    }

    return searchSpecialEventsAttendance(request, map);

}

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

/**
 * The onSubmit function receives the form/command object that was modified by the input form
 * and saves it to the db/*from   w  ww .j a va2s  . com*/
 *
 * @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();
        String error = "";

        MessageSourceAccessor msa = getMessageSourceAccessor();

        String[] locationList = request.getParameterValues("locationId");
        if (locationList != null) {
            LocationService ls = Context.getLocationService();

            String deleted = msa.getMessage("general.deleted");
            String notDeleted = msa.getMessage("Location.cannot.delete");
            for (String p : locationList) {
                //TODO convenience method deleteLocation(Integer) ??
                try {
                    ls.purgeLocation(ls.getLocation(Integer.valueOf(p)));
                    if (!"".equals(success.toString())) {
                        success.append("<br/>");
                    }
                    success.append(p).append(" ").append(deleted);
                } catch (DataIntegrityViolationException e) {
                    error = handleLocationIntegrityException(e, error, notDeleted);
                } catch (APIException e) {
                    error = handleLocationIntegrityException(e, error, notDeleted);
                }
            }
        } else {
            error = msa.getMessage("Location.select");
        }

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

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