Example usage for javax.transaction UserTransaction begin

List of usage examples for javax.transaction UserTransaction begin

Introduction

In this page you can find the example usage for javax.transaction UserTransaction begin.

Prototype

void begin() throws NotSupportedException, SystemException;

Source Link

Document

Create a new transaction and associate it with the current thread.

Usage

From source file:org.alfresco.repo.imap.LoadTester.java

@Override
public void setUp() throws Exception {
    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean("ServiceRegistry");
    authenticationService = serviceRegistry.getAuthenticationService();
    imapService = serviceRegistry.getImapService();
    importerService = serviceRegistry.getImporterService();
    NodeService nodeService = serviceRegistry.getNodeService();
    SearchService searchService = serviceRegistry.getSearchService();
    NamespaceService namespaceService = serviceRegistry.getNamespaceService();
    PersonService personService = serviceRegistry.getPersonService();
    FileFolderService fileFolderService = serviceRegistry.getFileFolderService();
    TransactionService transactionService = serviceRegistry.getTransactionService();
    PermissionService permissionService = serviceRegistry.getPermissionService();

    // start the transaction
    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();

    authenticationService.authenticate(USER_NAME, USER_PASSWORD.toCharArray());

    anotherUserName = "test_imap_user";

    NodeRef person = personService.getPerson(anotherUserName);

    if (person != null) {
        personService.deletePerson(anotherUserName);
        PropertyMap testUser = new PropertyMap();
        testUser.put(ContentModel.PROP_USERNAME, anotherUserName);
        testUser.put(ContentModel.PROP_FIRSTNAME, anotherUserName);
        testUser.put(ContentModel.PROP_LASTNAME, anotherUserName);
        testUser.put(ContentModel.PROP_EMAIL, anotherUserName + "@alfresco.com");
        testUser.put(ContentModel.PROP_JOBTITLE, "jobTitle");
        personService.createPerson(testUser);

    }//ww  w  .j  a  v  a  2  s .  c o m
    if (authenticationService.authenticationExists(anotherUserName)) {
        authenticationService.deleteAuthentication(anotherUserName);
    }
    authenticationService.createAuthentication(anotherUserName, anotherUserName.toCharArray());

    user = new AlfrescoImapUser(anotherUserName + "@alfresco.com", anotherUserName, anotherUserName);

    String storePath = "workspace://SpacesStore";
    String companyHomePathInStore = "/app:company_home";

    StoreRef storeRef = new StoreRef(storePath);
    NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef);

    List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, companyHomePathInStore, null,
            namespaceService, false);
    NodeRef companyHomeNodeRef = nodeRefs.get(0);

    ChildApplicationContextFactory imap = (ChildApplicationContextFactory) ctx.getBean("imap");
    ApplicationContext imapCtx = imap.getApplicationContext();
    ImapServiceImpl imapServiceImpl = (ImapServiceImpl) imapCtx.getBean("imapService");

    // Delete test folder
    nodeRefs = searchService.selectNodes(storeRootNodeRef, companyHomePathInStore + "/"
            + NamespaceService.CONTENT_MODEL_PREFIX + ":" + TEST_IMAP_ROOT_FOLDER_NAME, null, namespaceService,
            false);
    if (nodeRefs.size() == 1) {
        NodeRef ch = nodeRefs.get(0);
        nodeService.deleteNode(ch);
    }

    // Creating IMAP test folder for IMAP root
    LinkedList<String> folders = new LinkedList<String>();
    folders.add(TEST_IMAP_ROOT_FOLDER_NAME);
    FileFolderServiceImpl.makeFolders(fileFolderService, companyHomeNodeRef, folders, ContentModel.TYPE_FOLDER);

    // Setting IMAP root
    RepositoryFolderConfigBean imapHome = new RepositoryFolderConfigBean();
    imapHome.setStore(storePath);
    imapHome.setRootPath(companyHomePathInStore);
    imapHome.setFolderPath(TEST_IMAP_ROOT_FOLDER_NAME);
    imapServiceImpl.setImapHome(imapHome);

    // Starting IMAP
    imapServiceImpl.startupInTxn(true);

    nodeRefs = searchService.selectNodes(storeRootNodeRef, companyHomePathInStore + "/"
            + NamespaceService.CONTENT_MODEL_PREFIX + ":" + TEST_IMAP_ROOT_FOLDER_NAME, null, namespaceService,
            false);

    // Used to create User's folder
    NodeRef userFolderRef = imapService.getUserImapHomeRef(anotherUserName);
    permissionService.setPermission(userFolderRef, anotherUserName, PermissionService.ALL_PERMISSIONS, true);

    importTestData("imap/load_test_data.acp", userFolderRef);

    reauthenticate(anotherUserName, anotherUserName);

    AlfrescoImapFolder testDataFolder = imapService.getOrCreateMailbox(user, TEST_DATA_FOLDER_NAME, true,
            false);

    SimpleStoredMessage m = testDataFolder.getMessages().get(0);
    m = testDataFolder.getMessage(m.getUid());

    AlfrescoImapFolder folder = imapService.getOrCreateMailbox(user, TEST_FOLDER_NAME, false, true);

    logger.info("Creating folders...");
    long t = System.currentTimeMillis();

    try {
        for (int i = 0; i < MESSAGE_QUANTITY; i++) {
            System.out.println("i = " + i);
            folder.appendMessage(m.getMimeMessage(), new Flags(), new Date());
        }
    } catch (Exception e) {
        logger.error(e, e);
    }

    t = System.currentTimeMillis() - t;
    logger.info("Create time: " + t + " ms (" + t / 1000 + " s (" + t / 60000 + " min))");

    txn.commit();
}

