@Test @SuppressWarnings("serial") public void testConvertJpaPersistenceException() { EntityNotFoundException entityNotFound = new EntityNotFoundException(); assertSame(JpaObjectRetrievalFailureException.class, EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityNotFound).getClass()); NoResultException noResult = new NoResultException(); assertSame(EmptyResultDataAccessException.class, EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(noResult).getClass()); NonUniqueResultException nonUniqueResult = new NonUniqueResultException(); assertSame(IncorrectResultSizeDataAccessException.class, EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(nonUniqueResult).getClass()); OptimisticLockException optimisticLock = new OptimisticLockException(); assertSame(JpaOptimisticLockingFailureException.class, EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(optimisticLock).getClass()); EntityExistsException entityExists = new EntityExistsException("foo"); assertSame(DataIntegrityViolationException.class, EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityExists).getClass()); TransactionRequiredException transactionRequired = new TransactionRequiredException("foo"); assertSame(InvalidDataAccessApiUsageException.class, EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(transactionRequired).getClass()); PersistenceException unknown = new PersistenceException() { }; assertSame(JpaSystemException.class, EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(unknown).getClass()); }
final EntityExistsException converted = new EntityExistsException( cause.getMessage() ); handlePersistenceException( converted ); return converted;
@Override public Exception translate(Throwable e) { if (e.getCause() != null && isRelevantCause(e.getCause())) { return translate(e.getCause()); } Class<? extends Throwable> c = e.getClass(); if (c.equals(org.apache.openjpa.persistence.EntityExistsException.class)) { return new javax.persistence.EntityExistsException(e.getMessage(), e); } else if (c.equals(javax.validation.ConstraintViolationException.class)) { return (Exception) e; } LOG.info("Cannot translate '{}' to specific subtype, will return generic PersistenceException", e.getClass().getName()); return new PersistenceException(e); }
} catch (final SQLException e) { if (e.getSQLState().equals("23000") && e.getErrorCode() == 1062) { throw new EntityExistsException("Entity already exists: ", e); } else { throw new CloudRuntimeException("DB Exception on: " + pstmt, e);
} catch (final SQLException e) { if (e.getSQLState().equals("23000") && e.getErrorCode() == 1062) { throw new EntityExistsException("Entity already exists ", e);
if(student.getKey() != null){ if (containsStudent(student)) { throw new EntityExistsException("Object already exists"); } } mgr.makePersistent(student);
@Override public RuntimeException mapManagedFlushFailure(String message, RuntimeException failure, SessionImplementor session) { // OGM-specific if ( EntityAlreadyExistsException.class.isInstance( failure ) ) { throw new EntityExistsException( failure ); } // Let ORM deal with the others else { return delegate.mapManagedFlushFailure( message, failure, session ); } } }
@Override @Transactional( propagation = Propagation.REQUIRED, readOnly = false) @CachePut( value = "greetings", key = "#result.id") public Greeting create(Greeting greeting) { logger.info("> create"); counterService.increment("method.invoked.greetingServiceBean.create"); // Ensure the entity object to be created does NOT exist in the // repository. Prevent the default behavior of save() which will update // an existing entity if the entity matching the supplied id exists. if (greeting.getId() != null) { // Cannot create Greeting with specified ID value logger.error( "Attempted to create a Greeting, but id attribute was not null."); throw new EntityExistsException( "The id attribute must be null to persist a new entity."); } Greeting savedGreeting = greetingRepository.save(greeting); logger.info("< create"); return savedGreeting; }
@Override @Transactional( propagation = Propagation.REQUIRED, readOnly = false) @CachePut( value = "greetings", key = "#result.id") public Greeting create(Greeting greeting) { logger.info("> create"); counterService.increment("method.invoked.greetingServiceBean.create"); // Ensure the entity object to be created does NOT exist in the // repository. Prevent the default behavior of save() which will update // an existing entity if the entity matching the supplied id exists. if (greeting.getId() != null) { // Cannot create Greeting with specified ID value logger.error( "Attempted to create a Greeting, but id attribute was not null."); throw new EntityExistsException( "The id attribute must be null to persist a new entity."); } Greeting savedGreeting = greetingRepository.save(greeting); logger.info("< create"); return savedGreeting; }
private void throwPersistException(SQLException e, Entity entity) throws SQLException { log.log(Level.FINER, e.toString(), e); String sqlState = e.getSQLState(); JdbcMetaData metaData = _persistenceUnit.getMetaData(); if (metaData.isUniqueConstraintSQLState(sqlState)) { // jpa/0ga5 throw new EntityExistsException(L.l("Trying to persist an entity '{0}[{1}]' that already exists. Entity state '{2}'", entity.getClass().getName(), entity.__caucho_getPrimaryKey(), entity.__caucho_getEntityState())); } else if (metaData.isForeignKeyViolationSQLState(sqlState)) { // jpa/0o42 throw new IllegalStateException(L.l("Trying to persist an entity of class '{0}' with PK '{1}' would break a foreign key constraint. The entity state is '{2}'. Please make sure there are associated entities for all required relationships. If you are merging an entity make sure the association fields are annotated with cascade=MERGE or cascade=ALL.", entity.getClass().getName(), entity.__caucho_getPrimaryKey(), entity.__caucho_getEntityState())); } throw e; }
public Subject createSubject(Subject whoami, Subject subjectToCreate, String password) throws SubjectException, EntityExistsException { if (getSubjectByName(subjectToCreate.getName()) != null) { throw new EntityExistsException("A user named [" + subjectToCreate.getName() + "] already exists."); } if (subjectToCreate.getFsystem()) { throw new SubjectException("Cannot create new system users: " + subjectToCreate.getName()); } entityManager.persist(subjectToCreate); createPrincipal(whoami, subjectToCreate.getName(), password); return subjectToCreate; }
public <T extends WithId<T>> T create(final T entity) { Kind kind = entity.getKind(); Map<String, T> cache = caches.getCache(kind.getModelName()); Optional<String> id = entity.getId(); String idVal; final T entityToCreate; if (!id.isPresent()) { idVal = KeyGenerator.createKey(); entityToCreate = entity.withId(idVal); } else { idVal = id.get(); if (cache.containsKey(idVal)) { throw new EntityExistsException("There already exists a " + kind + " with id " + idVal); } entityToCreate = entity; } this.<T, T>doWithDataAccessObject(kind.getModelClass(), d -> d.create(entityToCreate)); cache.put(idVal, entityToCreate); broadcast("created", kind.getModelName(), idVal); return entityToCreate; }
/** * If in a transaction this method will check for existence and register the * object if it is new. The instance of the entity provided will become * managed. * * @param entity * @throws IllegalArgumentException * if the given Object is not an entity. */ public void persist(Object entity) { try { verifyOpen(); if (entity == null) { throw new IllegalArgumentException(ExceptionLocalization.buildMessage("not_an_entity", new Object[] { entity })); } try { getActivePersistenceContext(checkForTransaction(false)).registerNewObjectForPersist(entity, new IdentityHashMap()); } catch (RuntimeException exception) { if (exception instanceof ValidationException) { throw new EntityExistsException(exception.getLocalizedMessage(), exception); } throw exception; } } catch (RuntimeException exception) { setRollbackOnly(); throw exception; } }
/** * If in a transaction this method will check for existence and register the object if * it is new. The instance of the entity provided will become managed. * @param entity * @throws IllegalArgumentException if the given Object is not an entity */ public void persist(Object entity){ try { verifyOpen(); if (entity == null){ throw new IllegalArgumentException(ExceptionLocalization.buildMessage("not_an_entity", new Object[] {entity})); } try { getActivePersistenceContext(checkForTransaction(!isExtended())).registerNewObjectForPersist(entity, new IdentityHashtable()); } catch (RuntimeException e) { if (ValidationException.class.isAssignableFrom(e.getClass())){ throw new EntityExistsException(e.getLocalizedMessage() , e); } throw e; } } catch (RuntimeException e) { this.setRollbackOnly(); throw e; } }
/** * {@inheritDoc} */ @PreAuthorize("hasPermission(#userCreator.id, 'USER', 'ProfilePermission.CREATE_FORUM_FAQ')") @Override public SimplePage createPage(SimplePage simplePage, JCUser userCreator) throws EntityExistsException { if (getDao().isExist(simplePage.getPathName())) { String msg = "SimplePage with pathName = " + simplePage.getPathName() + " already exists."; logger.info(msg); throw new EntityExistsException(msg); } this.getDao().saveOrUpdate(simplePage); Group group = groupDao.getGroupByName(AdministrationGroup.ADMIN.getName()); securityService.createAclBuilder().grant(GeneralPermission.WRITE).to(group).on(simplePage).flush(); logger.info("SimplePage registered: {}", simplePage.getName()); return simplePage; }
/** * @see org.rhq.enterprise.server.auth.SubjectManagerLocal#createSubject(Subject, Subject) */ @RequiredPermission(Permission.MANAGE_SECURITY) public Subject createSubject(Subject whoami, Subject subject) throws SubjectException { // Make sure there's not an existing subject with the same name. if (getSubjectByName(subject.getName()) != null) { throw new EntityExistsException("A user named [" + subject.getName() + "] already exists."); } if (subject.getFsystem()) { throw new SubjectException("Cannot create new system subjects: " + subject.getName()); } // we are ignoring roles - anything the caller gave us is thrown out subject.setRoles(null); subject.setLdapRoles(null); subject.setOwnedGroups(null); Configuration configuration = subject.getUserConfiguration(); if (configuration != null) { configuration = entityManager.merge(configuration); subject.setUserConfiguration(configuration); } entityManager.persist(subject); return subject; }
throw new EntityExistsException(LOCALISER.msg("EM.EntityIsPersistent", StringUtils.toJVMIDString(entity)));
throwException(new EntityExistsException(LOCALISER.msg("EM.EntityIsPersistent", StringUtils.toJVMIDString(entity))));
@Test public void testFilteredJPAExceptions() { assertFalse(predicate.apply(new EntityExistsException())); assertFalse(predicate.apply(new EntityNotFoundException())); assertFalse(predicate.apply(new LockTimeoutException())); assertFalse(predicate.apply(new NoResultException())); assertFalse(predicate.apply(new NonUniqueResultException())); assertFalse(predicate.apply(new OptimisticLockException())); assertFalse(predicate.apply(new PessimisticLockException())); assertFalse(predicate.apply(new QueryTimeoutException())); assertFalse(predicate.apply(new TransactionRequiredException())); }
@Test public void testNestedFilteredJPAExceptions() { assertFalse(predicate.apply(wrapCause(new EntityExistsException()))); assertFalse(predicate.apply(wrapCause(new EntityNotFoundException()))); assertFalse(predicate.apply(wrapCause(new LockTimeoutException()))); assertFalse(predicate.apply(wrapCause(new NoResultException()))); assertFalse(predicate.apply(wrapCause(new NonUniqueResultException()))); assertFalse(predicate.apply(wrapCause(new OptimisticLockException()))); assertFalse(predicate.apply(wrapCause(new PessimisticLockException()))); assertFalse(predicate.apply(wrapCause(new QueryTimeoutException()))); assertFalse(predicate.apply(wrapCause(new TransactionRequiredException()))); }