Java Code Examples for org.alfresco.service.transaction.TransactionService

The following are top voted examples for showing how to use org.alfresco.service.transaction.TransactionService. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: alfresco-repository   File: FileFolderLoader.java   View source code 7 votes vote down vote up
/**
 * @param repoState             keep track of repository readiness
 * @param transactionService    ensure proper rollback, where required
 * @param repositoryHelper      access standard repository paths
 * @param fileFolderService     perform actual file-folder manipulation
 */
public FileFolderLoader(
        RepositoryState repoState,
        TransactionService transactionService,
        Repository repositoryHelper,
        FileFolderService fileFolderService,
        NodeService nodeService,
        ContentService contentService,
        BehaviourFilter policyBehaviourFilter)
{
    this.repoState = repoState;
    this.transactionService = transactionService;
    this.repositoryHelper = repositoryHelper;
    this.fileFolderService = fileFolderService;
    this.nodeService = nodeService;
    this.contentService = contentService;
    this.policyBehaviourFilter = policyBehaviourFilter;
    
    this.normalDistribution = new NormalDistributionHelper();
}
 
Example 2
Project: alfresco-repository   File: ModelValidatorTest.java   View source code 7 votes vote down vote up
@Before
public void setUp() throws Exception
{
    ctx = ApplicationContextHelper.getApplicationContext();
    this.modelValidator = (ModelValidator)ctx.getBean("modelValidator");
    this.dictionaryDAO = (DictionaryDAO)ctx.getBean("dictionaryDAO");
    this.qnameDAO = (QNameDAO)ctx.getBean("qnameDAO");
    this.namespaceDAO = (NamespaceDAO)ctx.getBean("namespaceDAO");
    this.nodeService = (NodeService)ctx.getBean("NodeService");
    this.fileFolderService = (FileFolderService)ctx.getBean("FileFolderService");
    this.contentService = (ContentService)ctx.getBean("contentService");
    this.versionService = (VersionService)ctx.getBean("VersionService");
    this.transactionService = (TransactionService)ctx.getBean("TransactionService");
    this.nodeArchiveService = (NodeArchiveService)ctx.getBean("nodeArchiveService");

    this.modelName = "modelvalidatortest" + System.currentTimeMillis();
    addModel();
}
 
Example 3
Project: alfresco-repository   File: MultiTNodeServiceInterceptorTest.java   View source code 6 votes vote down vote up
@Override
public void setUp() throws Exception
{
    transactionService = (TransactionService) ctx.getBean("TransactionService");
    tenantAdminService = (TenantAdminService) ctx.getBean("tenantAdminService");
    tenantService = (TenantService) ctx.getBean("tenantService");
    interceptor = (MultiTNodeServiceInterceptor) ctx.getBean("multiTNodeServiceInterceptor");
    
    // If MT is disabled, then disable all tests
    if (!tenantAdminService.isEnabled())
    {
        enableTest = false;
        return;
    }
    
    // Create a tenant
    RetryingTransactionCallback<Object> createTenantCallback = new RetryingTransactionCallback<Object>()
    {
        public Object execute() throws Throwable
        {
            tenantAdminService.createTenant(tenant1, tenant1Pwd.toCharArray());
            return null;
        }
    };
    transactionService.getRetryingTransactionHelper().doInTransaction(createTenantCallback, false, true);
}
 
Example 4
Project: alfresco-repository   File: LockKeeperImplTest.java   View source code 6 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    applicationContext = ApplicationContextHelper.getApplicationContext();
    nodeService = (NodeService)applicationContext.getBean("nodeService");
    repositoryHelper = (Repository)this.applicationContext.getBean("repositoryHelper");
    transactionService = (TransactionService)applicationContext.getBean("transactionService");
    
    ChildApplicationContextFactory fileServersSubSystem = (ChildApplicationContextFactory) applicationContext.getBean("fileServers");
    assertNotNull("fileServers subsystem is null", fileServersSubSystem);
    lockKeeper =  (LockKeeper)fileServersSubSystem.getApplicationContext().getBean("lockKeeper");
    
	assertNotNull("nodeService is null", nodeService);
	assertNotNull("lockKeeper is null", lockKeeper);
	assertNotNull("transactionService is null", transactionService);

    
    AuthenticationUtil.setRunAsUserSystem();
    AuthenticationUtil.setFullyAuthenticatedUser("bugsBunny");
}
 
Example 5
Project: alfresco-repository   File: CifsAuthenticatorBase.java   View source code 6 votes vote down vote up
/**
 * Does work in a transaction. This will be a writeable transaction unless the system is in read-only mode.
 * 
 * @param callback
 *            a callback that does the work
 * @return the result, or <code>null</code> if not applicable
 */
protected <T> T doInTransaction(RetryingTransactionHelper.RetryingTransactionCallback<T> callback)
{
    // Get the transaction service

    TransactionService txService = getTransactionService();
    
 // the repository is read-only, we settle for a read-only transaction
 if (txService.isReadOnly() || !txService.getAllowWrite())
 {
     return txService.getRetryingTransactionHelper().doInTransaction(callback, 
     		/* READ ONLY */ true, 
     		/* DOES NOT REQUIRE NEW TRAN */false);
 }
	
 // otherwise we want force a writable transaction 
    return txService.getRetryingTransactionHelper().doInTransaction(callback, 
            /* READ/WRITE */ false, 
            /* DOES NOT REQUIRE NEW TRAN */false);

}
 
Example 6
Project: alfresco-repository   File: MultiUserRenditionTest.java   View source code 6 votes vote down vote up
public  void initContextAndCreateUser()
{
    appContext = ApplicationContextHelper.getApplicationContext();

    authenticationService = (MutableAuthenticationService) appContext.getBean("AuthenticationService");
    contentService = (ContentService) appContext.getBean("ContentService");
    nodeService = (NodeService) appContext.getBean("NodeService");
    permissionService = (PermissionService) appContext.getBean("PermissionService");
    personService = (PersonService) appContext.getBean("PersonService");
    renditionService = (RenditionService) appContext.getBean("RenditionService");
    repositoryHelper = (Repository) appContext.getBean("repositoryHelper");
    transactionService = (TransactionService) appContext.getBean("TransactionService");
    txnHelper = transactionService.getRetryingTransactionHelper();
    ownableService = (OwnableService) appContext.getBean("ownableService");

    ADMIN_USER = AuthenticationUtil.getAdminUserName();
    
    // Create a nonAdminUser
    createUser(NON_ADMIN_USER);

}
 
