javax.transaction.UserTransaction Java Examples

The following examples show how to use javax.transaction.UserTransaction. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JBossStandAloneJtaPlatform.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected UserTransaction locateUserTransaction() {
	//Try WildFly first as it's the "new generation":
	try {
		return wildflyBasedAlternative.locateUserTransaction();
	}
	catch ( Exception ignore) {
		// ignore and look for Arjuna class
	}

	try {
		final Class jbossUtClass = serviceRegistry()
				.getService( ClassLoaderService.class )
				.classForName( JBOSS_UT_CLASS_NAME );
		return (UserTransaction) jbossUtClass.getMethod( "userTransaction" ).invoke( null );
	}
	catch ( Exception e ) {
		throw new JtaPlatformException( "Could not obtain JBoss Transactions user transaction instance", e );
	}
}
 
Example #2
Source File: JtaTransactionManager.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Find the JTA UserTransaction through a default JNDI lookup:
 * "java:comp/UserTransaction".
 * @return the JTA UserTransaction reference, or {@code null} if not found
 * @see #DEFAULT_USER_TRANSACTION_NAME
 */
@Nullable
protected UserTransaction findUserTransaction() {
	String jndiName = DEFAULT_USER_TRANSACTION_NAME;
	try {
		UserTransaction ut = getJndiTemplate().lookup(jndiName, UserTransaction.class);
		if (logger.isDebugEnabled()) {
			logger.debug("JTA UserTransaction found at default JNDI location [" + jndiName + "]");
		}
		this.userTransactionObtainedFromJndi = true;
		return ut;
	}
	catch (NamingException ex) {
		if (logger.isDebugEnabled()) {
			logger.debug("No JTA UserTransaction found at default JNDI location [" + jndiName + "]", ex);
		}
		return null;
	}
}
 
Example #3
Source File: QueryAndJtaTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * verify that queries on indexes work with transaction
 * @see bug#40842
 * @throws Exception
 */
public void testIndexOnCommitForPut() throws Exception {
  AttributesFactory af = new AttributesFactory();
  af.setDataPolicy(DataPolicy.REPLICATE);
  Region region = cache.createRegion("sample", af.create());
  qs.createIndex("foo", IndexType.FUNCTIONAL, "age", "/sample");
  Context ctx = cache.getJNDIContext();
  UserTransaction utx = (UserTransaction)ctx.lookup("java:/UserTransaction");
  Integer x = new Integer(0);
  utx.begin();
  region.create(x, new Person("xyz", 45));
  utx.commit();
  Query q = qs.newQuery("select * from /sample where age < 50");
  assertEquals(1, ((SelectResults)q.execute()).size());
  Person dsample = (Person)CopyHelper.copy(region.get(x));
  dsample.setAge(55);
  utx.begin();
  region.put(x, dsample);
  utx.commit();
  System.out.println((region.get(x)));
  assertEquals(0, ((SelectResults) q.execute()).size());
}
 
Example #4
Source File: JtaTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithDoubleRollback() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	TransactionStatus status = ptm.getTransaction(new DefaultTransactionDefinition());
	assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
	// first rollback
	ptm.rollback(status);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	try {
		// second rollback attempt
		ptm.rollback(status);
		fail("Should have thrown IllegalTransactionStateException");
	}
	catch (IllegalTransactionStateException ex) {
		// expected
	}

	verify(ut).begin();
	verify(ut).rollback();
}
 
Example #5
Source File: JtaTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithExistingTransactionAndSynchronizationOnActual() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	final TransactionSynchronization synch = mock(TransactionSynchronization.class);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			TransactionSynchronizationManager.registerSynchronization(synch);
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setRollbackOnly();
	verify(synch).beforeCompletion();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
}
 
Example #6
Source File: UserTransactionFactory.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public Object getObjectInstance(final Object object, final Name name, final Context context, final Hashtable environment) throws Exception {
    // get the transaction manager
    final TransactionManager transactionManager = SystemInstance.get().getComponent(TransactionManager.class);
    if (transactionManager == null) {
        throw new NamingException("transaction manager not found");
    }

    // if transaction manager implements user transaction we are done
    if (transactionManager instanceof UserTransaction) {
        return transactionManager;
    }

    // wrap transaction manager with user transaction
    return new CoreUserTransaction(transactionManager);
}
 
