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:com.att.pirates.controller.ProjectController.java

@RequestMapping(value = "/addProjectStatus/{prismId}/{applicationId}", method = RequestMethod.POST)
public String addProjectStatus(@PathVariable("prismId") String prismId,
        @PathVariable("applicationId") String applicationId,
        @Valid @ModelAttribute("projectStatusViewModel") ProjectStatusViewModel projectStatusViewModel,
        HttpServletRequest request, BindingResult result) {
    String sessionUser = (String) request.getSession().getAttribute("loginUser");
    if (sessionUser == null || sessionUser.isEmpty() || "Not Logged In".equalsIgnoreCase(sessionUser)) {
        request.getSession().setAttribute("loginUser", "Not Logged In");
        logger.error("[Merce]: user not logged in.. redirecting to logout page");
        return "redirect:/logout";
    }/*w  w w  .  ja  va 2 s.  c o  m*/

    NumberFormat defaultFormat = NumberFormat.getPercentInstance();
    defaultFormat.setMinimumFractionDigits(0);
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    int appId = Integer.parseInt(applicationId);
    String appName = DataService.getApplicationNameByPrismIdApplicationId(appId, prismId);
    int impactTypeId = DataService.getImpactTypeIdByPrismIdAndApplicationName(prismId, appName);

    if (result.hasErrors()) {
        StringBuilder sb = new StringBuilder();
        for (ObjectError r : result.getAllErrors()) {
            sb.append(r.getDefaultMessage());
        }
        logger.error(msgHeader + " addProjectStatus errors: " + sb.toString());
    }

    // refresh cahce?
    if (artifactHistory != null) {
        artifactHistory = null;
    }
    DataService.initializeProjectAppOwnerByPrismId(prismId);

    // TO
    if (impactTypeId != 3 && impactTypeId != 4) {
        // prefix. Agile
        if (projectStatusViewModel.getAgilePercentageComplete() == null
                || projectStatusViewModel.getAgilePercentageComplete().isEmpty()) {
            logger.error(msgHeader + " addProjectStatus Agile is not set, so keep record in database as is.");
        } else {
            logger.error(msgHeader + " addProjectStatus Agile is set, updateing ..");

            ProjectAppOwnerModel mod = DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner(
                    prismId, Integer.valueOf(applicationId), PiratesConstants.AGILE);
            if (mod != null && !mod.getPercentageComplete()
                    .equalsIgnoreCase(defaultFormat.format(
                            Double.parseDouble(projectStatusViewModel.getAgilePercentageComplete() == null ? "0"
                                    : projectStatusViewModel.getAgilePercentageComplete())))) {
                ProjectAppOwnerModel p = cloneProjectAppOwnerModel(mod);
                // now change the percentage completed to user input value
                mod.setPercentageComplete(projectStatusViewModel.getAgilePercentageComplete());

                // check if percentcomplete user entered is 100%, if so, check if the datecreated has been changed to an earlier date
                try {
                    if (projectStatusViewModel.getAgilePercentageComplete().equalsIgnoreCase("1.00")
                            && !sdf.format(sdf.parse(projectStatusViewModel.getAgileDateCreatedT()))
                                    .equals(sdf.format(new Date()))) {
                        logger.error(
                                "100% complete and user changed datecreated to a date that's other than today, using this date instead of today.. "
                                        + projectStatusViewModel.getAgileDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getAgileDateCreatedT());
                    } else {
                        logger.error("User chooses to use today as datecreated, using it .. "
                                + projectStatusViewModel.getAgileDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getAgileDateCreatedT());
                    }
                } catch (ParseException ex) {
                    logger.error(msgHeader + ex.getMessage());
                }

                DataService.processProjectStatusForArtifact(mod, PiratesConstants.AGILE, sessionUser, p);
            } else {
                if (mod != null && mod.getPercentageComplete()
                        .equalsIgnoreCase(defaultFormat.format(Double
                                .parseDouble(projectStatusViewModel.getAgilePercentageComplete() == null ? "0"
                                        : projectStatusViewModel.getAgilePercentageComplete())))) {
                    logger.error("Agile has same value as in the DB, ignoring..");
                } else {
                    logger.error(
                            "addProjectStatus error DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner returned null");
                }
            }
        }

        // 1. BR
        if (projectStatusViewModel.getBRPercentageComplete() == null
                || projectStatusViewModel.getBRPercentageComplete().isEmpty()) {
            logger.error(msgHeader + " addProjectStatus BR is not set, so keep record in database as is.");
        } else {
            logger.error(msgHeader + " addProjectStatus BR is set, updateing ..");

            ProjectAppOwnerModel mod = DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner(
                    prismId, Integer.valueOf(applicationId), PiratesConstants.BR);
            if (mod != null && !mod.getPercentageComplete()
                    .equalsIgnoreCase(defaultFormat.format(
                            Double.parseDouble(projectStatusViewModel.getBRPercentageComplete() == null ? "0"
                                    : projectStatusViewModel.getBRPercentageComplete())))) {
                ProjectAppOwnerModel p = cloneProjectAppOwnerModel(mod);
                // now change the percentage completed to user input value
                mod.setPercentageComplete(projectStatusViewModel.getBRPercentageComplete());

                // check if percentcomplete user entered is 100%, if so, check if the datecreated has been changed to an earlier date
                try {
                    if (projectStatusViewModel.getBRPercentageComplete().equalsIgnoreCase("1.00")
                            && !sdf.format(sdf.parse(projectStatusViewModel.getBRDateCreatedT()))
                                    .equals(sdf.format(new Date()))) {
                        logger.error(
                                "100% complete and user changed datecreated to a date that's other than today, using this date instead of today.. "
                                        + projectStatusViewModel.getBRDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getBRDateCreatedT());

                    } else {
                        logger.error("User chooses to use today as datecreated, using it .. "
                                + projectStatusViewModel.getBRDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getBRDateCreatedT());
                    }
                } catch (ParseException ex) {
                    logger.error(msgHeader + ex.getMessage());
                }

                DataService.processProjectStatusForArtifact(mod, PiratesConstants.BR, sessionUser, p);
            } else {
                if (mod != null && mod.getPercentageComplete()
                        .equalsIgnoreCase(defaultFormat.format(Double
                                .parseDouble(projectStatusViewModel.getBRPercentageComplete() == null ? "0"
                                        : projectStatusViewModel.getBRPercentageComplete())))) {
                    logger.error("BR has same value as in the DB, ignoring..");
                } else {
                    logger.error(
                            "addProjectStatus error DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner returned null");
                }
            }
        }

        // 2. SR
        if (projectStatusViewModel.getSRPercentageComplete() == null
                || projectStatusViewModel.getSRPercentageComplete().isEmpty()) {
            logger.error(msgHeader + " addProjectStatus SR is not set, so keep record in database as is.");
        } else {
            logger.error(msgHeader + " addProjectStatus SR is set, updateing ..");
            ProjectAppOwnerModel mod = DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner(
                    prismId, Integer.valueOf(applicationId), PiratesConstants.SR);
            if (mod != null && !mod.getPercentageComplete()
                    .equalsIgnoreCase(defaultFormat.format(
                            Double.parseDouble(projectStatusViewModel.getSRPercentageComplete() == null ? "0"
                                    : projectStatusViewModel.getSRPercentageComplete())))) {
                ProjectAppOwnerModel p = cloneProjectAppOwnerModel(mod);
                // now change the percentage completed to user input value
                mod.setPercentageComplete(projectStatusViewModel.getSRPercentageComplete());

                // check if percentcomplete user entered is 100%, if so, check if the datecreated has been changed to an earlier date
                try {
                    if (projectStatusViewModel.getSRPercentageComplete().equalsIgnoreCase("1.00")
                            && !sdf.format(sdf.parse(projectStatusViewModel.getSRDateCreatedT()))
                                    .equals(sdf.format(new Date()))) {
                        logger.error(
                                "100% complete and user changed datecreated to a date that's other than today, using this date instead of today.. "
                                        + projectStatusViewModel.getSRDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getSRDateCreatedT());

                    } else {
                        logger.error("User chooses to use today as datecreated, using it .. "
                                + projectStatusViewModel.getSRDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getSRDateCreatedT());
                    }
                } catch (ParseException ex) {
                    logger.error(msgHeader + ex.getMessage());
                }

                DataService.processProjectStatusForArtifact(mod, PiratesConstants.SR, sessionUser, p);
            } else {
                if (mod != null && mod.getPercentageComplete()
                        .equalsIgnoreCase(defaultFormat.format(Double
                                .parseDouble(projectStatusViewModel.getSRPercentageComplete() == null ? "0"
                                        : projectStatusViewModel.getSRPercentageComplete())))) {
                    logger.error("SR has same value as in the DB, ignoring..");
                } else {
                    logger.error(
                            "addProjectStatus error DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner returned null");
                }

            }
        }

        // 3. HLD
        if (projectStatusViewModel.getHLDPercentageComplete() == null
                || projectStatusViewModel.getHLDPercentageComplete().isEmpty()) {
            logger.error(msgHeader + " addProjectStatus HLD is not set, so keep record in database as is.");
        } else {
            logger.error(
                    msgHeader + " addProjectStatus HLD is set, updateing .. " + prismId + ", " + applicationId);
            ProjectAppOwnerModel mod = DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner(
                    prismId, Integer.valueOf(applicationId), PiratesConstants.HLD);
            if (mod != null && !mod.getPercentageComplete()
                    .equalsIgnoreCase(defaultFormat.format(
                            Double.parseDouble(projectStatusViewModel.getHLDPercentageComplete() == null ? "0"
                                    : projectStatusViewModel.getHLDPercentageComplete())))) {
                ProjectAppOwnerModel p = cloneProjectAppOwnerModel(mod);
                // now change the percentage completed to user input value
                mod.setPercentageComplete(projectStatusViewModel.getHLDPercentageComplete());

                // check if percentcomplete user entered is 100%, if so, check if the datecreated has been changed to an earlier date
                try {
                    if (projectStatusViewModel.getHLDPercentageComplete().equalsIgnoreCase("1.00")
                            && !sdf.format(sdf.parse(projectStatusViewModel.getHLDDateCreatedT()))
                                    .equals(sdf.format(new Date()))) {
                        logger.error(
                                "100% complete and user changed datecreated to a date that's other than today, using this date instead of today.. "
                                        + projectStatusViewModel.getHLDDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getHLDDateCreatedT());

                    } else {
                        logger.error("User chooses to use today as datecreated, using it .. "
                                + projectStatusViewModel.getHLDDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getHLDDateCreatedT());
                    }
                } catch (ParseException ex) {
                    logger.error(msgHeader + ex.getMessage());
                }

                DataService.processProjectStatusForArtifact(mod, PiratesConstants.HLD, sessionUser, p);
            } else {
                if (mod != null && mod.getPercentageComplete()
                        .equalsIgnoreCase(defaultFormat.format(Double
                                .parseDouble(projectStatusViewModel.getHLDPercentageComplete() == null ? "0"
                                        : projectStatusViewModel.getHLDPercentageComplete())))) {
                    logger.error("HLD has same value as in the DB, ignoring..");
                } else {
                    logger.error(
                            "addProjectStatus error DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner returned null");
                }
            }
        }

        // 4. AID
        if (projectStatusViewModel.getAIDPercentageComplete() == null
                || projectStatusViewModel.getAIDPercentageComplete().isEmpty()) {
            logger.error(msgHeader + " addProjectStatus AID is not set, so keep record in database as is.");
        } else {
            logger.error(msgHeader + " addProjectStatus AID is set, updateing ..");
            ProjectAppOwnerModel mod = DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner(
                    prismId, Integer.valueOf(applicationId), PiratesConstants.AID);
            if (mod != null && !mod.getPercentageComplete()
                    .equalsIgnoreCase(defaultFormat.format(
                            Double.parseDouble(projectStatusViewModel.getAIDPercentageComplete() == null ? "0"
                                    : projectStatusViewModel.getAIDPercentageComplete())))) {
                ProjectAppOwnerModel p = cloneProjectAppOwnerModel(mod);
                // now change the percentage completed to user input value
                mod.setPercentageComplete(projectStatusViewModel.getAIDPercentageComplete());

                // check if percentcomplete user entered is 100%, if so, check if the datecreated has been changed to an earlier date
                try {
                    if (projectStatusViewModel.getAIDPercentageComplete().equalsIgnoreCase("1.00")
                            && !sdf.format(sdf.parse(projectStatusViewModel.getAIDDateCreatedT()))
                                    .equals(sdf.format(new Date()))) {
                        logger.error(
                                "100% complete and user changed datecreated to a date that's other than today, using this date instead of today.. "
                                        + projectStatusViewModel.getAIDDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getAIDDateCreatedT());

                    } else {
                        logger.error("User chooses to use today as datecreated, using it .. "
                                + projectStatusViewModel.getAIDDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getAIDDateCreatedT());
                    }
                } catch (ParseException ex) {
                    logger.error(msgHeader + ex.getMessage());
                }

                DataService.processProjectStatusForArtifact(mod, PiratesConstants.AID, sessionUser, p);
            } else {
                if (mod != null && mod.getPercentageComplete()
                        .equalsIgnoreCase(defaultFormat.format(Double
                                .parseDouble(projectStatusViewModel.getAIDPercentageComplete() == null ? "0"
                                        : projectStatusViewModel.getAIDPercentageComplete())))) {
                    logger.error("AID has same value as in the DB, ignoring..");
                } else {
                    logger.error(
                            "addProjectStatus error DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner returned null");
                }
            }
        }

        // 5. DES
        if (projectStatusViewModel.getDESPercentageComplete() == null
                || projectStatusViewModel.getDESPercentageComplete().isEmpty()) {
            logger.error(msgHeader + " addProjectStatus DES is not set, so keep record in database as is.");
        } else {
            logger.error(msgHeader + " addProjectStatus DES is set, updateing ..");
            ProjectAppOwnerModel mod = DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner(
                    prismId, Integer.valueOf(applicationId), PiratesConstants.DES);
            if (mod != null && !mod.getPercentageComplete()
                    .equalsIgnoreCase(defaultFormat.format(
                            Double.parseDouble(projectStatusViewModel.getDESPercentageComplete() == null ? "0"
                                    : projectStatusViewModel.getDESPercentageComplete())))) {
                ProjectAppOwnerModel p = cloneProjectAppOwnerModel(mod);
                // now change the percentage completed to user input value
                mod.setPercentageComplete(projectStatusViewModel.getDESPercentageComplete());

                // check if percentcomplete user entered is 100%, if so, check if the datecreated has been changed to an earlier date
                try {
                    if (projectStatusViewModel.getDESPercentageComplete().equalsIgnoreCase("1.00")
                            && !sdf.format(sdf.parse(projectStatusViewModel.getDESDateCreatedT()))
                                    .equals(sdf.format(new Date()))) {
                        logger.error(
                                "100% complete and user changed datecreated to a date that's other than today, using this date instead of today.. "
                                        + projectStatusViewModel.getDESDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getDESDateCreatedT());

                    } else {
                        logger.error("User chooses to use today as datecreated, using it .. "
                                + projectStatusViewModel.getDESDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getDESDateCreatedT());
                    }
                } catch (ParseException ex) {
                    logger.error(msgHeader + ex.getMessage());
                }

                DataService.processProjectStatusForArtifact(mod, PiratesConstants.DES, sessionUser, p);
            } else {
                if (mod != null && mod.getPercentageComplete()
                        .equalsIgnoreCase(defaultFormat.format(Double
                                .parseDouble(projectStatusViewModel.getDESPercentageComplete() == null ? "0"
                                        : projectStatusViewModel.getDESPercentageComplete())))) {
                    logger.error("DES has same value as in the DB, ignoring..");
                } else {
                    logger.error(
                            "addProjectStatus error DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner returned null");
                }
            }
        }

        // 6. DEV
        if (projectStatusViewModel.getDEVPercentageComplete() == null
                || projectStatusViewModel.getDEVPercentageComplete().isEmpty()) {
            logger.error(msgHeader + " addProjectStatus DEV is not set, so keep record in database as is.");
        } else {
            logger.error(msgHeader + " addProjectStatus DEV is set, updateing ..");
            ProjectAppOwnerModel mod = DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner(
                    prismId, Integer.valueOf(applicationId), PiratesConstants.DEV);
            if (mod != null && !mod.getPercentageComplete()
                    .equalsIgnoreCase(defaultFormat.format(
                            Double.parseDouble(projectStatusViewModel.getDEVPercentageComplete() == null ? "0"
                                    : projectStatusViewModel.getDEVPercentageComplete())))) {
                ProjectAppOwnerModel p = cloneProjectAppOwnerModel(mod);
                // now change the percentage completed to user input value
                mod.setPercentageComplete(projectStatusViewModel.getDEVPercentageComplete());

                // check if percentcomplete user entered is 100%, if so, check if the datecreated has been changed to an earlier date
                try {
                    if (projectStatusViewModel.getDEVPercentageComplete().equalsIgnoreCase("1.00")
                            && !sdf.format(sdf.parse(projectStatusViewModel.getDEVDateCreatedT()))
                                    .equals(sdf.format(new Date()))) {
                        logger.error(
                                "100% complete and user changed datecreated to a date that's other than today, using this date instead of today.. "
                                        + projectStatusViewModel.getDEVDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getDEVDateCreatedT());

                    } else {
                        logger.error("User chooses to use today as datecreated, using it .. "
                                + projectStatusViewModel.getDEVDateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getDEVDateCreatedT());
                    }
                } catch (ParseException ex) {
                    logger.error(msgHeader + ex.getMessage());
                }

                DataService.processProjectStatusForArtifact(mod, PiratesConstants.DEV, sessionUser, p);
            } else {
                if (mod != null && mod.getPercentageComplete()
                        .equalsIgnoreCase(defaultFormat.format(Double
                                .parseDouble(projectStatusViewModel.getDEVPercentageComplete() == null ? "0"
                                        : projectStatusViewModel.getDEVPercentageComplete())))) {
                    logger.error("DEV has same value as in the DB, ignoring..");
                } else {
                    logger.error(
                            "addProjectStatus error DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner returned null");
                }
            }
        }

    } // end not impacttypeid = 3, to and tso 4

    // 7. IST
    if (projectStatusViewModel.getISTPercentageComplete() == null
            || projectStatusViewModel.getISTPercentageComplete().isEmpty()) {
        logger.error(msgHeader + " addProjectStatus IST is not set, so keep record in database as is.");
    } else {
        logger.error(msgHeader + " addProjectStatus IST is set, updateing ..");
        ProjectAppOwnerModel mod = DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner(
                prismId, Integer.valueOf(applicationId), PiratesConstants.IST);
        if (mod != null && !mod.getPercentageComplete()
                .equalsIgnoreCase(defaultFormat.format(
                        Double.parseDouble(projectStatusViewModel.getISTPercentageComplete() == null ? "0"
                                : projectStatusViewModel.getISTPercentageComplete())))) {
            ProjectAppOwnerModel p = cloneProjectAppOwnerModel(mod);
            // now change the percentage completed to user input value
            mod.setPercentageComplete(projectStatusViewModel.getISTPercentageComplete());

            // check if percentcomplete user entered is 100%, if so, check if the datecreated has been changed to an earlier date
            try {
                if (projectStatusViewModel.getISTPercentageComplete().equalsIgnoreCase("1.00")
                        && !sdf.format(sdf.parse(projectStatusViewModel.getISTDateCreatedT()))
                                .equals(sdf.format(new Date()))) {
                    logger.error(
                            "100% complete and user changed datecreated to a date that's other than today, using this date instead of today.. "
                                    + projectStatusViewModel.getISTDateCreatedT());
                    mod.setDateCreated(projectStatusViewModel.getISTDateCreatedT());

                } else {
                    logger.error("User chooses to use today as datecreated, using it .. "
                            + projectStatusViewModel.getISTDateCreatedT());
                    mod.setDateCreated(projectStatusViewModel.getISTDateCreatedT());
                }
            } catch (ParseException ex) {
                logger.error(msgHeader + ex.getMessage());
            }

            DataService.processProjectStatusForArtifact(mod, PiratesConstants.IST, sessionUser, p);
        } else {
            if (mod != null && mod.getPercentageComplete()
                    .equalsIgnoreCase(defaultFormat.format(
                            Double.parseDouble(projectStatusViewModel.getISTPercentageComplete() == null ? "0"
                                    : projectStatusViewModel.getISTPercentageComplete())))) {
                logger.error("IST has same value as in the DB, ignoring..");
            } else {
                logger.error(
                        "addProjectStatus error DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner returned null");
            }
        }
    }

    // 8. ISTExec
    if (projectStatusViewModel.getISTExecPercentageComplete() == null
            || projectStatusViewModel.getISTExecPercentageComplete().isEmpty()) {
        logger.error(msgHeader + " addProjectStatus ISTExec is not set, so keep record in database as is.");
    } else {
        logger.error(msgHeader + " addProjectStatus ISTExec is set, updateing ..");
        ProjectAppOwnerModel mod = DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner(
                prismId, Integer.valueOf(applicationId), PiratesConstants.ISTExec);
        if (mod != null && !mod.getPercentageComplete()
                .equalsIgnoreCase(defaultFormat.format(
                        Double.parseDouble(projectStatusViewModel.getISTExecPercentageComplete() == null ? "0"
                                : projectStatusViewModel.getISTExecPercentageComplete())))) {
            ProjectAppOwnerModel p = cloneProjectAppOwnerModel(mod);
            // now change the percentage completed to user input value
            mod.setPercentageComplete(projectStatusViewModel.getISTExecPercentageComplete());

            // check if percentcomplete user entered is 100%, if so, check if the datecreated has been changed to an earlier date
            try {
                if (projectStatusViewModel.getISTExecPercentageComplete().equalsIgnoreCase("1.00")
                        && !sdf.format(sdf.parse(projectStatusViewModel.getISTExecDateCreatedT()))
                                .equals(sdf.format(new Date()))) {
                    logger.error(
                            "100% complete and user changed datecreated to a date that's other than today, using this date instead of today.. "
                                    + projectStatusViewModel.getISTExecDateCreatedT());
                    mod.setDateCreated(projectStatusViewModel.getISTExecDateCreatedT());

                } else {
                    logger.error("User chooses to use today as datecreated, using it .. "
                            + projectStatusViewModel.getISTExecDateCreatedT());
                    mod.setDateCreated(projectStatusViewModel.getISTExecDateCreatedT());
                }
            } catch (ParseException ex) {
                logger.error(msgHeader + ex.getMessage());
            }

            DataService.processProjectStatusForArtifact(mod, PiratesConstants.ISTExec, sessionUser, p);
        } else {
            if (mod != null && mod.getPercentageComplete()
                    .equalsIgnoreCase(defaultFormat.format(Double
                            .parseDouble(projectStatusViewModel.getISTExecPercentageComplete() == null ? "0"
                                    : projectStatusViewModel.getISTExecPercentageComplete())))) {
                logger.error("ISTExec has same value as in the DB, ignoring..");
            } else {
                logger.error(
                        "addProjectStatus error DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner returned null");
            }
        }
    }

    if (impactTypeId != 3 && impactTypeId != 4) {
        // 8. CloseOut
        if (projectStatusViewModel.getCloseOutPercentageComplete() == null
                || projectStatusViewModel.getCloseOutPercentageComplete().isEmpty()) {
            logger.error(
                    msgHeader + " addProjectStatus Closeout is not set, so keep record in database as is.");
        } else {
            logger.error(msgHeader + " addProjectStatus Closeout is set, updateing ..");
            ProjectAppOwnerModel mod = DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner(
                    prismId, Integer.valueOf(applicationId), PiratesConstants.CLOSEOUT);
            if (mod != null && !mod.getPercentageComplete()
                    .equalsIgnoreCase(defaultFormat.format(Double
                            .parseDouble(projectStatusViewModel.getCloseOutPercentageComplete() == null ? "0"
                                    : projectStatusViewModel.getCloseOutPercentageComplete())))) {
                ProjectAppOwnerModel p = cloneProjectAppOwnerModel(mod);
                // now change the percentage completed to user input value
                mod.setPercentageComplete(projectStatusViewModel.getCloseOutPercentageComplete());

                // check if percentcomplete user entered is 100%, if so, check if the datecreated has been changed to an earlier date
                try {
                    if (projectStatusViewModel.getCloseOutPercentageComplete().equalsIgnoreCase("1.00")
                            && !sdf.format(sdf.parse(projectStatusViewModel.getCODateCreatedT()))
                                    .equals(sdf.format(new Date()))) {
                        logger.error(
                                "100% complete and user changed datecreated to a date that's other than today, using this date instead of today.. "
                                        + projectStatusViewModel.getCODateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getCODateCreatedT());

                    } else {
                        logger.error("User chooses to use today as datecreated, using it .. "
                                + projectStatusViewModel.getCODateCreatedT());
                        mod.setDateCreated(projectStatusViewModel.getCODateCreatedT());
                    }
                } catch (ParseException ex) {
                    logger.error(msgHeader + ex.getMessage());
                }

                DataService.processProjectStatusForArtifact(mod, PiratesConstants.CLOSEOUT, sessionUser, p);
            } else {
                if (mod != null && mod.getPercentageComplete()
                        .equalsIgnoreCase(defaultFormat.format(Double.parseDouble(
                                projectStatusViewModel.getCloseOutPercentageComplete() == null ? "0"
                                        : projectStatusViewModel.getCloseOutPercentageComplete())))) {
                    logger.error("CloseOut has same value as in the DB, ignoring..");
                } else {
                    logger.error(
                            "addProjectStatus error DataService.getProjectAppOwnerByPrismIdAppNameArtifactNamePrimaryOwner returned null");
                }
            }
        }
    } // end  && impactTypeId != 4 (TSO) &&  && impactTypeId != 3 (TO)

    // prismId will be considered while expanding the placeholders
    // return "redirect:/impact_pirates/projects/index/{prismId}";
    if (artifactHistory != null) {
        artifactHistory = null;
    }
    DataService.initializeProjectAppOwnerByPrismId(prismId);
    return "redirect:/projects/index/{prismId}";
}