From source file:org.alfresco.repo.importer.ExportSourceImporter.java

@SuppressWarnings("unchecked")
public void doImport() {
    UserTransaction userTransaction = null;
    try {//www.ja v a2  s  .c  o  m
        AuthenticationUtil.pushAuthentication();
        userTransaction = transactionService.getUserTransaction();
        userTransaction.begin();
        AuthenticationUtil.setRunAsUserSystem();
        if (clearAllChildren) {
            logger.debug("clear all children");
            List<NodeRef> refs = searchService.selectNodes(nodeService.getRootNode(storeRef), path, null,
                    namespacePrefixResolver, false);

            for (NodeRef ref : refs) {
                if (logger.isDebugEnabled()) {
                    logger.debug("clear node ref" + ref);
                }
                for (ChildAssociationRef car : nodeService.getChildAssocs(ref)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("delete child" + car.getChildRef());
                    }
                    nodeService.deleteNode(car.getChildRef());
                }
            }
        }

        if (caches != null) {
            logger.debug("clearing caches");
            for (SimpleCache cache : caches) {

                cache.clear();
            }
        }

        File tempFile = TempFileProvider.createTempFile("ExportSourceImporter-", ".xml");
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile), "UTF-8"));
        XMLWriter xmlWriter = createXMLExporter(writer);
        exportSource.generateExport(xmlWriter);
        xmlWriter.close();

        Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(tempFile), "UTF-8"));

        Location location = new Location(storeRef);
        location.setPath(path);

        importerService.importView(reader, location, REPLACE_BINDING, null);
        reader.close();

        if (caches != null) {
            for (SimpleCache cache : caches) {
                cache.clear();
            }
        }
        logger.debug("about to commit");
        userTransaction.commit();
    } catch (Throwable t) {
        try {
            if (userTransaction != null) {
                logger.debug("rolling back due to exception", t);
                userTransaction.rollback();
            }
        } catch (Exception ex) {
            logger.debug("exception during rollback", ex);
        }
        throw new ExportSourceImporterException("Failed to import", t);
    } finally {
        AuthenticationUtil.popAuthentication();
    }
}

From source file:org.alfresco.repo.importer.FileSourceImporter.java