Example #7
Source File: QueryAndJtaTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public void testIndexOnCommitForDestroy() throws Exception {
  AttributesFactory af = new AttributesFactory();
  af.setDataPolicy(DataPolicy.REPLICATE);
  Region region = cache.createRegion("sample", af.create());
  qs.createIndex("foo", IndexType.FUNCTIONAL, "age", "/sample");
  Context ctx = cache.getJNDIContext();
  UserTransaction utx = (UserTransaction)ctx.lookup("java:/UserTransaction");
  Integer x = new Integer(0);
  utx.begin();
  region.create(x, new Person("xyz", 45));
  utx.commit();
  Query q = qs.newQuery("select * from /sample where age < 50");
  assertEquals(1, ((SelectResults)q.execute()).size());
  Person dsample = (Person)CopyHelper.copy(region.get(x));
  dsample.setAge(55);
  utx.begin();
  region.destroy(x);
  utx.commit();
  System.out.println((region.get(x)));
  assertEquals(0, ((SelectResults) q.execute()).size());
}
 
Example #8
Source File: LazyCCMXATransactionTestCase.java    From ironjacamar with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Constructor
 * @param connectionFactory The CF
 * @param userTransaction The UT
 * @param enlist Enlistment
 * @param primary Primary worker
 * @param step1 Step 1 trigger
 * @param step2 Step 2 trigger
 * @param step3 Step 3 trigger
 * @param step4 Step 4 trigger
 * @param done Done trigger
 */
public Worker(LazyConnectionFactory connectionFactory, UserTransaction userTransaction,
              boolean enlist, boolean primary,
              CountDownLatch step1, CountDownLatch step2, CountDownLatch step3, CountDownLatch step4,
              CountDownLatch done)
{
   this.throwable = null;
   this.connectionFactory = connectionFactory;
   this.userTransaction = userTransaction;
   this.enlist = enlist;
   this.primary = primary;
   this.step1 = step1;
   this.step2 = step2;
   this.step3 = step3;
   this.step4 = step4;
   this.done = done;
}
 
Example #9
Source File: JtaTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationSupportsAndSynchronizationNever() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_NEVER);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
	ptm.afterPropertiesSet();

	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
 
Example #10
Source File: JtaTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithSystemExceptionOnIsExisting() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willThrow(new SystemException("system exception"));

	try {
		JtaTransactionManager ptm = newJtaTransactionManager(ut);
		TransactionTemplate tt = new TransactionTemplate(ptm);
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown TransactionSystemException");
	}
	catch (TransactionSystemException ex) {
		// expected
	}
}
 
Example #11
Source File: JtaTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithExistingAndPropagationSupports() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	final TransactionSynchronization synch = mock(TransactionSynchronization.class);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			TransactionSynchronizationManager.registerSynchronization(synch);
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setRollbackOnly();
	verify(synch).beforeCompletion();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
}
 
Example #12
Source File: JtaTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithIsolationLevel() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION);

	try {
		JtaTransactionManager ptm = newJtaTransactionManager(ut);
		TransactionTemplate tt = new TransactionTemplate(ptm);
		tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown InvalidIsolationLevelException");
	}
	catch (InvalidIsolationLevelException ex) {
		// expected
	}
}
 
Example #13
Source File: JtaTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithRollbackAndSynchronizationNever() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	ptm.setTransactionSynchronizationName("SYNCHRONIZATION_NEVER");
	tt.setTimeout(10);
	ptm.afterPropertiesSet();

	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setTransactionTimeout(10);
	verify(ut).begin();
	verify(ut, atLeastOnce()).getStatus();
	verify(ut).rollback();
}
 
