Example usage for org.springframework.dao DataIntegrityViolationException getMessage

List of usage examples for org.springframework.dao DataIntegrityViolationException getMessage

Introduction

In this page you can find the example usage for org.springframework.dao DataIntegrityViolationException getMessage.

Prototype

@Override
@Nullable
public String getMessage() 

Source Link

Document

Return the detail message, including the message from the nested exception if there is one.

Usage

From source file:net.bhira.sample.api.dao.EmployeeDaoImpl.java

/**
 * @see net.bhira.sample.api.dao.EmployeeDao#save(net.bhira.sample.model.Employee)
 *///from   w  w  w . j a  v  a  2 s. co  m
@Override
public void save(Employee employee)
        throws ObjectNotFoundException, InvalidObjectException, InvalidReferenceException {
    try {
        if (employee == null) {
            throw new InvalidObjectException("Employee object is null.");
        }

        employee.initForSave();
        employee.validate();
        boolean isNew = employee.isNew();
        int count = 0;

        if (isNew) {
            // for new employee, construct SQL insert statement
            KeyHolder keyHolder = new GeneratedKeyHolder();
            count = jdbcTemplate.update(new PreparedStatementCreator() {
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement pstmt = connection.prepareStatement(SQL_INSERT,
                            Statement.RETURN_GENERATED_KEYS);
                    pstmt.setLong(1, employee.getCompanyId());
                    if (employee.getDepartmentId() == 0) {
                        pstmt.setNull(2, java.sql.Types.BIGINT);
                    } else {
                        pstmt.setLong(2, employee.getDepartmentId());
                    }
                    pstmt.setString(3, employee.getName());
                    if (employee.getManagerId() == 0) {
                        pstmt.setNull(4, java.sql.Types.BIGINT);
                    } else {
                        pstmt.setLong(4, employee.getManagerId());
                    }
                    pstmt.setString(5, employee.getSalutation());
                    pstmt.setString(6, employee.getSex() == null ? null : employee.getSex().toString());
                    pstmt.setDate(7, employee.getDOB() == null ? null : new Date(employee.getDOB().getTime()));
                    pstmt.setString(8, employee.getTitle());
                    pstmt.setString(9, employee.getAddress());
                    pstmt.setTimestamp(10, new Timestamp(employee.getCreated().getTime()));
                    pstmt.setTimestamp(11, new Timestamp(employee.getModified().getTime()));
                    pstmt.setString(12, employee.getCreatedBy());
                    pstmt.setString(13, employee.getModifiedBy());
                    return pstmt;
                }
            }, keyHolder);

            // fetch the newly created auto-increment ID
            employee.setId(keyHolder.getKey().longValue());
            LOG.debug("inserted employee, count = {}, id = {}", count, employee.getId());

        } else {
            // for existing employee, construct SQL update statement
            Long deptId = employee.getDepartmentId() == 0 ? null : employee.getDepartmentId();
            Long mgrId = employee.getManagerId() == 0 ? null : employee.getManagerId();
            String sex = employee.getSex() == null ? null : employee.getSex().toString();
            Date dob = employee.getDOB() == null ? null : new Date(employee.getDOB().getTime());
            Object[] args = new Object[] { employee.getCompanyId(), deptId, employee.getName(), mgrId,
                    employee.getSalutation(), sex, dob, employee.getTitle(), employee.getAddress(),
                    employee.getModified(), employee.getModifiedBy(), employee.getId() };
            count = jdbcTemplate.update(SQL_UPDATE, args);
            LOG.debug("updated employee, count = {}, id = {}", count, employee.getId());
        }

        // if insert/update has 0 count value, then rollback
        if (count <= 0) {
            throw new ObjectNotFoundException("Employee with ID " + employee.getId() + " was not found.");
        }

        // update dependent entries, as needed
        if (isNew) {

            // for new model if there is contact info, save it to contact info table and then
            // add entry in relationship table
            if (employee.getContactInfo() != null) {
                contactInfoDao.save(employee.getContactInfo());
                Object[] args = new Object[] { employee.getId(), employee.getContactInfo().getId() };
                jdbcTemplate.update(SQL_CINFO_REL_INSERT, args);
            }

        } else {
            // for existing model, fetch contact info ID from relationship table
            List<Long> cinfoIds = jdbcTemplate.queryForList(SQL_CINFO_REL_LOAD, Long.class,
                    new Object[] { employee.getId() });
            Long cinfoId = (cinfoIds != null && !cinfoIds.isEmpty()) ? cinfoIds.get(0) : null;

            if (employee.getContactInfo() == null) {
                // clean up old contact info entry, if needed
                if (cinfoId != null) {
                    jdbcTemplate.update(SQL_CINFO_REL_DELETE, new Object[] { employee.getId() });
                    contactInfoDao.delete(cinfoId);
                }

            } else {
                // insert/update contact info entry
                if (cinfoId != null) {
                    employee.getContactInfo().setId(cinfoId);
                    contactInfoDao.save(employee.getContactInfo());
                } else {
                    contactInfoDao.save(employee.getContactInfo());
                    Object[] args = new Object[] { employee.getId(), employee.getContactInfo().getId() };
                    jdbcTemplate.update(SQL_CINFO_REL_INSERT, args);
                }
            }
        }

    } catch (DataIntegrityViolationException dive) {
        String msg = dive.getMessage();
        if (msg != null) {
            if (msg.contains("fk_employee_compy")) {
                throw new InvalidReferenceException("Invalid reference for attribute 'companyId'", dive);
            } else if (msg.contains("fk_employee_dept")) {
                throw new InvalidReferenceException("Invalid reference for attribute 'departmentId'", dive);
            } else if (msg.contains("fk_employee_mgr")) {
                throw new InvalidReferenceException("Invalid reference for attribute 'managerId'", dive);
            }
        }
        throw dive;
    }
}