@SuppressWarnings("unchecked")
public void doImport() {
    UserTransaction userTransaction = null;
    try {//from  www  .j  a v a  2  s  . com
        long start = System.nanoTime();
        userTransaction = transactionService.getUserTransaction();
        userTransaction.begin();
        authenticationContext.setSystemUserAsCurrentUser();
        if (clearAllChildren) {
            List<NodeRef> refs = searchService.selectNodes(nodeService.getRootNode(storeRef), path, null,
                    namespacePrefixResolver, false);
            for (NodeRef ref : refs) {
                for (ChildAssociationRef car : nodeService.getChildAssocs(ref)) {
                    nodeService.deleteNode(car.getChildRef());
                }
            }
        }

        if (caches != null) {
            for (SimpleCache cache : caches) {

                cache.clear();
            }
        }

        Reader reader = new BufferedReader(new FileReader(fileLocation));

        Location location = new Location(storeRef);
        location.setPath(path);

        importerService.importView(reader, location, REPLACE_BINDING, null);
        reader.close();

        if (caches != null) {
            for (SimpleCache cache : caches) {
                cache.clear();
            }
        }

        userTransaction.commit();
        long end = System.nanoTime();
        s_logger.info("Imported " + fileLocation + " in " + ((end - start) / 1e9f) + " seconds");
    } catch (Throwable t) {
        try {
            if (userTransaction != null) {
                userTransaction.rollback();
            }
        } catch (Exception ex) {
        }
        try {
            authenticationContext.clearCurrentSecurityContext();
        } catch (Exception ex) {
        }
        throw new ExportSourceImporterException("Failed to import", t);
    } finally {
        authenticationContext.clearCurrentSecurityContext();
    }
}

From source file:org.alfresco.repo.node.cleanup.TransactionCleanupTest.java

@Test
public void testPurgeUnusedTransactions() throws Exception {
    // Execute transactions that update a number of nodes. For nodeRef1, all but the last txn will be unused.

    // run the transaction cleaner to clean up any existing unused transactions
    worker.doClean();//from ww  w  .  ja va2s . c  om

    final long start = System.currentTimeMillis();
    final Long minTxnId = nodeDAO.getMinTxnId();

    final Map<NodeRef, List<String>> txnIds = createTransactions();
    final List<String> txnIds1 = txnIds.get(nodeRef1);
    final List<String> txnIds2 = txnIds.get(nodeRef2);
    final List<String> txnIds3 = txnIds.get(nodeRef3);
    // Pure delete: final List<String> txnIds4 = txnIds.get(nodeRef4);
    // Pure delete: final List<String> txnIds5 = txnIds.get(nodeRef5);

    // Double-check that n4 and n5 are present in deleted form
    nodesCache.clear();
    UserTransaction txn = transactionService.getUserTransaction(true);
    txn.begin();
    try {
        assertNotNull("Node 4 is deleted but not purged", nodeDAO.getNodeRefStatus(nodeRef4));
        assertNotNull("Node 5 is deleted but not purged", nodeDAO.getNodeRefStatus(nodeRef5));
    } finally {
        txn.rollback();
    }

    // run the transaction cleaner
    worker.setPurgeSize(5); // small purge size
    List<String> reports = worker.doClean();
    for (String report : reports) {
        logger.debug(report);
    }

    // Get transactions committed after the test started
    RetryingTransactionCallback<List<Transaction>> getTxnsCallback = new RetryingTransactionCallback<List<Transaction>>() {
        @Override
        public List<Transaction> execute() throws Throwable {
            return nodeDAO.getTxnsByCommitTimeAscending(Long.valueOf(start), Long.valueOf(Long.MAX_VALUE),
                    Integer.MAX_VALUE, null, false);
        }
    };
    List<Transaction> txns = transactionService.getRetryingTransactionHelper().doInTransaction(getTxnsCallback,
            true, false);

    List<String> expectedUnusedTxnIds = new ArrayList<String>(10);
    expectedUnusedTxnIds.addAll(txnIds1.subList(0, txnIds1.size() - 1));

    List<String> expectedUsedTxnIds = new ArrayList<String>(5);
    expectedUsedTxnIds.add(txnIds1.get(txnIds1.size() - 1));
    expectedUsedTxnIds.addAll(txnIds2);
    expectedUsedTxnIds.addAll(txnIds3);
    // 4 and 5 should not be in the list because they are deletes

    // check that the correct transactions have been purged i.e. all except the last one to update the node
    // i.e. in this case, all but the last one in txnIds1
    int numFoundUnusedTxnIds = 0;
    for (String txnId : expectedUnusedTxnIds) {
        if (!containsTransaction(txns, txnId)) {
            numFoundUnusedTxnIds++;
        } else if (txnIds1.contains(txnId)) {
            fail("Unused transaction(s) were not purged: " + txnId);
        }
    }
    assertEquals(9, numFoundUnusedTxnIds);

    // check that the correct transactions remain i.e. all those in txnIds2, txnIds3, txnIds4 and txnIds5
    int numFoundUsedTxnIds = 0;
    for (String txnId : expectedUsedTxnIds) {
        if (containsTransaction(txns, txnId)) {
            numFoundUsedTxnIds++;
        }
    }

    assertEquals(3, numFoundUsedTxnIds);

    // Get transactions committed after the test started
    RetryingTransactionCallback<List<Long>> getTxnsUnusedCallback = new RetryingTransactionCallback<List<Long>>() {
        @Override
        public List<Long> execute() throws Throwable {
            return nodeDAO.getTxnsUnused(minTxnId, Long.MAX_VALUE, Integer.MAX_VALUE);
        }
    };
    List<Long> txnsUnused = transactionService.getRetryingTransactionHelper()
            .doInTransaction(getTxnsUnusedCallback, true, false);
    assertEquals(0, txnsUnused.size());

    // Double-check that n4 and n5 were removed as well
    nodesCache.clear();
    assertNull("Node 4 was not cleaned up", nodeDAO.getNodeRefStatus(nodeRef4));
    assertNull("Node 5 was not cleaned up", nodeDAO.getNodeRefStatus(nodeRef5));
}