From source file:com.pedra.storefront.controllers.pages.PickupInStoreController.java

private String getViewWithBindingErrorMessages(final Model model, final BindingResult bindingErrors) {
    for (final ObjectError error : bindingErrors.getAllErrors()) {
        if (isTypeMismatchError(error)) {
            model.addAttribute(ERROR_MSG_TYPE, QUANTITY_INVALID_BINDING_MESSAGE_KEY);
        } else {/*from w ww . java  2  s.c o m*/
            model.addAttribute(ERROR_MSG_TYPE, error.getDefaultMessage());
        }
    }
    return ControllerConstants.Views.Fragments.Cart.AddToCartPopup;
}

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

/**
 * /*from   w w  w  .  ja va  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");

    /** Log Here **/
    userActivityLog ual = new userActivityLog();
    ual.setSystemUserId(userDetails.getId());
    ual.setMapping("/saveParticipantExport.do");
    ual.setRequestMethod("POST");
    ual.setMethodAccessed("saveExport");
    ual.setModuleId(moduleId);
    ual.setProgramId(programId);

    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("CLIENT IDENTIFIER").append(delimiter);
        exportRow.append("DOB").append(delimiter);
        exportRow.append("SEX").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);
        ual.setMiscNotes("mav view:" + mav.getViewName() + "^^^^^" + "No Results.");

    } else {
        if (exportDetails.getUniqueId() > 0) {
            /* Delete progress bar entry */
            exportManager.deleteProgressBar(exportDetails.getUniqueId());
        }

        mav.setViewName("/importExport/exportDownloadModal");
        mav.addObject("exportFileName", exportFileName);
        ual.setMiscNotes("mav view:" + mav.getViewName() + "^^^^^exportFileName:" + exportFileName
                + "^^^^^exportDetails:" + exportDetails.getId());

    }

    usermanager.saveUserActivityLog(ual);

    return mav;
}