Example 7
Project: alfresco-repository   File: BaseAlfrescoSpringTest.java   View source code 6 votes vote down vote up
/**
 * On setup in transaction override
 */
@SuppressWarnings("deprecation")
@Override
protected void onSetUpInTransaction() throws Exception
{
    super.onSetUpInTransaction();

    // Get a reference to the node service
    this.nodeService = (NodeService) this.applicationContext.getBean("nodeService");
    this.contentService = (ContentService) this.applicationContext.getBean("contentService");
    this.authenticationService = (MutableAuthenticationService) this.applicationContext.getBean("authenticationService");
    this.actionService = (ActionService)this.applicationContext.getBean("actionService");
    this.transactionService = (TransactionService)this.applicationContext.getBean("transactionComponent");

    // Authenticate as the system user
    authenticationComponent = (AuthenticationComponent) this.applicationContext
            .getBean("authenticationComponent");
    authenticationComponent.setSystemUserAsCurrentUser();
    
    // Create the store and get the root node
    this.storeRef = this.nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis());
    this.rootNodeRef = this.nodeService.getRootNode(this.storeRef);
}
 
Example 8
Project: alfresco-remote-api   File: RuleServiceTest.java   View source code 6 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    super.setUp();
    this.transactionService = (TransactionService) getServer().getApplicationContext().getBean("TransactionService");
    this.nodeService = (NodeService) getServer().getApplicationContext().getBean("NodeService");
    this.fileFolderService = (FileFolderService) getServer().getApplicationContext().getBean("FileFolderService");
    this.ruleService = (RuleService) getServer().getApplicationContext().getBean("RuleService");
    this.actionService = (ActionService) getServer().getApplicationContext().getBean("ActionService");
    this.authenticationComponent = (AuthenticationComponent) getServer().getApplicationContext().getBean("authenticationComponent");

    this.authenticationComponent.setSystemUserAsCurrentUser();

    createTestFolders();

    assertNotNull(testWorkNodeRef);
    assertNotNull(testNodeRef);
    assertNotNull(testNodeRef2);
}
 
Example 9
Project: alfresco-repository   File: CacheTest.java   View source code 6 votes vote down vote up
/**
 * Starts off with a <tt>null</tt> in the backing cache and adds a value to the
 * transactional cache.  There should be no problem with this.
 */
public void testNullValue() throws Throwable
{
    TransactionService transactionService = serviceRegistry.getTransactionService();
    UserTransaction txn = transactionService.getUserTransaction();

    txn.begin();
    
    TransactionalCache.putSharedCacheValue(backingCache, "A", null, null);
    transactionalCache.put("A", "AAA");
    
    try
    {
        txn.commit();
    }
    catch (Throwable e)
    {
        try {txn.rollback();} catch (Throwable ee) {}
        throw e;
    }
}
 
Example 10
Project: alfresco-repository   File: DBQueryTest.java   View source code 6 votes vote down vote up
@Before
public void setup() throws Exception
{
    nodeService = (NodeService) ctx.getBean("dbNodeService");
    dictionaryService = (DictionaryService) ctx.getBean("dictionaryService");
    dictionaryDAO = (DictionaryDAO) ctx.getBean("dictionaryDAO");
    namespacePrefixResolver = (DictionaryNamespaceComponent) ctx.getBean("namespaceService");
    transactionService = (TransactionService) ctx.getBean("transactionComponent");
    retryingTransactionHelper = (RetryingTransactionHelper) ctx.getBean("retryingTransactionHelper");
    tenantService = (TenantService) ctx.getBean("tenantService");
    serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    namespaceDao = (NamespaceDAO) ctx.getBean("namespaceDAO");
    authenticationComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent");
    contentService = (ContentService) ctx.getBean("contentService");

    loadTestModel();
    createTestData();
}
 
Example 11
Project: alfresco-repository   File: RemoteCredentialsServicesTest.java   View source code 6 votes vote down vote up
@BeforeClass public static void initTestsContext() throws Exception
{
    ApplicationContext testContext = APP_CONTEXT_INIT.getApplicationContext();
    
    PRIVATE_REMOTE_CREDENTIALS_SERVICE = (RemoteCredentialsService)testContext.getBean("remoteCredentialsService");
    REMOTE_CREDENTIALS_SERVICE = (RemoteCredentialsService)testContext.getBean("RemoteCredentialsService");
    
    AUTHENTICATION_SERVICE = (MutableAuthenticationService)testContext.getBean("authenticationService");
    BEHAVIOUR_FILTER       = (BehaviourFilter)testContext.getBean("policyBehaviourFilter");
    DICTIONARY_SERVICE     = (DictionaryService)testContext.getBean("dictionaryService");
    NAMESPACE_SERVICE      = (NamespaceService)testContext.getBean("namespaceService");
    REPOSITORY_HELPER      = (Repository)testContext.getBean("repositoryHelper");
    NODE_SERVICE           = (NodeService)testContext.getBean("nodeService");
    PUBLIC_NODE_SERVICE    = (NodeService)testContext.getBean("NodeService");
    PERSON_SERVICE         = (PersonService)testContext.getBean("personService");
    TRANSACTION_HELPER     = (RetryingTransactionHelper)testContext.getBean("retryingTransactionHelper");
    TRANSACTION_SERVICE    = (TransactionService)testContext.getBean("TransactionService");
    PERMISSION_SERVICE     = (PermissionService)testContext.getBean("permissionService");

    // Switch to a test shared system container
    RemoteCredentialsServiceImpl.setSharedCredentialsSystemContainerName(SHARED_SYSTEM_CONTAINER_NAME);
}
 