From source file:org.alfresco.repo.replication.ReplicationServiceIntegrationTest.java

@Override
protected void setUp() throws Exception {
    if (AlfrescoTransactionSupport.getTransactionReadState() != TxnReadState.TXN_NONE) {
        fail("Dangling transaction detected, left by a previous test.");
    }//from ww  w  .  j av  a2  s  .  c  o m

    replicationActionExecutor = (ReplicationActionExecutor) ctx.getBean("replicationActionExecutor");
    replicationService = (ReplicationService) ctx.getBean("replicationService");
    replicationParams = (ReplicationParams) ctx.getBean("replicationParams");
    transactionService = (TransactionService) ctx.getBean("transactionService");
    transferService = (TransferService2) ctx.getBean("transferService2");
    contentService = (ContentService) ctx.getBean("contentService");
    jobLockService = (JobLockService) ctx.getBean("jobLockService");
    actionService = (ActionService) ctx.getBean("actionService");
    scriptService = (ScriptService) ctx.getBean("scriptService");
    nodeService = (NodeService) ctx.getBean("NodeService");
    lockService = (LockService) ctx.getBean("lockService");
    repositoryHelper = (Repository) ctx.getBean("repositoryHelper");
    actionTrackingService = (ActionTrackingService) ctx.getBean("actionTrackingService");
    scheduledPersistedActionService = (ScheduledPersistedActionService) ctx
            .getBean("scheduledPersistedActionService");

    // Set the current security context as admin
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

    replicationParams.setEnabled(true);

    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();

    // Zap any existing replication entries
    replicationRoot = ReplicationDefinitionPersisterImpl.REPLICATION_ACTION_ROOT_NODE_REF;
    for (ChildAssociationRef child : nodeService.getChildAssocs(replicationRoot)) {
        QName type = nodeService.getType(child.getChildRef());
        if (ReplicationDefinitionPersisterImpl.ACTION_TYPES.contains(type)) {
            nodeService.deleteNode(child.getChildRef());
        }
    }

    // Create the test folder structure
    destinationFolder = makeNode(repositoryHelper.getCompanyHome(), ContentModel.TYPE_FOLDER,
            "ReplicationTransferDestination");
    folder1 = makeNode(repositoryHelper.getCompanyHome(), ContentModel.TYPE_FOLDER);
    folder2 = makeNode(repositoryHelper.getCompanyHome(), ContentModel.TYPE_FOLDER);
    folder2a = makeNode(folder2, ContentModel.TYPE_FOLDER);
    folder2b = makeNode(folder2, ContentModel.TYPE_FOLDER);

    content1_1 = makeNode(folder1, ContentModel.TYPE_CONTENT);
    content1_2 = makeNode(folder1, ContentModel.TYPE_CONTENT);
    thumbnail1_3 = makeNode(folder1, ContentModel.TYPE_THUMBNAIL);
    authority1_4 = makeNode(folder1, ContentModel.TYPE_AUTHORITY);
    content2a_1 = makeNode(folder2a, ContentModel.TYPE_CONTENT);
    thumbnail2a_2 = makeNode(folder2a, ContentModel.TYPE_THUMBNAIL);
    zone2a_3 = makeNode(folder2a, ContentModel.TYPE_ZONE);

    deletedFolder = makeNode(repositoryHelper.getCompanyHome(), ContentModel.TYPE_FOLDER);
    nodeService.deleteNode(deletedFolder);

    // Tell the transfer service not to use HTTP
    makeTransferServiceLocal();

    // Finish setup
    txn.commit();
}