From source file:com.sap.sapbasket.storefront.controllers.pages.CartPageController.java

@RequestMapping(value = "/update", method = RequestMethod.POST)
public String updateCartQuantities(@RequestParam("entryNumber") final long entryNumber, final Model model,
        @Valid final UpdateQuantityForm form, final BindingResult bindingResult,
        final HttpServletRequest request, final RedirectAttributes redirectModel)
        throws CMSItemNotFoundException {
    if (bindingResult.hasErrors()) {
        for (final ObjectError error : bindingResult.getAllErrors()) {
            if ("typeMismatch".equals(error.getCode())) {
                GlobalMessages.addErrorMessage(model, "basket.error.quantity.invalid");
            } else {
                GlobalMessages.addErrorMessage(model, error.getDefaultMessage());
            }/*from w w  w . ja v  a 2 s  . c  o m*/
        }
    } else if (getCartFacade().hasEntries()) {
        try {
            final CartModificationData cartModification = getCartFacade().updateCartEntry(entryNumber,
                    form.getQuantity().longValue());
            addFlashMessage(form, request, redirectModel, cartModification);

            // Redirect to the cart page on update success so that the browser doesn't re-post again
            return REDIRECT_CART_URL;
        } catch (final CommerceCartModificationException ex) {
            LOG.warn("Couldn't update product with the entry number: " + entryNumber + ".", ex);
        }
    }

    prepareDataForPage(model);

    return ControllerConstants.Views.Pages.Cart.CartPage;
}