From source file:org.openmrs.module.vcttrac.web.controller.VCTClientViewController.java

private void editCodeTest(HttpServletRequest request, ModelAndView mav) {
    //      DateFormat df = Context.getDateFormat();
    //      boolean cseCaught = false;
    try {/*from  www .  j a  v  a 2 s .c  o  m*/
        VCTModuleService service = (VCTModuleService) ServiceContext.getInstance()
                .getService(VCTModuleService.class);

        if (request.getParameter("clientCode") != null && request.getParameter("testCode") != null
                && request.getParameter("testCode").compareTo("") != 0) {
            VCTClient client = service.getClientById(Integer.valueOf(request.getParameter("clientCode")));
            if (null != client) {
                client.setCodeTest(request.getParameter("testCode"));
                client.setDateChanged(new Date());
                client.setChangedBy(Context.getAuthenticatedUser());
                service.saveVCTClient(client);

                //save sample code
                //saveSampleCode(client);
            }
        }

        //         String msg = getMessageSourceAccessor().getMessage();
        request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Form.saved");
    } catch (ConstraintViolationException cve) {
        //         cseCaught = true;
        log.info(">>>>>>>VCT>>Save>>Code>>Test>> " + cve.getMessage());
        cve.printStackTrace();
        request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                "The CODE TEST '" + request.getParameter("testCode") + "' is arleady in use.");

    } catch (DataIntegrityViolationException dive) {
        //         cseCaught = true;
        log.info(">>>>>>>VCT>>Save>>Code>>Test>> " + dive.getMessage());
        dive.printStackTrace();
        request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                "The CODE TEST '" + request.getParameter("testCode") + "' is arleady in use.");

    } catch (Exception e) {
        log.info(">>>>>>>VCT>>Save>>Code>>Test>> " + e.getMessage());
        e.printStackTrace();
        //if (!cseCaught)
        request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                "An error occured when trying to save the CODE TEST, please check your log file.");

    }
}

From source file:org.openmrs.module.vcttrac.web.controller.VCTClientViewController.java

/**
 * Auto generated method comment/*from  ww w .j  a v  a 2  s  .  c om*/
 * 
 * @param request
 * @param mav
 * @throws ParseException
 */
