Example usage for org.springframework.validation BindingResult getAllErrors

List of usage examples for org.springframework.validation BindingResult getAllErrors

Introduction

In this page you can find the example usage for org.springframework.validation BindingResult getAllErrors.

Prototype

List<ObjectError> getAllErrors();

Source Link

Document

Get all errors, both global and field ones.

Usage

From source file:cz.PA165.vozovyPark.controller.DriveController.java

@RequestMapping(value = "/drive/newUserDrive", method = RequestMethod.POST)
public String addNewUserDrive(@Valid @ModelAttribute("drive") DriveDTO drive, BindingResult result,
        ModelMap model, HttpServletRequest req) throws ParseException { // @Valid validates model after binding user input to it
    if (result.hasErrors()) {
        model.put("state", DriveStateEnum.values());
        model.put("user", userService.getByUsername(getLoggedUsername()));
        List<UserDTO> userLoggedInList = userService.getByUsername(getLoggedUsername());
        UserDTO userLoggedIn = userLoggedInList.get(0);
        if (userLoggedIn.getIsAdmin()) {
            model.put("vehicle", vehicleService.findAll());
        } else {//from   w  w w  .  j a v a  2 s.co m
            model.put("vehicle", vehicleService.findByUserClass(userLoggedIn.getUserClass()));
        }
        req.getSession().setAttribute("message", result.getAllErrors().toString());
        return "/drive/driveForm";
    }

    if (!isIntervalFree(drive)) {
        model.put("state", DriveStateEnum.values());
        List<UserDTO> userLoggedInList = userService.getByUsername(getLoggedUsername());
        UserDTO userLoggedIn = userLoggedInList.get(0);
        if (userLoggedIn.getIsAdmin()) {
            model.put("vehicle", vehicleService.findAll());
        } else {
            model.put("vehicle", vehicleService.findByUserClass(userLoggedIn.getUserClass()));
        }
        model.put("user", userService.getByUsername(getLoggedUsername()));
        req.getSession().setAttribute("message",
                "Selected car is not available for this date, please select a vehicle or date.");
        return "/redirect:drive/driveForm";
    }
    driveService.createDrive(drive);
    return "redirect:/drive/usersDrives/";
}

From source file:net.sf.sze.frontend.zeugnis.ZeugnisController.java

/**
 * Speichert die neu angelegte BU und SoL-Bewertung .
 * @param halbjahrId die Id des Schulhalbjahres
 * @param klassenId die Id der Klasse//from   w  w  w. ja  v  a  2s . c om
 * @param schuelerId die Id des Schuelers
 * @param newZeugnis als Container fr die AG-Bewertungen.
 * @param action String der angibt was zu tun ist.
 * @param prevId die Id des vorherigen Schlers
 * @param nextId die Id des nachfolgenden Schlers
 * @param result das Bindingresult.
 * @param model das Model
 * @return die logische View
 */
@RequestMapping(value = URL.ZeugnisPath.ZEUGNIS_EDIT_BU_SOL, method = RequestMethod.POST)
public String updateBuSoL(@PathVariable(URL.Session.P_HALBJAHR_ID) Long halbjahrId,
        @PathVariable(URL.Session.P_KLASSEN_ID) Long klassenId,
        @PathVariable(URL.Session.P_SCHUELER_ID) Long schuelerId, @RequestParam(Common.P_PREV_ID) Long prevId,
        @RequestParam(Common.P_NEXT_ID) Long nextId,
        @RequestParam(value = Common.P_ACTION, required = false) String action,
        @ModelAttribute("zeugnis") Zeugnis newZeugnis, BindingResult result, Model model) {
    final Zeugnis zeugnis = zeugnisErfassungsService.getZeugnis(halbjahrId, schuelerId);
    zeugnis.setBuBewertungsText(newZeugnis.getBuBewertungsText());
    zeugnis.setSoLBewertungsText(newZeugnis.getSoLBewertungsText());

    validator.validate(zeugnis, result);
    if (result.hasErrors()) {
        LOG.info("Fehler:" + result.getAllErrors());
        fillBuSoLModel(model, halbjahrId, klassenId, schuelerId, newZeugnis, prevId, nextId);
        return EDIT_ZEUGNIS_BU_SOL;
    }

    LOG.debug("Update Zeugnis: " + zeugnis);
    zeugnisErfassungsService.save(zeugnis);
    return URL.getPrevNextUrlOrZeugnisUrl(action, URL.ZeugnisPath.ZEUGNIS_EDIT_BU_SOL, halbjahrId, klassenId,
            schuelerId, prevId, nextId);

}

From source file:com.daimler.spm.storefront.controllers.pages.QuoteController.java

