List of usage examples for org.springframework.dao DataIntegrityViolationException getMessage
@Override
@Nullable
public String getMessage()
From source file:se.sawano.spring.examples.springdata.UserRepositoryTestIT.java
@Test(expected = DataIntegrityViolationException.class) public void repositoryShouldCheckNullConstraintForLastName() throws Exception { User user = new User("FirstName", null); try {/*from ww w . ja v a 2 s .c o m*/ userRepository.save(user); fail(); } catch (DataIntegrityViolationException e) { assertTrue("Could not find column name in error message: ", e.getMessage().contains("USER column: LASTNAME")); throw e; } }
From source file:org.openhie.openempi.dao.UserDaoTest.java
public void testUpdateUser() throws Exception { User user = dao.get(-1);/*www . ja va2 s . c o m*/ Address address = user.getAddress(); address.setAddress("new address"); dao.saveUser(user); flush(); user = dao.get(-1); assertEquals(address, user.getAddress()); assertEquals("new address", user.getAddress().getAddress()); // verify that violation occurs when adding new user with same username user.setId(null); endTransaction(); try { dao.saveUser(user); flush(); fail("saveUser didn't throw DataIntegrityViolationException"); } catch (DataIntegrityViolationException e) { assertNotNull(e); log.debug("expected exception: " + e.getMessage()); } }
From source file:org.sakaiproject.iclicker.dao.IClickerDaoImplTest.java
public void testUserKeys() { ClickerUserKey key1 = new ClickerUserKey("123456789", "aaronz"); dao.save(key1);/*from ww w . ja v a 2s . c o m*/ Long keyId = key1.getId(); assertNotNull(keyId); assertTrue(dao.countAll(ClickerUserKey.class) > 0); ClickerUserKey keyFind = dao.findOneBySearch(ClickerUserKey.class, new Search(new Restriction("userId", "aaronz"))); assertNotNull(keyFind); assertEquals(keyFind, key1); // update the key should work key1.setUserKey("aaaaaabbbbb"); dao.save(key1); // trying to save another key for this user should fail ClickerUserKey key2 = new ClickerUserKey("abcdefgh", "aaronz"); try { dao.save(key2); fail("Should have thrown an exception"); } catch (DataIntegrityViolationException e) { assertNotNull(e.getMessage()); } assertNull(key2.getId()); }
From source file:org.openhie.openempi.service.impl.UserManagerImpl.java
/** * {@inheritDoc}//from ww w .j ava 2 s . c o m */ public User saveUser(User user) throws UserExistsException { if (user.getVersion() == null) { // if new user, lowercase userId user.setUsername(user.getUsername().toLowerCase()); } // Get and prepare password management-related artifacts boolean passwordChanged = false; if (passwordEncoder != null) { // Check whether we have to encrypt (or re-encrypt) the password if (user.getVersion() == null) { // New user, always encrypt passwordChanged = true; } else { // Existing user, check password in DB String currentPassword = dao.getUserPassword(user.getUsername()); if (currentPassword == null) { passwordChanged = true; } else { if (!currentPassword.equals(user.getPassword())) { passwordChanged = true; } } } // If password was changed (or new user), encrypt it if (passwordChanged) { user.setPassword(passwordEncoder.encodePassword(user.getPassword(), null)); } } else { log.warn("PasswordEncoder not set, skipping password encryption..."); } try { return dao.saveUser(user); } catch (DataIntegrityViolationException e) { e.printStackTrace(); log.warn(e.getMessage()); throw new UserExistsException("User '" + user.getUsername() + "' already exists!"); } catch (EntityExistsException e) { // needed for JPA e.printStackTrace(); log.warn(e.getMessage()); throw new UserExistsException("User '" + user.getUsername() + "' already exists!"); } }
From source file:com.mazmy.service.driver.DefaultDriverService.java
/** * Creates a new driver.//from w ww . j a v a2 s .c o m * * @param driverDO * @return * @throws ConstraintsViolationException if a driver already exists with the given username, ... . */ @Override public DriverDO create(DriverDO driverDO) throws ConstraintsViolationException { DriverDO driver = null; try { driver = driverRepository.save(driverDO); } catch (DataIntegrityViolationException e) { LOG.warn("Some constraints are thrown due to driver creation", e); throw new ConstraintsViolationException(e.getMessage()); } return driver; }
From source file:br.com.mv.modulo.web.GenericCrudController.java
@RequestMapping(value = "/save", method = RequestMethod.POST) public String save(@ModelAttribute @Valid T t, final BindingResult bindingResult, RedirectAttributes redirectAttrs, Model model, SessionStatus status) { if (bindingResult.hasErrors()) { model.addAttribute("org.springframework.validation.BindingResult.strategy", bindingResult); model.addAttribute(getModelName(), t); return getFormPageName(); } else {//w w w .j a v a 2 s . c o m try { genericCrudBusiness.save(t); status.setComplete(); redirectAttrs.addFlashAttribute(EnumTipoMensagem.SUCESSO.getDescricao(), genericMessages.getSaveSuccess()); } catch (DataIntegrityViolationException e) { redirectAttrs.addFlashAttribute(EnumTipoMensagem.ERRO.getDescricao(), e.getMessage()); log.trace("Erro de integridade:", e); } catch (Exception e) { redirectAttrs.addFlashAttribute(EnumTipoMensagem.ERRO.getDescricao(), e.getMessage()); log.error("Erro ao salvar:", e); } } return getReturnToListURL(); }
From source file:com.francetelecom.clara.cloud.presentation.tools.PopulateDatasService.java
private Application createApp(String beanName, SampleAppFactory appFactory) throws BusinessException, MalformedURLException { // create app String appLabel = appFactory.getAppLabel(); String appCode = appFactory.getAppCode(); String appDescription = appFactory.getAppDescription(); String appVersionControl = appFactory.getApplicationVersionControl(); if (appLabel == null) { appLabel = beanName.substring(0, beanName.indexOf("LogicalModelCatalog")); }//w w w.ja v a 2 s . c o m if (appCode == null) { appCode = appLabel.substring(0, 4) + 1; } if (appDescription == null) { appDescription = "Sample app description for " + appLabel; } if (appVersionControl == null) { appVersionControl = "http://default.version.control.url"; } String applicationUID; try { applicationUID = manageApplication.createPublicApplication(appCode, appLabel, appDescription, new URL(appVersionControl), WicketSession.get().getPaasUser().getSsoId()); return manageApplication.findApplicationByUID(applicationUID); } catch (DataIntegrityViolationException dataException) { logger.error(dataException.getMessage()); throw new BusinessException(dataException); } catch (BusinessException be) { throw be; } catch (Exception e) { Throwable rootCauseException = ExceptionUtils.getRootCause(e); if (rootCauseException instanceof ConstraintViolationException) { logger.error(rootCauseException.getMessage()); throw new BusinessException(rootCauseException); } logger.error(e.getMessage()); throw new TechnicalException(e); } }
From source file:net.bhira.sample.api.dao.DepartmentDaoImpl.java
/** * @see net.bhira.sample.api.dao.DepartmentDao#save(net.bhira.sample.model.Department) *///from w w w. j a va 2 s . c om @Override public void save(Department department) throws ObjectNotFoundException, DuplicateNameException, InvalidObjectException, InvalidReferenceException { try { if (department == null) { throw new InvalidObjectException("Department object is null."); } department.initForSave(); department.validate(); boolean isNew = department.isNew(); int count = 0; if (isNew) { // for new department, 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, department.getCompanyId()); pstmt.setString(2, department.getName()); pstmt.setString(3, department.getBillingAddress()); pstmt.setString(4, department.getShippingAddress()); pstmt.setTimestamp(5, new Timestamp(department.getCreated().getTime())); pstmt.setTimestamp(6, new Timestamp(department.getModified().getTime())); pstmt.setString(7, department.getCreatedBy()); pstmt.setString(8, department.getModifiedBy()); return pstmt; } }, keyHolder); // fetch the newly created auto-increment ID department.setId(keyHolder.getKey().longValue()); LOG.debug("inserted department, count = {}, id = {}", count, department.getId()); } else { // for existing department, construct SQL update statement Object[] args = new Object[] { department.getCompanyId(), department.getName(), department.getBillingAddress(), department.getShippingAddress(), department.getModified(), department.getModifiedBy(), department.getId() }; count = jdbcTemplate.update(SQL_UPDATE, args); LOG.debug("updated department, count = {}, id = {}", count, department.getId()); } // if insert/update has 0 count value, then rollback if (count <= 0) { throw new ObjectNotFoundException("Department with ID " + department.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 (department.getContactInfo() != null) { contactInfoDao.save(department.getContactInfo()); Object[] args = new Object[] { department.getId(), department.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[] { department.getId() }); Long cinfoId = (cinfoIds != null && !cinfoIds.isEmpty()) ? cinfoIds.get(0) : null; if (department.getContactInfo() == null) { // clean up old contact info entry, if needed if (cinfoId != null) { jdbcTemplate.update(SQL_CINFO_REL_DELETE, new Object[] { department.getId() }); contactInfoDao.delete(cinfoId); } } else { // insert/update contact info entry if (cinfoId != null) { department.getContactInfo().setId(cinfoId); contactInfoDao.save(department.getContactInfo()); } else { contactInfoDao.save(department.getContactInfo()); Object[] args = new Object[] { department.getId(), department.getContactInfo().getId() }; jdbcTemplate.update(SQL_CINFO_REL_INSERT, args); } } } } catch (DataIntegrityViolationException dive) { String msg = dive.getMessage(); if (msg != null) { if (msg.contains("uq_department")) { throw new DuplicateNameException("Duplicate department name " + department.getName(), dive); } else if (msg.contains("fk_department_compy")) { throw new InvalidReferenceException("Invalid reference for attribute 'companyId'", dive); } } throw dive; } }
From source file:com.viettel.logistic.wms.service.GoodsServiceImpl.java
@Override @Transactional/* w ww . ja va 2 s .c o m*/ public ResultDTO importGoodsFile(List<GoodsDTO> lstGoodsDTO) { ResultDTO resultDTO = new ResultDTO(); GoodsPackingDTO goodPackingDTO; List<String> listSequenSe = new ArrayList<>(); try { for (GoodsDTO goodsDTO : lstGoodsDTO) { goodPackingDTO = new GoodsPackingDTO(); //Insert du lieu hang hoa resultDTO = goodsBusiness.createObject(goodsDTO); if (resultDTO.getMessage().equalsIgnoreCase(ParamUtils.SUCCESS)) { goodPackingDTO.setGoodsId(resultDTO.getId()); //Set GoodsPacking default & Insert du lieu kieu kien goodPackingDTO.setPackingDefault("1"); goodPackingDTO.setUnitTypeName(goodsDTO.getUnitType()); goodPackingDTO.setPackingVolume(goodsDTO.getVolumeReal()); goodPackingDTO.setPackingWeight(goodsDTO.getWeight()); goodPackingDTO.setPackingSize(goodsDTO.getOriginSize()); goodPackingDTO.setUnitType(goodsDTO.getUnitType()); //Get Sequences listSequenSe = goodsPackingBusiness.getListSequense("GOODS_PACKING_SEQ", 1); if (listSequenSe != null) { goodPackingDTO.setCode(listSequenSe.get(0)); goodPackingDTO.setPackingNumber(listSequenSe.get(0)); } resultDTO = goodsPackingBusiness.createObject(goodPackingDTO); } } } catch (DataIntegrityViolationException he) { resultDTO.setMessage(he.getMessage()); return resultDTO; } return resultDTO; }
From source file:net.jkratz.igdb.controller.advice.ErrorController.java
@RequestMapping(produces = "application/json") @ExceptionHandler(DataIntegrityViolationException.class) @ResponseStatus(value = HttpStatus.CONFLICT) public @ResponseBody Map<String, Object> handleDataIntegrityViolationException( DataIntegrityViolationException ex) throws IOException { logger.error("Data Integrity Error", ex); Map<String, Object> map = Maps.newHashMap(); map.put("error", "Data Integrity Error"); map.put("message", ex.getMessage()); if (ex.getRootCause() != null) { map.put("cause", ex.getRootCause().getMessage()); }/* ww w. j a va 2 s. c om*/ return map; }