From source file:de.dominikschadow.duke.encounters.controller.EncounterController.java

@PostMapping("/encounter/create")
@PreAuthorize("hasAnyRole('USER','ADMIN')")
public String saveEncounter(@Valid final Encounter encounter, final Model model, final BindingResult result) {
    if (result.hasErrors()) {
        model.addAttribute("formErrors", result.getAllErrors());
        return "user/createEncounter";
    }/*  ww w .ja v a 2  s .  c om*/

    encounterService.createEncounter(encounter);
    model.addAttribute("confirmable", true);

    return "redirect:/encounters";
}

From source file:de.hybris.platform.acceleratorservices.web.payment.controllers.SilentOrderPostMockController.java

@RequestMapping(value = "/process", method = RequestMethod.POST)
public String doValidateAndPost(@Valid final SopPaymentDetailsForm form, final BindingResult bindingResult,
        final HttpServletRequest request, final Model model) {
    final Map<String, String> params = cloneRequestParameters(request);

    // Remove values that we must not post back to the caller
    params.remove("card_cvNumber");

    getSopPaymentDetailsValidator().validate(form, bindingResult);

    if (bindingResult.hasErrors()) {
        // Validation errors
        params.put("decision", "REJECT");
        params.put("reasonCode", "102");
        params.put("decision_publicSignature", getMockedPublicDigest("REJECT" + "102"));

        // Remove card number on validation error
        params.remove("card_accountNumber");

        final List<String> missingFields = new ArrayList<String>();
        final List<String> invalidFields = new ArrayList<String>();

        for (final ObjectError objectError : bindingResult.getAllErrors()) {
            if (objectError instanceof FieldError) {
                final FieldError fieldError = (FieldError) objectError;

                if (fieldError.getRejectedValue() == null || "".equals(fieldError.getRejectedValue())) {
                    missingFields.add(fieldError.getField());
                } else {
                    invalidFields.add(fieldError.getField());
                }/*from w w w  .  j a  va2  s .  co  m*/
            }
        }

        for (int i = 0; i < missingFields.size(); i++) {
            params.put("MissingField" + i, missingFields.get(i));
        }
        for (int i = 0; i < invalidFields.size(); i++) {
            params.put("InvalidField" + i, invalidFields.get(i));
        }
    } else {
        // No validation errors create subscription ID

        final String subscriptionId = UUID.randomUUID().toString();
        params.put("ccAuthReply_cvCode", "M");
        params.put("paySubscriptionCreateReply_subscriptionID", subscriptionId);
        params.put("paySubscriptionCreateReply_subscriptionIDPublicSignature",
                getMockedPublicDigest(subscriptionId));

        processTransactionDecision(request, null, params, false);

        //Mask the card number in the response
        final String endPortion = form.getCard_accountNumber().trim()
                .substring(form.getCard_accountNumber().length() - 4);
        final String maskedCardNumber = "************" + endPortion;

        params.put("card_accountNumber", maskedCardNumber);
    }

    model.addAttribute("postParams", params);
    model.addAttribute("postUrl", params.get("orderPage_receiptResponseURL"));

    return SOP_REDIRECT_POST_PAGE;
}