Example 12
Project: alfresco-repository   File: RepoAdminServiceImplTest.java   View source code 6 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    super.setUp();
    
    repoAdminService = (RepoAdminService) ctx.getBean("RepoAdminService");
    dictionaryService = (DictionaryService) ctx.getBean("DictionaryService");
    transactionService = (TransactionService) ctx.getBean("TransactionService");
    nodeService = (NodeService) ctx.getBean("NodeService");
    contentService = (ContentService) ctx.getBean("ContentService");
    searchService = (SearchService) ctx.getBean("SearchService");
    namespaceService = (NamespaceService) ctx.getBean("NamespaceService");
    behaviourFilter = (BehaviourFilter)ctx.getBean("policyBehaviourFilter");
    dictionaryDAO = (DictionaryDAO) ctx.getBean("dictionaryDAO");
    
    DbNodeServiceImpl dbNodeService = (DbNodeServiceImpl)ctx.getBean("dbNodeService");
    dbNodeService.setEnableTimestampPropagation(false);
    
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
}
 
Example 13
Project: alfresco-repository   File: RhinoScriptTest.java   View source code 6 votes vote down vote up
protected void setUp() throws Exception
{
    super.setUp();
    ctx = ApplicationContextHelper.getApplicationContext();
    transactionService = (TransactionService)ctx.getBean("transactionComponent");
    contentService = (ContentService)ctx.getBean("contentService");
    nodeService = (NodeService)ctx.getBean("nodeService");
    scriptService = (ScriptService)ctx.getBean("scriptService");
    serviceRegistry = (ServiceRegistry)ctx.getBean("ServiceRegistry");
    
    this.authenticationComponent = (AuthenticationComponent)ctx.getBean("authenticationComponent");
    this.authenticationComponent.setSystemUserAsCurrentUser();
    
    DictionaryDAO dictionaryDao = (DictionaryDAO)ctx.getBean("dictionaryDAO");
    
    // load the system model
    ClassLoader cl = BaseNodeServiceTest.class.getClassLoader();
    InputStream modelStream = cl.getResourceAsStream("alfresco/model/contentModel.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);
    
    DictionaryComponent dictionary = new DictionaryComponent();
    dictionary.setDictionaryDAO(dictionaryDao);
    BaseNodeServiceTest.loadModel(ctx);
}
 
Example 14
Project: alfresco-repository   File: HttpAlfrescoContentReader.java   View source code 6 votes vote down vote up
public HttpAlfrescoContentReader(
        TransactionService transactionService,
        AuthenticationService authenticationService,
        String baseHttpUrl,
        String contentUrl)
{
    super(contentUrl);
    this.transactionService = transactionService;
    this.authenticationService = authenticationService;
    this.baseHttpUrl = baseHttpUrl;
    // Helpers
    this.httpClient = new HttpClient();
    this.ticketCallback = new PropagateTicketCallback();
    // A trip to the remote server has not been made
    cachedExists = false;
    cachedSize = 0L;
    cachedLastModified = 0L;
}
 
Example 15
Project: alfresco-repository   File: RepoUsageComponentTest.java   View source code 6 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    ctx = ApplicationContextHelper.getApplicationContext();
    if (AlfrescoTransactionSupport.isActualTransactionActive())
    {
        fail("Test started with transaction in progress");
    }
    
    transactionService = (TransactionService) ctx.getBean("transactionComponent");
    repoUsageComponent = (RepoUsageComponent) ctx.getBean("repoUsageComponent");
    jobLockService = (JobLockService) ctx.getBean("jobLockService");
    
    AuthenticationUtil.setRunAsUserSystem();
    
    txn = transactionService.getUserTransaction();
    txn.begin();
    
    restrictionsBefore = repoUsageComponent.getRestrictions();
}
 
Example 16
Project: alfresco-repository   File: NodeStringLengthWorker.java   View source code 5 votes vote down vote up
public NodeStringLengthWorker(
        NodeDAO nodeDAO, JobLockService jobLockService, TransactionService transactionService, QNameDAO qnameDAO,
        BehaviourFilter behaviourFilter,
        int queryRange, int threadCount)
{
    this.nodeDAO = nodeDAO;
    this.jobLockService = jobLockService;
    this.transactionService = transactionService;
    this.qnameDAO = qnameDAO;
    this.behaviourFilter = behaviourFilter;
    
    this.queryRange = queryRange;
    this.threadCount = threadCount;
    this.batchSize = 100;
}
 
Example 17
Project: alfresco-repository   File: FreeMarkerModelLuceneFunctionTest.java   View source code 5 votes vote down vote up
public void setUp() throws Exception
{

    authenticationComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent");
    serviceRegistry = (ServiceRegistry) ctx.getBean("ServiceRegistry");

    this.authenticationComponent.setSystemUserAsCurrentUser();

    TransactionService transactionService = (TransactionService) ctx.getBean(ServiceRegistry.TRANSACTION_SERVICE
            .getLocalName());
    tx = transactionService.getUserTransaction();
    tx.begin();
}
 
Example 18
Project: alfresco-repository   File: RepoTransferReceiverImplTest.java   View source code 5 votes vote down vote up
/**
 * Called during the transaction setup
 */
protected void onSetUp() throws Exception
{
    super.onSetUp();
    System.out.println("java.io.tmpdir == " + System.getProperty("java.io.tmpdir"));

    // Get the required services
    this.nodeService = (NodeService) this.applicationContext.getBean("nodeService");
    this.contentService = (ContentService) this.applicationContext.getBean("contentService");
    this.authenticationService = (MutableAuthenticationService) this.applicationContext
            .getBean("authenticationService");
    this.actionService = (ActionService) this.applicationContext.getBean("actionService");
    this.transactionService = (TransactionService) this.applicationContext.getBean("transactionComponent");
    this.authenticationComponent = (AuthenticationComponent) this.applicationContext
            .getBean("authenticationComponent");
    this.receiver = (RepoTransferReceiverImpl) this.getApplicationContext().getBean("transferReceiver");
    this.policyComponent = (PolicyComponent) this.getApplicationContext().getBean("policyComponent");
    this.searchService = (SearchService) this.getApplicationContext().getBean("searchService");
    this.repositoryHelper = (Repository) this.getApplicationContext().getBean("repositoryHelper");
    this.namespaceService = (NamespaceService) this.getApplicationContext().getBean("namespaceService");
    this.dummyContent = "This is some dummy content.";        
    this.dummyContentBytes = dummyContent.getBytes("UTF-8");
    setTransactionDefinition(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW));
    authenticationComponent.setSystemUserAsCurrentUser();

    startNewTransaction();
    guestHome = repositoryHelper.getGuestHome();
    endTransaction();
}
 