From source file:org.alfresco.repo.replication.ReplicationServiceIntegrationTest.java

/**
 * Test that the action service can find the executor
 *  for us, and that it has everything it needs
 *///from w  w  w  .  j  a v a2s  . co  m
public void testBasicExecution() throws Exception {
    // We need the test transfer target for this test
    makeTransferTarget();

    // Ensure the destination is empty 
    // (don't want to get confused with older runs)
    assertEquals(0, nodeService.getChildAssocs(destinationFolder).size());

    // First one with no target, which isn't allowed
    ReplicationDefinition rd = replicationService.createReplicationDefinition(ACTION_NAME, "Test");
    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();
    try {
        actionService.executeAction(rd, replicationRoot);
        fail("Shouldn't be permitted with no Target defined");
    } catch (ReplicationServiceException e) {
    }
    txn.rollback();

    // Now no payload, also not allowed
    rd.setTargetName(TRANSFER_TARGET);
    txn = transactionService.getUserTransaction();
    txn.begin();
    try {
        actionService.executeAction(rd, replicationRoot);
        fail("Shouldn't be permitted with no payload defined");
    } catch (ReplicationServiceException e) {
    }
    txn.rollback();

    // Invalid Transfer Target, not allowed
    rd = replicationService.createReplicationDefinition(ACTION_NAME, "Test");
    rd.setTargetName("I am an invalid target that isn't there");
    rd.getPayload().add(folder1);
    txn = transactionService.getUserTransaction();
    txn.begin();
    try {
        actionService.executeAction(rd, replicationRoot);
        fail("Shouldn't be permitted with an invalid transfer target");
    } catch (ReplicationServiceException e) {
    }
    txn.rollback();

    // Can't send Folder2a if Folder2 isn't there, as it
    //  won't have anywhere to put it
    rd = replicationService.createReplicationDefinition(ACTION_NAME, "Test");
    rd.setTargetName(TRANSFER_TARGET);
    rd.getPayload().add(folder2a);
    txn = transactionService.getUserTransaction();
    txn.begin();
    try {
        actionService.executeAction(rd, replicationRoot);
        fail("Shouldn't be able to send Folder2a when Folder2 is missing!");
    } catch (ReplicationServiceException e) {
    }
    txn.rollback();

    // Next a proper one with a transient definition,
    //  and a sensible set of folders
    rd = replicationService.createReplicationDefinition(ACTION_NAME, "Test");
    rd.setTargetName(TRANSFER_TARGET);
    rd.getPayload().add(folder1);
    // A deleted folder is fine, will be skipped
    rd.getPayload().add(deletedFolder);

    // Will execute without error
    txn = transactionService.getUserTransaction();
    txn.begin();
    try {
        actionService.executeAction(rd, replicationRoot);
    } catch (ReplicationServiceException e) {
        // This shouldn't happen normally! Something is wrong!
        // Tidy up before we throw the exception
        txn.rollback();
        throw e;
    }
    txn.commit();

    // Now with one that's in the repo
    ReplicationDefinition rd2 = replicationService.createReplicationDefinition(ACTION_NAME2, "Test");
    rd2.setTargetName(TRANSFER_TARGET);
    rd2.getPayload().add(folder2);
    replicationService.saveReplicationDefinition(rd2);
    rd2 = replicationService.loadReplicationDefinition(ACTION_NAME2);

    // Again no errors
    txn = transactionService.getUserTransaction();
    txn.begin();
    actionService.executeAction(rd2, replicationRoot);
    txn.commit();

    // Now disabled, not allowed
    assertEquals(true, rd.isEnabled());
    rd.setEnabled(false);
    assertEquals(false, rd.isEnabled());
    txn = transactionService.getUserTransaction();
    txn.begin();
    try {
        actionService.executeAction(rd, replicationRoot);
        fail("Shouldn't be permitted when disabled");
    } catch (ReplicationServiceException e) {
        //check if throwed exception is of expected type
        assertTrue(e instanceof DisabledReplicationJobException);
        assertTrue(actionService instanceof RuntimeActionService);
        if (actionService instanceof RuntimeActionService) {
            RuntimeActionService runtimeActionService = (RuntimeActionService) actionService;
            //check if throwed exception is considered handled 
            assertTrue(runtimeActionService.onLogException(rd, log, e, e.getMessage()));
        }

    }
    txn.rollback();
    rd.setEnabled(true);

    // Schedule it for 0.5 seconds into the future
    // Ensure that it is run to completion 
    txn = transactionService.getUserTransaction();
    txn.begin();

    ((ActionImpl) rd2).setExecutionStatus(ActionStatus.New);

    replicationService.enableScheduling(rd2);
    rd2.setScheduleStart(new Date(System.currentTimeMillis() + 500));
    replicationService.saveReplicationDefinition(rd2);

    txn.commit();

    // Wait for it to run
    Thread.sleep(2000);
    for (int i = 0; i < 100; i++) {
        txn = transactionService.getUserTransaction();
        txn.begin();
        rd2 = replicationService.loadReplicationDefinition(ACTION_NAME2);
        txn.commit();

        if (rd2.getExecutionStatus().equals(ActionStatus.New)
                || rd2.getExecutionStatus().equals(ActionStatus.Pending)
                || rd2.getExecutionStatus().equals(ActionStatus.Running)) {
            Thread.sleep(50);
        }
    }

    // Check it worked
    assertEquals(ActionStatus.Completed, rd2.getExecutionStatus());
}

