public void testCannotFlushWithoutGettingTransaction() { EntityManager em = entityManagerFactory.createEntityManager(); try { doInstantiateAndSave(em); fail("Should have thrown TransactionRequiredException"); } catch (TransactionRequiredException ex) { // expected } // TODO following lines are a workaround for Hibernate bug // If Hibernate throws an exception due to flush(), // it actually HAS flushed, meaning that the database // was updated outside the transaction deleteAllPeopleUsingEntityManager(sharedEntityManager); setComplete(); }
/** * releases an event on a JPA resource. If it is the second release of a 6-eyes process the controlled object entry * is updated. If it is a 4-eyes process the real object is updated. * * @param entityManager * EntityManager for performing the release. Could be null in case of a INVOKE event. If JDBC, use new * JdbcBridgeEntityManager(connection) * @param remark * comment * @throws ResourceApplyException * if the release action fails. */ @CibetContext public Object release(EntityManager entityManager, String remark) throws ResourceApplyException { log.debug("start release"); if (entityManager != null) { if ((entityManager instanceof CEntityManager && ((CEntityManager) entityManager).supportsTransactions() || !(entityManager instanceof CEntityManager)) && !entityManager.isJoinedToTransaction()) { String err = "release method must be called within a transaction boundary"; log.error(err); throw new TransactionRequiredException(err); } Context.internalRequestScope().setApplicationEntityManager(entityManager); } if (getExecutionStatus() != ExecutionStatus.SCHEDULED) { Context.internalRequestScope().setScheduledDate(getScheduledDate()); } DcActuator dc = (DcActuator) Configuration.instance().getActuator(getActuator()); Object obj = dc.release(this, remark); return obj; }
@Test public void releasepersistNoTransaction() throws Exception { log.info("start releasepersistNoTransaction()"); List<String> schemes = new ArrayList<String>(); schemes.add(FourEyesActuator.DEFAULTNAME); registerSetpoint(TEntity.class.getName(), schemes, ControlEvent.INSERT, ControlEvent.RELEASE); Context.requestScope().setRemark("created"); TEntity ent = createTEntity(12, "Hirsch"); persist(ent); Assert.assertEquals(0, ent.getId()); List<Controllable> l = DcLoader.findUnreleased(); Assert.assertEquals(1, l.size()); Controllable co = l.get(0); Assert.assertEquals("created", co.getCreateRemark()); Context.sessionScope().setUser("tester2"); try { co.release(applEman, "blabla"); Assert.fail(); } catch (TransactionRequiredException e) { } }
@Test public void releasePersistNoTransaction() throws Exception { log.info("start releasePersistNoTransaction()"); registerSetpoint(TEntity.class, FourEyesActuator.DEFAULTNAME, ControlEvent.INSERT, ControlEvent.RELEASE); Context.requestScope().setRemark("created"); TEntity ent = persistTEntity(); Assert.assertEquals(0, ent.getId()); List<Controllable> l = DcLoader.findUnreleased(); Assert.assertEquals(1, l.size()); Controllable co = l.get(0); Assert.assertEquals("created", co.getCreateRemark()); Context.sessionScope().setUser("test2"); applEman.getTransaction().commit(); try { co.release(applEman, null); Assert.fail(); } catch (TransactionRequiredException e) { } applEman.getTransaction().begin(); }
private void transactionStarted(final InstanceId instanceId) { if (instanceId == null) { throw new NullPointerException("instanceId is null"); } if (!isTransactionActive()) { throw new TransactionRequiredException(); } final Map<EntityManagerFactory, EntityManagerTracker> entityManagers = entityManagersByDeploymentId.get(instanceId); if (entityManagers == null) { return; } for (final Map.Entry<EntityManagerFactory, EntityManagerTracker> entry : entityManagers.entrySet()) { final EntityManagerFactory entityManagerFactory = entry.getKey(); final EntityManagerTracker value = entry.getValue(); final EntityManager entityManager = value.getEntityManager(); if (value.autoJoinTx) { entityManager.joinTransaction(); } final EntityManagerTxKey txKey = new EntityManagerTxKey(entityManagerFactory); transactionRegistry.putResource(txKey, entityManager); } }
/** * Join an existing transaction, if not already joined. * @param enforce whether to enforce the transaction * (i.e. whether failure to join is considered fatal) */ private void doJoinTransaction(boolean enforce) { if (this.jta) { // Let's try whether we're in a JTA transaction. try { this.target.joinTransaction(); logger.debug("Joined JTA transaction"); } catch (TransactionRequiredException ex) { if (!enforce) { logger.debug("No JTA transaction to join: " + ex); } else { throw ex; } } } else { if (TransactionSynchronizationManager.isSynchronizationActive()) { if (!TransactionSynchronizationManager.hasResource(this.target) && !this.target.getTransaction().isActive()) { enlistInCurrentTransaction(); } logger.debug("Joined local transaction"); } else { if (!enforce) { logger.debug("No local transaction to join"); } else { throw new TransactionRequiredException("No local transaction to join"); } } } }
@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()); }
@Transactional(propagation = Propagation.NOT_SUPPORTED) public void testContainerEntityManagerProxyRejectsJoinTransactionWithoutTransaction() { try { createContainerManagedEntityManager().joinTransaction(); fail("Should have thrown a TransactionRequiredException"); } catch (TransactionRequiredException e) { /* expected */ } }
/** * Return the EntityManager instance for persistence of the Cibet entities. * * @return * @throws CibetException * if no EntityManager set in CibetContext */ @Override public EntityManager getOrCreateEntityManager(boolean transacted) { EntityManager manager = (EntityManager) getProperty(CIBET_ENTITYMANAGER); if (manager == null) { manager = Context.getOrCreateEntityManagers(); if (manager == null) { throw new CibetException("No Cibet EntityManager set in CibetContext"); } } if (log.isDebugEnabled()) { log.debug("get Cibet EntityManager from CibetContext: " + manager); } EntityManagerType emType = (EntityManagerType) getProperty(ENTITYMANAGER_TYPE); if (EntityManagerType.JTA == emType) { try { manager.joinTransaction(); log.debug("... and join JTA transaction"); } catch (TransactionRequiredException e) { log.info("... but cannot join transaction: " + e.getMessage()); } } if (transacted && manager instanceof CEntityManager && ((CEntityManager) manager).supportsTransactions() && !manager.isJoinedToTransaction()) { throw new TransactionRequiredException(); } return manager; }
@Override public void flush() { if (entityManager != null && (!handleTransactions || isTransactionActive())) { try { entityManager.flush(); } catch (IllegalStateException ise) { throw new FlowableException("Error while flushing EntityManager, illegal state", ise); } catch (TransactionRequiredException tre) { throw new FlowableException("Cannot flush EntityManager, an active transaction is required", tre); } catch (PersistenceException pe) { throw new FlowableException("Error while flushing EntityManager: " + pe.getMessage(), pe); } } }
@Override public void flush() { if (entityManager != null && (!handleTransactions || isTransactionActive())) { try { entityManager.flush(); } catch (IllegalStateException ise) { throw new ActivitiException("Error while flushing EntityManager, illegal state", ise); } catch (TransactionRequiredException tre) { throw new ActivitiException("Cannot flush EntityManager, an active transaction is required", tre); } catch (PersistenceException pe) { throw new ActivitiException("Error while flushing EntityManager: " + pe.getMessage(), pe); } } }
public void updateStatus(Users id, PeopleAccountStatus stat) throws ApplicationException { id.setStatus(stat); try { userFacade.update(id); } catch (TransactionRequiredException ex) { throw new ApplicationException("Need a transaction to update the user status"); } }
public void flush() { if (entityManager != null && (!handleTransactions || isTransactionActive()) ) { try { entityManager.flush(); } catch (IllegalStateException ise) { throw new ActivitiException("Error while flushing EntityManager, illegal state", ise); } catch (TransactionRequiredException tre) { throw new ActivitiException("Cannot flush EntityManager, an active transaction is required", tre); } catch (PersistenceException pe) { throw new ActivitiException("Error while flushing EntityManager: " + pe.getMessage(), pe); } } }
/** * Register an entity manager with a transaction manager. * * @param manager The entity manager to register, which is a non-proxy one * @param local The thread local that maintains the entity managers for the various threads * @param transactionManager The transaction manager to register with */ private static void registerEntityManagerUnknown(EntityManager manager, final ThreadLocal<EntityManager> local, final TransactionManager transactionManager) throws Exception { try { manager.joinTransaction(); Synchronization sync = new JTASynchronization(manager, local); transactionManager.getTransaction().registerSynchronization(sync); } catch (TransactionRequiredException exc) { registerEntityManagerResourceLocal(manager, local, transactionManager); } }
public Long serializeProcedureSubmissionSet(long trackerID, Calendar submissionDate, String submissionFilename) throws JAXBException, FileNotFoundException, IllegalStateException, EntityExistsException, IllegalArgumentException, TransactionRequiredException, XMLloadingException, IOException { this.submissionset = new SubmissionSet(); this.submission = new Submission(); this.submissionset.getSubmission().add(this.submission); this.submission.setTrackerID(trackerID); this.submission.setSubmissionDate(submissionDate); this.loadProcedureResults(submissionFilename); return this.serializeSubmissionSet(); }
public Long serializeSpecimenSubmissionSet(long trackerID, Calendar submissionDate, String submissionFilename) throws JAXBException, FileNotFoundException, IllegalStateException, EntityExistsException, IllegalArgumentException, TransactionRequiredException, XMLloadingException, IOException { this.submissionset = new SubmissionSet(); this.submission = new Submission(); this.submissionset.getSubmission().add(this.submission); this.submission.setTrackerID(trackerID); this.submission.setSubmissionDate(submissionDate); this.loadSpecimens(submissionFilename); return this.serializeSubmissionSet(); }
public void serialize(T object, Class<T> clazz) throws JAXBException, IllegalStateException, EntityExistsException, IllegalArgumentException, TransactionRequiredException, RuntimeException, Exception { if (toXml) { if (Connector.validType(clazz)) { this.marshall(object); } else { logger.error("class {} cannot be serializeda as a xml document"); throw new Exception("class " + clazz.getName() + "cannot be serializeda as a xml document"); } } else { this.persist(object); } }
/** * Reset entity-Manager this should fail (no-transaction), but to be sure. */ private void resetEntityManager() { try { em.clear(); } catch (TransactionRequiredException e) { // expected. } }
public void flush() { if (entityManager != null && (!handleTransactions || isTransactionActive()) ) { try { entityManager.flush(); } catch (IllegalStateException ise) { throw new ProcessEngineException("Error while flushing EntityManager, illegal state", ise); } catch (TransactionRequiredException tre) { throw new ProcessEngineException("Cannot flush EntityManager, an active transaction is required", tre); } catch (PersistenceException pe) { throw new ProcessEngineException("Error while flushing EntityManager: " + pe.getMessage(), pe); } } }
/** * Convert the given runtime exception to an appropriate exception from the * {@code org.springframework.dao} hierarchy. * Return null if no translation is appropriate: any other exception may * have resulted from user code, and should not be translated. * <p>The most important cases like object not found or optimistic locking failure * are covered here. For more fine-granular conversion, JpaTransactionManager etc * support sophisticated translation of exceptions via a JpaDialect. * @param ex runtime exception that occurred * @return the corresponding DataAccessException instance, * or {@code null} if the exception should not be translated */ public static DataAccessException convertJpaAccessExceptionIfPossible(RuntimeException ex) { // Following the JPA specification, a persistence provider can also // throw these two exceptions, besides PersistenceException. if (ex instanceof IllegalStateException) { return new InvalidDataAccessApiUsageException(ex.getMessage(), ex); } if (ex instanceof IllegalArgumentException) { return new InvalidDataAccessApiUsageException(ex.getMessage(), ex); } // Check for well-known PersistenceException subclasses. if (ex instanceof EntityNotFoundException) { return new JpaObjectRetrievalFailureException((EntityNotFoundException) ex); } if (ex instanceof NoResultException) { return new EmptyResultDataAccessException(ex.getMessage(), 1, ex); } if (ex instanceof NonUniqueResultException) { return new IncorrectResultSizeDataAccessException(ex.getMessage(), 1, ex); } if (ex instanceof QueryTimeoutException) { return new org.springframework.dao.QueryTimeoutException(ex.getMessage(), ex); } if (ex instanceof LockTimeoutException) { return new CannotAcquireLockException(ex.getMessage(), ex); } if (ex instanceof PessimisticLockException) { return new PessimisticLockingFailureException(ex.getMessage(), ex); } if (ex instanceof OptimisticLockException) { return new JpaOptimisticLockingFailureException((OptimisticLockException) ex); } if (ex instanceof EntityExistsException) { return new DataIntegrityViolationException(ex.getMessage(), ex); } if (ex instanceof TransactionRequiredException) { return new InvalidDataAccessApiUsageException(ex.getMessage(), ex); } // If we have another kind of PersistenceException, throw it. if (ex instanceof PersistenceException) { return new JpaSystemException((PersistenceException) ex); } // If we get here, we have an exception that resulted from user code, // rather than the persistence provider, so we return null to indicate // that translation should not occur. return null; }
@Test(expected = TransactionRequiredException.class) public void transactionRequiredExceptionOnJoinTransaction() { EntityManagerFactory emf = mock(EntityManagerFactory.class); EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf); em.joinTransaction(); }
@Test(expected = TransactionRequiredException.class) public void transactionRequiredExceptionOnFlush() { EntityManagerFactory emf = mock(EntityManagerFactory.class); EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf); em.flush(); }
@Test(expected = TransactionRequiredException.class) public void transactionRequiredExceptionOnPersist() { EntityManagerFactory emf = mock(EntityManagerFactory.class); EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf); em.persist(new Object()); }
@Test(expected = TransactionRequiredException.class) public void transactionRequiredExceptionOnMerge() { EntityManagerFactory emf = mock(EntityManagerFactory.class); EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf); em.merge(new Object()); }
@Test(expected = TransactionRequiredException.class) public void transactionRequiredExceptionOnRemove() { EntityManagerFactory emf = mock(EntityManagerFactory.class); EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf); em.remove(new Object()); }
@Test(expected = TransactionRequiredException.class) public void transactionRequiredExceptionOnRefresh() { EntityManagerFactory emf = mock(EntityManagerFactory.class); EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf); em.refresh(new Object()); }
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { switch (method.getName()) { case "equals": // Only consider equal when proxies are identical. return (proxy == args[0]); case "hashCode": // Use hashCode of EntityManager proxy. return hashCode(); case "unwrap": // JPA 2.0: handle unwrap method - could be a proxy match. Class<?> targetClass = (Class<?>) args[0]; if (targetClass == null) { return currentEntityManager(); } else if (targetClass.isInstance(proxy)) { return proxy; } break; case "isOpen": // Handle isOpen method: always return true. return true; case "close": // Handle close method: suppress, not valid. return null; case "getTransaction": throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use @UnitOfWork instead"); } // Retrieve the EntityManager bound to the current execution context EntityManager target = currentEntityManager(); if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain un-flushed... if (!hasActiveTransaction(target)) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Invoke method on current EntityManager. try { return method.invoke(target, args); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } }
@Test(expected = TransactionRequiredException.class) public void requiresTransactionForPersist() { createProxy().persist(new Object()); }
@Test(expected = TransactionRequiredException.class) public void requiresTransactionForMerge() { createProxy().merge(new Object()); }
@Test(expected = TransactionRequiredException.class) public void requiresTransactionForRemove() { createProxy().remove(new Object()); }
@Test(expected = TransactionRequiredException.class) public void requiresTransactionForFlush() { createProxy().flush(); }
@Test(expected = TransactionRequiredException.class) public void requiresTransactionForRefresh() { createProxy().refresh(new Object()); }
@Test(expected = TransactionRequiredException.class) public void requiresTransactionForRefreshWithProperties() { createProxy().refresh(new Object(), new HashMap<>()); }