Example 19
Project: alfresco-repository   File: KeyStoreTests.java   View source code 5 votes vote down vote up
@Before
public void setup() throws SystemException, NotSupportedException
{
   	transactionService = (TransactionService)ctx.getBean("transactionService");
   	keyStoreChecker = (KeyStoreChecker)ctx.getBean("keyStoreChecker");
   	encryptionKeysRegistry = (EncryptionKeysRegistry)ctx.getBean("encryptionKeysRegistry");
   	keyResourceLoader = (KeyResourceLoader)ctx.getBean("springKeyResourceLoader");
       backupEncryptor = (DefaultEncryptor)ctx.getBean("backupEncryptor");

   	toDelete = new ArrayList<String>(10);

       AuthenticationUtil.setRunAsUserSystem();
	UserTransaction txn = transactionService.getUserTransaction();
	txn.begin();
}
 
Example 20
Project: alfresco-remote-api   File: TestEnterpriseAtomPubTCK.java   View source code 5 votes vote down vote up
@Before
public void setup() throws Exception
{
	JettyComponent jetty = getTestFixture().getJettyComponent();
	
	final SearchService searchService = (SearchService)jetty.getApplicationContext().getBean("searchService");;
	final NodeService nodeService = (NodeService)jetty.getApplicationContext().getBean("nodeService");
	final FileFolderService fileFolderService = (FileFolderService)jetty.getApplicationContext().getBean("fileFolderService");
	final NamespaceService namespaceService = (NamespaceService)jetty.getApplicationContext().getBean("namespaceService");
	final TransactionService transactionService = (TransactionService)jetty.getApplicationContext().getBean("transactionService");
	final String name = "abc" + System.currentTimeMillis();

	transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>()
	{
		@Override
		public Void execute() throws Throwable
		{
			AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

               Repository repositoryHelper = (Repository)jetty.getApplicationContext().getBean("repositoryHelper");
			NodeRef companyHome = repositoryHelper.getCompanyHome();
			fileFolderService.create(companyHome, name, ContentModel.TYPE_FOLDER).getNodeRef();

			return null;
		}
	}, false, true);

   	int port = jetty.getPort();
   	Map<String, String> cmisParameters = new HashMap<String, String>();
   	cmisParameters.put(TestParameters.DEFAULT_RELATIONSHIP_TYPE, "R:cm:replaces");
   	cmisParameters.put(TestParameters.DEFAULT_TEST_FOLDER_PARENT, "/" + name);
   	clientContext = new OpenCMISClientContext(BindingType.ATOMPUB,
   			MessageFormat.format(CMIS_URL, "localhost", String.valueOf(port), "alfresco"), "admin", "admin", cmisParameters, jetty.getApplicationContext());

       overrideVersionableAspectProperties(jetty.getApplicationContext());
}
 
Example 21
Project: alfresco-repository   File: ModelUsageDataCollectorTest.java   View source code 5 votes vote down vote up
@Before
public void setUp()
{
    mockDescriptorDAO = mock(DescriptorDAO.class);
    mockCollectorService = mock(HBDataCollectorService.class);

    Descriptor mockDescriptor = mock(Descriptor.class);
    when(mockDescriptor.getId()).thenReturn("mock_id");
    when(mockDescriptorDAO.getDescriptor()).thenReturn(mockDescriptor);

    CustomModelsInfo mockCustomModelsInfo = mock(CustomModelsInfo.class);
    CustomModelService customModelService = mock(CustomModelService.class);
    when(customModelService.getCustomModelsInfo()).thenReturn(mockCustomModelsInfo);

    TransactionService mockTransactionService = mock(TransactionService.class);
    RetryingTransactionHelper mockRetryingTransactionHelper = mock(RetryingTransactionHelper.class);
    when(mockRetryingTransactionHelper.doInTransaction(any(RetryingTransactionHelper.RetryingTransactionCallback.class), anyBoolean())).thenReturn(mockCustomModelsInfo);
    when(mockTransactionService.getRetryingTransactionHelper()).thenReturn(mockRetryingTransactionHelper);

    usageModelCollector = new ModelUsageDataCollector("acs.repository.usage.model","1.0", "0 0 0 ? * *" );

    usageModelCollector.setHbDataCollectorService(mockCollectorService);
    usageModelCollector.setCurrentRepoDescriptorDAO(mockDescriptorDAO);
    usageModelCollector.setCustomModelService(customModelService);
    usageModelCollector.setTransactionService(mockTransactionService);

    collectedData = usageModelCollector.collectData();
}
 
Example 22
Project: alfresco-repository   File: AbstractLockStoreTxTest.java   View source code 5 votes vote down vote up
@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();
    }
}
 
Example 23
Project: alfresco-remote-api   File: RemoteFileFolderLoaderTest.java   View source code 5 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    super.setUp();
    
    this.repositoryHelper = (Repository)getServer().getApplicationContext().getBean("repositoryHelper");
    this.nodeService = (NodeService)getServer().getApplicationContext().getBean("nodeService");
    this.transactionService = (TransactionService) getServer().getApplicationContext().getBean("TransactionService");
    this.fileFolderService = (FileFolderService) getServer().getApplicationContext().getBean("FileFolderService");

    // Get the path of the shared folder home
    final NodeRef companyHomeNodeRef = repositoryHelper.getCompanyHome();
    final NodeRef sharedHomeNodeRef = repositoryHelper.getSharedHome();
    RetryingTransactionCallback<NodeRef> createFolderWork = new RetryingTransactionCallback<NodeRef>()
    {
        @Override
        public NodeRef execute() throws Throwable
        {
            List<FileInfo> sharedHomeFileInfos = fileFolderService.getNamePath(companyHomeNodeRef, sharedHomeNodeRef);
            sharedHomePath = "/" + sharedHomeFileInfos.get(0).getName();

            String folderName = UUID.randomUUID().toString();
            // Create a folder
            FileInfo folderInfo = fileFolderService.create(sharedHomeNodeRef, folderName, ContentModel.TYPE_FOLDER);
            loadHomePath = sharedHomePath + "/" + folderName;
            // Done
            return folderInfo.getNodeRef();
        }
    };
    AuthenticationUtil.pushAuthentication();            // Will be cleared later
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

    loadHomeNodeRef = transactionService.getRetryingTransactionHelper().doInTransaction(createFolderWork);
}
 
