List of usage examples for javax.persistence EntityExistsException EntityExistsException
public EntityExistsException(Throwable cause)
EntityExistsException
exception with the specified cause. From source file:org.easyj.orm.jpa.JPAEntityDao.java
/** * Persiste a entidade no banco de dados de acordo com o mapeamento do JPA * * @param t Entidade a ser persistida/*from w ww. j av a 2 s . c o m*/ * @return T entidade persistida no banco:<br> * @throws EntityExistsException quando a entidade j existe no banco de dados * @throws PersistenceException para algum erro de inconsisncia de dados ou erro genrico de persistncia * @throws Exception qualquer outro erro inesperado */ public <T> T save(T t) throws EntityExistsException, PersistenceException, Exception { T newT = null; if (t != null) { try { logger.debug("Saving entity: {} [{}]", t.getClass().getSimpleName(), t.toString()); newT = merge(t); logger.debug("Entity saved successfully: {} [{}]", t.getClass().getSimpleName(), newT); } catch (EntityExistsException e) { logger.error("Error saving entity: Entity already exists"); throw e; } catch (PersistenceException e) { if (e instanceof RollbackException && e.getCause().getClass() == PersistenceException.class) { e = (PersistenceException) e.getCause(); } String msg; if (e.getCause() instanceof ConstraintViolationException) { msg = e.getCause().getCause().getMessage(); logger.error("Error saving entity: some constraint violation occurred: [{}] - {}", t.toString(), msg); if (msg.toLowerCase().indexOf("duplicate") > -1) { throw new EntityExistsException(msg); } else { throw (ConstraintViolationException) e.getCause(); } } else if (e.getCause() instanceof DataException) { logger.error("Error saving entity: inconsistent data", e); } else if (e.getCause() instanceof PropertyValueException) { logger.error("Error saving entity: missing mandatory (NOT NULL) values", e); } else { logger.error("Error saving entity: generic persistence error", e); } throw e; } catch (Exception e) { logger.error("Error saving entity: UNEXPECTED ERROR", e); throw e; } } return newT; }
From source file:io.syndesis.dao.manager.DataManager.java
public <T extends WithId<T>> T create(final T entity) { Kind kind = entity.getKind();/*w ww.j ava 2 s.c o m*/ Cache<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.keySet().contains(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; }
From source file:com.redhat.ipaas.api.v1.rest.DataManager.java
public <T extends WithId> T create(T entity) { String kind = entity.kind();/*from w ww . j av a 2s.c o m*/ Cache<String, WithId> cache = caches.getCache(kind); Optional<String> id = entity.getId(); String idVal; if (!id.isPresent()) { idVal = generatePK(cache); entity = (T) entity.withId(idVal); } else { idVal = id.get(); if (cache.keySet().contains(idVal)) { throw new EntityExistsException("There already exists a " + kind + " with id " + idVal); } } T finalEntity = entity; cache.put(idVal, (T) doWithDataAccessObject(kind, d -> d.create(finalEntity))); return entity; }
From source file:com.clustercontrol.commons.util.JpaTransactionManager.java
/** * ??//from w w w.j ava2s .c o m * ????EntityExistsException * * Eclipselink(2.4.1?)???persist()?EntityExistsException? * ?????????? * * Eclipselink(2.4.1?)???In-memory?Cascade.remove??? * DB?????????? * * @param clazz ?Entity * @param primaryKey ?PrimaryKey * @throws EntityExistsException */ public <T> void checkEntityExists(Class<T> clazz, Object primaryKey) throws EntityExistsException { String strPk = ""; if (primaryKey instanceof String) { strPk = "primaryKey = " + primaryKey; } else { strPk = primaryKey.toString(); } Object obj = em.find(clazz, primaryKey, JpaPersistenceConfig.JPA_EXISTS_CHECK_HINT_MAP, ObjectPrivilegeMode.NONE); if (obj != null) { // ? EntityExistsException e = new EntityExistsException(clazz.getSimpleName() + ", " + strPk); throw e; } }
From source file:edu.kit.dama.mdm.core.jpa.MetaDataManagerJpa.java
@Override public final <T> T persist(T entity) throws UnauthorizedAccessAttemptException { //persist()// www .ja v a2 s . c o m //auf internes contains() pruefen, falls "TRUE" throw EntityExistsException() if (contains(entity)) { throw new EntityExistsException("Cannot persist existing entity"); } EntityTransaction transaction = entityManager.getTransaction(); try { transaction.begin(); entityManager.persist(entity); } catch (RuntimeException re) { LOGGER.error("Failed to persist entity", re); throw re; } finally { finalizeEntityManagerAccess("persist", transaction, entity); } return entity; }
From source file:jef.database.DbUtils.java
/** * RuntimeException//from w w w . ja v a 2 s . com * * @param e * @return */ public static PersistenceException toRuntimeException(SQLException e) { String s = e.getSQLState(); if (e instanceof SQLIntegrityConstraintViolationException) { return new EntityExistsException(e); } else if (e instanceof SQLTimeoutException) { return new QueryTimeoutException(s, e); } return new PersistenceException(s, e); }
From source file:org.apache.syncope.core.rest.controller.ResourceController.java
@PreAuthorize("hasRole('RESOURCE_CREATE')") public ResourceTO create(final ResourceTO resourceTO) { if (StringUtils.isBlank(resourceTO.getName())) { SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.RequiredValuesMissing); sce.getElements().add("Resource name"); throw sce; }/*from w w w. j a va 2 s .co m*/ if (resourceDAO.find(resourceTO.getName()) != null) { throw new EntityExistsException("Resource '" + resourceTO.getName() + "'"); } ExternalResource resource = resourceDAO.save(binder.create(resourceTO)); return binder.getResourceTO(resource); }
From source file:org.apache.syncope.core.rest.controller.SchemaController.java
@PreAuthorize("hasRole('SCHEMA_CREATE')") @SuppressWarnings("unchecked") public <T extends AbstractSchemaTO> T create(final AttributableType attrType, final SchemaType schemaType, final T schemaTO) { if (StringUtils.isBlank(schemaTO.getName())) { SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.RequiredValuesMissing); sce.getElements().add("Schema name"); throw sce; }/* ww w.j a va 2s.co m*/ final AttributableUtil attrUtil = AttributableUtil.getInstance(attrType); if (doesSchemaExist(schemaType, schemaTO.getName(), attrUtil)) { throw new EntityExistsException(schemaType + "/" + attrType + "/" + schemaTO.getName()); } T created; switch (schemaType) { case VIRTUAL: AbstractVirSchema virSchema = attrUtil.newVirSchema(); binder.create((VirSchemaTO) schemaTO, virSchema); virSchema = virSchemaDAO.save(virSchema); created = (T) binder.getVirSchemaTO(virSchema); break; case DERIVED: AbstractDerSchema derSchema = attrUtil.newDerSchema(); binder.create((DerSchemaTO) schemaTO, derSchema); derSchema = derSchemaDAO.save(derSchema); created = (T) binder.getDerSchemaTO(derSchema); break; case NORMAL: default: AbstractNormalSchema normalSchema = attrUtil.newSchema(); binder.create((SchemaTO) schemaTO, normalSchema); normalSchema = schemaDAO.save(normalSchema); created = (T) binder.getSchemaTO(normalSchema, attrUtil); } return created; }
From source file:org.batoo.jpa.core.impl.manager.EntityManagerImpl.java
/** * Cascaded implementation of {@link #persist(Object)}. * <p>/*w ww . j ava 2 s .c o m*/ * Also manages a direct or indirect requirement to an implicit flush. * * @param entity * the entity to cascade * @param processed * registry of processed entities * @param instances * the managed instances * @param <T> * the type of the entity * @return true if an implicit flush is required, false otherwise * * @since 2.0.0 */ @SuppressWarnings("unchecked") public <T> boolean persistImpl(T entity, ArrayList<Object> processed, LinkedList<ManagedInstance<?>> instances) { if (entity == null) { return false; } if (processed.contains(entity)) { return false; } if (entity instanceof EnhancedInstance) { final ManagedInstance<T> instance = (ManagedInstance<T>) ((EnhancedInstance) entity) .__enhanced__$$__getManagedInstance(); if (instance.getStatus() == Status.DETACHED) { throw new EntityExistsException("Entity has been previously detached"); } } final ManagedInstance<T> existing = this.session.get(entity); if (existing != null) { processed.add(entity); instances.add(existing); switch (existing.getStatus()) { case REMOVED: existing.setStatus(Status.MANAGED); return existing.cascadePersist(this, processed, instances); case NEW: case MANAGED: return existing.cascadePersist(this, processed, instances); case DETACHED: // noop } } final Class<T> clazz = (Class<T>) (entity instanceof EnhancedInstance ? entity.getClass().getSuperclass() : entity.getClass()); final EntityTypeImpl<T> type = this.metamodel.entity(clazz); final ManagedInstance<T> instance = type.getManagedInstance(this.session, entity); instance.setStatus(Status.NEW); instance.enhanceCollections(); boolean requiresFlush = !instance.fillIdValues(); this.session.putExternal(instance); processed.add(entity); instances.add(instance); requiresFlush |= instance.cascadePersist(this, processed, instances); return requiresFlush; }
From source file:org.ejbca.core.ejb.ra.UserAdminSessionBean.java
@Override public void addUser(Admin admin, UserDataVO userDataVO, boolean clearpwd) throws AuthorizationDeniedException, EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, PersistenceException { final int endEntityProfileId = userDataVO.getEndEntityProfileId(); final int caid = userDataVO.getCAId(); final String username = StringTools.strip(userDataVO.getUsername()); // Check if administrator is authorized to add user to CA. assertAuthorizedToCA(admin, caid, username, LogConstants.EVENT_ERROR_ADDEDENDENTITY); final GlobalConfiguration globalConfiguration = getGlobalConfiguration(admin); if (globalConfiguration.getEnableEndEntityProfileLimitations()) { // Check if administrator is authorized to add user. assertAuthorizedToEndEntityProfile(admin, endEntityProfileId, AccessRulesConstants.CREATE_RIGHTS, caid, username, LogConstants.EVENT_ERROR_ADDEDENDENTITY); }//from w w w . j av a 2 s .c o m final String originalDN = userDataVO.getDN(); canonicalizeUser(admin, userDataVO); if (log.isTraceEnabled()) { log.trace(">addUser(" + userDataVO.getUsername() + ", password, " + userDataVO.getDN() + ", " + originalDN + ", " + userDataVO.getSubjectAltName() + ", " + userDataVO.getEmail() + ", profileId: " + endEntityProfileId + ")"); } final String endEntityProfileName = endEntityProfileSession.getEndEntityProfileName(admin, endEntityProfileId); final String dn = userDataVO.getDN(); final String altName = userDataVO.getSubjectAltName(); final String email = userDataVO.getEmail(); final int type = userDataVO.getType(); String newpassword = userDataVO.getPassword(); EndEntityProfile profile = null; // Only look this up if we need it.. if (userDataVO.getPassword() == null) { profile = endEntityProfileSession.getEndEntityProfile(admin, endEntityProfileId); if (profile.useAutoGeneratedPasswd()) { // special case used to signal regeneration of password newpassword = profile.getAutoGeneratedPasswd(); } } if (globalConfiguration.getEnableEndEntityProfileLimitations()) { if (profile == null) { profile = endEntityProfileSession.getEndEntityProfile(admin, endEntityProfileId); } // Check if user fulfills it's profile. try { final String dirattrs = userDataVO.getExtendedinformation() != null ? userDataVO.getExtendedinformation().getSubjectDirectoryAttributes() : null; profile.doesUserFullfillEndEntityProfile(username, userDataVO.getPassword(), dn, altName, dirattrs, email, userDataVO.getCertificateProfileId(), clearpwd, (type & SecConst.USER_KEYRECOVERABLE) != 0, (type & SecConst.USER_SENDNOTIFICATION) != 0, userDataVO.getTokenType(), userDataVO.getHardTokenIssuerId(), caid, userDataVO.getExtendedinformation()); } catch (UserDoesntFullfillEndEntityProfile e) { final String msg = intres.getLocalizedMessage("ra.errorfullfillprofile", endEntityProfileName, dn, e.getMessage()); logSession.log(admin, caid, LogConstants.MODULE_RA, new Date(), username, null, LogConstants.EVENT_ERROR_ADDEDENDENTITY, msg); throw e; } } // Get CAInfo, to be able to read configuration final CAInfo caInfo = caAdminSession.getCAInfoOrThrowException(admin, caid); // Check if approvals is required. (Only do this if store users, otherwise this approval is disabled.) if (caInfo.isUseUserStorage()) { final int numOfApprovalsRequired = getNumOfApprovalRequired(admin, CAInfo.REQ_APPROVAL_ADDEDITENDENTITY, caid, userDataVO.getCertificateProfileId()); if (numOfApprovalsRequired > 0) { AddEndEntityApprovalRequest ar = new AddEndEntityApprovalRequest(userDataVO, clearpwd, admin, null, numOfApprovalsRequired, caid, endEntityProfileId); if (ApprovalExecutorUtil.requireApproval(ar, NONAPPROVABLECLASSNAMES_ADDUSER)) { approvalSession.addApprovalRequest(admin, ar, globalConfiguration); throw new WaitingForApprovalException(intres.getLocalizedMessage("ra.approvalad")); } } } // Check if the subjectDN serialnumber already exists. if (caInfo.isDoEnforceUniqueSubjectDNSerialnumber()) { if (caInfo.isUseUserStorage()) { if (!isSubjectDnSerialnumberUnique(caid, dn, username)) { throw new EjbcaException(ErrorCode.SUBJECTDN_SERIALNUMBER_ALREADY_EXISTS, "Error: SubjectDN Serialnumber already exists."); } } else { log.warn( "CA configured to enforce unique SubjectDN serialnumber, but not to store any user data. Check will be ignored. Please verify your configuration."); } } // Store a new UserData in the database, if this CA is configured to do so. if (caInfo.isUseUserStorage()) { try { // Create the user in one go with all parameters at once. This was important in EJB2.1 so the persistence layer only creates *one* single // insert statement. If we do a home.create and the some setXX, it will create one insert and one update statement to the database. // Probably not important in EJB3 anymore. final UserData userData = new UserData(username, newpassword, clearpwd, dn, caid, userDataVO.getCardNumber(), altName, email, type, endEntityProfileId, userDataVO.getCertificateProfileId(), userDataVO.getTokenType(), userDataVO.getHardTokenIssuerId(), userDataVO.getExtendedinformation()); // Since persist will not commit and fail if the user already exists, we need to check for this // Flushing the entityManager will not allow us to rollback the persisted user if this is a part of a larger transaction. if (UserData.findByUsername(entityManager, username) != null) { throw new EntityExistsException("User " + username + " already exists."); } entityManager.persist(userData); // Although UserDataVO should always have a null password for // autogenerated end entities, the notification framework // expect it to exist. Since nothing else but printing is done after // this point it is safe to set the password userDataVO.setPassword(newpassword); // Send notifications, if they should be sent sendNotification(admin, userDataVO, UserDataConstants.STATUS_NEW); if ((type & SecConst.USER_PRINT) != 0) { if (profile == null) { profile = endEntityProfileSession.getEndEntityProfile(admin, endEntityProfileId); } print(admin, profile, userDataVO); } final String msg = intres.getLocalizedMessage("ra.addedentity", username); logSession.log(admin, caid, LogConstants.MODULE_RA, new Date(), username, null, LogConstants.EVENT_INFO_ADDEDENDENTITY, msg); } catch (PersistenceException e) { // PersistenceException could also be caused by various database problems. final String msg = intres.getLocalizedMessage("ra.errorentityexist", username); logSession.log(admin, caid, LogConstants.MODULE_RA, new Date(), username, null, LogConstants.EVENT_ERROR_ADDEDENDENTITY, msg); throw e; } catch (Exception e) { final String msg = intres.getLocalizedMessage("ra.erroraddentity", username); logSession.log(admin, caid, LogConstants.MODULE_RA, new Date(), username, null, LogConstants.EVENT_ERROR_ADDEDENDENTITY, msg, e); log.error(msg, e); throw new EJBException(e); } } if (log.isTraceEnabled()) { log.trace("<addUser(" + username + ", password, " + dn + ", " + email + ")"); } }