Example usage for java.text ParseException getMessage

List of usage examples for java.text ParseException getMessage

Introduction

In this page you can find the example usage for java.text ParseException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.egov.ptis.domain.service.property.PropertyService.java

/**
 * Returns formatted property occupation date
 *
 * @param dateOfCompletion// w  w  w .j  a v  a 2  s . c o  m
 * @return
 */
public Date getPropOccupatedDate(final String dateOfCompletion) {
    LOGGER.debug("Entered into getPropOccupatedDate, dateOfCompletion: " + dateOfCompletion);
    Date occupationDate = null;
    try {
        if (dateOfCompletion != null && !"".equals(dateOfCompletion))
            occupationDate = dateFormatter.parse(dateOfCompletion);
    } catch (final ParseException e) {
        LOGGER.error(e.getMessage(), e);
    }
    LOGGER.debug("Exiting from getPropOccupatedDate");
    return occupationDate;
}

From source file:org.egov.ptis.domain.service.property.PropertyService.java

/**
 * Returns property completion date based on the property type
 *
 * @param basicProperty/*from  w  w w  .  jav a 2s.  com*/
 * @param newProperty
 * @return
 */
private Date getPropertyCompletionDate(final BasicProperty basicProperty, final PropertyImpl newProperty) {
    LOGGER.debug("Entered into getPropertyCompletionDate - basicProperty.upicNo=" + basicProperty.getUpicNo());
    Date propCompletionDate = null;
    final String propertyTypeMasterCode = newProperty.getPropertyDetail().getPropertyTypeMaster().getCode();
    if (propertyTypeMasterCode.equalsIgnoreCase(OWNERSHIP_TYPE_VAC_LAND)) {
        for (final PropertyStatusValues propstatval : basicProperty.getPropertyStatusValuesSet())
            if (propstatval.getExtraField1() != null)
                try {
                    propCompletionDate = dateFormatter.parse(propstatval.getExtraField1());
                } catch (final ParseException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            else
                propCompletionDate = basicProperty.getPropOccupationDate();
    } else {
        final List<Floor> floorList = newProperty.getPropertyDetail().getFloorDetails();
        propCompletionDate = getLowestDtOfCompFloorWise(floorList);
        if (propCompletionDate == null)
            propCompletionDate = basicProperty.getPropOccupationDate();
    }

    LOGGER.debug("propCompletionDate=" + propCompletionDate + "\nExiting from getPropertyCompletionDate");
    return propCompletionDate;
}

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";
    }//from   ww w.  j  a  v  a  2s .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:org.jasig.schedassist.web.owner.schedule.BlockBuilderFormBackingObjectValidator.java