From source file:de.hybris.platform.customerticketingaddon.controllers.pages.AccountSupportTicketsPageController.java

/**
 * Build the error message list with map contains the validation error code and localised message.
 *
 * @param bindingResult//w ww  .  jav  a2  s  . co m
 * @return Map of error code and message
 */
protected List<Map<String, String>> buildErrorMessagesMap(final BindingResult bindingResult) {
    return bindingResult.getAllErrors().stream()
            .filter(err -> err.getCode() != null && err.getCode().length() > 0).map(err -> {
                final Map<String, String> map = Maps.newHashMap();
                map.put(err.getCodes()[0].replaceAll("\\.", "-"), err.getDefaultMessage());
                return map;
            }).collect(Collectors.toList());
}

From source file:de.seitenbau.govdata.edit.gui.controller.EditController.java

@RequestMapping
public void submitForm(@Valid @ModelAttribute("editForm") EditForm editForm, BindingResult result,
        ActionResponse response, ActionRequest request) {
    // fix zeitbezug dates if they are in the wrong temporal order
    Date fromDate = parseDate(editForm.getTemporalCoverageFrom());
    Date untilDate = parseDate(editForm.getTemporalCoverageUntil());
    if (fromDate != null && untilDate != null && fromDate.after(untilDate)) {
        editForm.setTemporalCoverageFrom(formatDate(untilDate));
        editForm.setTemporalCoverageUntil(formatDate(fromDate));
    } else {/*w  w  w. j  av a  2  s  .c  o m*/
        editForm.setTemporalCoverageFrom(formatDate(fromDate));
        editForm.setTemporalCoverageUntil(formatDate(untilDate));
    }

    // check if form is valid
    if (!result.hasErrors()) {
        try {
            User ckanUser = getCkanuserFromRequestProxy(request);
            saveDataset(editForm, ckanUser);

            // get the name in the same way he new name is created for new datasets
            if (editForm.isNewDataset()) {
                editForm.setName(registryClient.getInstance().mungeTitleToName(editForm.getTitle()));
            }

            // reload saved dataset, so we reflect the actual saved data
            editForm = loadDataset(ckanUser, editForm.getName());

            response.setRenderParameter(MESSAGE_TYPE, MessageType.SUCCESS.toString());
            response.setRenderParameter(MESSAGE, "od.editform.save.success");
        } catch (OpenDataRegistryException | PortalException | SystemException e) {
            response.setRenderParameter(MESSAGE_TYPE, MessageType.ERROR.toString());
            if (StringUtils.isNotEmpty(e.getMessage())) {
                response.setRenderParameter(MESSAGE, e.getMessage());
            } else {
                response.setRenderParameter(MESSAGE, "od.editform.save.error");
                e.printStackTrace(); // just so we can look it up... we don't know yet what's going on.
            }
        }
    } else {
        response.setRenderParameter(MESSAGE_TYPE, MessageType.WARNING.toString());
        response.setRenderParameter(MESSAGE, "od.editform.save.warning");
        log.warn("Form has errors: " + result.getAllErrors());
    }
}

