List of usage examples for org.springframework.validation BindingResult getAllErrors
List<ObjectError> getAllErrors();
From source file:org.wallride.web.controller.admin.article.ArticleBulkDeleteController.java
@RequestMapping public String delete(@Valid @ModelAttribute("form") ArticleBulkDeleteForm form, BindingResult errors, String query, AuthorizedUser authorizedUser, RedirectAttributes redirectAttributes) { redirectAttributes.addAttribute("query", query); if (!form.isConfirmed()) { errors.rejectValue("confirmed", "Confirmed"); }/* ww w . j av a 2 s. c o m*/ if (errors.hasErrors()) { logger.debug("Errors: {}", errors); return "redirect:/_admin/{language}/articles/index"; } Collection<Article> articles = null; try { articles = articleService.bulkDeleteArticle(form.buildArticleBulkDeleteRequest(), errors); } catch (ValidationException e) { if (errors.hasErrors()) { logger.debug("Errors: {}", errors); return "redirect:/_admin/{language}/articles/index"; } throw e; } List<String> errorMessages = null; if (errors.hasErrors()) { errorMessages = new ArrayList<>(); for (ObjectError error : errors.getAllErrors()) { errorMessages.add(messageSourceAccessor.getMessage(error)); } } redirectAttributes.addFlashAttribute("deletedArticles", articles); redirectAttributes.addFlashAttribute("errorMessages", errorMessages); return "redirect:/_admin/{language}/articles/index"; }
From source file:com.rr.generic.ui.reports.reportController.java
/** * //from w w w . j a v a2 s . c o m * @param surveyId * @param session * @param request * @return * @throws Exception */ @RequestMapping(value = "/saveParticipantReport.do", method = RequestMethod.POST) public ModelAndView saveReport(@ModelAttribute(value = "reportDetails") reportRequest reportDetails, @RequestParam List<Integer> selectedSites, BindingResult errors, HttpSession session, HttpServletRequest request) throws Exception { if (errors.hasErrors()) { for (ObjectError error : errors.getAllErrors()) { System.out.println(error.getDefaultMessage()); } } User userDetails = (User) session.getAttribute("userDetails"); SimpleDateFormat datesearchFormat = new SimpleDateFormat("MM/dd/yyyy"); Date startDate = datesearchFormat.parse(reportDetails.getStartDate()); Date endDate = datesearchFormat.parse(reportDetails.getEndDate()); datesearchFormat.applyPattern("yyyy-MM-dd"); String realStartDate = datesearchFormat.format(startDate); String realEndDate = datesearchFormat.format(endDate); String reportFileName = ""; String registryName = programmanager.getProgramById(programId).getProgramName().replaceAll(" ", "-") .toLowerCase(); /* Get the client engagements */ List<engagements> engagements = engagementmanager.getEngagementByMultipleEntity(programId, selectedSites, realStartDate, realEndDate); Integer reportRequestId = 0; /* Loop through sessions here */ if (engagements != null && engagements.size() > 0) { reportDetails.setProgramId(programId); reportDetails.setSystemUserId(userDetails.getId()); reportDetails.setSelectedDateRange(reportDetails.getStartDate() + " - " + reportDetails.getEndDate()); reportDetails.setStartDateTime(startDate); reportDetails.setEndDateTime(endDate); reportRequestId = reportmanager.saveReportRequest(reportDetails); if (selectedSites != null && !"".equals(selectedSites)) { StringBuilder selectedSiteNames = new StringBuilder(); for (Integer site : selectedSites) { programHierarchyDetails siteDetails = hierarchymanager.getProgramHierarchyItemDetails(site); reportRequestEntity reportSite = new reportRequestEntity(); reportSite.setSiteName(siteDetails.getName()); reportSite.setReportRequestId(reportRequestId); reportSite.setEntity3Id(site); reportmanager.saveReportRequestEntity(reportSite); } } progressBar newProgressBar = new progressBar(); newProgressBar.setExportId(reportDetails.getUniqueId()); newProgressBar.setPercentComplete(0); reportmanager.saveProgessBar(newProgressBar); DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssS"); Date date = new Date(); String fileName = ""; String delimiter = ","; if (reportDetails.getFileTypeId() == 1) { fileName = new StringBuilder().append("participantReport").append(dateFormat.format(date)) .append(".csv").toString(); delimiter = ","; } else if (reportDetails.getFileTypeId() == 2) { fileName = new StringBuilder().append("participantReport").append(dateFormat.format(date)) .append(".txt").toString(); delimiter = ","; } else if (reportDetails.getFileTypeId() == 3) { fileName = new StringBuilder().append("participantReport").append(dateFormat.format(date)) .append(".txt").toString(); delimiter = "|"; } else if (reportDetails.getFileTypeId() == 4) { fileName = new StringBuilder().append("participantReport").append(dateFormat.format(date)) .append(".txt").toString(); delimiter = "\t"; } /* Create new export file */ InputStream inputStream = null; OutputStream outputStream = null; fileSystem dir = new fileSystem(); dir.setDir(registryName, "reports"); File newFile = new File(dir.getDir() + fileName); /* Create the empty file in the correct location */ try { if (newFile.exists()) { int i = 1; while (newFile.exists()) { int iDot = fileName.lastIndexOf("."); newFile = new File(dir.getDir() + fileName.substring(0, iDot) + "_(" + ++i + ")" + fileName.substring(iDot)); } fileName = newFile.getName(); newFile.createNewFile(); } else { newFile.createNewFile(); } } catch (IOException e) { e.printStackTrace(); } /* Read in the file */ FileInputStream fileInput = null; File file = new File(dir.getDir() + fileName); fileInput = new FileInputStream(file); reportFileName = fileName; FileWriter fw = null; try { fw = new FileWriter(file, true); } catch (IOException ex) { Logger.getLogger(exportManager.class.getName()).log(Level.SEVERE, null, ex); } reportDetails.setReportFileName(reportFileName); reportmanager.updateReportRequest(reportDetails); StringBuilder reportRow = new StringBuilder(); reportRow.append("ORGCODE").append(delimiter); reportRow.append("PARTICIP").append(delimiter); reportRow.append("STATE").append(delimiter); reportRow.append("GLUCTEST").append(delimiter); reportRow.append("GDM").append(delimiter); /* P */ reportRow.append("RISKTEST").append(delimiter); /* P */ reportRow.append("AGE").append(delimiter); /* P */ reportRow.append("ETHNIC").append(delimiter); /* P */ reportRow.append("AIAN").append(delimiter); /* P */ reportRow.append("ASIAN").append(delimiter); /* P */ reportRow.append("BLACK").append(delimiter); /* P */ reportRow.append("NHOPI").append(delimiter); /* P */ reportRow.append("WHITE").append(delimiter); /* P */ reportRow.append("SEX").append(delimiter); /* P */ reportRow.append("HEIGHT").append(delimiter); reportRow.append("DATE").append(delimiter); reportRow.append("WEIGHT").append(delimiter); reportRow.append("PA").append(delimiter); reportRow.append(System.getProperty("line.separator")); fw.write(reportRow.toString()); Integer participantId = 0; List<programExportFields> exportFields = programmanager.getProgramExportFields(programId); List<String> tableinfo = new ArrayList<String>(); Integer fieldId = 0; Integer customFieldId = 0; Integer validationValue = 0; String fieldTypeValue = ""; Integer crosswalkId = 0; for (programExportFields field : exportFields) { if (field.getFieldType() == 1) { fieldTypeValue = "1"; programClientFields fieldDetails = clientmanager.getClientFieldDetails(programId, field.getFieldId()); fieldId = fieldDetails.getFieldId(); customFieldId = fieldDetails.getCustomfieldId(); validationValue = fieldDetails.getValidationId(); crosswalkId = fieldDetails.getCrosswalkId(); } else { fieldTypeValue = "2"; programEngagementFields fieldDetails = engagementmanager.getEngagementFieldDetails(programId, field.getFieldId()); fieldId = fieldDetails.getFieldId(); customFieldId = fieldDetails.getCustomfieldId(); validationValue = fieldDetails.getValidationId(); crosswalkId = fieldDetails.getCrosswalkId(); } if (fieldId > 0) { dataElements fieldDetails = clientmanager.getFieldDetails(fieldId); tableinfo.add(fieldTypeValue + "-" + fieldDetails.getSaveToTableName() + "-" + fieldDetails.getSaveToTableCol() + "-" + validationValue + "-" + crosswalkId); } else if (customFieldId > 0) { customProgramFields fieldDetails = clientmanager.getCustomFieldDetails(customFieldId); tableinfo.add(fieldTypeValue + "-" + fieldDetails.getSaveToTable() + "-" + fieldDetails.getSaveToTableCol() + "-" + validationValue + "-" + crosswalkId); } } Integer totalDone = 0; float percentComplete; progressBar reportProgressBar = reportmanager.getProgressBar(reportDetails.getUniqueId()); for (engagements engagement : engagements) { reportRow = new StringBuilder(); programHierarchyDetails hierarchyDetails = hierarchymanager.getProgramHierarchyItemDetails( clientmanager.getClientEntities(engagement.getProgramPatientId()).getEntity3Id()); String siteDisplayId = ""; if (hierarchyDetails.getDisplayId() != null) { siteDisplayId = hierarchyDetails.getDisplayId(); } reportRow.append(siteDisplayId).append(delimiter); if (tableinfo != null & tableinfo.size() > 0) { for (String table : tableinfo) { String[] tableInfoArray = table.split("-"); String fieldValue = ""; String fieldType = tableInfoArray[0]; String tablename = tableInfoArray[1]; String tableCol = tableInfoArray[2]; String validation = tableInfoArray[3]; String crosswalk = tableInfoArray[4]; if ("1".equals(fieldType)) { fieldValue = clientmanager.getTableData(tablename, tableCol, engagement.getProgramPatientId()); } else { fieldValue = engagementmanager.getTableData(tablename, tableCol, engagement.getId(), engagement.getProgramPatientId()); } if (!"".equals(crosswalk) && !"0".equals(crosswalk)) { crosswalkData cwData = clientmanager .getCrosswalkDataByTarget(Integer.parseInt(crosswalk), fieldValue); if (cwData != null) { fieldValue = cwData.getDescValue(); } else { fieldValue = ""; } } /* If date format to correct display format */ if ("4".equals(validation)) { if ("dob".equals(tableCol)) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date dob = format.parse(fieldValue); Date today = new Date(); format.applyPattern("yyyy"); String dobAsString = format.format(dob); String todayAsString = format.format(today); Integer age = Integer.parseInt(todayAsString) - Integer.parseInt(dobAsString); reportRow.append(age).append(delimiter); } else { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date formatedDate = format.parse(fieldValue); format.applyPattern("MM/dd/yy"); reportRow.append(format.format(formatedDate)).append(delimiter); } } else { reportRow.append(fieldValue).append(delimiter); } } } reportRow.append(System.getProperty("line.separator")); fw.write(reportRow.toString()); //Update progress bar totalDone = totalDone + 1; percentComplete = ((float) totalDone) / engagements.size(); reportProgressBar.setPercentComplete(Math.round(percentComplete * 100)); reportmanager.saveProgessBar(reportProgressBar); } fw.close(); } ModelAndView mav = new ModelAndView(); /* If no results are found */ if (reportFileName.isEmpty()) { mav.setViewName("/reports/reportModal"); savedExports newexportDetails = new savedExports(); reportDetails.setFileTypeId(1); programOrgHierarchy level1 = hierarchymanager.getProgramOrgHierarchyBydspPos(1, programId); programOrgHierarchy level2 = hierarchymanager.getProgramOrgHierarchyBydspPos(2, programId); programOrgHierarchy level3 = hierarchymanager.getProgramOrgHierarchyBydspPos(3, programId); List<programHierarchyDetails> level1Items = hierarchymanager.getProgramHierarchyItems(level1.getId(), userDetails.getId()); mav.addObject("level1Items", level1Items); mav.addObject("level1Name", level1.getName()); mav.addObject("level2Name", level2.getName()); mav.addObject("level3Name", level3.getName()); mav.addObject("exportDetails", newexportDetails); mav.addObject("showDateRange", true); mav.addObject("noresults", true); } else { if (reportDetails.getUniqueId() > 0) { /* Delete progress bar entry */ reportmanager.deleteProgressBar(reportDetails.getUniqueId()); } mav.setViewName("/reports/reportDownloadModal"); mav.addObject("reportFileName", reportFileName); } return mav; }
From source file:com.rr.wabshs.ui.importexport.importExportController.java
/** * /*from w w w. j av a 2 s .c o m*/ * @param surveyId * @param session * @param request * @return * @throws Exception */ @RequestMapping(value = "/saveParticipantExport.do", method = RequestMethod.POST) public ModelAndView saveExport(@ModelAttribute(value = "exportDetails") savedExports exportDetails, @RequestParam List<Integer> selectedSites, BindingResult errors, HttpSession session, HttpServletRequest request) throws Exception { if (errors.hasErrors()) { for (ObjectError error : errors.getAllErrors()) { System.out.println(error.getDefaultMessage()); } } User userDetails = (User) session.getAttribute("userDetails"); SimpleDateFormat datesearchFormat = new SimpleDateFormat("MM/dd/yyyy"); Date startDate = datesearchFormat.parse(exportDetails.getStartDate()); Date endDate = datesearchFormat.parse(exportDetails.getEndDate()); datesearchFormat.applyPattern("yyyy-MM-dd"); String realStartDate = datesearchFormat.format(startDate); String realEndDate = datesearchFormat.format(endDate); String exportFileName = ""; String registryName = programmanager.getProgramById(programId).getProgramName().replaceAll(" ", "-") .toLowerCase(); /* Get the client engagements */ List<engagements> engagements = engagementmanager.getEngagementByMultipleEntity(programId, selectedSites, realStartDate, realEndDate); Integer exportId = 0; /* Loop through sessions here */ if (engagements != null && engagements.size() > 0) { exportDetails.setProgramId(programId); exportDetails.setSystemUserId(userDetails.getId()); exportDetails.setSelectedDateRange(exportDetails.getStartDate() + " - " + exportDetails.getEndDate()); exportDetails.setDownloadType(1); exportDetails.setTotalRecords(engagements.size()); exportId = exportManager.saveExport(exportDetails); if (selectedSites != null && !"".equals(selectedSites)) { StringBuilder selectedSiteNames = new StringBuilder(); for (Integer site : selectedSites) { programHierarchyDetails siteDetails = hierarchymanager.getProgramHierarchyItemDetails(site); savedExportSites exportSite = new savedExportSites(); exportSite.setExportId(exportId); exportSite.setSiteName(siteDetails.getName()); exportSite.setSiteId(site); exportManager.saveExportSite(exportSite); } } progressBar newProgressBar = new progressBar(); newProgressBar.setExportId(exportDetails.getUniqueId()); newProgressBar.setPercentComplete(0); exportManager.saveProgessBar(newProgressBar); DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssS"); Date date = new Date(); String fileName = ""; String delimiter = ","; if (exportDetails.getExportType() == 1) { fileName = new StringBuilder().append("clientExport").append(dateFormat.format(date)).append(".csv") .toString(); delimiter = ","; } else if (exportDetails.getExportType() == 2) { fileName = new StringBuilder().append("clientExport").append(dateFormat.format(date)).append(".txt") .toString(); delimiter = ","; } else if (exportDetails.getExportType() == 3) { fileName = new StringBuilder().append("clientExport").append(dateFormat.format(date)).append(".txt") .toString(); delimiter = "|"; } else if (exportDetails.getExportType() == 4) { fileName = new StringBuilder().append("clientExport").append(dateFormat.format(date)).append(".txt") .toString(); delimiter = "\t"; } /* Create new export file */ InputStream inputStream = null; OutputStream outputStream = null; fileSystem dir = new fileSystem(); dir.setDir(registryName, "exportFiles"); File newFile = new File(dir.getDir() + fileName); /* Create the empty file in the correct location */ try { if (newFile.exists()) { int i = 1; while (newFile.exists()) { int iDot = fileName.lastIndexOf("."); newFile = new File(dir.getDir() + fileName.substring(0, iDot) + "_(" + ++i + ")" + fileName.substring(iDot)); } fileName = newFile.getName(); newFile.createNewFile(); } else { newFile.createNewFile(); } } catch (IOException e) { e.printStackTrace(); } /* Read in the file */ FileInputStream fileInput = null; File file = new File(dir.getDir() + fileName); fileInput = new FileInputStream(file); exportFileName = fileName; FileWriter fw = null; try { fw = new FileWriter(file, true); } catch (IOException ex) { Logger.getLogger(exportManager.class.getName()).log(Level.SEVERE, null, ex); } exportDetails.setExportFile(exportFileName); exportManager.saveExport(exportDetails); StringBuilder exportRow = new StringBuilder(); exportRow.append("PATIENT NUMBER").append(delimiter); exportRow.append("FIRST NAME").append(delimiter); exportRow.append("LAST NAME").append(delimiter); exportRow.append("DOB").append(delimiter); exportRow.append("GENDER").append(delimiter); /* P */ exportRow.append("VISIT DATE").append(delimiter); /* P */ exportRow.append("WEIGHT").append(delimiter); /* P */ exportRow.append("HEIGHT").append(delimiter); /* P */ exportRow.append("BP SYSTOLIC").append(delimiter); /* P */ exportRow.append("BP DIASTOLIC").append(delimiter); /* P */ exportRow.append(System.getProperty("line.separator")); fw.write(exportRow.toString()); Integer participantId = 0; List<programExportFields> exportFields = programmanager.getProgramExportFields(programId); List<String> tableinfo = new ArrayList<String>(); Integer fieldId = 0; Integer customFieldId = 0; Integer validationValue = 0; String fieldTypeValue = ""; Integer crosswalkId = 0; for (programExportFields field : exportFields) { if (field.getFieldType() == 1) { fieldTypeValue = "1"; programClientFields fieldDetails = clientmanager.getClientFieldDetails(programId, field.getFieldId()); fieldId = fieldDetails.getFieldId(); customFieldId = fieldDetails.getCustomfieldId(); validationValue = fieldDetails.getValidationId(); crosswalkId = fieldDetails.getCrosswalkId(); } else { fieldTypeValue = "2"; programEngagementFields fieldDetails = engagementmanager.getEngagementFieldDetails(programId, field.getFieldId()); fieldId = fieldDetails.getFieldId(); customFieldId = fieldDetails.getCustomfieldId(); validationValue = fieldDetails.getValidationId(); crosswalkId = fieldDetails.getCrosswalkId(); } if (fieldId > 0) { dataElements fieldDetails = clientmanager.getFieldDetails(fieldId); tableinfo.add(fieldTypeValue + "-" + fieldDetails.getSaveToTableName() + "-" + fieldDetails.getSaveToTableCol() + "-" + validationValue + "-" + crosswalkId); } else if (customFieldId > 0) { customProgramFields fieldDetails = clientmanager.getCustomFieldDetails(customFieldId); tableinfo.add(fieldTypeValue + "-" + fieldDetails.getSaveToTable() + "-" + fieldDetails.getSaveToTableCol() + "-" + validationValue + "-" + crosswalkId); } } Integer totalDone = 0; float percentComplete; progressBar exportProgressBar = exportManager.getProgressBar(exportDetails.getUniqueId()); for (engagements engagement : engagements) { exportRow = new StringBuilder(); programHierarchyDetails hierarchyDetails = hierarchymanager.getProgramHierarchyItemDetails( clientmanager.getClientEntities(engagement.getProgramPatientId()).getEntity3Id()); String siteDisplayId = ""; if (hierarchyDetails.getDisplayId() != null) { siteDisplayId = hierarchyDetails.getDisplayId(); } //exportRow.append(siteDisplayId).append(delimiter); if (tableinfo != null & tableinfo.size() > 0) { for (String table : tableinfo) { String[] tableInfoArray = table.split("-"); String fieldValue = ""; String fieldType = tableInfoArray[0]; String tablename = tableInfoArray[1]; String tableCol = tableInfoArray[2]; String validation = tableInfoArray[3]; String crosswalk = tableInfoArray[4]; if ("1".equals(fieldType)) { fieldValue = clientmanager.getTableData(tablename, tableCol, engagement.getProgramPatientId()); } else { fieldValue = engagementmanager.getTableData(tablename, tableCol, engagement.getId(), engagement.getProgramPatientId()); } if ("55".equals(crosswalk) && "0".equals(fieldValue)) { fieldValue = "2"; } /* If date format to correct display format */ if ("4".equals(validation)) { if ("dob".equals(tableCol)) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date dob = format.parse(fieldValue); Date today = new Date(); format.applyPattern("yyyy"); String dobAsString = format.format(dob); String todayAsString = format.format(today); Integer age = Integer.parseInt(todayAsString) - Integer.parseInt(dobAsString); exportRow.append(age).append(delimiter); } else { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date formatedDate = format.parse(fieldValue); format.applyPattern("MM/dd/yy"); exportRow.append(format.format(formatedDate)).append(delimiter); } } else { exportRow.append(fieldValue).append(delimiter); } } } exportRow.append(System.getProperty("line.separator")); fw.write(exportRow.toString()); //Update progress bar totalDone = totalDone + 1; percentComplete = ((float) totalDone) / engagements.size(); exportProgressBar.setPercentComplete(Math.round(percentComplete * 100)); exportManager.saveProgessBar(exportProgressBar); } fw.close(); } ModelAndView mav = new ModelAndView(); /* If no results are found */ if (exportFileName.isEmpty()) { mav.setViewName("/importExport/exportModal"); savedExports newexportDetails = new savedExports(); exportDetails.setExportType(1); programOrgHierarchy level1 = hierarchymanager.getProgramOrgHierarchyBydspPos(1, programId); programOrgHierarchy level2 = hierarchymanager.getProgramOrgHierarchyBydspPos(2, programId); programOrgHierarchy level3 = hierarchymanager.getProgramOrgHierarchyBydspPos(3, programId); Integer userId; if (userDetails.getRoleId() == 2) { userId = 0; } else { userId = userDetails.getId(); } List<programHierarchyDetails> level1Items = hierarchymanager.getProgramHierarchyItems(level1.getId(), userId); mav.addObject("level1Items", level1Items); mav.addObject("level1Name", level1.getName()); mav.addObject("level2Name", level2.getName()); mav.addObject("level3Name", level3.getName()); mav.addObject("exportDetails", newexportDetails); mav.addObject("showDateRange", true); mav.addObject("noresults", true); } else { if (exportDetails.getUniqueId() > 0) { /* Delete progress bar entry */ exportManager.deleteProgressBar(exportDetails.getUniqueId()); } mav.setViewName("/importExport/exportDownloadModal"); mav.addObject("exportFileName", exportFileName); } return mav; }
From source file:org.openmrs.module.OpenmrsLite.page.controller.EditPatientDemographicsPageController.java
/** * @should void the old person name and replace it with a new one when it is edited * @should not void the existing name if there are no changes in the name *//*from w w w . j a va 2s . co m*/ public String post(UiSessionContext sessionContext, PageModel model, @SpringBean("patientService") PatientService patientService, @RequestParam("patientId") @BindParams Patient patient, @BindParams PersonName name, @RequestParam("returnUrl") String returnUrl, @SpringBean("nameTemplateGivenFamily") NameTemplate nameTemplate, HttpServletRequest request, @SpringBean("messageSourceService") MessageSourceService messageSourceService, Session session, @SpringBean("patientValidator") PatientValidator patientValidator, UiUtils ui) throws Exception { sessionContext.requireAuthentication(); if (patient.getPersonName() != null && name != null) { PersonName currentName = patient.getPersonName(); if (!currentName.equalsContent(name)) { //void the old name and replace it with the new one patient.addName(name); currentName.setVoided(true); } } BindingResult errors = new BeanPropertyBindingResult(patient, "patient"); patientValidator.validate(patient, errors); if (!errors.hasErrors()) { try { patientService.savePatient(patient); InfoErrorMessageUtil.flashInfoMessage(request.getSession(), ui.message("OpenmrsLite.editDemographicsMessage.success", patient.getPersonName())); return "redirect:" + returnUrl; } catch (Exception e) { log.warn("Error occurred while saving patient demographics", e); session.setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, "OpenmrsLite.save.fail"); } } else { model.addAttribute("errors", errors); StringBuffer errorMessage = new StringBuffer( messageSourceService.getMessage("error.failed.validation")); errorMessage.append("<ul>"); for (ObjectError error : errors.getAllErrors()) { errorMessage.append("<li>"); errorMessage.append(messageSourceService.getMessage(error.getCode(), error.getArguments(), error.getDefaultMessage(), null)); errorMessage.append("</li>"); } errorMessage.append("</ul>"); session.setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, errorMessage.toString()); } model.addAttribute("patient", patient); model.addAttribute("nameTemplate", nameTemplate); model.addAttribute("returnUrl", returnUrl); //redisplay the form return null; }
From source file:org.openmrs.module.registration.page.controller.EditPatientDemographicsPageController.java
/** * @should void the old person name and replace it with a new one when it is edited * @should not void the existing name if there are no changes in the name *///from w w w. j a v a2 s. c om public String post(UiSessionContext sessionContext, PageModel model, @SpringBean("patientService") PatientService patientService, @RequestParam("patientId") @BindParams Patient patient, @BindParams PersonName name, @RequestParam("returnUrl") String returnUrl, @SpringBean("nameTemplateGivenFamily") NameTemplate nameTemplate, HttpServletRequest request, @SpringBean("messageSourceService") MessageSourceService messageSourceService, Session session, @SpringBean("patientValidator") PatientValidator patientValidator, UiUtils ui) throws Exception { sessionContext.requireAuthentication(); if (patient.getPersonName() != null && name != null) { PersonName currentName = patient.getPersonName(); if (!currentName.equalsContent(name)) { //void the old name and replace it with the new one patient.addName(name); currentName.setVoided(true); } } BindingResult errors = new BeanPropertyBindingResult(patient, "patient"); patientValidator.validate(patient, errors); if (!errors.hasErrors()) { try { patientService.savePatient(patient); InfoErrorMessageUtil.flashInfoMessage(request.getSession(), ui.message("registration.editDemographicsMessage.success", patient.getPersonName())); return "redirect:" + returnUrl; } catch (Exception e) { log.warn("Error occurred while saving patient demographics", e); session.setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, "registration.save.fail"); } } else { model.addAttribute("errors", errors); StringBuffer errorMessage = new StringBuffer( messageSourceService.getMessage("error.failed.validation")); errorMessage.append("<ul>"); for (ObjectError error : errors.getAllErrors()) { errorMessage.append("<li>"); errorMessage.append(messageSourceService.getMessage(error.getCode(), error.getArguments(), error.getDefaultMessage(), null)); errorMessage.append("</li>"); } errorMessage.append("</ul>"); session.setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, errorMessage.toString()); } model.addAttribute("patient", patient); model.addAttribute("nameTemplate", nameTemplate); model.addAttribute("returnUrl", returnUrl); //redisplay the form return null; }
From source file:org.wallride.web.controller.admin.customfield.CustomFieldBulkDeleteController.java
@RequestMapping public String delete(@Valid @ModelAttribute("form") CustomFieldBulkDeleteForm form, BindingResult errors, String query, AuthorizedUser authorizedUser, RedirectAttributes redirectAttributes) { redirectAttributes.addAttribute("query", query); if (!form.isConfirmed()) { errors.rejectValue("confirmed", "Confirmed"); }/* ww w. jav a 2 s . c om*/ if (errors.hasErrors()) { logger.debug("Errors: {}", errors); return "redirect:/_admin/{language}/customfields/index"; } Collection<CustomField> customFields = null; try { customFields = customFieldService.bulkDeleteCustomField(form.buildCustomFieldBulkDeleteRequest(), errors); } catch (ValidationException e) { if (errors.hasErrors()) { logger.debug("Errors: {}", errors); return "redirect:/_admin/{language}/customfields/index"; } throw e; } List<String> errorMessages = null; if (errors.hasErrors()) { errorMessages = new ArrayList<>(); for (ObjectError error : errors.getAllErrors()) { errorMessages.add(messageSourceAccessor.getMessage(error)); } } redirectAttributes.addFlashAttribute("deletedCustomFields", customFields); redirectAttributes.addFlashAttribute("errorMessages", errorMessages); return "redirect:/_admin/{language}/customfields/index"; }
From source file:fr.univrouen.poste.web.candidat.MyPosteCandidatureController.java
@RequestMapping(value = "/{id}/addMemberReviewFile", method = RequestMethod.POST, produces = "text/html") @PreAuthorize("hasPermission(#id, 'review')") public String addMemberReviewFile(@PathVariable("id") Long id, @Valid MemberReviewFile memberReviewFile, BindingResult bindingResult, Model uiModel, HttpServletRequest request) throws IOException { if (bindingResult.hasErrors()) { logger.warn(bindingResult.getAllErrors()); return "redirect:/postecandidatures/" + id.toString(); }/*from w ww. j a v a 2 s .c o m*/ uiModel.asMap().clear(); // get PosteCandidature from id PosteCandidature postecandidature = PosteCandidature.findPosteCandidature(id); // upload file MultipartFile file = memberReviewFile.getFile(); // sometimes file is null here, but I don't know how to reproduce this issue ... maybe that can occur only with some specifics browsers ? if (file != null) { String filename = file.getOriginalFilename(); Long fileSize = file.getSize(); boolean filenameAlreadyUsed = false; for (MemberReviewFile rFile : postecandidature.getMemberReviewFiles()) { if (rFile.getFilename().equals(filename)) { filenameAlreadyUsed = true; break; } } if (filenameAlreadyUsed) { uiModel.addAttribute("filename_already_used", filename); logger.info("addMemberReviewFile - upload restriction sur '" + filename + "' un fichier de mme nom existe dj pour une candidature de " + postecandidature.getCandidat().getEmailAddress()); } else { if (fileSize != 0) { String contentType = file.getContentType(); // cf https://github.com/EsupPortail/esup-dematec/issues/8 - workaround pour viter mimetype erron comme application/text-plain:formatted contentType = contentType.replaceAll(":.*", ""); InputStream inputStream = file.getInputStream(); //byte[] bytes = IOUtils.toByteArray(inputStream); memberReviewFile.setFilename(filename); memberReviewFile.setFileSize(fileSize); memberReviewFile.setContentType(contentType); logger.info("Upload and set file in DB with filesize = " + fileSize); memberReviewFile.getBigFile().setBinaryFileStream(inputStream, fileSize); memberReviewFile.getBigFile().persist(); Calendar cal = Calendar.getInstance(); Date currentTime = cal.getTime(); memberReviewFile.setSendTime(currentTime); User currentUser = getCurrentUser(); memberReviewFile.setMember(currentUser); postecandidature.getMemberReviewFiles().add(memberReviewFile); //postecandidature.setModification(currentTime); postecandidature.persist(); logService.logActionFile(LogService.UPLOAD_REVIEW_ACTION, postecandidature, memberReviewFile, request, currentTime); } } } else { String userId = SecurityContextHolder.getContext().getAuthentication().getName(); String ip = request.getRemoteAddr(); String userAgent = request.getHeader("User-Agent"); logger.warn(userId + "[" + ip + "] tried to add a 'null file' ... his userAgent is : " + userAgent); } return "redirect:/postecandidatures/" + id.toString(); }
From source file:fr.univrouen.poste.web.candidat.MyPosteCandidatureController.java
@RequestMapping(value = "/{id}/addFile", method = RequestMethod.POST, produces = "text/html") @PreAuthorize("hasPermission(#id, 'manage')") public String addFile(@PathVariable("id") Long id, @Valid PosteCandidatureFile posteCandidatureFile, BindingResult bindingResult, Model uiModel, HttpServletRequest request) throws IOException { if (bindingResult.hasErrors()) { logger.warn(bindingResult.getAllErrors()); return "redirect:/postecandidatures/" + id.toString(); }/*from w ww .ja v a 2 s .c om*/ uiModel.asMap().clear(); // get PosteCandidature from id PosteCandidature posteCandidature = PosteCandidature.findPosteCandidature(id); // upload file MultipartFile file = posteCandidatureFile.getFile(); // sometimes file is null here, but I don't know how to reproduce this issue ... maybe that can occur only with some specifics browsers ? if (file != null) { String filename = file.getOriginalFilename(); boolean filenameAlreadyUsed = false; for (PosteCandidatureFile pcFile : posteCandidature.getCandidatureFiles()) { if (pcFile.getFilename().equals(filename)) { filenameAlreadyUsed = true; break; } } if (filenameAlreadyUsed) { uiModel.addAttribute("filename_already_used", filename); logger.warn("Upload Restriction sur '" + filename + "' un fichier de mme nom existe dj pour une candidature de " + posteCandidature.getCandidat().getEmailAddress()); } else { Long fileSize = file.getSize(); if (fileSize != 0) { String contentType = file.getContentType(); // cf https://github.com/EsupPortail/esup-dematec/issues/8 - workaround pour viter mimetype erron comme application/text-plain:formatted contentType = contentType.replaceAll(":.*", ""); logger.info("Try to upload file '" + filename + "' with size=" + fileSize + " and contentType=" + contentType); Long maxFileMoSize = posteCandidatureFile.getFileType().getCandidatureFileMoSizeMax(); Long maxFileSize = maxFileMoSize * 1024 * 1024; String mimeTypeRegexp = posteCandidatureFile.getFileType() .getCandidatureContentTypeRestrictionRegexp(); String filenameRegexp = posteCandidatureFile.getFileType() .getCandidatureFilenameRestrictionRegexp(); boolean sizeRestriction = maxFileSize > 0 && fileSize > maxFileSize; boolean contentTypeRestriction = !contentType.matches(mimeTypeRegexp); boolean filenameRestriction = !filename.matches(filenameRegexp); if (sizeRestriction || contentTypeRestriction || filenameRestriction) { String restriction = sizeRestriction ? "SizeRestriction" : ""; restriction = contentTypeRestriction || filenameRestriction ? restriction + "ContentTypeRestriction" : restriction; uiModel.addAttribute("upload_restricion_size_contentype", restriction); logger.info("addFile - upload restriction sur " + filename + "' avec taille=" + fileSize + " et contentType=" + contentType + " pour une candidature de " + posteCandidature.getCandidat().getEmailAddress()); } else { InputStream inputStream = file.getInputStream(); //byte[] bytes = IOUtils.toByteArray(inputStream); posteCandidatureFile.setFilename(filename); posteCandidatureFile.setFileSize(fileSize); posteCandidatureFile.setContentType(contentType); logger.info("Upload and set file in DB with filesize = " + fileSize); posteCandidatureFile.getBigFile().setBinaryFileStream(inputStream, fileSize); posteCandidatureFile.getBigFile().persist(); Calendar cal = Calendar.getInstance(); Date currentTime = cal.getTime(); posteCandidatureFile.setSendTime(currentTime); posteCandidature.getCandidatureFiles().add(posteCandidatureFile); posteCandidature.setModification(currentTime); posteCandidature.persist(); logService.logActionFile(LogService.UPLOAD_ACTION, posteCandidature, posteCandidatureFile, request, currentTime); returnReceiptService.logActionFile(LogService.UPLOAD_ACTION, posteCandidature, posteCandidatureFile, request, currentTime); pdfService.updateNbPages(posteCandidatureFile.getId()); } } } } else { String userId = SecurityContextHolder.getContext().getAuthentication().getName(); String ip = request.getRemoteAddr(); String userAgent = request.getHeader("User-Agent"); logger.warn(userId + "[" + ip + "] tried to add a 'null file' ... his userAgent is : " + userAgent); } return "redirect:/postecandidatures/" + id.toString(); }