@ResponseBody
@RequestMapping(value = "/{quoteCode}/expiration", method = RequestMethod.POST)
@RequireHardLogIn// ww  w.  j  a  va  2 s  .  c  o m
public ResponseEntity<String> setQuoteExpiration(@PathVariable("quoteCode") final String quoteCode,
        final QuoteForm quoteForm, final BindingResult bindingResult) {
    smartValidator.validate(quoteForm, bindingResult, QuoteForm.Seller.class);

    if (bindingResult.hasErrors()) {
        final String errorMessage = getMessageSource().getMessage(bindingResult.getAllErrors().get(0).getCode(),
                null, getI18nService().getCurrentLocale());
        return new ResponseEntity<String>(errorMessage, HttpStatus.BAD_REQUEST);
    }

    try {
        final Optional<Date> expirationTime = Optional
                .ofNullable(getExpirationDateFromString(quoteForm.getExpirationTime()));
        final CommerceCartMetadata cartMetadata = CommerceCartMetadataUtils.metadataBuilder()
                .expirationTime(expirationTime).removeExpirationTime(!expirationTime.isPresent()).build();

        getCartFacade().updateCartMetadata(cartMetadata);
    } catch (final IllegalArgumentException e) {
        LOG.warn(String.format("Invalid expiration time input for quote %s", quoteCode), e);
        return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);
    } catch (final IllegalStateException | IllegalQuoteStateException | UnknownIdentifierException
            | ModelSavingException e) {
        LOG.error(String.format("Failed to update expiration time for quote %s", quoteCode), e);
        return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    return new ResponseEntity<String>(HttpStatus.OK);
}

From source file:com.daimler.spm.storefront.controllers.pages.QuoteController.java

/**
 * Update quote name and description/* ww w . j av  a 2 s.  c  o  m*/
 *
 * @param quoteCode
 * @param quoteForm
 * @param bindingResult
 * @return response entity
 */