Example 24
Project: alfresco-repository   File: CacheTest.java   View source code 5 votes vote down vote up
/**
 * Time how long it takes to create and complete a whole lot of transactions
 */
public void testInitializationPerformance() throws Exception
{
    TransactionService transactionService = serviceRegistry.getTransactionService();
    long start = System.nanoTime();
    int count = 10000;
    for (int i = 0; i < count; i++)
    {
        UserTransaction txn = transactionService.getUserTransaction();
        try
        {
            txn.begin();
            transactionalCache.contains("A");
        }
        finally
        {
            try { txn.rollback(); } catch (Throwable ee) {ee.printStackTrace();}
        }
    }
    long end = System.nanoTime();
    
    // report
    System.out.println(
            "Cache initialization performance test: \n" +
            "   count:       " + count + "\n" +
            "   transaction: " + (end-start)/((long)count) + " ns\\count"); 
}
 
Example 25
Project: alfresco-repository   File: PolicyComponentTransactionTest.java   View source code 5 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    applicationContext = ApplicationContextHelper.getApplicationContext();
    // initialise policy test model
    DictionaryBootstrap bootstrap = new DictionaryBootstrap();
    List<String> bootstrapModels = new ArrayList<String>();
    bootstrapModels.add(TEST_MODEL);
    bootstrap.setModels(bootstrapModels);
    bootstrap.setDictionaryDAO((DictionaryDAO)applicationContext.getBean("dictionaryDAO"));
    bootstrap.setTenantService((TenantService)applicationContext.getBean("tenantService"));
    bootstrap.bootstrap();
    
    // retrieve policy component
    this.policyComponent = (PolicyComponent)applicationContext.getBean("policyComponent");
    this.behaviourFilter = (BehaviourFilter) applicationContext.getBean("policyBehaviourFilter");
    this.trxService = (TransactionService) applicationContext.getBean("transactionComponent");
    this.nodeService = (NodeService) applicationContext.getBean("nodeService");
    this.nodeLocatorService = (NodeLocatorService) applicationContext.getBean("nodeLocatorService");
    this.authenticationComponent = (AuthenticationComponent)applicationContext.getBean("authenticationComponent");
    this.authenticationComponent.setSystemUserAsCurrentUser();
    
    // Register Policy
    if (sideEffectDelegate == null)
    {
     sideEffectDelegate = policyComponent.registerClassPolicy(SideEffectTestPolicy.class);
	
     // Bind Behaviour to side effect policy
     QName policyName = QName.createQName(TEST_NAMESPACE, "sideEffect");
     Behaviour baseBehaviour = new JavaBehaviour(this, "sideEffectTest", NotificationFrequency.TRANSACTION_COMMIT);
     this.policyComponent.bindClassBehaviour(policyName, BASE_TYPE, baseBehaviour);
    }

    this.companyHome = nodeLocatorService.getNode(CompanyHomeNodeLocator.NAME, null, null);
    createAndEnableBehaviours();
}
 
Example 26
Project: alfresco-repository   File: CacheTest.java   View source code 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
Project: alfresco-repository   File: DbNodeServiceImplPropagationTest.java   View source code 5 votes vote down vote up
@Override
protected void onSetUpInTransaction() throws Exception
{
    super.onSetUpInTransaction();
    txnService = (TransactionService) applicationContext.getBean("transactionComponent");
    nodeDAO = (NodeDAO) applicationContext.getBean("nodeDAO");
    dialect = (Dialect) applicationContext.getBean("dialect");
    nodeService = (NodeService) applicationContext.getBean("dbNodeService");
    
    authenticationComponent = (AuthenticationComponent) applicationContext.getBean("authenticationComponent");
    
    authenticationComponent.setSystemUserAsCurrentUser();
    
    DictionaryDAO dictionaryDao = (DictionaryDAO) applicationContext.getBean("dictionaryDAO");
    // load the system model
    ClassLoader cl = BaseNodeServiceTest.class.getClassLoader();
    InputStream modelStream = cl.getResourceAsStream("alfresco/model/contentModel.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);
    
    DictionaryComponent dictionary = new DictionaryComponent();
    dictionary.setDictionaryDAO(dictionaryDao);
    dictionaryService = loadModel(applicationContext);
    
    txn = restartAuditableTxn(txn);
}
 
Example 28
Project: alfresco-repository   File: ActivityServiceImplTest.java   View source code 5 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    activityService = (ActivityService)ctx.getBean("activityService");
    scriptService = (ScriptService)ctx.getBean("ScriptService");
    siteService = (SiteService)ctx.getBean("SiteService");
    nodeArchiveService = (NodeArchiveService)ctx.getBean("nodeArchiveService");
    transactionService = (TransactionService)ctx.getBean("TransactionService");
    
    postDAO = (ActivityPostDAO)ctx.getBean("postDAO");
    
    authenticationService = (MutableAuthenticationService)ctx.getBean("AuthenticationService");
    
    authenticationService.authenticate(AuthenticationUtil.getAdminUserName(), ADMIN_PW.toCharArray());
}
 
Example 29
Project: alfresco-remote-api   File: PersonServiceTest.java   View source code 5 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    super.setUp();
    MockitoAnnotations.initMocks(this);

    ApplicationContext ctx = getServer().getApplicationContext();
    this.authenticationService = (MutableAuthenticationService)ctx.getBean("AuthenticationService");
    this.authenticationComponent = (AuthenticationComponent)ctx.getBean("authenticationComponent");
    this.personService = (PersonService)ctx.getBean("PersonService");
    this.userNameMatcherImpl = (UserNameMatcherImpl)ctx.getBean("userNameMatcher");
    this.nodeService = (NodeService)ctx.getBean("NodeService");
    this.contentService = (ContentService)ctx.getBean("contentService");
    this.userUsageTrackingComponent = (UserUsageTrackingComponent)ctx.getBean("userUsageTrackingComponent");
    this.contentUsage = (ContentUsageImpl)ctx.getBean("contentUsageImpl");
    this.transactionService = (TransactionService) ctx.getBean("TransactionService");

	serviceRegistry = (ServiceDescriptorRegistry) ctx.getBean("ServiceRegistry");
	serviceRegistry.setMockSearchService(mockSearchService);
    when(mockSearchService.query(any())).thenReturn(mockSearchServiceQueryResultSet);
    when(mockSearchServiceQueryResultSet.getNodeRefs()).thenReturn(dummySearchServiceQueryNodeRefs);

    // enable usages
    contentUsage.setEnabled(true);
    contentUsage.init();
    userUsageTrackingComponent.setEnabled(true);
    userUsageTrackingComponent.init();
    userUsageTrackingComponent.bootstrapInternal();

    this.authenticationComponent.setSystemUserAsCurrentUser();

    // Create users
    createUser(USER_ONE);
    createUser(USER_TWO);
    createUser(USER_THREE);
    
    // Do tests as user one
    this.authenticationComponent.setCurrentUser(USER_ONE);
}
 