Example #14
Source File: BeanManagedUserTransactionStrategy.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
protected void applyTransactionTimeout()
{
    Integer transactionTimeout = getDefaultTransactionTimeoutInSeconds();

    if (transactionTimeout == null)
    {
        //the default configured for the container will be used
        return;
    }

    try
    {
        UserTransaction userTransaction = resolveUserTransaction();

        if (userTransaction != null && userTransaction.getStatus() != Status.STATUS_ACTIVE)
        {
            userTransaction.setTransactionTimeout(transactionTimeout);
        }
    }
    catch (SystemException e)
    {
        LOGGER.log(Level.WARNING, "UserTransaction#setTransactionTimeout failed", e);
    }
}
 
Example #15
Source File: JtaTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithExistingTransactionAndRollbackOnly() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	final TransactionSynchronization synch = mock(TransactionSynchronization.class);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			TransactionSynchronizationManager.registerSynchronization(synch);
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setRollbackOnly();
	verify(synch).beforeCompletion();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
}
 
Example #16
Source File: JtaTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationSupportsAndSynchronizationOnActual() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
	ptm.afterPropertiesSet();

	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
 
Example #17
Source File: TransactionAwareSingletonTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testRollback() throws Throwable
{
    UserTransaction txn = transactionService.getUserTransaction();
    try
    {
        txn.begin();

        singleton.put(INTEGER_TWO);
        check(INTEGER_TWO, true);
        check(null, false);

        // rollback
        txn.rollback();
    }
    catch (Throwable e)
    {
        try { txn.rollback(); } catch (Throwable ee) {}
        throw e;
    }
    check(null, true);
    check(null, false);
}
 
Example #18
Source File: JtaTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithNotSupportedExceptionOnNestedBegin() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);
	willThrow(new NotSupportedException("not supported")).given(ut).begin();

	try {
		JtaTransactionManager ptm = newJtaTransactionManager(ut);
		TransactionTemplate tt = new TransactionTemplate(ptm);
		tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown NestedTransactionNotSupportedException");
	}
	catch (NestedTransactionNotSupportedException ex) {
		// expected
	}
}
 
Example #19
Source File: QueryAndJtaTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public void testIndexOnCommitForDestroy() throws Exception {
  AttributesFactory af = new AttributesFactory();
  af.setDataPolicy(DataPolicy.REPLICATE);
  Region region = cache.createRegion("sample", af.create());
  qs.createIndex("foo", IndexType.FUNCTIONAL, "age", "/sample");
  Context ctx = cache.getJNDIContext();
  UserTransaction utx = (UserTransaction)ctx.lookup("java:/UserTransaction");
  Integer x = new Integer(0);
  utx.begin();
  region.create(x, new Person("xyz", 45));
  utx.commit();
  Query q = qs.newQuery("select * from /sample where age < 50");
  assertEquals(1, ((SelectResults)q.execute()).size());
  Person dsample = (Person)CopyHelper.copy(region.get(x));
  dsample.setAge(55);
  utx.begin();
  region.destroy(x);
  utx.commit();
  System.out.println((region.get(x)));
  assertEquals(0, ((SelectResults) q.execute()).size());
}
 
Example #20
Source File: JtaTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithIllegalStateExceptionOnRollbackOnly() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);
	willThrow(new IllegalStateException("no existing transaction")).given(ut).setRollbackOnly();

	try {
		JtaTransactionManager ptm = newJtaTransactionManager(ut);
		TransactionTemplate tt = new TransactionTemplate(ptm);
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				status.setRollbackOnly();
			}
		});
		fail("Should have thrown TransactionSystemException");
	}
	catch (TransactionSystemException ex) {
		// expected
	}
}
 
Example #21
Source File: JtaTransaction.java    From cdi with Apache License 2.0 6 votes vote down vote up
private UserTransaction getUserTransaction() {
    try {
        logger.debug("Attempting to look up standard UserTransaction.");
        return (UserTransaction) new InitialContext().lookup(
                USER_TRANSACTION_LOCATION);
    } catch (NamingException ex) {
        logger.debug("Could not look up standard UserTransaction.", ex);

        try {
            logger.debug("Attempting to look up JBoss proprietary UserTransaction.");
            return (UserTransaction) new InitialContext().lookup(
                    JBOSS_USER_TRANSACTION_LOCATION);
        } catch (NamingException ex1) {
            logger.debug("Could not look up JBoss proprietary UserTransaction.", ex1);
        }
    }

    return null;
}
 