@ResponseBody
@RequestMapping(value = "/{quoteCode}/metadata", method = RequestMethod.POST)
@RequireHardLogIn
public ResponseEntity<String> setQuoteMetadata(@PathVariable("quoteCode") final String quoteCode,
        final QuoteForm quoteForm, final BindingResult bindingResult) {
    smartValidator.validate(quoteForm, bindingResult, QuoteForm.Buyer.class);

    if (bindingResult.hasErrors()) {
        final String errorMessage = getMessageSource().getMessage(bindingResult.getAllErrors().get(0).getCode(),
                null, getI18nService().getCurrentLocale());
        return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
    }

    try {
        final Optional<String> quoteName = Optional.ofNullable(quoteForm.getName());
        final Optional<String> quoteDescription = Optional.ofNullable(quoteForm.getDescription());

        final CommerceCartMetadata cartMetadata = CommerceCartMetadataUtils.metadataBuilder().name(quoteName)
                .description(quoteDescription).build();

        getCartFacade().updateCartMetadata(cartMetadata);
    } catch (final IllegalArgumentException e) {
        LOG.warn(String.format("Invalid metadata input for quote %s", quoteCode), e);
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    } catch (final IllegalStateException | UnknownIdentifierException | ModelSavingException e) {
        LOG.error(String.format("Failed to update metadata for quote %s", quoteCode), e);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    return new ResponseEntity<>(HttpStatus.OK);
}

From source file:com.athena.peacock.controller.web.alm.crowd.AlmUserController.java

@RequestMapping(value = "/usermanagement", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody DtoJsonResponse addUser(@Valid @RequestBody AlmUserAddDto userData, BindingResult result) {

    if (result.hasErrors()) {
        DtoJsonResponse response = new DtoJsonResponse();
        response.setSuccess(false);//w w w.  j  ava  2  s.c  o  m

        StringBuilder sb = new StringBuilder();

        Iterator<FieldError> iter = result.getFieldErrors().iterator();
        FieldError error = null;

        while (iter.hasNext()) {
            error = iter.next();
            sb.append(",").append(error.getField());
        }

        if (StringUtils.isEmpty(sb.toString())) {
            response.setMsg(" ? ? ?.");
        } else {
            response.setMsg(sb.toString().substring(1)
                    + "?  ? ? ?.");
        }

        response.setData(result.getAllErrors());
        return response;
    }

    return service.addUser(userData);
}

From source file:com.athena.peacock.controller.web.alm.crowd.AlmUserController.java

@RequestMapping(value = "/usermanagement", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody DtoJsonResponse modifyUser(@RequestBody AlmUserAddDto userData, BindingResult result) {

    if (result.hasErrors()) {
        DtoJsonResponse response = new DtoJsonResponse();
        response.setSuccess(false);/*from  ww  w  . j  a v a2  s. c o m*/

        StringBuilder sb = new StringBuilder();

        Iterator<FieldError> iter = result.getFieldErrors().iterator();
        FieldError error = null;

        while (iter.hasNext()) {
            error = iter.next();
            sb.append(",").append(error.getField());
        }

        if (StringUtils.isEmpty(sb.toString())) {
            response.setMsg(" ? ? ?.");
        } else {
            response.setMsg(sb.toString().substring(1)
                    + "?  ? ? ?.");
        }

        response.setData(result.getAllErrors());
        return response;
    }

    return service.modifyUser(userData);
}

From source file:org.wallride.web.controller.admin.user.UserBulkDeleteController.java

@RequestMapping
public String delete(@Valid @ModelAttribute("form") UserBulkDeleteForm form, BindingResult errors, String query,
        AuthorizedUser authorizedUser, RedirectAttributes redirectAttributes) {
    redirectAttributes.addAttribute("query", query);

    if (!form.isConfirmed()) {
        errors.rejectValue("confirmed", "Confirmed");
    }/* w ww  . j  av  a2 s  .c o m*/
    if (errors.hasErrors()) {
        logger.debug("Errors: {}", errors);
        return "redirect:/_admin/user/";
    }

    Collection<User> users = null;
    try {
        users = userService.bulkDeleteUser(form.buildUserBulkDeleteRequest(), errors);
    } catch (ValidationException e) {
        if (errors.hasErrors()) {
            logger.debug("Errors: {}", errors);
            return "redirect:/_admin/user/";
        }
        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", users);
    redirectAttributes.addFlashAttribute("errorMessages", errorMessages);
    return "redirect:/_admin/{language}/users/index";
}

From source file:org.wallride.web.controller.admin.page.PageBulkDeleteController.java

@RequestMapping
public String delete(@Valid @ModelAttribute("form") PageBulkDeleteForm form, BindingResult errors, String query,
        RedirectAttributes redirectAttributes) {
    redirectAttributes.addAttribute("query", query);

    if (!form.isConfirmed()) {
        errors.rejectValue("confirmed", "Confirmed");
    }//from  w  ww.  ja v a  2  s  .  co  m
    if (errors.hasErrors()) {
        logger.debug("Errors: {}", errors);
        return "redirect:/_admin/{language}/pages/index";
    }

    Collection<Page> pages = null;
    try {
        pages = pageService.bulkDeletePage(form.buildPageBulkDeleteRequest(), errors);
    } catch (ValidationException e) {
        if (errors.hasErrors()) {
            logger.debug("Errors: {}", errors);
            return "redirect:/_admin/{language}/pages/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("deletedPages", pages);
    redirectAttributes.addFlashAttribute("errorMessages", errorMessages);
    return "redirect:/_admin/{language}/pages/index";
}

From source file:org.wallride.web.controller.admin.tag.TagBulkDeleteController.java

@RequestMapping
public String delete(@Valid @ModelAttribute("form") TagBulkDeleteForm form, BindingResult errors, String query,
        AuthorizedUser authorizedUser, RedirectAttributes redirectAttributes) {
    redirectAttributes.addAttribute("query", query);

    if (!form.isConfirmed()) {
        errors.rejectValue("confirmed", "Confirmed");
    }/*  w  ww. jav a2  s .c om*/
    if (errors.hasErrors()) {
        logger.debug("Errors: {}", errors);
        return "redirect:/_admin/{language}/tags/index";
    }

    Collection<Tag> tags = null;
    try {
        tags = tagService.bulkDeleteTag(form.buildTagBulkDeleteRequest(), errors);
    } catch (ValidationException e) {
        if (errors.hasErrors()) {
            logger.debug("Errors: {}", errors);
            return "redirect:/_admin/{language}/tags/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("deletedTags", tags);
    redirectAttributes.addFlashAttribute("errorMessages", errorMessages);
    return "redirect:/_admin/{language}/tags/index";
}

From source file:com.rr.generic.ui.importexport.importExportController.java

/**
 * /*www . j  av a 2s . 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);

        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("participantExport").append(dateFormat.format(date))
                    .append(".csv").toString();
            delimiter = ",";
        } else if (exportDetails.getExportType() == 2) {
            fileName = new StringBuilder().append("participantExport").append(dateFormat.format(date))
                    .append(".txt").toString();
            delimiter = ",";
        } else if (exportDetails.getExportType() == 3) {
            fileName = new StringBuilder().append("participantExport").append(dateFormat.format(date))
                    .append(".txt").toString();
            delimiter = "|";
        } else if (exportDetails.getExportType() == 4) {
            fileName = new StringBuilder().append("participantExport").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("ORGCODE").append(delimiter);
        exportRow.append("PARTICIP").append(delimiter);
        exportRow.append("STATE").append(delimiter);
        exportRow.append("GLUCTEST").append(delimiter);
        exportRow.append("GDM").append(delimiter); /* P */
        exportRow.append("RISKTEST").append(delimiter); /* P */
        exportRow.append("AGE").append(delimiter); /* P */
        exportRow.append("ETHNIC").append(delimiter); /* P */
        exportRow.append("AIAN").append(delimiter); /* P */
        exportRow.append("ASIAN").append(delimiter); /* P */
        exportRow.append("BLACK").append(delimiter); /* P */
        exportRow.append("NHOPI").append(delimiter); /* P */
        exportRow.append("WHITE").append(delimiter); /* P */
        exportRow.append("SEX").append(delimiter); /* P */
        exportRow.append("HEIGHT").append(delimiter);
        exportRow.append("DATE").append(delimiter);
        exportRow.append("WEIGHT").append(delimiter);
        exportRow.append("PA").append(delimiter);

        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);

        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 (exportDetails.getUniqueId() > 0) {
            /* Delete progress bar entry */
            exportManager.deleteProgressBar(exportDetails.getUniqueId());
        }

        mav.setViewName("/importExport/exportDownloadModal");
        mav.addObject("exportFileName", exportFileName);
    }

    return mav;
}