From source file:org.alfresco.repo.replication.ReplicationServiceIntegrationTest.java

/**
 * Check that the locking works./*  ww w.j ava 2s  . c o  m*/
 * Take a 10 second lock on the job, then execute.
 * Ensure that we really wait a little over 10 seconds.
 */
public void testReplicationExecutionLocking() throws Exception {
    // We need the test transfer target for this test
    makeTransferTarget();

    // Create a task
    ReplicationDefinition rd = replicationService.createReplicationDefinition(ACTION_NAME, "Test");
    rd.setTargetName(TRANSFER_TARGET);
    rd.getPayload().add(folder1);
    rd.getPayload().add(folder2);

    // Get the lock, and run
    long start = System.currentTimeMillis();
    String token = jobLockService.getLock(rd.getReplicationQName(), 10 * 1000, 1, 1);

    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();
    try {
        actionService.executeAction(rd, replicationRoot);
    } catch (ReplicationServiceException e) {
        // This shouldn't happen normally! Something is wrong!
        // Tidy up before we throw the exception
        txn.rollback();
        throw e;
    }
    txn.commit();
    long end = System.currentTimeMillis();

    assertTrue("Should wait for the lock, but didn't (waited " + ((end - start) / 1000.0) + " seconds, not 10)",
            end - start > 10000);
}

From source file:org.alfresco.repo.replication.ReplicationServiceIntegrationTest.java

/**
 * Check that cancelling works.//from   w  w  w .j av a  2  s  .c  o  m
 * Does this by taking a lock on the job, cancelling,
 *  releasing and seeing it abort.
 *  
 * Tests that when we ask for a replication task to be cancelled,
 *  that it starts, cancels, and the status is correctly recorded
 *  for it.
 */
