@Test public void testStatefulLocalNaming() { logger.info("starting session local stateful test"); try { userTransaction.begin(); logger.info(stateEngineLocal + ""); int result = stateEngineLocal.go(1); assertEquals(stateEngineLocal.getSpeed(), 1); logger.info(result + ""); logger.info(stateEngineLocal + ""); assertEquals(stateEngineLocal.getSpeed(), 1); stateEngineLocal.add(new MyData()); stateEngineLocal.log(); userTransaction.commit(); } catch (Exception ex) { try { userTransaction.rollback(); } catch (IllegalStateException | SecurityException | SystemException e) { logger.severe("extreme error. The rollback doesn't work"); } } }
@Test public void testPasswordConverter() { logger.info("starting persistence converter test"); Citizen citizen = new Citizen(); citizen.setPassword("prova"); try { userTransaction.begin(); entityManager.persist(citizen); userTransaction.commit(); } catch (NotSupportedException | SystemException | IllegalStateException | SecurityException | HeuristicMixedException | HeuristicRollbackException | RollbackException e) { fail(); } Citizen citizenFromDB = (Citizen) entityManager.createQuery("from citizen").getSingleResult(); assertEquals("the password is always converted by the converter", "prova", citizenFromDB.getPassword()); assertEquals("this is the password we have in the database", "cHJvdmE=", NEVER_DO_IT); }
/** * Tests annotation literals in a jar archive */ @Test @SuppressWarnings("unchecked") public void testTablePerClass() { logger.info("starting table per class inheritance test"); Vehicle vehicle = new Vehicle("peugeot", "car"); Car car = new Car("fiat", "car"); try { userTransaction.begin(); entityManager.persist(vehicle); entityManager.persist(car); userTransaction.commit(); } catch (NotSupportedException | SystemException | IllegalStateException | SecurityException | HeuristicMixedException | HeuristicRollbackException | RollbackException e) { fail(); } List<Vehicle> vehiclesFromDB = entityManager.createNativeQuery("select * from vehicle").getResultList(); assertEquals("the vehicle table exists", 1, vehiclesFromDB.size()); List<Car> carsFromDB = entityManager.createNativeQuery("select * from car").getResultList(); assertEquals("the car table exists", 1, carsFromDB.size()); }
/** * Tests annotation literals in a jar archive */ @Test @SuppressWarnings("unchecked") public void testJoin() { logger.info("starting joined inheritance event test"); Watch watch = new Watch(); TopicWatch topicWatch = new TopicWatch(); try { userTransaction.begin(); entityManager.persist(watch); entityManager.persist(topicWatch); userTransaction.commit(); } catch (NotSupportedException | SystemException | IllegalStateException | SecurityException | HeuristicMixedException | HeuristicRollbackException | RollbackException e) { fail(); } List<Watch> watchesFromDB = entityManager.createNativeQuery("select * from JBP_FORUMS_WATCH").getResultList(); assertEquals("the watch table exists", 2, watchesFromDB.size()); List<TopicWatch> topicWatchesFromDB = entityManager.createNativeQuery("select * from JBP_FORUMS_TOPICSWATCH") .getResultList(); assertEquals("the topic watch table exists", 1, topicWatchesFromDB.size()); }
@Test public void testSearch() { Forum forum = entityManager.find(Forum.class, 0); Poster poster = new Poster("root"); Topic topic = new Topic(forum, TOPIC_TEXT); topic.setPoster(poster); Post post = new Post(topic, POST_TEXT); post.setCreateDate(new Date()); post.setPoster(poster); try { userTransaction.begin(); entityManager.persist(poster); entityManager.persist(topic); entityManager.persist(post); userTransaction.commit(); } catch (NotSupportedException | SystemException | IllegalStateException | SecurityException | HeuristicMixedException | HeuristicRollbackException | RollbackException e) { e.printStackTrace(); } List<Topic> topics = findTopics(); List<Post> posts = findPosts(); assertEquals("find topics", 1, topics.size()); assertEquals("find posts", 1, posts.size()); }
@Test public void testDeleteManyToMany() { logger.info("starting merge many to many cascade test"); testPersistManyToMany(); try { userTransaction.begin(); Author davide_scala = (Author) entityManager.createQuery("from Author where fullName = :fullName") .setParameter("fullName", "Davide Scala").getSingleResult(); davide_scala.remove(); entityManager.remove(davide_scala); userTransaction.commit(); } catch (NotSupportedException | SystemException | IllegalStateException | SecurityException | HeuristicMixedException | HeuristicRollbackException | RollbackException e) { fail(); } @SuppressWarnings("unchecked") List<Book> booksFromDb = entityManager.createNativeQuery("select * from Book").getResultList(); assertEquals("the book table exists", 2, booksFromDb.size()); @SuppressWarnings("unchecked") List<Author> authorsFromDb = entityManager.createNativeQuery("select * from Author").getResultList(); assertEquals("the author table exists", 2, authorsFromDb.size()); @SuppressWarnings("unchecked") List<Author> bookAuthorsFromDb = entityManager.createNativeQuery("select * from Book_Author").getResultList(); assertEquals("the author table exists", 4, bookAuthorsFromDb.size()); }
@Test public void testDeleteBooksAllManyToMany() { logger.info("starting merge many to many cascade test"); testPersistManyToMany(); try { userTransaction.begin(); PMAuthor davide_scala = (PMAuthor) entityManager.createQuery("from PMAuthor where fullName = :fullName") .setParameter("fullName", "Davide Scala").getSingleResult(); entityManager.remove(davide_scala); userTransaction.commit(); } catch (NotSupportedException | SystemException | IllegalStateException | SecurityException | HeuristicMixedException | HeuristicRollbackException | RollbackException e) { fail(); } @SuppressWarnings("unchecked") List<PMBook> booksFromDb = entityManager.createNativeQuery("select * from PMBook").getResultList(); assertEquals("the pm book table exists", 1, booksFromDb.size()); @SuppressWarnings("unchecked") List<PMAuthor> authorsFromDb = entityManager.createNativeQuery("select * from PMAuthor").getResultList(); assertEquals("the pm author table exists", 2, authorsFromDb.size()); @SuppressWarnings("unchecked") List<PMAuthor> bookAuthorsFromDb = entityManager.createNativeQuery("select * from Book_PM_Author") .getResultList(); assertEquals("the pm book author table exists", 2, bookAuthorsFromDb.size()); }
@Test public void testDeleteBooksJoinTableAllManyToMany() { logger.info("starting merge many to many cascade test"); testPersistManyToMany(); try { userTransaction.begin(); AllAuthor davide_scala = (AllAuthor) entityManager.createQuery("from AllAuthor where fullName = :fullName") .setParameter("fullName", "Davide Scala").getSingleResult(); entityManager.remove(davide_scala); userTransaction.commit(); } catch (NotSupportedException | SystemException | IllegalStateException | SecurityException | HeuristicMixedException | HeuristicRollbackException | RollbackException e) { fail(); } @SuppressWarnings("unchecked") List<AllBook> booksFromDb = entityManager.createNativeQuery("select * from AllBook").getResultList(); assertEquals("the all book table doesn't exist", 0, booksFromDb.size()); @SuppressWarnings("unchecked") List<AllAuthor> authorsFromDb = entityManager.createNativeQuery("select * from AllAuthor").getResultList(); assertEquals("the all author table doesn't exist", 0, authorsFromDb.size()); @SuppressWarnings("unchecked") List<AllAuthor> bookAuthorsFromDb = entityManager.createNativeQuery("select * from Book_All_Author") .getResultList(); assertEquals("the all book author table exists", 0, bookAuthorsFromDb.size()); }
/** * Tests the fire of the event inside a failed transaction */ @Test public void testFailedTransaction() { Bill bill = null; try { userTransaction.begin(); bill = fire(); assertEquals( "The id generation passes through the always and it is incremented only by inprogess always observer method", 1, bill.getId()); throw new RollbackException(); } catch (NotSupportedException | SystemException | SecurityException | IllegalStateException | RollbackException e) { try { userTransaction.rollback(); assertEquals( "The id generation passes through the always and it is incremented only by transactional failure observer methods", 3, bill.getId()); } catch (SystemException se) { } } }
@Test @DisplayName( "Basic rollback test" ) public void basicRollbackTest() throws SQLException { TransactionManager txManager = com.arjuna.ats.jta.TransactionManager.transactionManager(); TransactionSynchronizationRegistry txSyncRegistry = new com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionSynchronizationRegistryImple(); AgroalDataSourceConfigurationSupplier configurationSupplier = new AgroalDataSourceConfigurationSupplier() .connectionPoolConfiguration( cp -> cp .transactionIntegration( new NarayanaTransactionIntegration( txManager, txSyncRegistry ) ) ); try ( AgroalDataSource dataSource = AgroalDataSource.from( configurationSupplier ) ) { txManager.begin(); Connection connection = dataSource.getConnection(); logger.info( format( "Got connection {0}", connection ) ); txManager.rollback(); assertTrue( connection.isClosed() ); } catch ( NotSupportedException | SystemException e ) { fail( "Exception: " + e.getMessage() ); } }
/** * Configuración inicial de la prueba. * * @generated */ @Before public void configTest() { try { utx.begin(); clearData(); insertData(); utx.commit(); } catch (IllegalStateException | SecurityException | HeuristicMixedException | HeuristicRollbackException | NotSupportedException | RollbackException | SystemException e) { e.printStackTrace(); try { utx.rollback(); } catch (IllegalStateException | SecurityException | SystemException e1) { e1.printStackTrace(); } } }
private void setSiteMembership(String authority, String siteName, String doAsUser) throws SystemException, Exception { String currentUser = authenticationComponent.getCurrentUserName(); UserTransaction txn = transactionService.getUserTransaction(); try { if (doAsUser != null) authenticationComponent.setCurrentUser(doAsUser); txn.begin(); siteService.setMembership(siteName, authority, SiteModel.SITE_COLLABORATOR); txn.commit(); } catch (Exception e) { txn.rollback(); throw e; } finally { authenticationComponent.setCurrentUser(currentUser); } }
/** * @see javax.transaction.TransactionManager#suspend() */ public Transaction suspend() throws SystemException { if (!isActive) { throw new SystemException( LocalizedStrings.TransactionManagerImpl_TRANSACTIONMANAGER_INVALID.toLocalizedString()); } Transaction txn = getTransaction(); if (null != txn) { GlobalTransaction gtx = getGlobalTransaction(txn); gtx.suspend(); transactionMap.remove(Thread.currentThread()); LogWriterI18n writer = TransactionUtils.getLogWriterI18n(); if (writer.infoEnabled()) writer.info( LocalizedStrings.TransactionManagerImpl_TRANSACTIONMANAGERIMPLSUSPENDTRANSACTION_SUSPENDED); } return txn; }
@Override protected void afterAfterCompletion() { // this method is a noop if there is a Synchronization! try { if ( isDriver ) { if ( !isInitiator ) { LOG.setManagerLookupClass(); } try { transactionCoordinator().afterTransaction( this, userTransaction.getStatus() ); } catch (SystemException e) { throw new TransactionException( "Unable to determine UserTransaction status", e ); } } } finally { isInitiator = false; } }
@Test @DisplayName( "Enroll connection after previous connection close test" ) public void enrollConnectionCloseTest() throws SQLException { TransactionManager txManager = com.arjuna.ats.jta.TransactionManager.transactionManager(); TransactionSynchronizationRegistry txSyncRegistry = new com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionSynchronizationRegistryImple(); AgroalDataSourceConfigurationSupplier configurationSupplier = new AgroalDataSourceConfigurationSupplier() .connectionPoolConfiguration( cp -> cp .transactionIntegration( new NarayanaTransactionIntegration( txManager, txSyncRegistry ) ) .connectionFactoryConfiguration( cf -> cf .autoCommit( true ) ) ); try ( AgroalDataSource dataSource = AgroalDataSource.from( configurationSupplier ) ) { txManager.begin(); Connection connection = dataSource.getConnection(); logger.info( format( "Got connection {0}", connection ) ); String connectionToString = connection.toString(); connection.close(); Connection secondConnection = dataSource.getConnection(); logger.info( format( "Got connection {0}", secondConnection ) ); // TODO: comparing toString is brittle. Find a better way to make sure the underlying physical connection is the same. assertEquals( connectionToString, secondConnection.toString(), "Expect the same connection under the same transaction" ); assertFalse( secondConnection.getAutoCommit(), "AutoCommit temporarily disabled in enlisted connection" ); secondConnection.close(); txManager.commit(); assertTrue( connection.isClosed() ); assertTrue( secondConnection.isClosed() ); } catch ( NotSupportedException | SystemException | RollbackException | HeuristicMixedException | HeuristicRollbackException e ) { fail( "Exception: " + e.getMessage() ); } }
@Override public int transactionStatus() { try { return transactionManager.getStatus(); } catch (SystemException e) { throw new RuntimeException(e); } }
@Override public Transaction getTransaction() throws SystemException { final Transaction transaction = delegate.getTransaction(); if ( selectedApplicationServer == ApplicationServer.WEBSPHERE ) { return transaction != null ? new WebSphereTransaction( transaction ) : null; } return transaction; }
@Override public void registerSynchronization(final Synchronization synchronization) throws RollbackException, IllegalStateException, SystemException { final InvocationHandler ih = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ( "afterCompletion".equals( method.getName() ) ) { int status = args[2].equals(Boolean.TRUE) ? Status.STATUS_COMMITTED : Status.STATUS_UNKNOWN; synchronization.afterCompletion(status); } else if ( "beforeCompletion".equals( method.getName() ) ) { synchronization.beforeCompletion(); } else if ( "toString".equals( method.getName() ) ) { return synchronization.toString(); } return null; } }; final Object synchronizationCallback = Proxy.newProxyInstance( getClass().getClassLoader(), new Class[] {synchronizationCallbackClass}, ih ); try { registerSynchronizationMethod.invoke( extendedJTATransaction, synchronizationCallback ); } catch (Exception e) { throw new HibernateException(e); } }
@Override public void markRollbackOnly() { try { getTransactionManager().setRollbackOnly(); } catch ( SystemException se ) { throw new TransactionException("Could not set transaction to rollback only", se); } }
public void resume(Transaction tx) throws InvalidTransactionException, IllegalStateException, SystemException { if (!(tx instanceof SimpleTransaction)) { throw new IllegalStateException("Transaction must be a SimpleTransaction to resume"); } SimpleTransaction.resume((SimpleTransaction) tx); }
private void init() throws SystemException { this.cache = (GemFireCacheImpl) CacheFactory.getAnyInstance(); LogWriter logger = this.cache.getLogger(); if (logger.fineEnabled()) { logger.fine("JCAManagedConnection:init. Inside init"); } gfTxMgr = cache.getTxManager(); this.initDone = true; }
/** * Check if we are in a global transactoin according to the transaction manager * * @return - true if in a global transaction */ private boolean inGlobalTransaction() { try { return SimpleTransactionManager.getInstance().getTransaction() != null; } catch (SystemException e) { return false; } }
/** * Get the local transaction - may be null oif we are outside a transaction. * * @return - the transaction * @throws IndexerException */ private SimpleTransaction getTransaction() throws IndexerException { try { return SimpleTransactionManager.getInstance().getTransaction(); } catch (SystemException e) { throw new IndexerException("Failed to get transaction", e); } }
private boolean inTransaction() { try { Transaction tx = getTransactionManager().getTransaction(); return tx != null && tx.getStatus() == Status.STATUS_ACTIVE; } catch (SystemException e) { return false; } }
@Test public void canVersionDocsWithoutSpecialInputFileNameExtension() throws HeuristicMixedException, IOException, SystemException, HeuristicRollbackException, NotSupportedException, RollbackException { testCanVersionDocsWithoutSpecialInputFileNameExtension(file -> streamingNodeImporterFactory.getNodeImporter(resourceAsFile("classpath:bulkimport-autoversion/"+file))); }
@Before public void setup() throws SystemException, NotSupportedException { try { nodeService = (NodeService)ctx.getBean("nodeService"); fileFolderService = (FileFolderService)ctx.getBean("fileFolderService"); transactionService = (TransactionService)ctx.getBean("transactionService"); bulkImporter = (MultiThreadedBulkFilesystemImporter)ctx.getBean("bulkFilesystemImporter"); contentService = (ContentService)ctx.getBean("contentService"); actionService = (ActionService)ctx.getBean("actionService"); ruleService = (RuleService)ctx.getBean("ruleService"); versionService = (VersionService)ctx.getBean("versionService"); AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName()); String s = "BulkFilesystemImport" + System.currentTimeMillis(); txn = transactionService.getUserTransaction(); txn.begin(); AuthenticationUtil.pushAuthentication(); AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName()); StoreRef storeRef = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, s); rootNodeRef = nodeService.getRootNode(storeRef); top = nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("{namespace}top"), ContentModel.TYPE_FOLDER).getChildRef(); topLevelFolder = fileFolderService.create(top, s, ContentModel.TYPE_FOLDER); txn.commit(); } catch(Throwable e) { fail(e.getMessage()); } }
@Before public void setup() throws SystemException, NotSupportedException { super.setup(); //change cmisHiddenConfing default value switchCmisHiddenConfig(); }
@Test public void testAddNullTransaction() throws Exception { try { utx.begin(); GlobalTransaction gtx = tm.getGlobalTransaction(); Transaction txn = null; gtx.addTransaction(txn); utx.commit(); fail("SystemException not thrown on adding null transaction"); } catch (SystemException e) { utx.commit(); } }
public void testLockRevertedOnRollback() throws NotSupportedException, SystemException { // Preconditions of test assertEquals(LockStatus.NO_LOCK, lockService.getLockStatus(noAspectNode)); assertFalse(lockService.isLocked(noAspectNode)); assertEquals(LockStatus.NO_LOCK, lockService.getLockStatus(rootNodeRef)); assertFalse(lockService.isLocked(rootNodeRef)); // Lock noAspectNode lockService.lock(noAspectNode, LockType.WRITE_LOCK, 0, Lifetime.EPHEMERAL); // Lock rootNodeRef lockService.lock(rootNodeRef, LockType.NODE_LOCK, 0, Lifetime.EPHEMERAL); // Sometime later, a refresh occurs (so this should not be reverted to unlocked, but to this state) lockService.lock(rootNodeRef, LockType.NODE_LOCK, 3600, Lifetime.EPHEMERAL); // Rollback endTransaction(); // This lock should not be present. assertEquals(LockStatus.NO_LOCK, lockService.getLockStatus(noAspectNode)); assertFalse(lockService.isLocked(noAspectNode)); // This lock should still be present. assertEquals(LockStatus.LOCK_OWNER, lockService.getLockStatus(rootNodeRef)); assertTrue(lockService.isLocked(rootNodeRef)); }
@Override public boolean enlistResource( final XAResource xaResource ) throws RollbackException, IllegalStateException, SystemException { if ( xaResource == null ) { return false; } return delegate.enlistResource( (XAResource) newProxyInstance( currentThread().getContextClassLoader(), new Class<?>[] { onePhaseXAResourceClass }, new DelegatingInvocationHandler( xaResource ) ) ); }
private void carRealTransactionalLifecycle(CarService carService) throws IllegalStateException, SystemException, NotSupportedException { assertNoCoordination(); if (carService.getCar(BLACK_CAR_PLATE) != null) { carService.deleteCar(BLUE_PLATE); } ut.begin(); carService.addCar(createBlueCar()); ut.rollback(); Assert.assertNull(carService.getCar(BLUE_PLATE)); }
/** * Get the status of the global transaction associated with this thread * * @see javax.transaction.TransactionManager#getStatus() */ public int getStatus() throws SystemException { if (!isActive) { throw new SystemException( LocalizedStrings.TransactionManagerImpl_TRANSACTIONMANAGER_INVALID.toLocalizedString()); } GlobalTransaction gtx = getGlobalTransaction(); if (gtx == null) { return Status.STATUS_NO_TRANSACTION; } return gtx.getStatus(); }
/** * This status is a combination of the internal status, as recorded during explicit operations, * and the status provided by the Spring support. * * @see Status */ public synchronized int getStatus() throws SystemException { TransactionInfo txnInfo = getTransactionInfo(); // if the txn info is null, then we are outside a transaction if (txnInfo == null) { return internalStatus; // this is checked in getTransactionInfo } // normally the internal status is correct, but we only need to double check // for the case where the transaction was marked for rollback, or rolledback // in a deeper transaction TransactionStatus txnStatus = txnInfo.getTransactionStatus(); if (internalStatus == Status.STATUS_ROLLEDBACK) { // explicitly rolled back at some point return internalStatus; } else if (txnStatus.isRollbackOnly()) { // marked for rollback at some point in the stack return Status.STATUS_MARKED_ROLLBACK; } else { // just rely on the internal status return internalStatus; } }
public synchronized void setRollbackOnly() throws IllegalStateException, SystemException { // just a check TransactionInfo txnInfo = getTransactionInfo(); int status = getStatus(); // check the status if (status == Status.STATUS_MARKED_ROLLBACK) { // this is acceptable } else if (status == Status.STATUS_NO_TRANSACTION) { throw new IllegalStateException("The transaction has not been started yet"); } else if (status == Status.STATUS_ROLLING_BACK || status == Status.STATUS_ROLLEDBACK) { throw new IllegalStateException("The transaction has already been rolled back"); } else if (status == Status.STATUS_COMMITTING || status == Status.STATUS_COMMITTED) { throw new IllegalStateException("The transaction has already been committed"); } else if (status != Status.STATUS_ACTIVE) { throw new IllegalStateException("The transaction is not active: " + status); } // mark for rollback txnInfo.getTransactionStatus().setRollbackOnly(); // make sure that we record the fact that we have been marked for rollback internalStatus = Status.STATUS_MARKED_ROLLBACK; // done if (logger.isDebugEnabled()) { logger.debug("Set transaction status to rollback only: " + this); } }
@Override public void setRollbackOnly() throws IllegalStateException { try { tm.setRollbackOnly(); } catch (SystemException e) { throw new IllegalStateException(e); } }
@Override public Transaction getTransaction() { try { javax.transaction.Transaction jtx = tm.getTransaction(); if (jtx == null) { return null; } return transactions.computeIfAbsent(jtx, this::doCreateTransactionWrapper); } catch (SystemException e) { throw new RuntimeException("Unable to get transaction", e); } }
@Override public Status getStatus() { try { if (suspended) { return Status.SUSPENDED; } return toStatus(getTransaction().getStatus()); } catch (SystemException e) { throw new RuntimeException("Exception caught while getting transaction status", e); } }
/** * Get the Global Transaction associated with the calling thread */ GlobalTransaction getGlobalTransaction() throws SystemException { Transaction txn = getTransaction(); if (txn == null) { return null; } GlobalTransaction gtx = (GlobalTransaction) globalTransactionMap.get(txn); return gtx; }
@Override protected Object doSuspend(Object transaction) { JtaTransactionObject txObject = (JtaTransactionObject) transaction; try { return doJtaSuspend(txObject); } catch (SystemException ex) { throw new TransactionSystemException("JTA failure on suspend", ex); } }
/** * Perform a JTA resume on the JTA TransactionManager. * <p>Can be overridden in subclasses, for specific JTA implementations. * @param txObject the JtaTransactionObject containing the UserTransaction * @param suspendedTransaction the suspended JTA Transaction object * @throws InvalidTransactionException if thrown by JTA methods * @throws SystemException if thrown by JTA methods * @see #getTransactionManager() * @see javax.transaction.TransactionManager#resume(javax.transaction.Transaction) */ protected void doJtaResume(JtaTransactionObject txObject, Object suspendedTransaction) throws InvalidTransactionException, SystemException { if (getTransactionManager() == null) { throw new TransactionSuspensionNotSupportedException( "JtaTransactionManager needs a JTA TransactionManager for suspending a transaction: " + "specify the 'transactionManager' or 'transactionManagerName' property"); } getTransactionManager().resume((Transaction) suspendedTransaction); }