public void validate(Object command, Errors errors) {
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "startTimePhrase", "field.required",
            "Start time field is required.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "endTimePhrase", "field.required",
            "End time field is required.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "daysOfWeekPhrase", "field.required",
            "Days of week field is required.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "startDatePhrase", "field.required",
            "Start date field is required.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "endDatePhrase", "field.required",
            "End date field is required.");

    BlockBuilderFormBackingObject fbo = (BlockBuilderFormBackingObject) command;

    if (!StringUtils.isBlank(fbo.getDaysOfWeekPhrase())) {
        Matcher daysMatcher = DAYS_OF_WEEK_PATTERN.matcher(fbo.getDaysOfWeekPhrase());
        if (!daysMatcher.matches()) {
            errors.rejectValue("daysOfWeekPhrase", "invalid.daysOfWeekPhrase",
                    "Days of week must contain only 'NMTWRFS' (N is Sunday, S is Saturday).");
        }/*w  ww  . j a va2 s .co m*/
    }

    if (!StringUtils.isBlank(fbo.getStartDatePhrase())) {
        Matcher m = DATE_PATTERN.matcher(fbo.getStartDatePhrase());
        if (!m.matches()) {
            errors.rejectValue("startDatePhrase", "startDatePhrase.invalidFormat",
                    "Start Date must contain 2 digit month, 2 digit day, and 4 digit year (mm/dd/yyyy).");
        }
    }
    if (!StringUtils.isBlank(fbo.getEndDatePhrase())) {
        Matcher m = DATE_PATTERN.matcher(fbo.getEndDatePhrase());
        if (!m.matches()) {
            errors.rejectValue("endDatePhrase", "endDatePhrase.invalidFormat",
                    "End Date must contain 2 digit month, 2 digit day, and 4 digit year (mm/dd/yyyy).");
        }
    }

    SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
    Date startDate = null;
    Date endDate = null;
    if (!StringUtils.isBlank(fbo.getStartDatePhrase())) {
        try {
            startDate = dateFormat.parse(fbo.getStartDatePhrase());
        } catch (ParseException e) {
            errors.rejectValue("startDatePhrase", "field.parseexception",
                    "Start date does not match expected format (mm/dd/yyyy).");
        }
    }
    if (!StringUtils.isBlank(fbo.getEndDatePhrase())) {
        try {
            endDate = dateFormat.parse(fbo.getEndDatePhrase());
        } catch (ParseException e) {
            errors.rejectValue("endDatePhrase", "field.parseexception",
                    "End date does not match expected format (mm/dd/yyyy).");
        }
    }

    if (null != startDate && null != endDate) {
        if (CommonDateOperations.approximateDifference(startDate, endDate) > 730) {
            errors.rejectValue("endDatePhrase", "endDatePhrase.toofarout",
                    "End date is more than 2 years after startDate; please scale back your end date.");
        }
    }

    boolean startTimePhraseValid = true;
    boolean endTimePhraseValid = true;
    Matcher startTimeMatcher = null;
    if (!StringUtils.isBlank(fbo.getStartTimePhrase())) {
        startTimeMatcher = TIME_PATTERN.matcher(fbo.getStartTimePhrase());
        if (!startTimeMatcher.matches()) {
            errors.rejectValue("startTimePhrase", "field.timeparseexception",
                    "Start time does not match expected format (hh:mm am|pm).");
            startTimePhraseValid = false;
        } else if (Integer.parseInt(startTimeMatcher.group(1)) > 12) {
            errors.rejectValue("startTimePhrase", "field.militarytime",
                    "Start time should start with a number between 1 and 12; do not use military time.");
            startTimePhraseValid = false;
        }
    } else {
        startTimePhraseValid = false;
    }
    Matcher endTimeMatcher = null;
    if (!StringUtils.isBlank(fbo.getEndTimePhrase())) {
        endTimeMatcher = TIME_PATTERN.matcher(fbo.getEndTimePhrase());
        if (!endTimeMatcher.matches()) {
            errors.rejectValue("endTimePhrase", "field.timeparseexception",
                    "End time does not match expected format (hh:mm am|pm).");
            endTimePhraseValid = false;
        } else if (Integer.parseInt(endTimeMatcher.group(1)) > 12) {
            errors.rejectValue("endTimePhrase", "field.militarytime",
                    "End time should start with a number between 1 and 12; do not use military time.");
            endTimePhraseValid = false;
        }
    } else {
        endTimePhraseValid = false;
    }
    // TODO validate difference between start and end time phrase (>= 15 minutes)not 
    if (startTimePhraseValid && endTimePhraseValid) {
        long minutesDifference = approximateMinutesDifference(startTimeMatcher, endTimeMatcher);
        if (minutesDifference < 15) {
            errors.rejectValue("endTimePhrase", "endTimePhrase.tooshort",
                    "End time has to be at least 15 minutes later than the start time.");
        }
    }

    if (fbo.getVisitorsPerAppointment() < 1) {
        errors.rejectValue("visitorsPerAppointment", "visitors.toosmall",
                "Visitors per appointment must be greater than or equal to 1.");
    }
    if (fbo.getVisitorsPerAppointment() > 99) {
        errors.rejectValue("visitorsPerAppointment", "visitors.toosmall",
                "Maximum allowed value for visitors per appointment is 99.");
    }

    if (StringUtils.isBlank(fbo.getMeetingLocation())) {
        // forcibly set to null to guarantee proper storage
        fbo.setMeetingLocation(null);
    } else {
        if (fbo.getMeetingLocation().length() > 100) {
            errors.rejectValue("location", "location.toolong", "Location field is too long ("
                    + fbo.getMeetingLocation().length() + "); maximum length is 100 characters.");
        }
    }
    if (!errors.hasErrors()) {
        // try to run the block builder and report any inputformatexceptions
        try {
            if (null != startDate && null != endDate) {
                AvailableBlockBuilder.createBlocks(fbo.getStartTimePhrase(), fbo.getEndTimePhrase(),
                        fbo.getDaysOfWeekPhrase(), startDate, endDate);
            }
        } catch (InputFormatException e) {
            errors.reject("createBlocksFailed", e.getMessage());
        }
    }
}

From source file:org.apache.flume.sink.hdfs.BucketWriter.java

/**
 * Open file handles, write data, update stats, handle file rolling and
 * batching / flushing. <br />//from www. j  a v  a 2 s .c o m
 * If the write fails, the file is implicitly closed and then the
 * IOException is rethrown. <br />
 * We rotate before append, and not after, so that the active file rolling
 * mechanism will never roll an empty file. This also ensures that the file
 * creation time reflects when the first event was written.
 * 
 * @throws IOException
 * @throws InterruptedException
 * @throws ParseException
 */