private void saveCodeTest(HttpServletRequest request, ModelAndView mav) {
    DateFormat df = Context.getDateFormat();
    boolean cseCaught = false;
    try {
        VCTModuleService service = (VCTModuleService) ServiceContext.getInstance()
                .getService(VCTModuleService.class);

        if (request.getParameter("clientId") != null && request.getParameter("clientCode") != null
                && request.getParameter("clientCode").compareTo("") != 0) {
            VCTClient client = service.getClientById(Integer.valueOf(request.getParameter("clientId")));
            if (null != client) {
                client.setCodeTest(request.getParameter("testCode"));
                Obs counselingObs = client.getCounselingObs();

                Date obsDatetime = df.parse(request.getParameter("obsDate"));

                Obs hivTestingDone = new Obs();
                hivTestingDone.setPerson(client.getClient());
                hivTestingDone.setCreator(Context.getAuthenticatedUser());
                hivTestingDone.setDateCreated(new Date());
                hivTestingDone.setLocation(counselingObs.getLocation());
                hivTestingDone.setObsDatetime(obsDatetime);
                hivTestingDone.setConcept(Context.getConceptService()
                        .getConcept(VCTConfigurationUtil.getHivTestingDoneConceptId()));
                hivTestingDone.setValueNumeric(1.0);

                counselingObs.addGroupMember(hivTestingDone);

                Context.getObsService().saveObs(hivTestingDone, "Client has been tested");

                //               client.setCounselingObs(newCounselingObs);
                service.saveVCTClient(client);

                //save sample code
                saveSampleCode(client);
            }
        }

        String msg = getMessageSourceAccessor().getMessage("Form.saved");
        request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR, msg);
    } catch (ConstraintViolationException cve) {
        cseCaught = true;
        log.info(">>>>>>>VCT>>Save>>Code>>Test>> " + cve.getMessage());
        cve.printStackTrace();
        request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                "The CODE TEST '" + request.getParameter("testCode") + "' is arleady in use.");

    } catch (DataIntegrityViolationException dive) {
        cseCaught = true;
        log.info(">>>>>>>VCT>>Save>>Code>>Test>> " + dive.getMessage());
        dive.printStackTrace();
        request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                "The CODE TEST '" + request.getParameter("testCode") + "' is arleady in use.");

    } catch (Exception e) {
        log.info(">>>>>>>VCT>>Save>>Code>>Test>> " + e.getMessage());
        e.printStackTrace();
        //if (!cseCaught)
        request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                "An error occured when trying to save the CODE TEST, please check your log file.");

    }
}

From source file:com.glaf.oa.assesscontent.web.springmvc.AssesscontentController.java

/**
 * //from  www.j av  a  2  s .  co  m
 * 
 * @param request
 * @param modelMap
 * @throws UnsupportedEncodingException
 */
@ResponseBody
@RequestMapping("/delete")
public ModelAndView delete(HttpServletRequest request, ModelMap modelMap) throws IOException {
    // JSONObject rowJSON = new JSONObject();

    // LoginContext loginContext = RequestUtils.getLoginContext( request );
    // Map<String, Object> params = RequestUtils.getParameterMap( request );
    Long contentid = null;
    String scontentId = request.getParameter("contentid");
    if (scontentId == null) {
        modelMap.addAttribute("message", "");
        return new ModelAndView("/oa/assessquestion/makeAssessIndex", modelMap);
    }
    contentid = Long.valueOf(scontentId);
    try {
        assesscontentService.deleteById(contentid);

    } catch (DataIntegrityViolationException de) {
        de.printStackTrace();
        logger.error("AssesscontentController.class,method=delete,?=" + de.getMessage());
        modelMap.addAttribute("message", "?");
        return new ModelAndView("/oa/assessquestion/makeAssessIndex", modelMap);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("AssesscontentController.class,method=delete,=" + e.getMessage());
        modelMap.addAttribute("message", "");
        return new ModelAndView("/oa/assessquestion/makeAssessIndex", modelMap);
    }
    return new ModelAndView("/oa/assessquestion/makeAssessIndex", modelMap);

}

From source file:com.glaf.oa.assesscontent.web.springmvc.AssesscontentController.java

/**
 * // ww w . ja v  a 2 s. c om
 * 
 * @param request
 * @param modelMap
 * @throws UnsupportedEncodingException
 */
