List of usage examples for javax.servlet.http HttpServletRequest getParameterValues
public String[] getParameterValues(String name);
String
objects containing all of the values the given request parameter has, or null
if the parameter does not exist. From source file:controller.CommercialController.java
@RequestMapping("regub/commercial/contrats/commodifiercontrat") String modifiercontratAction(HttpServletRequest request, HttpSession session, Model model) throws InterruptedException { int idContrat = clecontrat; String[] choixrayon = request.getParameterValues("rayon"); String[] choixregion = request.getParameterValues("region"); //String titrecontrat = request.getParameter("titre"); String freqcontrat = request.getParameter("frequence"); String durecontrat = request.getParameter("duree"); String datedebutcontrat = request.getParameter("datedebut"); String datefincontrat = request.getParameter("datefin"); String daterecepcontrat = request.getParameter("datereception"); String datevalidcontrat = request.getParameter("datevalidation"); String tarifcontrat = request.getParameter("tarif"); String choixstatut = request.getParameter("statut"); Set<Region> mySetregion = tableaureg(choixregion); Set<Typerayon> mySettyperayon = tableauray(choixrayon); //Chargement des infos lies au contrat qui se sera modifi Video vid = VidBDD.modifcontrat(idContrat); vid.setFrequence(Integer.parseInt(freqcontrat)); vid.setDuree(Integer.parseInt(durecontrat)); //System.out.println(""+titrecontrat); System.out.println("" + datedebutcontrat); //vid.setDateDebut(ConvertToSqlDate(datedebutcontrat)); vid.setDateFin(ConvertToSqlDate(datefincontrat)); //vid.setDateReception(ConvertToSqlDate(daterecepcontrat)); //vid.setDateValidation(ConvertToSqlDate(datevalidcontrat)); if (Integer.parseInt(choixstatut) == 1) { DateFormat dateformat = new SimpleDateFormat("dd-MM-yyyy"); Date currentDate = new Date(); String datecourante = dateformat.format(currentDate); vid.setDateValidation(ConvertToSqlDate(datecourante)); }/*from w w w.ja va2 s .com*/ vid.setStatut(Integer.parseInt(choixstatut)); vid.setTarif(Double.parseDouble(tarifcontrat)); vid.setRegions(mySetregion); vid.setTyperayons(mySettyperayon); //Thread.sleep(2000); VidBDD.updComContrat(vid, "modifier"); return "redirect:/regub/commercial/contrats/" + vid.getClient().getIdClient(); //return listClientAction(request, session, model); }
From source file:alfio.controller.api.admin.EventApiController.java
@RequestMapping("/events/{eventName}/export.csv") public void downloadAllTicketsCSV(@PathVariable("eventName") String eventName, HttpServletRequest request, HttpServletResponse response, Principal principal) throws IOException { List<String> fields = Arrays .asList(Optional.ofNullable(request.getParameterValues("fields")).orElse(new String[] {})); Event event = loadEvent(eventName, principal); Map<Integer, TicketCategory> categoriesMap = eventManager.loadTicketCategories(event).stream() .collect(Collectors.toMap(TicketCategory::getId, Function.identity())); ZoneId eventZoneId = event.getZoneId(); Predicate<String> contains = FIXED_FIELDS::contains; response.setContentType("text/csv;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=" + eventName + "-export.csv"); try (ServletOutputStream out = response.getOutputStream(); CSVWriter writer = new CSVWriter(new OutputStreamWriter(out))) { for (int marker : BOM_MARKERS) {//UGLY-MODE_ON: specify that the file is written in UTF-8 with BOM, thanks to alexr http://stackoverflow.com/a/4192897 out.write(marker);/* w ww.j a v a 2 s .c o m*/ } writer.writeNext(fields.stream().map(f -> { if (f.startsWith(CUSTOM_FIELDS_PREFIX)) { return f.substring(CUSTOM_FIELDS_PREFIX.length()); } return f; }).toArray(String[]::new)); eventManager.findAllConfirmedTicketsForCSV(eventName, principal.getName()).stream().map(t -> { List<String> line = new ArrayList<>(); if (fields.contains("ID")) { line.add(t.getUuid()); } if (fields.contains("Creation")) { line.add(t.getCreation().withZoneSameInstant(eventZoneId).toString()); } if (fields.contains("Category")) { line.add(categoriesMap.get(t.getCategoryId()).getName()); } if (fields.contains("Event")) { line.add(eventName); } if (fields.contains("Status")) { line.add(t.getStatus().toString()); } if (fields.contains("OriginalPrice")) { line.add(MonetaryUtil.centsToUnit(t.getSrcPriceCts()).toString()); } if (fields.contains("PaidPrice")) { line.add(MonetaryUtil.centsToUnit(t.getFinalPriceCts()).toString()); } if (fields.contains("Discount")) { line.add(MonetaryUtil.centsToUnit(t.getDiscountCts()).toString()); } if (fields.contains("VAT")) { line.add(MonetaryUtil.centsToUnit(t.getVatCts()).toString()); } if (fields.contains("ReservationID")) { line.add(t.getTicketsReservationId()); } if (fields.contains("Full Name")) { line.add(t.getFullName()); } if (fields.contains("First Name")) { line.add(t.getFirstName()); } if (fields.contains("Last Name")) { line.add(t.getLastName()); } if (fields.contains("E-Mail")) { line.add(t.getEmail()); } if (fields.contains("Locked")) { line.add(String.valueOf(t.getLockedAssignment())); } if (fields.contains("Language")) { line.add(String.valueOf(t.getUserLanguage())); } if (fields.contains("Confirmation")) { line.add(t.getTicketReservation().getConfirmationTimestamp().withZoneSameInstant(eventZoneId) .toString()); } if (fields.contains("Billing Address")) { line.add(t.getTicketReservation().getBillingAddress()); } //obviously not optimized Map<String, String> additionalValues = ticketFieldRepository.findAllValuesForTicketId(t.getId()); fields.stream().filter(contains.negate()).filter(f -> f.startsWith(CUSTOM_FIELDS_PREFIX)) .forEachOrdered(field -> { String customFieldName = field.substring(CUSTOM_FIELDS_PREFIX.length()); line.add(additionalValues.getOrDefault(customFieldName, "").replaceAll("\"", "")); }); return line.toArray(new String[line.size()]); }).forEachOrdered(writer::writeNext); writer.flush(); out.flush(); } }
From source file:com.enonic.cms.web.portal.services.ServicesProcessorBase.java
private ExtendedMap parseSimpleRequest(HttpServletRequest request) { ExtendedMap formItems = new ExtendedMap(true); Enumeration paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String key = paramNames.nextElement().toString(); String[] values = request.getParameterValues(key); if (values != null) { if (values.length == 1 && values[0] != null) { String value = values[0]; if ("true".equals(value)) { formItems.putBoolean(key, true); } else if ("false".equals(value)) { formItems.putBoolean(key, false); } else { formItems.putString(key, value); }/*from w ww.j a v a2 s . c o m*/ } else if (values.length > 1) { formItems.put(key, values); } } else { formItems.put(key, ""); } } return formItems; }
From source file:fr.paris.lutece.plugins.document.web.spaces.DocumentSpaceJspBean.java
private String getRequestData(HttpServletRequest request, DocumentSpace space) { String strErrorUrl = null;//from w w w . java 2s.c o m String strParentId = request.getParameter(PARAMETER_PARENT_SPACE_ID); String strName = request.getParameter(PARAMETER_NAME); String strDescription = request.getParameter(PARAMETER_DESCRIPTION); String strViewType = request.getParameter(PARAMETER_VIEW_TYPE); String strIcon = request.getParameter(PARAMETER_ICON); String[] strDocumentType = request.getParameterValues(PARAMETER_DOCUMENT_TYPE); String strAllowCreation = request.getParameter(PARAMETER_ALLOW_CREATION); String strWorkgroup = request.getParameter(PARAMETER_WORKGROUP_KEY); boolean bAllowCreation = ((strAllowCreation != null) && (strAllowCreation.equals("on"))) ? true : false; // Mandatory fields if (StringUtils.isBlank(strName) || StringUtils.isBlank(strDescription)) { return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FIELDS, AdminMessage.TYPE_STOP); } space.setIdParent(IntegerUtils.convert(strParentId)); space.setName(strName); space.setDescription(strDescription); space.setViewType(strViewType); space.setIdIcon(IntegerUtils.convert(strIcon)); space.resetAllowedDocumentTypesList(); space.setDocumentCreationAllowed(bAllowCreation); space.setWorkgroup(strWorkgroup); if (strDocumentType != null) { for (int i = 0; i < strDocumentType.length; i++) { space.addAllowedDocumentType(strDocumentType[i]); } } return strErrorUrl; }
From source file:fr.paris.lutece.plugins.workflow.modules.evaluation.web.EvaluationTaskComponent.java
/** * * @param config the config//from w w w . j av a 2s. co m * @param request request * @param task the task * @return error url */ private String getCriteriasData(TaskEvaluationConfig config, HttpServletRequest request, ITask task) { List<TaskEvaluationCriteria> criterias = new ArrayList<TaskEvaluationCriteria>(); String[] tabCriteriasChecked = request.getParameterValues(PARAMETER_CRITERIAS_CHECKED); if (tabCriteriasChecked != null) { //save criteria for (int cpt = 0; cpt < tabCriteriasChecked.length; cpt++) { String strIdCriteria = request.getParameter(PARAMETER_ID_CRITERIA + "_" + tabCriteriasChecked[cpt]); String strMandatoryCriteria = request .getParameter(PARAMETER_MANDATORY_CRITERIA + "_" + tabCriteriasChecked[cpt]); String strCriteriaTitle = request .getParameter(PARAMETER_CRITERIA_TITLE + "_" + tabCriteriasChecked[cpt]); String strCriteriaBestScore = request .getParameter(PARAMETER_CRITERIA_BEST_SCORE + "_" + tabCriteriasChecked[cpt]); int nCriteriaBestScore = WorkflowUtils.convertStringToInt(strCriteriaBestScore); Object[] tabCriteriaNum = { cpt + 1 }; if (((strCriteriaTitle == null) || strCriteriaTitle.trim().equals(WorkflowUtils.EMPTY_STRING))) { return AdminMessageService.getMessageUrl(request, MESSAGE_MANDATORY_CRITERIA_TITLE, tabCriteriaNum, AdminMessage.TYPE_STOP); } else if (((strCriteriaBestScore == null) || strCriteriaBestScore.trim().equals(WorkflowUtils.EMPTY_STRING))) { return AdminMessageService.getMessageUrl(request, MESSAGE_MANDATORY_CRITERIA_BEST_SCORE, tabCriteriaNum, AdminMessage.TYPE_STOP); } else if (nCriteriaBestScore < 0) { return AdminMessageService.getMessageUrl(request, MESSAGE_NUMERIC_CRITERIA_BEST_SCORE, tabCriteriaNum, AdminMessage.TYPE_STOP); } TaskEvaluationCriteria criteria = new TaskEvaluationCriteria(); criteria.setIdCriteria(Integer.parseInt(strIdCriteria)); criteria.setIdTask(task.getId()); criteria.setMandatory(strMandatoryCriteria != null); criteria.setTitle(strCriteriaTitle); criteria.setBestScore(strCriteriaBestScore); criterias.add(criteria); } } config.setEvaluationsCriteria(criterias); return null; }
From source file:cz.zcu.kiv.eegdatabase.logic.controller.experiment.DownloadMetadataZipController.java
@Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { // //ModelAndView mav = new ModelAndView("downloadMetadataZipView"); MetadataCommand mc = (MetadataCommand) command; int id = Integer.parseInt(request.getParameter("id")); Experiment fromDB = experimentDao.read(id); String scenarioName = fromDB.getScenario().getTitle(); Set<DataFile> files = fromDB.getDataFiles(); //gets a parameters from request //contents is in the request if user wants download data file String[] contents = request.getParameterValues("content"); //fileParam represents file metadata params String[] fileParam = request.getParameterValues("fileParam"); FileMetadataParamValId[] params = null; if (fileParam != null) { params = new FileMetadataParamValId[fileParam.length]; //go throws parameters and creates FileMetadataParamsValId instances //in the request data_file_id and file_metadata_param_def_id is separated //by # in the form file_id#file_metadata_param_def_id ///*from ww w .j a va 2 s . c o m*/ for (int i = 0; i < fileParam.length; i++) { String[] tmp = fileParam[i].split("#"); params[i] = new FileMetadataParamValId(Integer.parseInt(tmp[1]), Integer.parseInt(tmp[0])); } } Set<DataFile> newFiles = new HashSet<DataFile>(); if (fileParam != null || contents != null) { //go over data files selected from db for (DataFile item : files) { DataFile newItem = null; if (contents != null) { if (Arrays.asList(contents).contains(String.valueOf(item.getDataFileId()))) { newItem = new DataFile(); newItem.setDataFileId(item.getDataFileId()); newItem.setExperiment(item.getExperiment()); newItem.setFileContent(item.getFileContent()); newItem.setFilename(item.getFilename()); newItem.setMimetype(item.getMimetype()); newItem.setDescription(item.getDescription()); } } Set<FileMetadataParamVal> newVals = new HashSet<FileMetadataParamVal>(); if (params != null) { for (FileMetadataParamVal paramVal : item.getFileMetadataParamVals()) { for (FileMetadataParamValId paramId : params) { if (paramVal.getId().getDataFileId() == paramId.getDataFileId() && paramVal.getId() .getFileMetadataParamDefId() == paramId.getFileMetadataParamDefId()) { newVals.add(paramVal); } } } } if (!newVals.isEmpty()) { if (newItem == null) { newItem = new DataFile(); } newItem.setFileMetadataParamVals(newVals); } if (newItem != null) { newFiles.add(newItem); } } } Person user = personDao.getPerson(ControllerUtils.getLoggedUserName()); Timestamp currentTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime()); History history = new History(); log.debug("Setting downloading metadata"); history.setExperiment(fromDB); log.debug("Setting user"); history.setPerson(user); log.debug("Setting time of download"); history.setDateOfDownload(currentTimestamp); log.debug("Saving download history"); historyDao.create(history); File file = getZipGenerator().generate(fromDB, mc, newFiles, new byte[0], null); InputStream dataStream = new FileInputStream(file); response.setHeader("Content-Type", "application/zip"); if (scenarioName == null) { response.setHeader("Content-Disposition", "attachment;filename=Experiment_data.zip"); } else { String[] names = scenarioName.split(" "); scenarioName = names[0]; for (int i = 1; i < names.length; i++) { scenarioName += "_" + names[i]; } response.setHeader("Content-Disposition", "attachment;filename=" + scenarioName + ".zip"); } if (dataStream instanceof InputStream) { IOUtils.copyLarge(dataStream, response.getOutputStream()); dataStream.close(); } log.debug(zipGenerator); return null; }
From source file:com.hzc.framework.ssh.controller.WebUtil.java
/** * ?????bean<br/>// www . j av a 2 s .c o m * ??? * * @param <T> * @throws ValidationException */ public static <T> T packBean(Class<T> c) throws RuntimeException { try { HttpServletRequest request = ActionContext.getReq(); T newInstance = c.newInstance(); Field[] fields = c.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); String name = field.getName(); String value = request.getParameter(name); Class<?> type = field.getType(); if (type.isArray()) {//?string file Class<?> componentType = type.getComponentType(); if (componentType == String.class) { String[] values = request.getParameterValues(name); // if (null == value || "".equals(value)) continue; // String[] split = value.split(","); field.set(newInstance, values); } else if (componentType == File.class) { ServletContext servletContext = getServletContext(); File file = new File(servletContext.getRealPath("upload")); if (!file.exists()) file.mkdir(); MultipartRequest multi = new MultipartRequest(request, file.getAbsolutePath(), MAX_POST_SIZE, "UTF-8", new DefaultFileRenamePolicy()); Enumeration files = multi.getFileNames(); List<File> fileList = new ArrayList<File>(); if (files.hasMoreElements()) { File f = multi.getFile((String) files.nextElement()); fileList.add(f); } field.set(newInstance, fileList.toArray(new File[] {})); } } // else if (type == File.class) {//? // ServletContext servletContext = getServletContext(); // File file = new File(servletContext.getRealPath("upload")); // if (!file.exists()) // file.mkdir(); // MultipartRequest multi = // new MultipartRequest(request, file.getAbsolutePath(), 10 * 1024 * 1024, "UTF-8", new DefaultFileRenamePolicy()); // Enumeration files = multi.getFileNames(); // if (files.hasMoreElements()) { // field.set(newInstance, multi.getFile((String) files.nextElement())); // } // } // ? validation(field, name, value); if (null == value || "".equals(value.trim())) { continue; } if (type == Long.class) { field.set(newInstance, Long.parseLong(value)); } else if (type == String.class) { field.set(newInstance, value); } else if (type == Byte.class) { field.set(newInstance, Byte.parseByte(value)); } else if (type == Integer.class) { field.set(newInstance, Integer.parseInt(value)); } else if (type == Character.class) { field.set(newInstance, value.charAt(0)); } else if (type == Boolean.class) { field.set(newInstance, Boolean.parseBoolean(value)); } else if (type == Double.class) { field.set(newInstance, Double.parseDouble(value)); } else if (type == Float.class) { field.set(newInstance, Float.parseFloat(value)); } else if (type == Date.class) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); field.set(newInstance, sdf.parse(value)); } } return newInstance; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:cn.itcast.bbs.controller.BbsServlet.java
private void editTopic(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {//from w w w . j a v a 2 s . co m Topic topic = new Topic(); Enumeration<String> enums = request.getParameterNames(); while (enums.hasMoreElements()) { String key = enums.nextElement(); if (key.equals("method") || key.equals("typeId")) { continue; } String[] value = request.getParameterValues(key); BeanUtils.setProperty(topic, key, value); } service.updateTopic(topic); int typeId = Integer.parseInt(request.getParameter("typeId")); response.sendRedirect(request.getContextPath() + "/BbsServlet?method=showAllTopic&typeId=" + typeId); } catch (Exception e) { e.printStackTrace(); request.setAttribute("message", ""); request.getRequestDispatcher("/WEB-INF/bbs/message.jsp").forward(request, response); } }
From source file:com.adito.security.actions.ShowAvailableAccountsDispatchAction.java
/** * @param mapping/*from w w w .j a v a 2s .co m*/ * @param form * @param request * @param response * @return ActionForward * @throws Exception */ public ActionForward accountDeletion(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { PolicyUtil.checkPermission(PolicyConstants.ACCOUNTS_AND_GROUPS_RESOURCE_TYPE, PolicyConstants.PERM_DELETE, request); User currentUser = isSetupMode() ? null : LogonControllerFactory.getInstance().getUser(request); String[] accounts = request.getParameterValues("username"); boolean found = false; for (int i = 0; i < accounts.length; i++) { if (currentUser != null && accounts[i].equals(currentUser.getPrincipalName())) { found = true; } } if (!found) { UserDatabase udb = UserDatabaseManager.getInstance() .getUserDatabase(getSessionInfo(request).getUser().getRealm()); for (int i = 0; accounts != null && i < accounts.length; i++) { User user = udb.getAccount(accounts[i]); if (udb.supportsAccountCreation()) { try { // check to see if the user has a session, if so then logoff. Iterator loggedOnUserSessions = LogonControllerFactory.getInstance().getActiveSessions() .values().iterator(); while (loggedOnUserSessions.hasNext()) { SessionInfo element = (SessionInfo) loggedOnUserSessions.next(); if (element.getUser().equals(user)) { element.invalidate(); } } // Revoke all polices from the user PolicyDatabaseFactory.getInstance().revokeAllPoliciesFromPrincipal(user); udb.deleteAccount(user); CoreServlet.getServlet() .fireCoreEvent(new CoreEvent(this, CoreEventConstants.USER_REMOVED, null, null, CoreEvent.STATE_SUCCESSFUL) .addAttribute(CoreAttributeConstants.EVENT_ATTR_PRINCIPAL_ID, user.getPrincipalName()) .addAttribute(CoreAttributeConstants.EVENT_ATTR_FULL_NAME, user.getFullname())); } catch (Exception e) { CoreServlet.getServlet() .fireCoreEvent(new CoreEvent(this, CoreEventConstants.USER_REMOVED, null, null, e) .addAttribute(CoreAttributeConstants.EVENT_ATTR_PRINCIPAL_ID, user.getPrincipalName()) .addAttribute(CoreAttributeConstants.EVENT_ATTR_FULL_NAME, user.getFullname())); throw e; } } } } else { ActionMessages mesgs = new ActionMessages(); mesgs.add(Globals.ERROR_KEY, new ActionMessage("availableAccounts.cannotDeleteOwnAccount")); saveErrors(request, mesgs); } return mapping.findForward("refresh"); }
From source file:cn.vlabs.umt.ui.servlet.AuthorizationCodeServlet.java
/** * ?responseTypecode// w ww . j ava 2s . c om * @param request * @param response * @param oauthRequest * @throws IOException * @throws ServletException */ private void responseTypeIsCode(HttpServletRequest request, HttpServletResponse response, OAuthAuthzRequestWrap oauthRequest) throws IOException, ServletException { String[] scopses = request.getParameterValues("userScopes"); String redirectURI = getRedirectURI(request, oauthRequest); OAuthResponse resp; try { LoginInfo userLogin = UMTContext.getLoginInfo(request.getSession()); AuthorizationCodeBean bean = createAuthCodeBean(userLogin, oauthRequest); bean.updateScope(scopses); // bean.setExpiredTime(new Date(System.currentTimeMillis() + authorTimeout * 60l * 1000l)); getCodeServer().save(bean); resp = OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND) .setCode(bean.getCode()).setParam("state", bean.getState()).location(redirectURI) .buildQueryMessage(); response.sendRedirect(resp.getLocationUri()); } catch (OAuthSystemException e) { dealOAuthSystemError(redirectURI, e, request, response); } }