public void testReplicationExecutionCancelling() throws Exception {
    // We need the test transfer target for this test
    makeTransferTarget();

    // Create a task
    ReplicationDefinition rd = replicationService.createReplicationDefinition(ACTION_NAME, "Test");
    rd.setTargetName(TRANSFER_TARGET);
    rd.getPayload().add(folder1);
    rd.getPayload().add(folder2);

    // Get the lock for 2 seconds
    String token = jobLockService.getLock(rd.getReplicationQName(), 2 * 1000, 1, 1);

    // Request it be run async
    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();
    actionService.executeAction(rd, replicationRoot, false, true);
    assertEquals(ActionStatus.Pending, rd.getExecutionStatus());

    assertEquals(false, actionTrackingService.isCancellationRequested(rd));
    actionTrackingService.requestActionCancellation(rd);
    assertEquals(true, actionTrackingService.isCancellationRequested(rd));

    txn.commit();

    // Let it get going, will be waiting for the lock
    //  having registered with the action tracking service
    for (int i = 0; i < 100; i++) {
        // Keep asking for it to be cancelled ASAP
        actionTrackingService.requestActionCancellation(rd);

        if (rd.getExecutionStatus().equals(ActionStatus.Running)) {
            // Good, has started up
            // Stop waiting and do the cancel
            break;
        } else {
            // Still pending, wait a bit more
            Thread.sleep(10);
        }
    }

    // Ensure it started, and should shortly stop
    assertEquals(ActionStatus.Running, rd.getExecutionStatus());
    assertEquals(true, actionTrackingService.isCancellationRequested(rd));

    // Release our lock, should allow the replication task
    //  to get going and spot the cancel
    jobLockService.releaseLock(token, rd.getReplicationQName());

    // Let the main replication task run to cancelled/completed
    // This can take quite some time though...
    for (int i = 0; i < 10; i++) {
        if (rd.getExecutionStatus() == ActionStatus.Running) {
            Thread.sleep(1000);
        } else {
            // It has finished running, check it
            break;
        }
    }

    // Ensure it was cancelled
    assertEquals(null, rd.getExecutionFailureMessage());
    assertNotNull(rd.getLocalTransferReport());
    assertNotNull(rd.getRemoteTransferReport());
    assertEquals(ActionStatus.Cancelled, rd.getExecutionStatus());
}

From source file:org.alfresco.repo.replication.ReplicationServiceIntegrationTest.java

/**
 * Test that when we execute a replication task, the
 *  right stuff ends up being moved for us
 *//*from   w  w  w. j  a  va 2 s  .co  m*/
public void testExecutionResult() throws Exception {
    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();

    // Destination is empty
    assertEquals(0, nodeService.getChildAssocs(destinationFolder).size());

    // We need the test transfer target for this test
    makeTransferTarget();

    // Put in Folder 2, so we can send Folder 2a
    String folder2Name = (String) nodeService.getProperties(folder2).get(ContentModel.PROP_NAME);
    NodeRef folderT2 = makeNode(destinationFolder, ContentModel.TYPE_FOLDER, folder2Name);
    txn.commit();

    // Run a transfer
    ReplicationDefinition rd = replicationService.createReplicationDefinition(ACTION_NAME, "Test");
    rd.setTargetName(TRANSFER_TARGET);
    rd.getPayload().add(folder1);
    rd.getPayload().add(folder2a);

    assertEquals(null, rd.getLocalTransferReport());
    assertEquals(null, rd.getRemoteTransferReport());

    txn = transactionService.getUserTransaction();
    txn.begin();
    try {
        actionService.executeAction(rd, replicationRoot);
    } catch (ReplicationServiceException e) {
        // This shouldn't happen normally! Something is wrong!
        // Tidy up before we throw the exception
        txn.rollback();
        throw e;
    }
    txn.commit();

    // Correct things have turned up
    assertEquals(2, nodeService.getChildAssocs(destinationFolder).size());
    NodeRef c1 = nodeService.getChildAssocs(destinationFolder).get(0).getChildRef();
    NodeRef c2 = nodeService.getChildAssocs(destinationFolder).get(1).getChildRef();

    // The destination should have folder 1 (transfered) 
    //  and folder 2 (created). folder 2 will have
    //  folder 2a (transfered) but not 2b
    NodeRef folderT1 = null;
    boolean foundT1 = false;
    boolean foundT2 = false;
    if (nodeService.getProperty(folder1, ContentModel.PROP_NAME)
            .equals(nodeService.getProperty(c1, ContentModel.PROP_NAME))) {
        folderT1 = c1;
        foundT1 = true;
    }
    if (nodeService.getProperty(folder1, ContentModel.PROP_NAME)
            .equals(nodeService.getProperty(c2, ContentModel.PROP_NAME))) {
        folderT1 = c2;
        foundT1 = true;
    }
    if (c1.equals(folderT2) || c2.equals(folderT2)) {
        foundT2 = true;
    }

    if (!foundT1) {
        fail("Folder 1 not found in the destination");
    }
    if (!foundT2) {
        fail("Folder 2 not found in the destination");
    }

    // Folder 1 has 2*content + thumbnail
    assertEquals(3, nodeService.getChildAssocs(folderT1).size());
    // Won't have the authority, as that gets skipped
    for (ChildAssociationRef r : nodeService.getChildAssocs(folderT1)) {
        if (nodeService.getType(r.getChildRef()).equals(ContentModel.TYPE_AUTHORITY)) {
            fail("Found authority as " + r.getChildRef() + " but it shouldn't be transfered!");
        }
    }

    // Folder 2 has 2a but not 2b, since only
    //  2a was transfered
    assertEquals(1, nodeService.getChildAssocs(folderT2).size());
    NodeRef folderT2a = nodeService.getChildAssocs(folderT2).get(0).getChildRef();
    assertEquals(nodeService.getProperty(folder2a, ContentModel.PROP_NAME),
            nodeService.getProperty(folderT2a, ContentModel.PROP_NAME));
    // Won't have Folder 2b, as it wasn't on the payload
    for (ChildAssociationRef r : nodeService.getChildAssocs(folderT2)) {
        assertNotSame(nodeService.getProperty(folder2b, ContentModel.PROP_NAME),
                nodeService.getProperty(r.getChildRef(), ContentModel.PROP_NAME));
    }

    // Folder 2a has content + thumbnail
    assertEquals(2, nodeService.getChildAssocs(folderT2a).size());
    // Won't have the zone, as that gets skipped
    for (ChildAssociationRef r : nodeService.getChildAssocs(folderT2a)) {
        if (nodeService.getType(r.getChildRef()).equals(ContentModel.TYPE_ZONE)) {
            fail("Found zone as " + r.getChildRef() + " but it shouldn't be transfered!");
        }
    }

    // Check we got transfer reports, and they look sensible
    NodeRef localReport = rd.getLocalTransferReport();
    assertNotNull(localReport);
    NodeRef remoteReport = rd.getRemoteTransferReport();
    assertNotNull(remoteReport);

    txn = transactionService.getUserTransaction();
    txn.begin();

    ContentReader localReader = contentService.getReader(localReport, ContentModel.PROP_CONTENT);
    String localReportContent = localReader.getContentString();

    assertTrue("XML not found in:\n" + localReportContent, localReportContent.contains("<?xml"));
    assertTrue("Report XML not found in:\n" + localReportContent,
            localReportContent.contains("<report:transferReport"));

    ContentReader remoteReader = contentService.getReader(remoteReport, ContentModel.PROP_CONTENT);
    String remoteReportContent = remoteReader.getContentString();

    assertTrue("XML not found in:\n" + remoteReportContent, remoteReportContent.contains("<?xml"));
    assertTrue("Report Status not found in:\n" + remoteReportContent,
            remoteReportContent.contains("state=\"COMPLETE\""));

    txn.commit();
}