public synchronized void append(final Event event, Date... now) throws IOException, InterruptedException {
    checkAndThrowInterruptedException();
    // If idleFuture is not null, cancel it before we move forward to avoid
    // a
    // close call in the middle of the append.
    if (idleFuture != null) {
        idleFuture.cancel(false);
        // There is still a small race condition - if the idleFuture is
        // already
        // running, interrupting it can cause HDFS close operation to throw
        // -
        // so we cannot interrupt it while running. If the future could not
        // be
        // cancelled, it is already running - wait for it to finish before
        // attempting to write.
        if (!idleFuture.isDone()) {
            try {
                idleFuture.get(callTimeout, TimeUnit.MILLISECONDS);
            } catch (TimeoutException ex) {
                LOG.warn("Timeout while trying to cancel closing of idle file. Idle"
                        + " file close may have failed", ex);
            } catch (Exception ex) {
                LOG.warn("Error while trying to cancel closing of idle file. ", ex);
            }
        }
        idleFuture = null;
    }

    boolean shouldRotate = false;
    if (StringUtils.isNotBlank(timeRollerFlag)) {
        calendar.setTime(fileOpenTime);
        int lastDayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
        int lastYear = calendar.get(Calendar.YEAR);
        int lastHour = calendar.get(Calendar.HOUR_OF_DAY);
        int lastMin = calendar.get(Calendar.MINUTE);
        if (StringUtils.isNotBlank(formerField) && event.getHeaders().containsKey(formerField))
            try {
                now[0] = sdfParse.parse(event.getHeaders().get(formerField));
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        calendar.setTime(now[0]);
        int nowDayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
        int nowYear = calendar.get(Calendar.YEAR);
        int nowHour = calendar.get(Calendar.HOUR_OF_DAY);
        int nowMin = calendar.get(Calendar.MINUTE);

        // 
        boolean condition1 = false;
        boolean condition2 = false;
        if ("DAY".equals(timeRollerFlag)) {
            // ?+1+1now=1
            condition1 = (lastYear == nowYear && (nowDayOfYear == (lastDayOfYear + 1)))
                    || (nowYear == (lastYear + 1) && nowDayOfYear == 1);
            condition2 = (lastYear == nowYear && nowDayOfYear == lastDayOfYear);
        } else if ("HOUR".equals(timeRollerFlag)) {
            // day??+1day???=0
            condition1 = (lastDayOfYear == nowDayOfYear && nowHour == (lastHour + 1))
                    || (lastDayOfYear != nowDayOfYear && nowHour == 0);
            condition2 = (lastYear == nowYear && nowDayOfYear == lastDayOfYear && nowHour == lastHour);
        } else if ("MINUTE".equals(timeRollerFlag)) {
            condition1 = (lastHour == nowHour && nowMin == (lastMin + 1))
                    || (lastHour != nowHour && nowMin == 0);
            condition2 = (lastYear == nowYear && nowDayOfYear == lastDayOfYear && nowHour == lastHour
                    && nowMin == lastMin);
        }
        if (condition1 || !condition2) {
            LOG.info("rollflag = {},rolling", timeRollerFlag);
            shouldRotate = true;
            fileOpenTime = now[0];
        }
        fileSuffix = sdfFormat.format(now[0]);
    }

    // check if it's time to rotate the file
    if (shouldRotate() || shouldRotate) {
        boolean doRotate = true;

        if (isUnderReplicated) {
            if (maxConsecUnderReplRotations > 0
                    && consecutiveUnderReplRotateCount >= maxConsecUnderReplRotations) {
                doRotate = false;
                if (consecutiveUnderReplRotateCount == maxConsecUnderReplRotations) {
                    LOG.error("Hit max consecutive under-replication rotations ({}); "
                            + "will not continue rolling files under this path due to " + "under-replication",
                            maxConsecUnderReplRotations);
                }
            } else {
                LOG.warn("Block Under-replication detected. Rotating file.");
            }
            consecutiveUnderReplRotateCount++;
        } else {
            consecutiveUnderReplRotateCount = 0;
        }

        if (doRotate) {
            close();
        }
    }

    // If the bucket writer was closed due to roll timeout or idle timeout,
    // force a new bucket writer to be created. Roll count and roll size
    // will
    // just reuse this one
    if (!isOpen) {
        if (closed) {
            throw new BucketClosedException(
                    "This bucket writer was closed and " + "this handle is thus no longer valid");
        }
        open();
    }

    // write the event
    try {
        sinkCounter.incrementEventDrainAttemptCount();
        callWithTimeout(new CallRunner<Void>() {
            @Override
            public Void call() throws Exception {
                writer.append(event); // could block
                return null;
            }
        });
    } catch (IOException e) {
        LOG.warn("Caught IOException writing to HDFSWriter ({}). Closing file (" + bucketPath
                + ") and rethrowing exception.", e.getMessage());
        try {
            close(true);
        } catch (IOException e2) {
            LOG.warn("Caught IOException while closing file (" + bucketPath + "). Exception follows.", e2);
        }
        throw e;
    }

    // update statistics
    processSize += event.getBody().length;
    eventCounter++;
    batchCounter++;

    if (batchCounter == batchSize) {
        flush();
    }
}

From source file:com.turborep.turbotracker.vendor.controller.VendorInvoiceBillController.java

@RequestMapping(value = "/getAccountsPayableListCSV", method = RequestMethod.GET)
public @ResponseBody void printProjectsPDF(
        @RequestParam(value = "searchData", required = false) String searchData,
        @RequestParam(value = "fromDate", required = false) String fromDate,
        @RequestParam(value = "toDate", required = false) String toDate, HttpServletResponse theResponse,
        HttpServletRequest theRequest, HttpSession session)
        throws IOException, MessagingException, SQLException, JRException, VendorException {
    Connection connection = null;
    ConnectionProvider con = null;/*from w w  w.ja  v a  2s  .  co  m*/
    try {
        HashMap<String, Object> params = new HashMap<String, Object>();
        String path_JRXML = null;
        String filename = null;
        String printtype = null;
        String frmBillDate = "''";
        String toBillDate = "''";
        String queryBuild = null;
        if ((fromDate != null) && (fromDate.equals("") == false)) {
            queryBuild = getAccountsPayableListQuery(null, fromDate, toDate);
        } else {
            queryBuild = getAccountsPayableListQuery(null, null, toDate);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        SimpleDateFormat sdff = new SimpleDateFormat("yyyy-MM-dd");
        if (fromDate != null && !fromDate.trim().equals("")) {
            Date convertedCurrentDate = null;
            try {
                convertedCurrentDate = sdf.parse(fromDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            fromDate = sdff.format(convertedCurrentDate);
        }
        if (toDate != null && !toDate.trim().equals("")) {
            Date convertedCurrentDate = null;
            try {
                convertedCurrentDate = sdf.parse(toDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            toDate = sdff.format(convertedCurrentDate);
        }

        Calendar cal = Calendar.getInstance();
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        String formattedfrom = format1.format(cal.getTime());
        System.out.println("formattedfrom " + formattedfrom);

        cal.add(Calendar.MONTH, -6);
        String formattedto = format1.format(cal.getTime());
        System.out.println("formattedto " + formattedto);

        if (!fromDate.equals("") && !toDate.equals("")) {

            frmBillDate = fromDate;
            toBillDate = toDate;
        } else if (!fromDate.equals("") && toDate.equals("")) {
            frmBillDate = fromDate;
            toBillDate = formattedfrom;

        } else if (!toDate.equals("") && fromDate.equals("")) {
            frmBillDate = "";
            toBillDate = toDate;
        } else {
            frmBillDate = "";
            toBillDate = formattedfrom;
        }

        printtype = "xls";
        path_JRXML = theRequest.getSession().getServletContext()
                .getRealPath("/resources/jasper_reports/VendorAccountsPayable.jrxml");
        filename = "AccountsPayable.csv";
        logger.info("frmBillDate::" + frmBillDate + " ##toBillDate::" + toBillDate);
        //            params.put("frmBillDate", frmBillDate);
        params.put("toBillDate", toBillDate);

        con = itspdfService.connectionForJasper();
        //Have to set Params
        //params.put("CuInvoice", CuInvoice);

        connection = con.getConnection();
        JasperDesign jd = JRXmlLoader.load(path_JRXML);
        JRDesignQuery jdq = new JRDesignQuery();
        jdq.setText(queryBuild);
        jd.setQuery(jdq);
        //ReportService.ReportCall(theResponse,params,printtype,path_JRXML,filename,connection);
        ReportService.dynamicReportCall(theResponse, params, printtype, jd, filename, connection);

    } catch (SQLException e) {
        logger.error(e.getMessage());
        theResponse.sendError(500, e.getMessage());
        sendTransactionException("<b> AccountsPayable ==></b>" + toDate, "Vendor Invoice", e, session,
                theRequest);
    } finally {
        if (con != null) {
            con.closeConnection(connection);
            con = null;
        }
    }
}

From source file:org.kuali.kfs.module.cam.batch.service.impl.AssetDepreciationServiceImpl.java

/**
 * @see org.kuali.kfs.module.cam.batch.service.AssetDepreciationService#runDepreciation()
 *///from  w ww.j  a v a2  s. co  m
@Override
public void runDepreciation() {
    Integer fiscalYear = -1;
    Integer fiscalMonth = -1;
    String errorMsg = "";
    List<String> documentNos = new ArrayList<String>();
    List<String[]> reportLog = new ArrayList<String[]>();
    Collection<AssetObjectCode> assetObjectCodes = new ArrayList<AssetObjectCode>();
    boolean hasErrors = false;
    Calendar depreciationDate = dateTimeService.getCurrentCalendar();
    java.sql.Date depDate = null;
    Calendar currentDate = dateTimeService.getCurrentCalendar();
    String depreciationDateParameter = null;
    DateFormat dateFormat = new SimpleDateFormat(CamsConstants.DateFormats.YEAR_MONTH_DAY);
    boolean executeJob = false;
    String errorMessage = kualiConfigurationService
            .getPropertyValueAsString(CamsKeyConstants.Depreciation.DEPRECIATION_ALREADY_RAN_MSG);

    try {
        executeJob = runAssetDepreciation();
        if (executeJob) {
            LOG.info("*******" + CamsConstants.Depreciation.DEPRECIATION_BATCH + " HAS BEGUN *******");

            /*
             * Getting the system parameter "DEPRECIATION_DATE" When this parameter is used to determine which fiscal month and year
             * is going to be depreciated If blank then the system will take the system date to determine the fiscal period
             */
            if (parameterService.parameterExists(KfsParameterConstants.CAPITAL_ASSETS_BATCH.class,
                    CamsConstants.Parameters.DEPRECIATION_RUN_DATE_PARAMETER)) {
                depreciationDateParameter = parameterService.getParameterValueAsString(
                        KfsParameterConstants.CAPITAL_ASSETS_BATCH.class,
                        CamsConstants.Parameters.DEPRECIATION_RUN_DATE_PARAMETER);
            } else {
                throw new IllegalStateException(kualiConfigurationService.getPropertyValueAsString(
                        CamsKeyConstants.Depreciation.DEPRECIATION_DATE_PARAMETER_NOT_FOUND));
            }

            if (StringUtils.isBlank(depreciationDateParameter)) {
                depreciationDateParameter = dateFormat.format(dateTimeService.getCurrentDate());
            }
            // This validates the system parameter depreciation_date has a valid format of YYYY-MM-DD.
            if (!StringUtils.isBlank(depreciationDateParameter)) {
                try {
                    depreciationDate.setTime(dateFormat.parse(depreciationDateParameter.trim()));
                } catch (ParseException e) {
                    throw new IllegalArgumentException(kualiConfigurationService.getPropertyValueAsString(
                            CamsKeyConstants.Depreciation.INVALID_DEPRECIATION_DATE_FORMAT));
                }
            }
            if (LOG.isInfoEnabled()) {
                LOG.info(CamsConstants.Depreciation.DEPRECIATION_BATCH + "Depreciation run date: "
                        + depreciationDateParameter);
            }

            UniversityDate universityDate = businessObjectService.findBySinglePrimaryKey(UniversityDate.class,
                    new java.sql.Date(depreciationDate.getTimeInMillis()));
            if (universityDate == null) {
                throw new IllegalStateException(kualiConfigurationService
                        .getPropertyValueAsString(KFSKeyConstants.ERROR_UNIV_DATE_NOT_FOUND));
            }

            fiscalYear = universityDate.getUniversityFiscalYear();
            fiscalMonth = new Integer(universityDate.getUniversityFiscalAccountingPeriod());
            assetObjectCodes = getAssetObjectCodes(fiscalYear);
            // If the depreciation date is not = to the system date then, the depreciation process cannot run.
            if (LOG.isInfoEnabled()) {
                LOG.info(CamsConstants.Depreciation.DEPRECIATION_BATCH + "Fiscal Year = " + fiscalYear
                        + " & Fiscal Period=" + fiscalMonth);
            }
            int fiscalStartMonth = Integer
                    .parseInt(optionsService.getCurrentYearOptions().getUniversityFiscalYearStartMo());
            reportLog.addAll(depreciableAssetsDao.generateStatistics(true, null, fiscalYear, fiscalMonth,
                    depreciationDate, dateTimeService.toDateString(depreciationDate.getTime()),
                    assetObjectCodes, fiscalStartMonth, errorMessage));
            // update if fiscal period is 12
            // depreciationBatchDao.updateAssetsCreatedInLastFiscalPeriod(fiscalMonth, fiscalYear);
            updateAssetsDatesForLastFiscalPeriod(fiscalMonth, fiscalYear);
            // Retrieving eligible asset payment details
            LOG.info(CamsConstants.Depreciation.DEPRECIATION_BATCH
                    + "Getting list of asset payments eligible for depreciation.");
            Collection<AssetPaymentInfo> depreciableAssetsCollection = depreciationBatchDao
                    .getListOfDepreciableAssetPaymentInfo(fiscalYear, fiscalMonth, depreciationDate);
            // if we have assets eligible for depreciation then, calculate depreciation and create glpe's transactions
            if (depreciableAssetsCollection != null && !depreciableAssetsCollection.isEmpty()) {
                SortedMap<String, AssetDepreciationTransaction> depreciationTransactions = this
                        .calculateDepreciation(fiscalYear, fiscalMonth, depreciableAssetsCollection,
                                depreciationDate, assetObjectCodes);
                processGeneralLedgerPendingEntry(fiscalYear, fiscalMonth, documentNos,
                        depreciationTransactions);
            } else {
                throw new IllegalStateException(kualiConfigurationService.getPropertyValueAsString(
                        CamsKeyConstants.Depreciation.NO_ELIGIBLE_FOR_DEPRECIATION_ASSETS_FOUND));
            }
        }
    } catch (Exception e) {
        LOG.error("Error occurred");
        LOG.error(CamsConstants.Depreciation.DEPRECIATION_BATCH
                + "**************************************************************************");
        LOG.error(CamsConstants.Depreciation.DEPRECIATION_BATCH + "AN ERROR HAS OCCURRED! - ERROR: "
                + e.getMessage(), e);
        LOG.error(CamsConstants.Depreciation.DEPRECIATION_BATCH
                + "**************************************************************************");
        hasErrors = true;
        errorMsg = "Depreciation process ran unsucessfuly.\nReason:" + e.getMessage();
    } finally {
        if (!hasErrors && executeJob) {
            int fiscalStartMonth = Integer
                    .parseInt(optionsService.getCurrentYearOptions().getUniversityFiscalYearStartMo());
            reportLog.addAll(depreciableAssetsDao.generateStatistics(false, documentNos, fiscalYear,
                    fiscalMonth, depreciationDate, dateTimeService.toDateString(depreciationDate.getTime()),
                    assetObjectCodes, fiscalStartMonth, errorMessage));
        }
        // the report will be generated only when there is an error or when the log has something.
        if (!reportLog.isEmpty() || !errorMsg.trim().equals("")) {
            reportService.generateDepreciationReport(reportLog, errorMsg, depreciationDateParameter);
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("*******" + CamsConstants.Depreciation.DEPRECIATION_BATCH + " HAS ENDED *******");
        }
    }
}

From source file:org.apache.syncope.console.pages.ApprovalModalPage.java

public ApprovalModalPage(final PageReference pageRef, final ModalWindow window, final WorkflowFormTO formTO) {
    super();/* ww w  .ja  va 2 s  . c  o m*/

    IModel<List<WorkflowFormPropertyTO>> formProps = new LoadableDetachableModel<List<WorkflowFormPropertyTO>>() {

        private static final long serialVersionUID = 3169142472626817508L;

        @Override
        protected List<WorkflowFormPropertyTO> load() {
            return formTO.getProperties();
        }
    };

    final ListView<WorkflowFormPropertyTO> propView = new AltListView<WorkflowFormPropertyTO>("propView",
            formProps) {

        private static final long serialVersionUID = 9101744072914090143L;

        @Override
        @SuppressWarnings({ "unchecked", "rawtypes" })
        protected void populateItem(final ListItem<WorkflowFormPropertyTO> item) {
            final WorkflowFormPropertyTO prop = item.getModelObject();

            Label label = new Label("key", prop.getName() == null ? prop.getId() : prop.getName());
            item.add(label);

            FieldPanel field;
            switch (prop.getType()) {
            case Boolean:
                field = new AjaxDropDownChoicePanel("value", label.getDefaultModelObjectAsString(),
                        new Model<Boolean>(Boolean.valueOf(prop.getValue())))
                                .setChoices(Arrays.asList(new String[] { "Yes", "No" }));
                break;

            case Date:
                SimpleDateFormat df = StringUtils.isNotBlank(prop.getDatePattern())
                        ? new SimpleDateFormat(prop.getDatePattern())
                        : new SimpleDateFormat();
                Date parsedDate = null;
                if (StringUtils.isNotBlank(prop.getValue())) {
                    try {
                        parsedDate = df.parse(prop.getValue());
                    } catch (ParseException e) {
                        LOG.error("Unparsable date: {}", prop.getValue(), e);
                    }
                }

                field = new DateTimeFieldPanel("value", label.getDefaultModelObjectAsString(),
                        new Model<Date>(parsedDate), df.toLocalizedPattern());
                break;

            case Enum:
                MapChoiceRenderer<String, String> enumCR = new MapChoiceRenderer<String, String>(
                        prop.getEnumValues());

                field = new AjaxDropDownChoicePanel("value", label.getDefaultModelObjectAsString(),
                        new Model(prop.getValue())).setChoiceRenderer(enumCR).setChoices(new Model() {

                            private static final long serialVersionUID = -858521070366432018L;

                            @Override
                            public Serializable getObject() {
                                return new ArrayList<String>(prop.getEnumValues().keySet());
                            }
                        });
                break;

            case Long:
                field = new SpinnerFieldPanel<Long>("value", label.getDefaultModelObjectAsString(), Long.class,
                        new Model<Long>(NumberUtils.toLong(prop.getValue())), null, null);
                break;

            case String:
            default:
                field = new AjaxTextFieldPanel("value", PARENT_PATH, new Model<String>(prop.getValue()));
                break;
            }

            field.setReadOnly(!prop.isWritable());
            if (prop.isRequired()) {
                field.addRequiredLabel();
            }

            item.add(field);
        }
    };

    final AjaxButton userDetails = new IndicatingAjaxButton("userDetails",
            new Model<String>(getString("userDetails"))) {

        private static final long serialVersionUID = -4804368561204623354L;

        @Override
        protected void onSubmit(final AjaxRequestTarget target, final Form<?> form) {
            editUserWin.setPageCreator(new ModalWindow.PageCreator() {

                private static final long serialVersionUID = -7834632442532690940L;

                @Override
                public Page createPage() {
                    return new ViewUserModalPage(ApprovalModalPage.this.getPageReference(), editUserWin,
                            userRestClient.read(formTO.getUserId())) {

                        private static final long serialVersionUID = -2819994749866481607L;

                        @Override
                        protected void closeAction(final AjaxRequestTarget target, final Form form) {
                            setResponsePage(ApprovalModalPage.this);
                        }
                    };
                }
            });

            editUserWin.show(target);
        }
    };
    MetaDataRoleAuthorizationStrategy.authorize(userDetails, ENABLE,
            xmlRolesReader.getAllAllowedRoles("Users", "read"));

    final AjaxButton submit = new IndicatingAjaxButton(APPLY, new Model<String>(getString(SUBMIT))) {

        private static final long serialVersionUID = -958724007591692537L;

        @Override
        protected void onSubmit(final AjaxRequestTarget target, final Form<?> form) {

            Map<String, WorkflowFormPropertyTO> props = formTO.getPropertyMap();

            for (int i = 0; i < propView.size(); i++) {
                @SuppressWarnings("unchecked")
                ListItem<WorkflowFormPropertyTO> item = (ListItem<WorkflowFormPropertyTO>) propView.get(i);
                String input = ((FieldPanel) item.get("value")).getField().getInput();

                if (!props.containsKey(item.getModelObject().getId())) {
                    props.put(item.getModelObject().getId(), new WorkflowFormPropertyTO());
                }

                if (item.getModelObject().isWritable()) {
                    switch (item.getModelObject().getType()) {
                    case Boolean:
                        props.get(item.getModelObject().getId()).setValue(String.valueOf("0".equals(input)));
                        break;

                    case Date:
                    case Enum:
                    case String:
                    case Long:
                    default:
                        props.get(item.getModelObject().getId()).setValue(input);
                        break;
                    }
                }
            }

            formTO.setProperties(props.values());
            try {
                restClient.submitForm(formTO);

                ((Todo) pageRef.getPage()).setModalResult(true);
                window.close(target);
            } catch (SyncopeClientException e) {
                error(getString(Constants.ERROR) + ": " + e.getMessage());
                LOG.error("While submitting form {}", formTO, e);
                feedbackPanel.refresh(target);
            }
        }

        @Override
        protected void onError(final AjaxRequestTarget target, final Form<?> form) {
            feedbackPanel.refresh(target);
        }
    };

    final AjaxButton cancel = new IndicatingAjaxButton(CANCEL, new ResourceModel(CANCEL)) {

        private static final long serialVersionUID = -958724007591692537L;

        @Override
        protected void onSubmit(final AjaxRequestTarget target, final Form form) {
            window.close(target);
        }

        @Override
        protected void onError(final AjaxRequestTarget target, final Form form) {
            // nothing
        }
    };

    cancel.setDefaultFormProcessing(false);

    Form form = new Form(FORM);
    form.add(propView);
    form.add(userDetails);
    form.add(submit);
    form.add(cancel);

    MetaDataRoleAuthorizationStrategy.authorize(form, ENABLE,
            xmlRolesReader.getAllAllowedRoles("Approval", SUBMIT));

    editUserWin = new ModalWindow("editUserWin");
    editUserWin.setCssClassName(ModalWindow.CSS_CLASS_GRAY);
    editUserWin.setInitialHeight(USER_WIN_HEIGHT);
    editUserWin.setInitialWidth(USER_WIN_WIDTH);
    editUserWin.setCookieName("edit-user-modal");
    add(editUserWin);

    add(form);
}

From source file:org.apache.syncope.client.console.pages.ApprovalModalPage.java

public ApprovalModalPage(final PageReference pageRef, final ModalWindow window, final WorkflowFormTO formTO) {
    super();//w w  w .  j a va 2 s  .  c o m

    IModel<List<WorkflowFormPropertyTO>> formProps = new LoadableDetachableModel<List<WorkflowFormPropertyTO>>() {

        private static final long serialVersionUID = 3169142472626817508L;

        @Override
        protected List<WorkflowFormPropertyTO> load() {
            return formTO.getProperties();
        }
    };

    final ListView<WorkflowFormPropertyTO> propView = new AltListView<WorkflowFormPropertyTO>("propView",
            formProps) {

        private static final long serialVersionUID = 9101744072914090143L;

        @Override
        @SuppressWarnings({ "unchecked", "rawtypes" })
        protected void populateItem(final ListItem<WorkflowFormPropertyTO> item) {
            final WorkflowFormPropertyTO prop = item.getModelObject();

            Label label = new Label("key", prop.getName() == null ? prop.getId() : prop.getName());
            item.add(label);

            FieldPanel field;
            switch (prop.getType()) {
            case Boolean:
                field = new AjaxDropDownChoicePanel("value", label.getDefaultModelObjectAsString(),
                        new Model<Boolean>(Boolean.valueOf(prop.getValue())))
                                .setChoices(Arrays.asList(new String[] { "Yes", "No" }));
                break;

            case Date:
                SimpleDateFormat df = StringUtils.isNotBlank(prop.getDatePattern())
                        ? new SimpleDateFormat(prop.getDatePattern())
                        : new SimpleDateFormat();
                Date parsedDate = null;
                if (StringUtils.isNotBlank(prop.getValue())) {
                    try {
                        parsedDate = df.parse(prop.getValue());
                    } catch (ParseException e) {
                        LOG.error("Unparsable date: {}", prop.getValue(), e);
                    }
                }

                field = new DateTimeFieldPanel("value", label.getDefaultModelObjectAsString(),
                        new Model<Date>(parsedDate), df.toLocalizedPattern());
                break;

            case Enum:
                MapChoiceRenderer<String, String> enumCR = new MapChoiceRenderer<String, String>(
                        prop.getEnumValues());

                field = new AjaxDropDownChoicePanel("value", label.getDefaultModelObjectAsString(),
                        new Model(prop.getValue())).setChoiceRenderer(enumCR).setChoices(new Model() {

                            private static final long serialVersionUID = -858521070366432018L;

                            @Override
                            public Serializable getObject() {
                                return new ArrayList<String>(prop.getEnumValues().keySet());
                            }
                        });
                break;

            case Long:
                field = new SpinnerFieldPanel<Long>("value", label.getDefaultModelObjectAsString(), Long.class,
                        new Model<Long>(NumberUtils.toLong(prop.getValue())), null, null);
                break;

            case String:
            default:
                field = new AjaxTextFieldPanel("value", PARENT_PATH, new Model<String>(prop.getValue()));
                break;
            }

            field.setReadOnly(!prop.isWritable());
            if (prop.isRequired()) {
                field.addRequiredLabel();
            }

            item.add(field);
        }
    };

    final AjaxButton userDetails = new IndicatingAjaxButton("userDetails",
            new Model<String>(getString("userDetails"))) {

        private static final long serialVersionUID = -4804368561204623354L;

        @Override
        protected void onSubmit(final AjaxRequestTarget target, final Form<?> form) {
            editUserWin.setPageCreator(new ModalWindow.PageCreator() {

                private static final long serialVersionUID = -7834632442532690940L;

                @Override
                public Page createPage() {
                    return new ViewUserModalPage(ApprovalModalPage.this.getPageReference(), editUserWin,
                            userRestClient.read(formTO.getUserKey())) {

                        private static final long serialVersionUID = -2819994749866481607L;

                        @Override
                        protected void closeAction(final AjaxRequestTarget target, final Form form) {
                            setResponsePage(ApprovalModalPage.this);
                        }
                    };
                }
            });

            editUserWin.show(target);
        }
    };
    MetaDataRoleAuthorizationStrategy.authorize(userDetails, ENABLE,
            xmlRolesReader.getEntitlement("Users", "read"));

    final AjaxButton submit = new IndicatingAjaxButton(APPLY, new Model<String>(getString(SUBMIT))) {

        private static final long serialVersionUID = -958724007591692537L;

        @Override
        protected void onSubmit(final AjaxRequestTarget target, final Form<?> form) {

            Map<String, WorkflowFormPropertyTO> props = formTO.getPropertyMap();

            for (int i = 0; i < propView.size(); i++) {
                @SuppressWarnings("unchecked")
                ListItem<WorkflowFormPropertyTO> item = (ListItem<WorkflowFormPropertyTO>) propView.get(i);
                String input = ((FieldPanel) item.get("value")).getField().getInput();

                if (!props.containsKey(item.getModelObject().getId())) {
                    props.put(item.getModelObject().getId(), new WorkflowFormPropertyTO());
                }

                if (item.getModelObject().isWritable()) {
                    switch (item.getModelObject().getType()) {
                    case Boolean:
                        props.get(item.getModelObject().getId()).setValue(String.valueOf("0".equals(input)));
                        break;

                    case Date:
                    case Enum:
                    case String:
                    case Long:
                    default:
                        props.get(item.getModelObject().getId()).setValue(input);
                        break;
                    }
                }
            }

            formTO.getProperties().clear();
            formTO.getProperties().addAll(props.values());
            try {
                restClient.submitForm(formTO);

                ((Todo) pageRef.getPage()).setModalResult(true);
                window.close(target);
            } catch (SyncopeClientException e) {
                error(getString(Constants.ERROR) + ": " + e.getMessage());
                LOG.error("While submitting form {}", formTO, e);
                feedbackPanel.refresh(target);
            }
        }

        @Override
        protected void onError(final AjaxRequestTarget target, final Form<?> form) {
            feedbackPanel.refresh(target);
        }
    };

    final AjaxButton cancel = new IndicatingAjaxButton(CANCEL, new ResourceModel(CANCEL)) {

        private static final long serialVersionUID = -958724007591692537L;

        @Override
        protected void onSubmit(final AjaxRequestTarget target, final Form form) {
            window.close(target);
        }

        @Override
        protected void onError(final AjaxRequestTarget target, final Form form) {
            // nothing
        }
    };

    cancel.setDefaultFormProcessing(false);

    Form form = new Form(FORM);
    form.add(propView);
    form.add(userDetails);
    form.add(submit);
    form.add(cancel);

    MetaDataRoleAuthorizationStrategy.authorize(form, ENABLE,
            xmlRolesReader.getEntitlement("Approval", SUBMIT));

    editUserWin = new ModalWindow("editUserWin");
    editUserWin.setCssClassName(ModalWindow.CSS_CLASS_GRAY);
    editUserWin.setInitialHeight(USER_WIN_HEIGHT);
    editUserWin.setInitialWidth(USER_WIN_WIDTH);
    editUserWin.setCookieName("edit-user-modal");
    add(editUserWin);

    add(form);
}

From source file:org.egov.egf.web.actions.payment.PaymentAction.java

/**
 *
 * @return/*  www  . j  a v  a2  s.  c o m*/
 * @throws ValidationException this api is called from searchbills method is changed to save to enable csrf fix actaul method
 * name was generate payment. I doesnot save data but forwards to screen where for selected bill we can make payment
 */
@SkipValidation
@ValidationErrorPage("searchbills")
@Action(value = "/payment/payment-save")
public String save() throws ValidationException {
    final List<PaymentBean> paymentList = new ArrayList<PaymentBean>();
    final List<AppConfigValues> cutOffDateconfigValue = appConfigValuesService
            .getConfigValuesByModuleAndKey("EGF", "DataEntryCutOffDate");
    if (cutOffDateconfigValue != null && !cutOffDateconfigValue.isEmpty())
        try {
            date = df.parse(cutOffDateconfigValue.get(0).getValue());
            cutOffDate = formatter.format(date);
        } catch (final ParseException e) {

        }
    try {
        final String paymentMd = parameters.get("paymentMode")[0];
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Starting generatePayment...");
        if (LOGGER.isInfoEnabled())
            LOGGER.info("Expenditure type is--------------------------------- " + expType);

        if (null != contractorList && !contractorList.isEmpty())
            paymentList.addAll(contractorList);
        if (null != supplierList && !supplierList.isEmpty())
            paymentList.addAll(supplierList);
        if (null != contingentList && !contingentList.isEmpty())
            paymentList.addAll(contingentList);
        if (null != salaryList && !salaryList.isEmpty())
            paymentList.addAll(salaryList);
        if (null != pensionList && !pensionList.isEmpty())
            paymentList.addAll(pensionList);

        if (rtgsDefaultMode != null && rtgsDefaultMode.equalsIgnoreCase("Y")
                && !paymentMd.equalsIgnoreCase("rtgs"))
            if (paymentService.CheckForContractorSubledgerCodes(paymentList, rtgsModeRestrictionDateForCJV))
                throw new ValidationException(Arrays.asList(new ValidationError(
                        "Payment Mode of any bill having Contractor/Supplier subledger should  RTGS For Bill Date Greater than 01-Oct-2013",
                        "Payment Mode of any bill having Contractor/Supplier subledger should  RTGS For Bill Date Greater than 01-Oct-2013")));
        billList = new ArrayList<PaymentBean>();
        contractorIds = contractorIds + populateBillListFor(contractorList, contractorIds);
        supplierIds = supplierIds + populateBillListFor(supplierList, supplierIds);
        contingentIds = contingentIds + populateBillListFor(contingentList, contingentIds);
        salaryIds = salaryIds + populateBillListFor(salaryList, salaryIds);
        pensionIds = pensionIds + populateBillListFor(pensionList, pensionIds);
        // functionSel=
        if (salaryIds != null && salaryIds.length() > 0)
            disableExpenditureType = true;
        if (pensionIds != null && pensionIds.length() > 0) {
            disableExpenditureType = true;
            enablePensionType = true;
        }

        billregister = (EgBillregister) persistenceService.find(" from EgBillregister where id=?",
                billList.get(0).getBillId());
        if (billregister.getEgBillregistermis().getFunction() != null)
            setFunctionSel(billregister.getEgBillregistermis().getFunction().getId());
        loadbankBranch(billregister.getEgBillregistermis().getFund());
        miscount = billList.size();
        if (parameters.get("paymentMode")[0].equalsIgnoreCase("RTGS")) {
            paymentService.validateForRTGSPayment(contractorList, "Contractor");
            paymentService.validateForRTGSPayment(supplierList, "Supplier");
            if (billSubType == null || billSubType.equalsIgnoreCase(""))
                paymentService.validateForRTGSPayment(contingentList,
                        FinancialConstants.STANDARD_EXPENDITURETYPE_CONTINGENT);
        }

        if (!"Auto".equalsIgnoreCase(voucherTypeForULB.readVoucherTypes("Payment"))) {
            headerFields.add("vouchernumber");
            mandatoryFields.add("vouchernumber");
        }
        if (LOGGER.isInfoEnabled())
            LOGGER.info("Expenditure type is--------------------------------- " + expType);
        voucherdate = formatter.format(new Date());
    } catch (final ValidationException e) {
        try {
            search();
        } catch (final Exception e1) {
            LOGGER.error(e.getMessage(), e1);
            final List<ValidationError> errors = new ArrayList<ValidationError>();
            errors.add(new ValidationError("exception", e1.getMessage()));
            throw new ValidationException(errors);
        }
        LOGGER.error(e.getErrors(), e);
        throw new ValidationException(e.getErrors());
    } catch (final ApplicationException e) {
        try {
            search();
        } catch (final Exception e1) {
            LOGGER.error(e.getMessage(), e1);
            final List<ValidationError> errors = new ArrayList<ValidationError>();
            errors.add(new ValidationError("exception", e1.getMessage()));
            throw new ValidationException(errors);
        }
        LOGGER.error(e.getMessage(), e);
        final List<ValidationError> errors = new ArrayList<ValidationError>();
        errors.add(new ValidationError("exception", e.getMessage()));
        throw new ValidationException(errors);
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Completed generatePayment.");
    if (getBankBalanceCheck() == null || "".equals(getBankBalanceCheck()))
        addActionMessage(getText("payment.bankbalance.controltype"));
    return "form";

}