Example #22
Source File: JtaTransactionManager.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * This implementation returns a JtaTransactionObject instance for the
 * JTA UserTransaction.
 * <p>The UserTransaction object will either be looked up freshly for the
 * current transaction, or the cached one looked up at startup will be used.
 * The latter is the default: Most application servers use a shared singleton
 * UserTransaction that can be cached. Turn off the "cacheUserTransaction"
 * flag to enforce a fresh lookup for every transaction.
 * @see #setCacheUserTransaction
 */
@Override
protected Object doGetTransaction() {
	UserTransaction ut = getUserTransaction();
	if (ut == null) {
		throw new CannotCreateTransactionException("No JTA UserTransaction available - " +
				"programmatic PlatformTransactionManager.getTransaction usage not supported");
	}
	if (!this.cacheUserTransaction) {
		ut = lookupUserTransaction(
				this.userTransactionName != null ? this.userTransactionName : DEFAULT_USER_TRANSACTION_NAME);
	}
	return doGetJtaTransaction(ut);
}
 
Example #23
Source File: JtaTransactionManagerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void jtaTransactionManagerWithExistingTransactionAndCommitException() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	final TransactionSynchronization synch = mock(TransactionSynchronization.class);
	willThrow(new OptimisticLockingFailureException("")).given(synch).beforeCommit(false);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
				TransactionSynchronizationManager.registerSynchronization(synch);
			}
		});
		fail("Should have thrown OptimisticLockingFailureException");
	}
	catch (OptimisticLockingFailureException ex) {
		// expected
	}
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setRollbackOnly();
	verify(synch).beforeCompletion();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
}
 
Example #24
Source File: FileFolderServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testGetReaderWriter() throws Exception
{
    // testing a failure
    txn.commit();
    txn = transactionService.getUserTransaction();
    txn.begin();

    FileInfo dirInfo = getByName(NAME_L0_FOLDER_A, true);

    UserTransaction rollbackTxn = null;
    try
    {
        rollbackTxn = transactionService.getNonPropagatingUserTransaction();
        rollbackTxn.begin();
        fileFolderService.getWriter(dirInfo.getNodeRef());
        fail("Failed to detect content write to folder");
    }
    catch (RuntimeException e)
    {
        // expected
    }
    finally
    {
        rollbackTxn.rollback();
    }

    FileInfo fileInfo = getByName(NAME_L1_FILE_A, false);

    ContentWriter writer = fileFolderService.getWriter(fileInfo.getNodeRef());
    assertNotNull("Writer is null", writer);
    // write some content
    String content = "ABC";
    writer.putContent(content);
    // read the content
    ContentReader reader = fileFolderService.getReader(fileInfo.getNodeRef());
    assertNotNull("Reader is null", reader);
    String checkContent = reader.getContentString();
    assertEquals("Content mismatch", content, checkContent);
}
 
Example #25
Source File: CommentsApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 
 * @param nodeRef
 * @param user
 * @param expectedStatus
 * @return
 * @throws Exception
 */
private Response updateComment(NodeRef nodeRef, String user, int expectedStatus) throws Exception
{
    Response response = null;
    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();
    AuthenticationUtil.setFullyAuthenticatedUser(user);

    String now = System.currentTimeMillis()+"";

    JSONObject comment = new JSONObject();
    comment.put("title", "Test title updated "+now);
    comment.put("content", "Test comment updated "+now);

    response = sendRequest(new PutRequest(MessageFormat.format(URL_PUT_COMMENT,
            new Object[] {nodeRef.getStoreRef().getProtocol(), nodeRef.getStoreRef().getIdentifier(), nodeRef.getId()}), comment.toString(), JSON), expectedStatus);

    assertEquals(expectedStatus, response.getStatus());

    // Normally, webscripts are in their own transaction.  The test infrastructure here forces us to have a transaction
    // around the calls.  if the WebScript fails, then we should rollback.
    if (response.getStatus() == 500)
    {
        txn.rollback();
    }
    else
    {
        txn.commit();
    }
    
    return response;
}
 