Example 30
Project: alfresco-repository   File: SOLRDAOTest.java   View source code 5 votes vote down vote up
@Override
public void setUp() throws Exception
{
    solrDAO = (SOLRDAO)ctx.getBean("solrDAO");
    nodeDAO = (NodeDAO)ctx.getBean("nodeDAO");
    authenticationComponent = (AuthenticationComponent)ctx.getBean("authenticationComponent");
    
    authenticationService = (MutableAuthenticationService)ctx.getBean("authenticationService");
    personService = (PersonService)ctx.getBean("PersonService");
    transactionService = (TransactionService)ctx.getBean("transactionComponent");
    nodeService = (NodeService) ctx.getBean("NodeService");
    aclDaoComponent = (AclDAO) ctx.getBean("aclDAO");
    
    authenticationComponent.setSystemUserAsCurrentUser();
}
 
Example 31
Project: alfresco-repository   File: TransferServiceImplTest.java   View source code 5 votes vote down vote up
/**
 * Called during the transaction setup
 */
protected void onSetUp() throws Exception
{
   
    super.onSetUp();
    
    // Get the required services
    this.transferService = (TransferService)this.applicationContext.getBean("TransferService");
    this.contentService = (ContentService)this.applicationContext.getBean("ContentService");
    this.transferServiceImpl = (TransferServiceImpl2)this.applicationContext.getBean("transferService2");
    this.searchService = (SearchService)this.applicationContext.getBean("SearchService");
    this.transactionService = (TransactionService)this.applicationContext.getBean("TransactionService");
    this.nodeService = (NodeService) this.applicationContext.getBean("nodeService");
    this.contentService = (ContentService) this.applicationContext.getBean("contentService");
    this.authenticationService = (MutableAuthenticationService) this.applicationContext.getBean("authenticationService");
    this.actionService = (ActionService)this.applicationContext.getBean("actionService");
    this.permissionService = (PermissionService)this.applicationContext.getBean("permissionService");
    this.receiver = (TransferReceiver)this.applicationContext.getBean("transferReceiver");
    this.transferManifestNodeFactory = (TransferManifestNodeFactory)this.applicationContext.getBean("transferManifestNodeFactory");
    this.authenticationComponent = (AuthenticationComponent) this.applicationContext.getBean("authenticationComponent");
    this.lockService = (LockService) this.applicationContext.getBean("lockService");
    this.personService = (PersonService)this.applicationContext.getBean("PersonService");
    this.descriptorService = (DescriptorService)this.applicationContext.getBean("DescriptorService");
    this.copyService = (CopyService)this.applicationContext.getBean("CopyService");
    this.taggingService = ((TaggingService)this.applicationContext.getBean("TaggingService"));
    this.categoryService = (CategoryService)this.applicationContext.getBean("CategoryService");
    this.repositoryHelper = (Repository) this.applicationContext.getBean("repositoryHelper");
    
    this.serverDescriptor = descriptorService.getServerDescriptor();
    
    REPO_ID_B = descriptorService.getCurrentRepositoryDescriptor().getId();
    
    authenticationComponent.setSystemUserAsCurrentUser();
    assertNotNull("receiver is null", this.receiver);     
}
 
Example 32
Project: alfresco-remote-api   File: UploadWebScriptTest.java   View source code 5 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    super.setUp();

    this.authenticationService = (MutableAuthenticationService) getServer().getApplicationContext().getBean("AuthenticationService");
    this.globalProperties = (Properties) getServer().getApplicationContext().getBean("global-properties");
    this.transactionService = (TransactionService) getServer().getApplicationContext().getBean("transactionService");
    this.siteService = (SiteService) getServer().getApplicationContext().getBean("SiteService");
    this.nodeService = (NodeService) getServer().getApplicationContext().getBean("nodeService");
    this.contentService = (ContentService) getServer().getApplicationContext().getBean("contentService");
    this.checkOutCheckInService = (CheckOutCheckInService) getServer().getApplicationContext().getBean("checkOutCheckInService");

    globalProperties.setProperty(AUTO_VERSION_PROPS_KEY, "true");

    transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>()
    {
        @Override
        public Void execute() throws Throwable
        {
            authenticationService.authenticate(ADMIN_CREDENTIAL, ADMIN_CREDENTIAL.toCharArray());
            fileName = "quick-2.pdf";
            file = getResourceFile(fileName);

            // Create a Public site
            SiteInfo siteInfo = createSite("site" + GUID.generate(), "doclib", SiteVisibility.PUBLIC);
            
            //Upload file in a site using webScript
            Response response = uploadFileWs(file, fileName, siteInfo.getShortName(), "doclib");
            assertNotNull("content of file", response.getContentAsString());
            JSONObject jsonRsp = (JSONObject) JSONValue.parse(response.getContentAsString());
            final String ssdNodeRefString = (String) jsonRsp.get("nodeRef");
            assertNotNull("nodeRef", ssdNodeRefString);
            documentSite = new NodeRef(ssdNodeRefString);

            return null;
        }
    });
}
 
Example 33
Project: alfresco-repository   File: ContentStoreCleanerScalabilityRunner.java   View source code 5 votes vote down vote up
@Override
protected synchronized int execute() throws ToolException
{
    ctx = super.getApplicationContext();
    
    nodeHelper = new NodeHelper();
    
    transactionService = (TransactionService) ctx.getBean("TransactionService");
    nodeDAO = (NodeDAO) ctx.getBean("nodeDAO");
    
    int orphanCount = 1000;
    
    contentStore = new NullContentStore(10000);
    
    loadData(orphanCount);

    System.out.println("Ready to clean store: " + contentStore);
    synchronized(this)
    {
        try { this.wait(10000L); } catch (InterruptedException e) {}
    }
    
    long beforeClean = System.currentTimeMillis();
    clean();
    long afterClean = System.currentTimeMillis();
    double aveClean = (double) (afterClean - beforeClean) / (double) orphanCount / 1000D;
    
    System.out.println();
    System.out.println(String.format("Cleaning took %3f per 1000 content URLs in DB", aveClean));
    
    return 0;
}
 
