/** * Create, find and delete car using XA Transactions * @param ut * @param em * @throws Exception */ protected void carLifecycleXA(UserTransaction ut, EntityManager em) throws Exception { ut.begin(); em.joinTransaction(); delete(em, Car.class, BLUE_PLATE); em.persist(createBlueCar()); ut.commit(); Car c = em.find(Car.class, BLUE_PLATE); assertBlueCar(c); ut.begin(); em.joinTransaction(); delete(em, Car.class, BLUE_PLATE); ut.commit(); }
/** * Create, find and delete car using XA Transactions * @param ut * @param em * @throws Exception */ protected void truckLifecycleXA(UserTransaction ut, EntityManager em) throws Exception { ut.begin(); em.joinTransaction(); delete(em, Truck.class, BLUE_PLATE); em.persist(createBlueTruck()); ut.commit(); Truck t = em.find(Truck.class, BLUE_PLATE); assertBlueTruck(t); ut.begin(); em.joinTransaction(); delete(em, Truck.class, BLUE_PLATE); ut.commit(); }
/** * If <em>wrapInUserTransaction</em> is true, starts a new UserTransaction * and returns it. Otherwise, or if establishing the transaction fail, it * will return null. */ private UserTransaction startUserTransaction() { if (wrapInUserTransaction == false) { return null; } UserTransaction userTransaction = null; try { userTransaction = UserTransactionHelper.lookupUserTransaction(); userTransaction.begin(); } catch (Throwable t) { UserTransactionHelper.returnUserTransaction(userTransaction); userTransaction = null; getLog().error("Failed to start UserTransaction for plugin: " + getName(), t); } return userTransaction; }
public void testMNT10533() throws Exception { String GROUP_NAME = "testMNT10533"; String GROUP_FULL_NAME = "GROUP_" + GROUP_NAME; policyComponent.bindClassBehaviour(QName.createQName(NamespaceService.ALFRESCO_URI, "beforeDeleteNode"), ContentModel.TYPE_AUTHORITY_CONTAINER, new JavaBehaviour( new GroupBehaviour(), "beforeDeleteNode")); UserTransaction transaction = null; transaction = transactionService.getUserTransaction(); transaction.begin(); try { authorityService.createAuthority(AuthorityType.GROUP, GROUP_NAME); assertNotNull(authorityService.getAuthorityNodeRef(GROUP_FULL_NAME)); authorityService.deleteAuthority(GROUP_FULL_NAME); assertNull(authorityService.getAuthorityNodeRef(GROUP_FULL_NAME)); } finally { transaction.commit(); } }
/** * 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 */ 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; } }
private void createUser(String userName) throws Exception { UserTransaction txn = transactionService.getUserTransaction(); try { txn.begin(); authenticationService.createAuthentication(userName, userName.toCharArray()); PropertyMap ppOne = new PropertyMap(4); ppOne.put(ContentModel.PROP_USERNAME, userName); ppOne.put(ContentModel.PROP_FIRSTNAME, userName.substring(0, userName.length()-4)); ppOne.put(ContentModel.PROP_LASTNAME, "user"); ppOne.put(ContentModel.PROP_EMAIL, userName + "@email.com"); ppOne.put(ContentModel.PROP_JOBTITLE, "jobTitle"); personService.createPerson(ppOne); txn.commit(); } catch (Exception e) { txn.rollback(); throw e; } }
private void createGroup(String groupName) throws Exception { UserTransaction txn = transactionService.getUserTransaction(); try { txn.begin(); authorityService.createAuthority(AuthorityType.GROUP, groupName); txn.commit(); } catch (Exception e) { txn.rollback(); throw e; } }
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); } }
@Override public void tearDown() throws Exception { // Deleting created test environment logger.debug("tearDown "); UserTransaction txn = transactionService.getUserTransaction(); txn.begin(); List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, companyHomePathInStore + "/" + NamespaceService.CONTENT_MODEL_PREFIX + ":" + IMAP_FOLDER_NAME, null, namespaceService, false); if (nodeRefs != null && nodeRefs.size() > 0) { fileFolderService.delete(nodeRefs.get(0)); } authenticationService.deleteAuthentication(anotherUserName); personService.deletePerson(anotherUserName); txn.commit(); // Closing client connection folder.close(false); store.close(); logger.debug("tearDown end"); }
public void behaviourHierarchyTestWork(QName createDocType, ClassFilter... disableTypes) throws Exception { UserTransaction transaction = trxService.getUserTransaction(); try { transaction.begin(); disableBehaviours(disableTypes); try { createDocOfType(createDocType); } finally { enableBehaviours(disableTypes); } transaction.commit(); } catch(Exception e) { try { transaction.rollback(); } catch (IllegalStateException ee) {} throw e; } }
/** * Monkeys with the created date on a link */ private void pushLinkCreatedDateBack(String name, int daysAgo) throws Exception { NodeRef container = siteService.getContainer(SITE_SHORT_NAME_LINKS, "links"); NodeRef node = nodeService.getChildByName(container, ContentModel.ASSOC_CONTAINS, name); Date created = (Date)nodeService.getProperty(node, ContentModel.PROP_CREATED); Date newCreated = new Date(created.getTime() - daysAgo*24*60*60*1000); UserTransaction txn = transactionService.getUserTransaction(); txn.begin(); this.policyBehaviourFilter.disableBehaviour(ContentModel.ASPECT_AUDITABLE); internalNodeService.setProperty(node, ContentModel.PROP_CREATED, newCreated); this.policyBehaviourFilter.enableBehaviour(ContentModel.ASPECT_AUDITABLE); txn.commit(); // Now chance something else on the node to have it re-indexed nodeService.setProperty(node, ContentModel.PROP_CREATED, newCreated); nodeService.setProperty(node, ContentModel.PROP_DESCRIPTION, "Forced change"); }
/** * @see TradeServices#getQuote(String) */ public QuoteDataBean getQuote(String symbol) throws Exception { QuoteDataBean quoteData = null; Connection conn = null; UserTransaction txn = null; try { if (Log.doTrace()) Log.trace("TradeDirect:getQuote - inSession(" + this.inSession + ")", symbol); conn = getConn(); quoteData = getQuote(conn, symbol); commit(conn); } catch (Exception e) { Log.error("TradeDirect:getQuote -- error getting quote", e); rollBack(conn, e); } finally { releaseConn(conn); } return quoteData; }
@Test public void testIndexOnCommitForInvalidate() 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.invalidate(x); utx.commit(); CacheUtils.log(((Person) region.get(x))); assertEquals(0, ((SelectResults) q.execute()).size()); }
/** * Monkeys with the created and published dates on a topic+posts */ private void pushCreatedDateBack(NodeRef node, int daysAgo) throws Exception { Date created = (Date)nodeService.getProperty(node, ContentModel.PROP_CREATED); Date newCreated = new Date(created.getTime() - daysAgo*24*60*60*1000); Date published = (Date)nodeService.getProperty(node, ContentModel.PROP_PUBLISHED); if(published == null) published = created; Date newPublished = new Date(published.getTime() - daysAgo*24*60*60*1000); UserTransaction txn = transactionService.getUserTransaction(); txn.begin(); this.policyBehaviourFilter.disableBehaviour(ContentModel.ASPECT_AUDITABLE); internalNodeService.setProperty(node, ContentModel.PROP_CREATED, newCreated); internalNodeService.setProperty(node, ContentModel.PROP_MODIFIED, newCreated); internalNodeService.setProperty(node, ContentModel.PROP_PUBLISHED, newPublished); this.policyBehaviourFilter.enableBehaviour(ContentModel.ASPECT_AUDITABLE); txn.commit(); // Now chance something else on the node to have it re-indexed nodeService.setProperty(node, ContentModel.PROP_CREATED, newCreated); nodeService.setProperty(node, ContentModel.PROP_MODIFIED, newCreated); nodeService.setProperty(node, ContentModel.PROP_PUBLISHED, newPublished); nodeService.setProperty(node, ContentModel.PROP_DESCRIPTION, "Forced change"); // Finally change any children (eg if updating a topic, do the posts) for(ChildAssociationRef ref : nodeService.getChildAssocs(node)) { pushCreatedDateBack(ref.getChildRef(), daysAgo); } }
@Override protected UserTransaction locateUserTransaction() { 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 ); } }
/** * Find the JTA TransactionManager through autodetection: checking whether the * UserTransaction object implements the TransactionManager, and checking the * fallback JNDI locations. * @param ut the JTA UserTransaction object * @return the JTA TransactionManager reference, or {@code null} if not found * @see #FALLBACK_TRANSACTION_MANAGER_NAMES */ protected TransactionManager findTransactionManager(UserTransaction ut) { if (ut instanceof TransactionManager) { if (logger.isDebugEnabled()) { logger.debug("JTA UserTransaction object [" + ut + "] implements TransactionManager"); } return (TransactionManager) ut; } // Check fallback JNDI locations. for (String jndiName : FALLBACK_TRANSACTION_MANAGER_NAMES) { try { TransactionManager tm = getJndiTemplate().lookup(jndiName, TransactionManager.class); if (logger.isDebugEnabled()) { logger.debug("JTA TransactionManager found at fallback JNDI location [" + jndiName + "]"); } return tm; } catch (NamingException ex) { if (logger.isDebugEnabled()) { logger.debug("No JTA TransactionManager found at fallback JNDI location [" + jndiName + "]", ex); } } } // OK, so no JTA TransactionManager is available... return null; }
/** * Based on the value of <em>wrapInUserTransaction</em>, wraps the * call to shutdown(UserTransaction) in a UserTransaction. */ public void shutdown() { UserTransaction userTransaction = startUserTransaction(); try { shutdown(userTransaction); } finally { resolveUserTransaction(userTransaction); } }
/** * Check if the user is an administrator user name * * @param cInfo ClientInfo */ protected final void checkForAdminUserName(ClientInfo cInfo) { // Check if the user name is an administrator UserTransaction tx = getTransactionService().getUserTransaction(); try { tx.begin(); if ( cInfo.getLogonType() == ClientInfo.LogonNormal && getAuthorityService().isAdminAuthority(cInfo.getUserName())) { // Indicate that this is an administrator logon cInfo.setLogonType(ClientInfo.LogonAdmin); } tx.commit(); } catch (Throwable ex) { try { tx.rollback(); } catch (Throwable ex2) { logger.error("Failed to rollback transaction", ex2); } // Re-throw the exception if ( ex instanceof RuntimeException) { throw (RuntimeException) ex; } else { throw new RuntimeException("Error during execution of transaction.", ex); } } }
@Test public void test000Noninvolvement() throws Exception { try { if (cache == null) { createCache(false); } javax.transaction.UserTransaction ut = (javax.transaction.UserTransaction) cache .getJNDIContext().lookup("java:/UserTransaction"); { ut.begin(); txRegion.put("transactionalPut", "xxx"); assertTrue("expect cache to be in a transaction", cache.getCacheTransactionManager().exists()); ut.commit(); } assertFalse("ensure there is no transaction before testing non-involvement", cache.getCacheTransactionManager().exists()); { ut.begin(); nonTxRegion.put("nontransactionalPut", "xxx"); assertFalse("expect cache to not be in a transaction", cache.getCacheTransactionManager().exists()); ut.commit(); } } finally { closeCache(); cache = null; } }
/** * MNT-9771 * @throws Exception */ public void testCommentPermissions() throws Exception { authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName()); UserTransaction txn = transactionService.getUserTransaction(); txn.begin(); NodeRef contentForUserContributor = fileFolderService.create(companyHomeNodeRef, "CommentyContributor" + System.currentTimeMillis(), ContentModel.TYPE_CONTENT).getNodeRef(); permissionService.setPermission(new SimplePermissionEntry(contentForUserContributor, getPermission(PermissionService.CONTRIBUTOR), USER_TEST, AccessStatus.ALLOWED)); NodeRef contentForUserConsumer = fileFolderService.create(companyHomeNodeRef, "CommentyConsumer" + System.currentTimeMillis(), ContentModel.TYPE_CONTENT).getNodeRef(); permissionService.setPermission(new SimplePermissionEntry(contentForUserConsumer, getPermission(PermissionService.CONSUMER), USER_TEST, AccessStatus.ALLOWED)); //Contributor should be able to add comments addComment(contentForUserContributor, USER_TEST, 200); txn.commit(); // Hack. Internally, the addComment starts and rolls back the next txn. //Consumer shouldn't be able to add comments see MNT-9883 addComment(contentForUserConsumer, USER_TEST, 500); txn = transactionService.getUserTransaction(); txn.begin(); nodeService.deleteNode(contentForUserContributor); nodeService.deleteNode(contentForUserConsumer); txn.commit(); }
private UserTransaction locateUserTransaction() { final UserTransaction userTransaction = jtaPlatform().retrieveUserTransaction(); if ( userTransaction == null ) { throw new TransactionException( "Unable to locate JTA UserTransaction" ); } return userTransaction; }
@Test public void test1One() throws Exception { UserTransaction utx = new UserTransactionImpl(); utx.begin(); Thread.sleep(2000); utx.setTransactionTimeout(2); utx.setTransactionTimeout(200); utx.setTransactionTimeout(3); Thread.sleep(5000); // utx.commit(); }
public BeanUsuarios() { try { ctx = new InitialContext(); utx = (UserTransaction) ctx.lookup("java:comp/env/UserTransaction"); em = (EntityManager) ctx.lookup("java:comp/env/persistence/LogicalName"); jpa = new UsuarioJpaController(utx, em.getEntityManagerFactory()); } catch (NamingException ex) { } }
@Override protected void tearDown() throws Exception { super.tearDown(); UserTransaction txn = transactionService.getUserTransaction(); txn.begin(); personManager.clearPeople(); // Zap any replication definitions we created AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName()); for(ReplicationDefinition rd : replicationService.loadReplicationDefinitions()) { replicationService.deleteReplicationDefinition(rd); } AuthenticationUtil.clearCurrentSecurityContext(); // Clear out the running actions for(ExecutionSummary es : actionTrackingService.getAllExecutingActions()) { executingActionsCache.remove( AbstractActionWebscript.getRunningId(es) ); } txn.commit(); }
public void testStartNewTransaction() throws Exception { // MNT-10096 class CustomListenerAdapter extends TransactionListenerAdapter { private String newTxnId; @Override public void afterRollback() { newTxnId = txnHelper.doInTransaction(new RetryingTransactionCallback<String>() { @Override public String execute() throws Throwable { return AlfrescoTransactionSupport.getTransactionId(); } }, true, false); } } UserTransaction txn = transactionService.getUserTransaction(); txn.begin(); String txnId = AlfrescoTransactionSupport.getTransactionId(); CustomListenerAdapter listener = new CustomListenerAdapter(); AlfrescoTransactionSupport.bindListener(listener); txn.rollback(); assertFalse("New transaction has not started", txnId.equals(listener.newTxnId)); }
/** * Create a new JtaTransactionManager instance. * @param userTransaction the JTA UserTransaction to use as direct reference * @param transactionManager the JTA TransactionManager to use as direct reference */ public JtaTransactionManager(UserTransaction userTransaction, TransactionManager transactionManager) { this(); Assert.notNull(userTransaction, "UserTransaction must not be null"); Assert.notNull(transactionManager, "TransactionManager must not be null"); this.userTransaction = userTransaction; this.transactionManager = transactionManager; }
private void deleteSite(String siteName, String doAsUser) throws Exception { String currentUser = authenticationComponent.getCurrentUserName(); UserTransaction txn = transactionService.getUserTransaction(); try { if (doAsUser != null) authenticationComponent.setCurrentUser(doAsUser); txn.begin(); siteService.deleteSite(siteName); txn.commit(); } catch (Exception e) { try { txn.rollback(); } catch (Exception e2) { } throw e; } finally { authenticationComponent.setCurrentUser(currentUser); } }
public boolean authenticate(RequiredAuthentication required, boolean isGuest) { // first look for the username key in the session - we add this by hand for some portals // when the WebScriptPortletRequest is created String portalUser = (String)req.getPortletSession().getAttribute(WebScriptPortletRequest.ALFPORTLETUSERNAME); if (portalUser == null) { portalUser = req.getRemoteUser(); } if (logger.isDebugEnabled()) { logger.debug("JSR-168 Remote user: " + portalUser); } if (isGuest || portalUser == null) { if (logger.isDebugEnabled()) logger.debug("Authenticating as Guest"); // authenticate as guest AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getGuestUserName()); } else { if (logger.isDebugEnabled()) logger.debug("Authenticating as user " + portalUser); UserTransaction txn = null; try { txn = txnService.getUserTransaction(); txn.begin(); if (!unprotAuthenticationService.authenticationExists(portalUser)) { throw new WebScriptException(HttpServletResponse.SC_FORBIDDEN, "User " + portalUser + " is not a known Alfresco user"); } AuthenticationUtil.setFullyAuthenticatedUser(portalUser); } catch (Throwable err) { throw new AlfrescoRuntimeException("Error authenticating user: " + portalUser, err); } finally { try { if (txn != null) { txn.rollback(); } } catch (Exception tex) { // nothing useful we can do with this } } } return true; }
/** * Test for MNT-13836 (new API) * @throws Exception */ public void testIsEnabled2() throws Exception { UserTransaction transaction = trxService.getUserTransaction(); try { transaction.begin(); disableBehaviours(new ClassFilter(B_TYPE, false)); try { assertEquals("Incorrect behaviour state: global: ", true, behaviourFilter.isEnabled()); // A_TYPE assertEquals("Incorrect behaviour state: class: ", true, behaviourFilter.isEnabled(A_TYPE)); assertEquals("Incorrect behaviour state: classAndInstance", true, behaviourFilter.isEnabled(companyHome, A_TYPE)); assertEquals("Incorrect behaviour state: instance", true, behaviourFilter.isEnabled(companyHome)); // B_TYPE assertEquals("Incorrect behaviour state: class: ", false, behaviourFilter.isEnabled(B_TYPE)); assertEquals("Incorrect behaviour state: classAndInstance", false, behaviourFilter.isEnabled(companyHome, B_TYPE)); assertEquals("Incorrect behaviour state: instance", true, behaviourFilter.isEnabled(companyHome)); // C_TYPE assertEquals("Incorrect behaviour state: class: ", true, behaviourFilter.isEnabled(C_TYPE)); assertEquals("Incorrect behaviour state: classAndInstance", true, behaviourFilter.isEnabled(companyHome, C_TYPE)); assertEquals("Incorrect behaviour state: instance", true, behaviourFilter.isEnabled(companyHome)); } finally { behaviourFilter.enableBehaviour(B_TYPE); } transaction.commit(); } catch(Exception e) { try { transaction.rollback(); } catch (IllegalStateException ee) {} throw e; } }
@Test public void test3ExceptionOnCommitAfterTimeOut() throws Exception { UserTransaction utx; utx = new UserTransactionImpl(); utx.setTransactionTimeout(2); utx.begin(); Thread.sleep(4000); try { utx.commit(); fail("TimeOut did not rollback the transaction"); } catch (Exception expected) { } }
/** * Test for MNT-13836 (new API) * @throws Exception */ public void testBehaviourHierarchySequence2() throws Exception { UserTransaction transaction = trxService.getUserTransaction(); try { transaction.begin(); disableBehaviours(new ClassFilter(A_TYPE, false), new ClassFilter(B_TYPE, true)); behaviourFilter.enableBehaviour(B_TYPE); assertEquals("Incorrect behaviour state: class: ", true, behaviourFilter.isEnabled(B_TYPE)); assertEquals("Incorrect behaviour state: classAndInstance", true, behaviourFilter.isEnabled(companyHome, B_TYPE)); assertEquals("Incorrect behaviour state: instance", true, behaviourFilter.isEnabled(companyHome)); 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; } assertTrue("Behavior should be executed for a_type.", aTypeBehavior.isExecuted()); assertEquals(1, aTypeBehavior.getExecutionCount()); assertTrue("Behavior should be executed for b_type.", bTypeBehavior.isExecuted()); assertEquals(1, bTypeBehavior.getExecutionCount()); assertTrue("Behavior should be executed for c_type.", cTypeBehavior.isExecuted()); assertEquals(1, cTypeBehavior.getExecutionCount()); }
/** * Build a UserTransaction handle based on the given TransactionManager. * @param transactionManager the TransactionManager * @return a corresponding UserTransaction handle */ protected UserTransaction buildUserTransaction(TransactionManager transactionManager) { if (transactionManager instanceof UserTransaction) { return (UserTransaction) transactionManager; } else { return new UserTransactionAdapter(transactionManager); } }
@Test public void test5TimeOutBeforeBegin() throws Exception { UserTransaction utx = new UserTransactionImpl(); utx.setTransactionTimeout(4); utx.begin(); Thread.sleep(6000); try { utx.commit(); fail("TimeOut did not rollback the transaction"); } catch (Exception expected) { } }
@Test public void testNotOnlyCurrentLockOwnerCanChangeInfo() throws NotSupportedException, SystemException { final TransactionService txService = (TransactionService) ctx.getBean("TransactionService"); UserTransaction txA = txService.getUserTransaction(); final NodeRef nodeRef = new NodeRef("workspace://SpacesStore/UUID-1"); Date now = new Date(); Date expires = new Date(now.getTime() + 180000); final LockState lockState1 = LockState.createLock(nodeRef, LockType.WRITE_LOCK, "jbloggs", expires, Lifetime.EPHEMERAL, null); txA.begin(); try { AuthenticationUtil.setFullyAuthenticatedUser("jbloggs"); // Set initial lock state lockStore.set(nodeRef, lockState1); // Set different lock state // Current lock owner is still authenticated (jbloggs) final LockState lockState2 = LockState.createWithOwner(lockState1, "csmith"); lockStore.set(nodeRef, lockState2); // Check update assertEquals(lockState2, lockStore.get(nodeRef)); // Incorrect lock owner - this shouldn't fail. See ACE-2181 final LockState lockState3 = LockState.createWithOwner(lockState1, "dsmithers"); lockStore.set(nodeRef, lockState3); // Check update. assertEquals(lockState3, lockStore.get(nodeRef)); } finally { txA.rollback(); } }
@Test public void test6CommitBeforeTimeOut() throws Exception { UserTransaction utx = new UserTransactionImpl(); utx.begin(); utx.setTransactionTimeout(6); Thread.sleep(2000); utx.commit(); }
/** * Tests a straight Ehcache adapter against a transactional cache both in and out * of a transaction. This is done repeatedly, pushing the count up. */ public void testPerformance() throws Exception { for (int i = 0; i < 6; i++) { int count = (int) Math.pow(10D, (double)i); // test standalone long timePlain = runPerformanceTestOnCache(objectCache, count); // do transactional cache in a transaction TransactionService transactionService = serviceRegistry.getTransactionService(); UserTransaction txn = transactionService.getUserTransaction(); txn.begin(); long timeTxn = runPerformanceTestOnCache(transactionalCache, count); long commitStart = System.nanoTime(); txn.commit(); long commitEnd = System.nanoTime(); long commitTime = (commitEnd - commitStart); // add this to the cache's performance overhead timeTxn += commitTime; // report System.out.println("Cache performance test: \n" + " count: " + count + "\n" + " direct: " + timePlain/((long)count) + " ns\\count \n" + " transaction: " + timeTxn/((long)count) + " ns\\count"); } }
/** * 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) {} } }
/** Execute the callback and ensure that the backing cache is left with the expected value */ private void executeAndCheck( RetryingTransactionCallback<Object> callback, boolean readOnly, String key, Object expectedValue, boolean mustContainKey) throws Throwable { if (expectedValue != null && !mustContainKey) { throw new IllegalArgumentException("Why have a value when the key should not be there?"); } TransactionService transactionService = serviceRegistry.getTransactionService(); UserTransaction txn = transactionService.getUserTransaction(readOnly); try { txn.begin(); callback.execute(); txn.commit(); } finally { try { txn.rollback(); } catch (Throwable ee) {} } Object actualValue = TransactionalCache.getSharedCacheValue(backingCache, key, null); assertEquals("Backing cache value was not correct", expectedValue, actualValue); assertEquals("Backing cache contains(key): ", mustContainKey, backingCache.contains(key)); // Clear the backing cache to ensure that subsequent tests don't run into existing data backingCache.clear(); }
protected void setUp() throws Exception { ctx = ApplicationContextHelper.getApplicationContext(); DictionaryDAO dictionaryDao = (DictionaryDAO) ctx.getBean("dictionaryDAO"); // load the system model ClassLoader cl = BaseNodeServiceTest.class.getClassLoader(); InputStream modelStream = cl.getResourceAsStream("alfresco/model/systemModel.xml"); assertNotNull(modelStream); M2Model model = M2Model.createModel(modelStream); dictionaryDao.putModel(model); // load the test model modelStream = cl.getResourceAsStream("org/alfresco/repo/node/BaseNodeServiceTest_model.xml"); assertNotNull(modelStream); model = M2Model.createModel(modelStream); dictionaryDao.putModel(model); nodeService = (NodeService) ctx.getBean("dbNodeService"); transactionService = (TransactionService) ctx.getBean("transactionComponent"); this.authenticationComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent"); this.authenticationComponent.setSystemUserAsCurrentUser(); // create a first store directly UserTransaction tx = transactionService.getUserTransaction(); tx.begin(); StoreRef storeRef = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis()); rootNodeRef = nodeService.getRootNode(storeRef); tx.commit(); }
/** * Based on the value of <em>wrapInUserTransaction</em>, wraps the * call to start(UserTransaction) in a UserTransaction. */ public void start() { UserTransaction userTransaction = startUserTransaction(); try { start(userTransaction); } finally { resolveUserTransaction(userTransaction); } }