Example #26
Source File: CacheTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Add 50K objects into the transactional cache and checks that the first object added
 * has been discarded.
 */
public void testMaxSizeOverrun() throws Exception
{
    TransactionService transactionService = serviceRegistry.getTransactionService();
    UserTransaction txn = transactionService.getUserTransaction();
    try
    {
        txn.begin();
        
        Object startValue = new Integer(-1);
        String startKey = startValue.toString();
        transactionalCache.put(startKey, startValue);
        
        assertEquals("The start value isn't correct", startValue, transactionalCache.get(startKey));
        
        for (int i = 0; i < 205000; i++)
        {
            Object value = Integer.valueOf(i);
            String key = value.toString();
            transactionalCache.put(key, value);
        }
        
        // Is the start value here?
        Object checkStartValue = transactionalCache.get(startKey);
        // Now, the cache should no longer contain the first value
        assertNull("The start value didn't drop out of the cache", checkStartValue);
        
        txn.commit();
    }
    finally
    {
        try { txn.rollback(); } catch (Throwable ee) {}
    }
}
 
Example #27
Source File: PolicyComponentTransactionTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Test for MNT-13836 (new API)
 * @throws Exception
 */
public void testBehaviourHierarchySequence1() throws Exception
{
    UserTransaction transaction = trxService.getUserTransaction();
    try
    {
        transaction.begin();
        disableBehaviours(new ClassFilter(A_TYPE, true), new ClassFilter(B_TYPE, true));

        behaviourFilter.enableBehaviour(B_TYPE);
        // Should be still disabled
        checkBehaviour(B_TYPE, companyHome, true, false, false, true);
        try
        {
            createDocOfType(C_TYPE);
        }
        finally
        {
            enableBehaviours(new ClassFilter(A_TYPE, true), new ClassFilter(B_TYPE, true));
        }
        transaction.commit();
    }
    catch(Exception e)
    {
        try { transaction.rollback(); } catch (IllegalStateException ee) {}
        throw e;
    }
    assertFalse("Behavior should not be executed for a_type.", aTypeBehavior.isExecuted());
    assertEquals(0, aTypeBehavior.getExecutionCount());
    assertFalse("Behavior should not be executed for b_type.", bTypeBehavior.isExecuted());
    assertEquals(0, bTypeBehavior.getExecutionCount());
    assertFalse("Behavior should not be executed for c_type.", cTypeBehavior.isExecuted());
    assertEquals(0, cTypeBehavior.getExecutionCount());
}
 
Example #28
Source File: TransactionUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/** Gets the status of the transaction in the current thread IF
 * transactions are available, otherwise returns STATUS_NO_TRANSACTION */
public static int getStatus() throws GenericTransactionException {
    UserTransaction ut = TransactionFactoryLoader.getInstance().getUserTransaction();
    if (ut != null) {
        try {
            return ut.getStatus();
        } catch (SystemException e) {
            throw new GenericTransactionException("System error, could not get status", e);
        }
    }
    return STATUS_NO_TRANSACTION;
}
 
Example #29
Source File: SpringAwareUserTransactionTest.java    From alfresco-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private UserTransaction getTxn()
{
    return new SpringAwareUserTransaction(
            transactionManager,
            false,
            TransactionDefinition.ISOLATION_DEFAULT,
            TransactionDefinition.PROPAGATION_REQUIRED,
            TransactionDefinition.TIMEOUT_DEFAULT);
}
 
Example #30
Source File: NarayanaConfigurationIT.java    From narayana-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void allDefaultBeansShouldBeLoaded() {
    this.context = new AnnotationConfigApplicationContext(NarayanaConfiguration.class);
    this.context.getBean(NarayanaBeanFactoryPostProcessor.class);
    this.context.getBean(XADataSourceWrapper.class);
    this.context.getBean(XAConnectionFactoryWrapper.class);
    this.context.getBean(NarayanaPropertiesInitializer.class);
    this.context.getBean(UserTransaction.class);
    this.context.getBean(TransactionManager.class);
    this.context.getBean(JtaTransactionManager.class);
    this.context.getBean(RecoveryManagerService.class);
    this.context.getBean(XARecoveryModule.class);
}