Example 34
Project: alfresco-repository   File: PerformanceNodeServiceTest.java   View source code 5 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    applicationContext = ApplicationContextHelper.getApplicationContext();
    DictionaryDAO dictionaryDao = (DictionaryDAO) applicationContext.getBean("dictionaryDAO");
    
    // load the system model
    ClassLoader cl = PerformanceNodeServiceTest.class.getClassLoader();
    InputStream modelStream = cl.getResourceAsStream("alfresco/model/contentModel.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);
    
    DictionaryComponent dictionary = new DictionaryComponent();
    dictionary.setDictionaryDAO(dictionaryDao);
    dictionaryService = loadModel(applicationContext);
    
    nodeService = (NodeService) applicationContext.getBean("nodeService");
    txnService = (TransactionService) applicationContext.getBean("transactionComponent");
    contentService = (ContentService) applicationContext.getBean("contentService");
    
    // create a first store directly
    RetryingTransactionCallback<NodeRef> createStoreWork = new RetryingTransactionCallback<NodeRef>()
    {
        public NodeRef execute()
        {
            StoreRef storeRef = nodeService.createStore(
                    StoreRef.PROTOCOL_WORKSPACE,
                    "Test_" + System.nanoTime());
            return nodeService.getRootNode(storeRef);
        }
    };
    rootNodeRef = txnService.getRetryingTransactionHelper().doInTransaction(createStoreWork);
}
 
Example 35
Project: alfresco-repository   File: CheckOutCheckInServiceImplTest.java   View source code 5 votes vote down vote up
/**
 * On setup in transaction implementation
 */
@Override
protected void onSetUpInTransaction() 
    throws Exception 
{
    // Set the services
    this.cociService = (CheckOutCheckInService)this.applicationContext.getBean("checkOutCheckInService");
    this.contentService = (ContentService)this.applicationContext.getBean("contentService");
    this.versionService = (VersionService)this.applicationContext.getBean("versionService");
    this.authenticationService = (MutableAuthenticationService)this.applicationContext.getBean("authenticationService");
    this.lockService = (LockService)this.applicationContext.getBean("lockService");
    this.transactionService = (TransactionService)this.applicationContext.getBean("transactionComponent");
    this.permissionService = (PermissionService)this.applicationContext.getBean("permissionService");
    this.copyService = (CopyService)this.applicationContext.getBean("copyService");
    this.personService = (PersonService) this.applicationContext.getBean("PersonService");
    ServiceRegistry serviceRegistry = (ServiceRegistry) this.applicationContext.getBean("ServiceRegistry");
    this.fileFolderService = serviceRegistry.getFileFolderService();
    this.nodeService = serviceRegistry.getNodeService();
    
    // Authenticate as system to create initial test data set
    this.authenticationComponent = (AuthenticationComponent)this.applicationContext.getBean("authenticationComponent");
    authenticationComponent.setSystemUserAsCurrentUser();
    
    RetryingTransactionCallback<Void> processInitWork = new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            initTestData();
            return null;
        }
    };
    // do the init test data in a new retrying transaction because
    // there may be problems with the DB that needs to be retried; 
    // That is how Alfresco works, it relies on optimistic locking and retries
    transactionService.getRetryingTransactionHelper().doInTransaction(processInitWork, false, true);

}
 
Example 36
Project: alfresco-repository   File: TransferServiceToBeRefactoredTest.java   View source code 5 votes vote down vote up
/**
 * Called during the transaction setup
 */
protected void onSetUp() throws Exception
{
    // Catch transactions left dangling by inadequate transaction handling during test failures
    if (AlfrescoTransactionSupport.getTransactionReadState() != TxnReadState.TXN_NONE)
    {
        fail("Dangling transaction at start of test.");
    }
    
    super.onSetUp();
    
    // Get the required services
    this.transferService = (TransferService)this.applicationContext.getBean("TransferService");
    this.contentService = (ContentService)this.applicationContext.getBean("ContentService");
    this.transferServiceImpl = (TransferServiceImpl2)this.applicationContext.getBean("transferService2");
    this.searchService = (SearchService)this.applicationContext.getBean("SearchService");
    this.transactionService = (TransactionService)this.applicationContext.getBean("TransactionService");
    this.nodeService = (NodeService) this.applicationContext.getBean("nodeService");
    this.contentService = (ContentService) this.applicationContext.getBean("contentService");
    this.authenticationService = (MutableAuthenticationService) this.applicationContext.getBean("authenticationService");
    this.actionService = (ActionService)this.applicationContext.getBean("actionService");
    this.permissionService = (PermissionService)this.applicationContext.getBean("permissionService");
    this.receiver = (TransferReceiver)this.applicationContext.getBean("transferReceiver");
    this.transferManifestNodeFactory = (TransferManifestNodeFactory)this.applicationContext.getBean("transferManifestNodeFactory");
    this.authenticationComponent = (AuthenticationComponent) this.applicationContext.getBean("authenticationComponent");
    this.lockService = (LockService) this.applicationContext.getBean("lockService");
    this.personService = (PersonService)this.applicationContext.getBean("PersonService");
    this.descriptorService = (DescriptorService)this.applicationContext.getBean("DescriptorService");
    this.copyService = (CopyService)this.applicationContext.getBean("CopyService");
    this.serverDescriptor = descriptorService.getServerDescriptor();
    this.repositoryHelper = (Repository) this.applicationContext.getBean("repositoryHelper");
    
    REPO_ID_B = descriptorService.getCurrentRepositoryDescriptor().getId();
    
    authenticationComponent.setSystemUserAsCurrentUser();
    setTransactionDefinition(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW));
    assertNotNull("receiver is null", this.receiver);     
}
 