@ResponseBody
@RequestMapping("/deleteType")
public ModelAndView deleteType(HttpServletRequest request, ModelMap modelMap) throws IOException {
    Long assesssortid = null;
    String assesssortId = request.getParameter("assesssortid");
    if (assesssortId == null) {
        modelMap.addAttribute("message", "");
        return new ModelAndView("/oa/assessquestion/makeAssessIndex", modelMap);
    }
    assesssortid = Long.valueOf(assesssortId);
    try {
        assesscontentService.deleteByParentId(assesssortid);
        assesssortService.deleteById(assesssortid);
    } catch (DataIntegrityViolationException de) {
        de.printStackTrace();
        logger.error(
                "AssesscontentController.class,method=deleteType,?=" + de.getMessage());
        modelMap.addAttribute("message", "?");
        return new ModelAndView("/oa/assessquestion/makeAssessIndex", modelMap);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("AssesscontentController.class,method=deleteType,=" + e.getMessage());
        modelMap.addAttribute("message", "");
        return new ModelAndView("/oa/assessquestion/makeAssessIndex", modelMap);
    }
    return new ModelAndView("/oa/assessquestion/makeAssessIndex", modelMap);

}

From source file:om.edu.squ.squportal.portlet.dps.role.db.RoleDbImpl.java

/**
 * //w ww.ja  va  2s  .  c  om
 * method name  : getApprovalStatus
 * @param studentNo
 * @param formName
 * @param roleName
 * @param locale
 * @return
 * RoleDbImpl
 * return type  : ApprovalStatus
 * 
 * purpose      : Get Approval Status Description 
 *               of a particular student 
 *               for a particular form 
 *               and a particular role of an approver
 *
 * Date          :   Jul 17, 2017 12:00:24 PM
 * @throws NotCorrectDBRecordException 
 */
public ApprovalStatus getApprovalStatus(String studentNo, String formName, String roleName, Locale locale)
        throws NotCorrectDBRecordException {
    String PROP_SQL_ROLE_STATUS_DESCRIPTION = queryPropsCommonRole
            .getProperty(Constants.CONST_PROP_SQL_ROLE_STATUS_DESCRIPTION);
    RowMapper<ApprovalStatus> rowMapper = new RowMapper<ApprovalStatus>() {

        @Override
        public ApprovalStatus mapRow(ResultSet rs, int rowNum) throws SQLException {
            ApprovalStatus approvalStatus = new ApprovalStatus();
            approvalStatus.setStatusCodeName(rs.getString(Constants.CONST_COLMN_STATUS_CODE_NAME));
            approvalStatus.setStatusDescription(rs.getString(Constants.CONST_COLMN_STATUS_DESC));
            approvalStatus.setStatusDescEng(rs.getString(Constants.CONST_COLMN_STATUS_DESC_EN));
            approvalStatus.setStatusDescAr(rs.getString(Constants.CONST_COLMN_STATUS_DESC_AR));
            return approvalStatus;
        }
    };

    Map<String, String> mapParamsRole = new HashMap<String, String>();
    mapParamsRole.put("paramFormName", formName);
    mapParamsRole.put("paramRoleName", roleName);
    mapParamsRole.put("paramStudentNo", studentNo);
    mapParamsRole.put("paramLocale", locale.getLanguage());

    try {
        return nPJdbcTemplDps.queryForObject(PROP_SQL_ROLE_STATUS_DESCRIPTION, mapParamsRole, rowMapper);
    } catch (DataIntegrityViolationException ex) {
        logger.error(
                "DB Error: Data Integrity Violation Exception -- throws at DB layer and catched at service");
        throw new NotCorrectDBRecordException(ex.getMessage());
    } catch (EmptyResultDataAccessException ex) {
        logger.error(
                "DB Error: Empty Result DataAccess Exception -- throws at DB layer and catched at service");
        throw new NotCorrectDBRecordException(ex.getMessage());
    }
}

From source file:org.openlmis.fulfillment.web.errorhandler.ServiceErrorHandling.java

/**
 * Handles data integrity violation exception.
 *
 * @param ex the data integrity exception
 * @return the user-oriented error message.
 */// ww w .j  a  v  a2 s. co  m
