@Override public String deleteBuilding(long buildingId) { AssertParam.throwIfNull(buildingId, "buildingId"); try { buildingRepository.delete(buildingId); Building deletedBuilding = buildingRepository.findOne(buildingId); boolean operationSuccessful = deletedBuilding == null; if (operationSuccessful) { return ResponseConstants.BUILDING_DELETE_SUCCESS; } else { return ResponseConstants.BUILDING_DELETE_FAILURE_DB_WRITE; } } catch (DataIntegrityViolationException e) { e.printStackTrace(); return ResponseConstants.BUILDING_DELETE_FAILURE_CONSTRAINT_VIOLATION; } }
@Override public String deleteEvaalFile(long evaalFileId) { AssertParam.throwIfNull(evaalFileId, "evaalFileId"); try{ evaalFileRepository.delete(evaalFileId); EvaalFile deletedEvaalFile = evaalFileRepository.findOne(evaalFileId); boolean operationSuccess = deletedEvaalFile == null; if(operationSuccess){ return ResponseConstants.EVAAL_DELETE_SUCCESS; }else{ return ResponseConstants.EVAAL_DELETE_FAILURE_DB_WRITE; } }catch(DataIntegrityViolationException e){ e.printStackTrace(); return ResponseConstants.EVAAL_DELETE_FAILURE_CONSTRAINT_VIOLATION; } }
@Override public JsonResult<User> register(User userToAdd) { if (userToAdd.getAccount() == null || !Util.checkEmail(userToAdd.getAccount())) { return JsonResult.<User>builder().error("注册帐号错误!").build(); } BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); final String rawPassword = userToAdd.getPassword(); userToAdd.setPassword(encoder.encode(rawPassword)); userToAdd.setLastPasswordResetDate(new Date()); Role userRole = roleRepository.findByName("ROLE_USER"); if (userRole == null){ userRole = roleRepository.save(new Role("ROLE_USER")); } userToAdd.setRoles(Collections.singletonList(userRole)); try { return JsonResult.<User>builder().data(userRepository.save(userToAdd)).build(); } catch (DataIntegrityViolationException e) { logger.debug(e.getMessage()); return JsonResult.<User>builder().error(e.getRootCause().getMessage()).build(); } }
public Serializable getPropertyById(Long id) { if (id == null) { throw new IllegalArgumentException("Cannot look up entity by null ID."); } Pair<Long, Serializable> entityPair = propertyCache.getByKey(id); if (entityPair == null) { // Remove from cache propertyCache.removeByKey(id); throw new DataIntegrityViolationException("No property value exists for ID " + id); } return entityPair.getSecond(); }
/** * Updates a property. The <b>alf_prop_root</b> entity is updated * to ensure concurrent modification is detected. * * @return Returns 1 always */ @Override public int updateValue(Long key, Serializable value) { // Remove all entries for the root PropertyRootEntity entity = getPropertyRoot(key); if (entity == null) { throw new DataIntegrityViolationException("No property root exists for ID " + key); } // Remove all links using the root deletePropertyLinks(key); // Create the new properties and update the cache createPropertyImpl(key, 0L, 0L, null, value); // Update the property root to detect concurrent modification updatePropertyRoot(entity); // Done if (logger.isDebugEnabled()) { logger.debug( "Updated property: \n" + " ID: " + key + "\n" + " Value: " + value); } return 1; }
public void updateAuditApplicationModel(Long id, Long modelId) { AuditApplicationEntity entity = getAuditApplicationById(id); if (entity == null) { throw new DataIntegrityViolationException("No audit application exists for ID " + id); } if (entity.getAuditModelId().equals(modelId)) { // There is nothing to update return; } // Update entity.setAuditModelId(modelId); updateAuditApplication(entity); }
@SuppressWarnings("unchecked") public void updateAuditApplicationDisabledPaths(Long id, Set<String> disabledPaths) { AuditApplicationEntity entity = getAuditApplicationById(id); if (entity == null) { throw new DataIntegrityViolationException("No audit application exists for ID " + id); } // Resolve the current set Long disabledPathsId = entity.getDisabledPathsId(); Set<String> oldDisabledPaths = (Set<String>) propertyValueDAO.getPropertyById(disabledPathsId); if (oldDisabledPaths.equals(disabledPaths)) { // Nothing changed return; } // Update the property propertyValueDAO.updateProperty(disabledPathsId, (Serializable) disabledPaths); // Do a precautionary update to ensure that the application row is locked appropriately updateAuditApplication(entity); }
public void updateNamespace(String oldNamespaceUri, String newNamespaceUri) { ParameterCheck.mandatory("newNamespaceUri", newNamespaceUri); Pair<Long, String> oldEntityPair = getNamespace(oldNamespaceUri); // incl. null check if (oldEntityPair == null) { throw new DataIntegrityViolationException( "Cannot update namespace as it doesn't exist: " + oldNamespaceUri); } // Find the value int updated = namespaceCache.updateValue(oldEntityPair.getFirst(), newNamespaceUri); if (updated != 1) { throw new ConcurrencyFailureException( "Incorrect update count: \n" + " Namespace: " + oldNamespaceUri + "\n" + " Rows Updated: " + updated); } // All the QNames need to be dumped qnameCache.clear(); // Done }
@Override protected int deleteContentDataEntity(Long id) { // Get the content urls try { ContentData contentData = getContentData(id).getSecond(); String contentUrl = contentData.getContentUrl(); if (contentUrl != null) { // It has been dereferenced and may be orphaned - we'll check later registerDereferencedContentUrl(contentUrl); } } catch (DataIntegrityViolationException e) { // Doesn't exist. The node doesn't enforce a FK constraint, so we protect against this. } // Issue the delete statement Map<String, Object> params = new HashMap<String, Object>(11); params.put("id", id); return template.delete(DELETE_CONTENT_DATA, params); }
public Pair<NodeVersionKey, Set<QName>> findByKey(NodeVersionKey nodeVersionKey) { Long nodeId = nodeVersionKey.getNodeId(); Set<Long> nodeIds = Collections.singleton(nodeId); Map<NodeVersionKey, Set<QName>> nodeAspectQNameIdsByVersionKey = selectNodeAspects(nodeIds); Set<QName> nodeAspectQNames = nodeAspectQNameIdsByVersionKey.get(nodeVersionKey); if (nodeAspectQNames == null) { // Didn't find a match. Is this because there are none? if (nodeAspectQNameIdsByVersionKey.size() == 0) { // This is OK. The node has no properties nodeAspectQNames = Collections.emptySet(); } else { // We found properties associated with a different node ID and version invalidateNodeCaches(nodeId); throw new DataIntegrityViolationException( "Detected stale node entry: " + nodeVersionKey + " (now " + nodeAspectQNameIdsByVersionKey.keySet() + ")"); } } // Done return new Pair<NodeVersionKey, Set<QName>>(nodeVersionKey, Collections.unmodifiableSet(nodeAspectQNames)); }
private void refreshFromGameAdminData(String address, Map<String, String> data) { String subId = data.get("SUBID"); String name = data.get("name"); GameServer server = gameServerRepository.findByAddress(address).orElseGet(this::newGameServer); boolean changed = !server.getId().equals(subId) || !server.getName().equals(name) || !server.getAddress().equals(address); server.setId(subId); server.setAddress(address); server.setName(name); try { server = gameServerRepository.save(server); if (changed) { initServerMetrics(server); } } catch (DataIntegrityViolationException e) { log.warn("Unable to update server data", e); } }
/** * Maps and handles custom behavior in the Edit page (POST mode) * @param message The information that is bound to the HTML form and used to update the database * @return Custom message sent to the client - in this case, a redirect */ @RequestMapping(value="/edit", method=RequestMethod.POST) public String submit(@ModelAttribute Message message) { try { String username = Util.getUsername(); message.setUsername(username); message = encryptMessage(message); messageRepository.save(message); // TO-DO: redirect and show a success message return "redirect:/cpanel.html"; } catch(DataIntegrityViolationException ex) // message is too long for DB field { return "redirect:/edit?error"; } }
@Override public void process(ResultItems resultItems, Task task) { List<IndustryInfo> industryInfos = resultItems.get("industryInfos"); if (industryInfos != null && industryInfos.size() > 0) { for (IndustryInfo industryInfo : industryInfos) { try { industryInfoDao.add(industryInfo); } catch (Exception e) { if (e instanceof DataIntegrityViolationException) { } else { e.printStackTrace(); } } } } }
@Override @Transactional(propagation = Propagation.MANDATORY) public void renameTermValue(Term term, String newValue) { final Taxonomy taxonomy = term.getTaxonomy(); newValue = newValue.trim(); checkTermValue(newValue, taxonomy, term.getParent()); term.setValue(newValue); try { save(term); invalidateFullValues(term); updateFullValues(taxonomy); }catch(DataIntegrityViolationException e2){ throw new DataIntegrityViolationException("SIBLING_CHECK"); } }
@Override protected DataAccessException doTranslate(String task, String sql, SQLException ex) { String sqlState = getSqlState(ex); if (sqlState != null && sqlState.length() >= 2) { String classCode = sqlState.substring(0, 2); if (logger.isDebugEnabled()) { logger.debug("Extracted SQL state class '" + classCode + "' from value '" + sqlState + "'"); } if (BAD_SQL_GRAMMAR_CODES.contains(classCode)) { return new BadSqlGrammarException(task, sql, ex); } else if (DATA_INTEGRITY_VIOLATION_CODES.contains(classCode)) { return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex); } else if (DATA_ACCESS_RESOURCE_FAILURE_CODES.contains(classCode)) { return new DataAccessResourceFailureException(buildMessage(task, sql, ex), ex); } else if (TRANSIENT_DATA_ACCESS_RESOURCE_CODES.contains(classCode)) { return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex); } else if (CONCURRENCY_FAILURE_CODES.contains(classCode)) { return new ConcurrencyFailureException(buildMessage(task, sql, ex), ex); } } return null; }
@RequestMapping(method=RequestMethod.POST, value="/cm/simple/relations") @ResponseBody 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()); } } }
/** * 新增/修改心跳,用ON DUPLICATE KEY UPDATE */ @Override public int register(JsfIns ins) throws Exception { if (ins != null) { try { String insKey = jsfInsDao.getInsKeyByInsKey(ins.getInsKey()); //如果实例不存在,或者实例状态为死亡,或者被逻辑删除,就需要新建或更新下实例 if (insKey == null || insKey.isEmpty()) { if (isSaveAppIns) { int jsfAppInsId = getJsfAppInsIdAndSaveAppIns(ins); ins.setJsfAppInsId(jsfAppInsId); }else { saveAppByJsfIns(ins); } int result = jsfInsDao.create(ins, InstanceStatus.online.value()); DBLog.info("add instance:{}", ins); return result; } else { DBLog.info("add instance is cancel, instance is exists : {}", ins); } } catch (DataIntegrityViolationException e) { logger.error("instance key:{}, error:{}", ins.getInsKey(), e.getMessage()); } } return 0; }
@Override public Response toResponse(final DataIntegrityViolationException exception) { log.error("DataIntegrityViolationException exception", exception); final Throwable root = ExceptionUtils.getRootCause(exception); Matcher matcher = PATTERN_FOREIGN_KEY.matcher(StringUtils.trimToEmpty(root.getMessage())); final String code; if (matcher.find()) { // Foreign key code = "foreign"; } else { matcher = PATTERN_UNICITY.matcher(root.getMessage()); if (matcher.find()) { // Duplicate entry code = "unicity"; } else { // Another SQL error code = "unknown"; matcher = null; } } return toResponse(Status.PRECONDITION_FAILED, newServerError(exception, matcher, code)); }
@Test(expected = ServiceException.class) public void testDuplicateLock(){ when(bizConfig.isNamespaceLockSwitchOff()).thenReturn(false); when(namespaceService.findOne(NAMESPACE_ID)).thenReturn(mockNamespace()); when(namespaceLockService.findLock(NAMESPACE_ID)).thenReturn(null); when(namespaceLockService.tryLock(any())).thenThrow(DataIntegrityViolationException.class); namespaceLockAspect.acquireLock(NAMESPACE_ID, CURRENT_USER); verify(bizConfig).isNamespaceLockSwitchOff(); verify(namespaceService).findOne(NAMESPACE_ID); verify(namespaceLockService, times(2)).findLock(NAMESPACE_ID); verify(namespaceLockService).tryLock(any()); }
private long prepareInstanceId(InstanceConfigAuditModel auditModel) { Instance instance = instanceService.findInstance(auditModel.getAppId(), auditModel .getClusterName(), auditModel.getDataCenter(), auditModel.getIp()); if (instance != null) { return instance.getId(); } instance = new Instance(); instance.setAppId(auditModel.getAppId()); instance.setClusterName(auditModel.getClusterName()); instance.setDataCenter(auditModel.getDataCenter()); instance.setIp(auditModel.getIp()); try { return instanceService.createInstance(instance).getId(); } catch (DataIntegrityViolationException ex) { //return the one exists return instanceService.findInstance(instance.getAppId(), instance.getClusterName(), instance.getDataCenter(), instance.getIp()).getId(); } }
@Test @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) public void testFailDeleteReferenceGeneFile() throws IOException { Resource resource = context.getResource(A3_FA_PATH); ReferenceRegistrationRequest request = new ReferenceRegistrationRequest(); request.setName("testReference3"); request.setPath(resource.getFile().getPath()); request.setType(BiologicalDataItemResourceType.FILE); FeatureIndexedFileRegistrationRequest geneRequest = new FeatureIndexedFileRegistrationRequest(); resource = context.getResource("classpath:templates/genes_sorted.gtf"); geneRequest.setPath(resource.getFile().getAbsolutePath()); request.setGeneFileRequest(geneRequest); Reference testRef = referenceManager.registerGenome(request); assertNotNull(testRef); assertNotNull(testRef.getGeneFile()); TestUtils.assertFail(() -> gffManager.unregisterGeneFile(testRef.getGeneFile().getId()), Collections.singletonList(DataIntegrityViolationException.class)); }
/** * Inserts a TN for a transfer with the specified trace number, for the current service client * @return true if the TN was inserted */ private boolean insertTN(final Long clientId, final String traceNumber) { return transactionHelper.runInNewTransaction(new TransactionCallback<Boolean>() { @Override public Boolean doInTransaction(final TransactionStatus status) { final TraceNumber tn = new TraceNumber(); tn.setDate(Calendar.getInstance()); tn.setClientId(clientId); tn.setTraceNumber(traceNumber); try { traceNumberDao.insert(tn); return true; } catch (DaoException e) { status.setRollbackOnly(); if (ExceptionUtils.indexOfThrowable(e, DataIntegrityViolationException.class) != -1) { // the unique constraint was violated - It means the trace number was already stored by a payment or by other reverse. // If it was inserted by a payment then we must reverse it. // If was inserted by other reverse then just ignore it. return false; } else { throw e; } } } }); }
@Override public boolean isOptimisticLocking(Exception cause) { Iterator<Throwable> it = ObjectHelper.createExceptionIterator(cause); while (it.hasNext()) { Throwable throwable = it.next(); // if its a SQL exception if (throwable instanceof SQLException) { SQLException se = (SQLException) throwable; if (isConstraintViolation(se)) { return true; } } if (throwable instanceof DataIntegrityViolationException) { return true; } // fallback to names String name = throwable.getClass().getName(); if (name.contains("ConstraintViolation") || hasClassName(name)) { return true; } } return false; }
@RequestMapping(method = POST) @PreAuthorize("isAuthenticated()") @ResponseBody @ResponseStatus(CREATED) public String create( @RequestParam("assetData") final MultipartFile assetData ) throws IOException { // Check duplicates final GridFSDBFile file = this.gridFs.findOne(Query.query(Criteria.where("filename").is(assetData.getOriginalFilename()))); if (file != null) { throw new DataIntegrityViolationException(String.format("Asset with name '%s' already exists", assetData.getOriginalFilename())); } else { try (InputStream usedStream = TikaInputStream.get(assetData.getInputStream())) { MediaType mediaType = null; try { mediaType = MediaType.parse(tika.detect(usedStream, assetData.getOriginalFilename())); } catch (IOException e) { log.warn("Could not detect content type", e); } this.gridFs.store(assetData.getInputStream(), assetData.getOriginalFilename(), Optional.ofNullable(mediaType).map(MediaType::toString).orElse(null)); return assetData.getOriginalFilename(); } } }
@PreAuthorize("hasAuthority('ADMIN')") @RequestMapping(value = "/user/create", method = RequestMethod.POST) public String handleUserCreateForm(@Valid @ModelAttribute("form") UserCreateForm form, BindingResult bindingResult) { LOGGER.debug("Processing user create form={}, bindingResult={}", form, bindingResult); if (bindingResult.hasErrors()) { return "userCreationPage"; } try { userService.create(form); } catch (DataIntegrityViolationException e) { LOGGER.warn("Exception occurred when trying to save the user, assuming duplicate email", e); bindingResult.reject("email.exists", "Email already exists"); return "userCreationPage"; } return "redirect:/users"; }
@RequestMapping(value = "/user/create", method = RequestMethod.POST) public String handleUserCreateForm(@Valid @ModelAttribute("form") UserCreateForm form, BindingResult bindingResult) { LOGGER.debug("Processing user create form={}, bindingResult={}", form, bindingResult); if (bindingResult.hasErrors()) { // failed validation return "createUser"; } try { final UserRole userRole=this.userManager.getUserRole(form.getRoleName()); form.setRole(userRole); this.userManager.saveUser(new User(form)); } catch (DataIntegrityViolationException e) { // probably email already exists - very rare case when multiple admins are adding same user // at the same time and form validation has passed for more than one of them. LOGGER.warn("Exception occurred when trying to save the user, assuming duplicate email", e); bindingResult.reject("email.exists", "Email already exists"); return "createUser"; } // ok, redirect return "redirect:/users"; }
@PreAuthorize("hasAuthority('ADMIN')") @RequestMapping(value = "/user/create", method = RequestMethod.POST) public String handleUserCreateForm(@Valid @ModelAttribute("form") MaUserEntity form, BindingResult bindingResult) { LOGGER.debug("[Myazure Weixin]: Processing user create form={}, bindingResult={}", form, bindingResult); if (bindingResult.hasErrors()) { // failed validation return "user_create"; } try { userService.create(form); } catch (DataIntegrityViolationException e) { LOGGER.warn("[Myazure Weixin]: Exception occurred when trying to save the user, assuming duplicate user name", e); bindingResult.rejectValue("userName", "userName", "name already exists"); return "user_create"; } return "redirect:/users"; }
/** * Creates a new Entity * * @return a reply... * @throws McBasicRestException */ protected ResponseEntity<T> createEntity(HttpServletRequest request, String orgMrn, T input) throws McBasicRestException { Organization org = this.organizationService.getOrganizationByMrn(orgMrn); if (org != null) { // Check that the entity being created belongs to the organization if (!MrnUtil.getOrgShortNameFromOrgMrn(orgMrn).equalsIgnoreCase(MrnUtil.getOrgShortNameFromEntityMrn(input.getMrn()))) { throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.MISSING_RIGHTS, request.getServletPath()); } input.setIdOrganization(org.getId()); try { input.setMrn(input.getMrn().toLowerCase()); T newEntity = this.entityService.save(input); return new ResponseEntity<>(newEntity, HttpStatus.OK); } catch (DataIntegrityViolationException e) { throw new McBasicRestException(HttpStatus.CONFLICT, e.getRootCause().getMessage(), request.getServletPath()); } } else { throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND, request.getServletPath()); } }
@Test public void testFallbackExceptionTranslation() throws HibernateException { SQLException sqlEx = new SQLException("argh", "27"); final GenericJDBCException gjex = new GenericJDBCException("mymsg", sqlEx); try { hibernateTemplate.execute(new HibernateCallback<Object>() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { throw gjex; } }); fail("Should have thrown DataIntegrityViolationException"); } catch (DataIntegrityViolationException ex) { // expected assertEquals(sqlEx, ex.getCause()); assertTrue(ex.getMessage().indexOf("mymsg") != -1); } }
/** * Map the passed exception to an error message. * Any potential exception (such as business exception) requiring a special message should be mapped here as well. */ public void error(Throwable e) { if (ExceptionUtil.isCausedBy(e, DataIntegrityViolationException.class)) { this.error("error_unique_constraint_violation"); } else if (ExceptionUtil.isCausedBy(e, OptimisticLockingFailureException.class)) { this.error("error_concurrent_modification"); } else if (ExceptionUtil.isCausedBy(e, AccessDeniedException.class)) { // works only if the spring security filter is before the exception filter, // that is if the exception filter handles the exception first. this.error("error_access_denied"); } else { this.error("status_exception_ko", getMessage(e)); log.error("====> !!ATTENTION!! DEVELOPERS should provide a less generic error message for the cause of this exception <===="); } }
@SuppressWarnings("serial") @Test public void customTranslateMethodTranslation() { final String TASK = "TASK"; final String SQL = "SQL SELECT *"; final DataAccessException customDex = new DataAccessException("") {}; final SQLException badSqlEx = new SQLException("", "", 1); SQLException intVioEx = new SQLException("", "", 6); SQLErrorCodeSQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator() { @Override protected DataAccessException customTranslate(String task, String sql, SQLException sqlex) { assertEquals(TASK, task); assertEquals(SQL, sql); return (sqlex == badSqlEx) ? customDex : null; } }; sext.setSqlErrorCodes(ERROR_CODES); // Shouldn't custom translate this assertEquals(customDex, sext.translate(TASK, SQL, badSqlEx)); DataIntegrityViolationException diex = (DataIntegrityViolationException) sext.translate(TASK, SQL, intVioEx); assertEquals(intVioEx, diex.getCause()); }
@ExceptionHandler(DataIntegrityViolationException.class) public ResponseEntity<?> dataIntegrityViolationException(DataIntegrityViolationException dve, HttpServletRequest request) { final ErrorDetail errorDetail = new ErrorDetail(); errorDetail.setTimeStamp(new Date().getTime()); errorDetail.setStatus(HttpStatus.NOT_ACCEPTABLE.value()); errorDetail.setTitle("Fields arleady exists " + dve.getCause().getCause().getMessage()); final String fieldValue = dve.getCause().getCause().getMessage().split("'")[1]; errorDetail.setDetail(fieldValue + " already exists. please use different one"); errorDetail.setDeveloperMessage(dve.getClass().getName()); final List<ValidationError> validationErrorList = new ArrayList<ValidationError>(); validationErrorList.add(new ValidationError(fieldValue, "Must be unique and already taken ")); errorDetail.getErrors().put("ValidationErrors", validationErrorList); return new ResponseEntity<>(errorDetail, null, HttpStatus.NOT_ACCEPTABLE); }
@Test(expected = DataIntegrityViolationException.class) public void addConnectionDuplicate() { Connection<TestFacebookApi> connection = connectionFactory.createConnection(new AccessGrant("123456789", null, "987654321", 3600L)); connectionRepository.addConnection(connection); connectionRepository.addConnection(connection); socialUserConnectionRepository.flush(); }
private void validateDeleteProperty(final String tenantDomain, final PropertyDefinition propDef) { final QName propName = propDef.getName(); // We need a separate transaction to do the qname delete "check" transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>() { @Override public Void execute() throws Throwable { return TenantUtil.runAsTenant(new TenantRunAsWork<Void>() { @Override public Void doWork() throws Exception { try { // The property QName may not have been created in the database if no // properties have been created that use it, so check first and then // try to delete it. if(qnameDAO.getQName(propName) != null) { qnameDAO.deleteQName(propName); } } catch(DataIntegrityViolationException e) { // catch data integrity violation e.g. foreign key constraint exception logger.debug(e); throw new ModelInUseException("Failed to validate property delete, property " + propName + " is in use"); } return null; } }, tenantDomain); } }, false, true); }