Example 37
Project: alfresco-repository   File: CacheTest.java   View source code 5 votes vote down vote up
/**
 * 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"); 
    }
}
 
Example 38
Project: alfresco-repository   File: CacheTest.java   View source code 4 votes vote down vote up
public void testTransactionalCacheDisableSharedCaches() throws Throwable
{
    // add item to global cache
    TransactionalCache.putSharedCacheValue(backingCache, NEW_GLOBAL_ONE, NEW_GLOBAL_ONE, null);
    TransactionalCache.putSharedCacheValue(backingCache, NEW_GLOBAL_TWO, NEW_GLOBAL_TWO, null);
    TransactionalCache.putSharedCacheValue(backingCache, NEW_GLOBAL_THREE, NEW_GLOBAL_THREE, null);
    
    TransactionService transactionService = serviceRegistry.getTransactionService();
    UserTransaction txn = transactionService.getUserTransaction();
    try
    {
        // begin a transaction
        txn.begin();
        
        // Go directly past ALL shared caches
        transactionalCache.setDisableSharedCacheReadForTransaction(true);
        
        // Try to get results in shared caches
        assertNull("Read of mutable shared cache MUST NOT use backing cache", transactionalCache.get(NEW_GLOBAL_ONE));
        assertNull("Value should not be in any cache", transactionalCache.get(UPDATE_TXN_THREE));
        
        // Update the transactional caches
        transactionalCache.put(NEW_GLOBAL_TWO, "An update");
        transactionalCache.put(UPDATE_TXN_THREE, UPDATE_TXN_THREE);
        
        // Try to get results in shared caches
        assertNull("Read of mutable shared cache MUST NOT use backing cache", transactionalCache.get(NEW_GLOBAL_ONE));
        assertEquals("Value should be in transactional cache", "An update", transactionalCache.get(NEW_GLOBAL_TWO));
        assertEquals("Value should be in transactional cache", UPDATE_TXN_THREE, transactionalCache.get(UPDATE_TXN_THREE));
        
        txn.commit();
        
        // Now check that values were not written through for any caches
        assertEquals("Out-of-txn read must return shared value", NEW_GLOBAL_ONE, transactionalCache.get(NEW_GLOBAL_ONE));
        assertNull("Value should be removed from shared cache", transactionalCache.get(NEW_GLOBAL_TWO));
        assertEquals("New values must be written to shared cache", UPDATE_TXN_THREE, transactionalCache.get(UPDATE_TXN_THREE));
    }
    catch (Throwable e)
    {
        if (txn.getStatus() == Status.STATUS_ACTIVE)
        {
            txn.rollback();
        }
        throw e;
    }
}
 
Example 39
Project: alfresco-repository   File: AclDaoComponentTest.java   View source code 4 votes vote down vote up
public void setUp() throws Exception
{
    if (AlfrescoTransactionSupport.getTransactionReadState() != TxnReadState.TXN_NONE)
    {
        throw new AlfrescoRuntimeException(
                "A previous tests did not clean up transaction: " +
                AlfrescoTransactionSupport.getTransactionId());
    }
    
    aclDaoComponent = (AclDAO) applicationContext.getBean("aclDAO");
    
    nodeService = (NodeService) applicationContext.getBean("nodeService");
    dictionaryService = (DictionaryService) applicationContext.getBean(ServiceRegistry.DICTIONARY_SERVICE
            .getLocalName());
    permissionService = (PermissionServiceSPI) applicationContext.getBean("permissionService");
    namespacePrefixResolver = (NamespacePrefixResolver) applicationContext
            .getBean(ServiceRegistry.NAMESPACE_SERVICE.getLocalName());
    authenticationService = (MutableAuthenticationService) applicationContext.getBean("authenticationService");
    authenticationComponent = (AuthenticationComponent) applicationContext.getBean("authenticationComponent");
    serviceRegistry = (ServiceRegistry) applicationContext.getBean(ServiceRegistry.SERVICE_REGISTRY);
    permissionModelDAO = (ModelDAO) applicationContext.getBean("permissionsModelDAO");
    personService = (PersonService) applicationContext.getBean("personService");
    authorityService = (AuthorityService) applicationContext.getBean("authorityService");
    
    authenticationComponent.setCurrentUser(authenticationComponent.getSystemUserName());
    authenticationDAO = (MutableAuthenticationDao) applicationContext.getBean("authenticationDao");
    transactionService = (TransactionService) applicationContext.getBean("transactionComponent");
    
    testTX = transactionService.getUserTransaction();
    testTX.begin();
    this.authenticationComponent.setSystemUserAsCurrentUser();
    
    StoreRef storeRef = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.nanoTime());
    rootNodeRef = nodeService.getRootNode(storeRef);

    QName children = ContentModel.ASSOC_CHILDREN;
    QName system = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "system");
    QName container = ContentModel.TYPE_CONTAINER;
    QName types = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "people");

    systemNodeRef = nodeService.createNode(rootNodeRef, children, system, container).getChildRef();
    NodeRef typesNodeRef = nodeService.createNode(systemNodeRef, children, types, container).getChildRef();
    Map<QName, Serializable> props = createPersonProperties("andy");
    nodeService.createNode(typesNodeRef, children, ContentModel.TYPE_PERSON, container, props).getChildRef();
    props = createPersonProperties("lemur");
    nodeService.createNode(typesNodeRef, children, ContentModel.TYPE_PERSON, container, props).getChildRef();

    // create an authentication object e.g. the user
    if(authenticationDAO.userExists("andy"))
    {
        authenticationService.deleteAuthentication("andy");
    }
    authenticationService.createAuthentication("andy", "andy".toCharArray());

    if(authenticationDAO.userExists("lemur"))
    {
        authenticationService.deleteAuthentication("lemur");
    }
    authenticationService.createAuthentication("lemur", "lemur".toCharArray());
    
    if(authenticationDAO.userExists(AuthenticationUtil.getAdminUserName()))
    {
        authenticationService.deleteAuthentication(AuthenticationUtil.getAdminUserName());
    }
    authenticationService.createAuthentication(AuthenticationUtil.getAdminUserName(), "admin".toCharArray());
    
    authenticationComponent.clearCurrentSecurityContext();
}
 
Example 40
Project: alfresco-repository   File: CommandExecutorImpl.java   View source code 4 votes vote down vote up
public TransactionService getTransactionService()
{
    return transactionService;
}