From source file:edu.swau.softball.web.CoachController.java

@RequestMapping(value = "/new", method = RequestMethod.POST)
public String create(@ModelAttribute("coach") User coach, BindingResult bindingResult,
        RedirectAttributes redirectAttributes, Model model) {
    validator.validate(coach, bindingResult);
    if (bindingResult.hasErrors()) {
        log.warn("Could not add coach. {}", bindingResult.getAllErrors());
        model.addAttribute("coach", teamService.all());
        return "/admin/coach/new";
    }//  w ww. ja v a 2  s .c om

    try {
        coach = service.create(coach);
        return "redirect:/admin/coach/show/" + coach.getId();
    } catch (Exception e) {
        log.error("Could not add coach.", e);
        bindingResult.reject("Could not add coach. {}", e.getMessage());
        model.addAttribute("teams", teamService.all());
        return "/admin/coach/new";
    }
}

From source file:edu.swau.softball.web.CoachController.java

@RequestMapping(value = "/edit", method = RequestMethod.POST)
public String update(@ModelAttribute("coach") User coach, BindingResult bindingResult,
        RedirectAttributes redirectAttributes, Model model) {
    validator.validate(coach, bindingResult);
    if (bindingResult.hasErrors()) {
        log.warn("Could not update coach. {}", bindingResult.getAllErrors());
        model.addAttribute("teams", teamService.all());
        return "/admin/coach/edit";
    }// w ww  .j av  a  2 s  .  c  o  m

    try {
        coach = service.create(coach);
        return "redirect:/admin/coach/show/" + coach.getId();
    } catch (Exception e) {
        log.error("Could not update coach.", e);
        bindingResult.reject("Could not update team. {}", e.getMessage());
        model.addAttribute("teams", teamService.all());
        return "/admin/coach/edit";
    }
}