From source file:org.alfresco.repo.search.impl.lucene.ADMLuceneTest.java

/**
 * @throws Exception//w w  w .  java  2 s  .c  o  m
 */
public void testDeleteIssue() throws Exception {

    testTX.commit();

    testTX = transactionService.getUserTransaction();
    testTX.begin();
    ChildAssociationRef testFind = nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN,
            QName.createQName("{namespace}testFind"), testSuperType);
    testTX.commit();

    ADMLuceneSearcherImpl searcher = buildSearcher();

    ResultSet results = searcher.query(rootNodeRef.getStoreRef(), "lucene", "QNAME:\"namespace:testFind\"");
    assertEquals(1, results.length());
    results.close();

    RetryingTransactionCallback<Object> createAndDeleteCallback = new RetryingTransactionCallback<Object>() {
        public Object execute() throws Throwable {
            for (int i = 0; i < 100; i += 10) {
                HashSet<ChildAssociationRef> refs = new HashSet<ChildAssociationRef>();
                for (int j = 0; j < i; j++) {
                    ChildAssociationRef test = nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN,
                            QName.createQName("{namespace}test"), testSuperType);
                    refs.add(test);
                }

                for (ChildAssociationRef car : refs) {
                    nodeService.deleteNode(car.getChildRef());
                }
            }
            return null;
        }
    };
    retryingTransactionHelper.doInTransaction(createAndDeleteCallback);

    UserTransaction tx3 = transactionService.getUserTransaction();
    tx3.begin();
    results = searcher.query(rootNodeRef.getStoreRef(), "lucene", "QNAME:\"namespace:testFind\"");
    assertEquals(1, results.length());
    results.close();
    tx3.commit();
}