@ExceptionHandler(DataIntegrityViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<Message.LocalizedMessage> handleDataIntegrityViolation(
        DataIntegrityViolationException ex) {
    if (ex.getCause() instanceof ConstraintViolationException) {
        ConstraintViolationException cause = (ConstraintViolationException) ex.getCause();
        String messageKey = CONSTRAINT_MAP.get(cause.getConstraintName());
        if (messageKey != null) {
            logger.error(CONSTRAINT_VIOLATION, ex);
            return new ResponseEntity<>(getLocalizedMessage(new Message(messageKey)), HttpStatus.BAD_REQUEST);
        } else {
            return new ResponseEntity<>(
                    logErrorAndRespond(CONSTRAINT_VIOLATION, MessageKeys.CONSTRAINT_VIOLATION, ex.getMessage()),
                    HttpStatus.BAD_REQUEST);
        }
    }

    return new ResponseEntity<>(
            logErrorAndRespond("Data integrity violation", DATA_INTEGRITY_VIOLATION, ex.getMessage()),
            CONFLICT);
}

From source file:com.gst.accounting.rule.service.AccountingRuleWritePlatformServiceJpaRepositoryImpl.java

/**
 * @param command//from  w w w.  j  a  v a2 s  .com
 * @param dve
 */
private void handleAccountingRuleIntegrityIssues(final JsonCommand command,
        final DataIntegrityViolationException dve) {
    final Throwable realCause = dve.getMostSpecificCause();
    if (realCause.getMessage().contains("accounting_rule_name_unique")) {
        throw new AccountingRuleDuplicateException(
                command.stringValueOfParameterNamed(AccountingRuleJsonInputParams.NAME.getValue()));
    } else if (realCause.getMessage().contains("UNIQUE_ACCOUNT_RULE_TAGS")) {
        throw new AccountingRuleDuplicateException();
    }

    logger.error(dve.getMessage(), dve);
    throw new PlatformDataIntegrityException("error.msg.accounting.rule.unknown.data.integrity.issue",
            "Unknown data integrity issue with resource Accounting Rule: " + realCause.getMessage());
}

From source file:com.oneops.cms.ws.rest.CmRestController.java

@RequestMapping(method = RequestMethod.POST, value = "/cm/simple/relations")
@ResponseBody/*  w ww .jav  a  2 s  .co  m*/
public CmsCIRelationSimple createCIRelation(@RequestParam(value = "value", required = false) String valueType,
        @RequestBody CmsCIRelationSimple relSimple,
        @RequestHeader(value = "X-Cms-Scope", required = false) String scope,
        @RequestHeader(value = "X-Cms-User", required = false) String userId) throws CIValidationException {

    scopeVerifier.verifyScope(scope, relSimple);

    CmsCIRelation rel = cmsUtil.custCIRelationSimple2CIRelation(relSimple, valueType);
    rel.setCreatedBy(userId);
    try {
        CmsCIRelation newRel = cmManager.createRelation(rel);
        return cmsUtil.custCIRelation2CIRelationSimple(newRel, valueType, false);
    } catch (DataIntegrityViolationException dive) {
        if (dive instanceof DuplicateKeyException) {
            throw new CIValidationException(CmsError.CMS_DUPCI_NAME_ERROR, dive.getMessage());
        } else {
            throw new CmsException(CmsError.CMS_EXCEPTION, dive.getMessage());
        }
    }
}

From source file:com.oneops.cms.ws.rest.CmRestController.java

@RequestMapping(method = RequestMethod.POST, value = "/cm/simple/cis")
@ResponseBody//w  ww  .ja  va2  s. c  om
public CmsCISimple createCISimple(@RequestParam(value = "value", required = false) String valueType,
        @RequestBody CmsCISimple ciSimple, @RequestHeader(value = "X-Cms-Scope", required = false) String scope,
        @RequestHeader(value = "X-Cms-User", required = false) String userId) throws CIValidationException {

    scopeVerifier.verifyScope(scope, ciSimple);

    CmsCI newCi = cmsUtil.custCISimple2CI(ciSimple, valueType);
    newCi.setCiId(0);
    newCi.setCiGoid(null);
    newCi.setCreatedBy(userId);
    try {
        CmsCI ci = cmManager.createCI(newCi);
        logger.debug(ci.getCiId());
        return cmsUtil.custCI2CISimple(ci, valueType);
    } catch (DataIntegrityViolationException dive) {
        if (dive instanceof DuplicateKeyException) {
            throw new CIValidationException(CmsError.CMS_DUPCI_NAME_ERROR, dive.getMessage());
        } else {
            throw new CmsException(CmsError.CMS_EXCEPTION, dive.getMessage());
        }
    }
}