Example usage for javax.transaction UserTransaction rollback

List of usage examples for javax.transaction UserTransaction rollback

Introduction

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

Prototype

void rollback() throws IllegalStateException, SecurityException, SystemException;

Source Link

Document

Roll back the transaction associated with the current thread.

Usage

From source file:org.alfresco.repo.cache.CacheTest.java

public void testTransactionalCacheStatsOnCommit() throws Throwable {
    // add item to global cache
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test1", "v", null);
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test2", "v", null);
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test3", "v", null);

    TransactionService transactionService = serviceRegistry.getTransactionService();
    UserTransaction txn = transactionService.getUserTransaction();

    final long hitsAtStart = cacheStats.count("transactionalCache", OpType.GET_HIT);
    final long missesAtStart = cacheStats.count("transactionalCache", OpType.GET_MISS);
    final long putsAtStart = cacheStats.count("transactionalCache", OpType.PUT);
    final long removesAtStart = cacheStats.count("transactionalCache", OpType.REMOVE);
    final long clearsAtStart = cacheStats.count("transactionalCache", OpType.CLEAR);

    try {/*from   w ww.  ja  va2  s . c  o  m*/
        // begin a transaction
        txn.begin();

        // Perform some puts
        transactionalCache.put("stats-test4", "v");
        transactionalCache.put("stats-test5", "v");
        transactionalCache.put("stats-test6", "v");
        transactionalCache.put("stats-test7", "v");
        transactionalCache.put("stats-test8", "v");

        // Perform some gets...
        // hits
        transactionalCache.get("stats-test3");
        transactionalCache.get("stats-test2");
        transactionalCache.get("stats-test1");
        // repeated hits won't touch the shared cache
        transactionalCache.get("stats-test2");
        transactionalCache.get("stats-test1");
        // misses - not yet committed
        transactionalCache.get("stats-miss1");
        transactionalCache.get("stats-miss2");
        transactionalCache.get("stats-miss3");
        transactionalCache.get("stats-miss4");
        // repeated misses won't touch the shared cache
        transactionalCache.get("stats-miss2");
        transactionalCache.get("stats-miss3");

        // Perform some removals
        transactionalCache.remove("stats-test1");
        transactionalCache.remove("stats-test2");
        transactionalCache.remove("stats-test3");
        transactionalCache.remove("stats-test9");
        transactionalCache.remove("stats-test10");
        transactionalCache.remove("stats-test11");
        transactionalCache.remove("stats-test12");
        transactionalCache.remove("stats-test13");

        // Check nothing has changed yet - changes not written through until commit or rollback
        assertEquals(hitsAtStart, cacheStats.count("transactionalCache", OpType.GET_HIT));
        assertEquals(missesAtStart, cacheStats.count("transactionalCache", OpType.GET_MISS));
        assertEquals(putsAtStart, cacheStats.count("transactionalCache", OpType.PUT));
        assertEquals(removesAtStart, cacheStats.count("transactionalCache", OpType.REMOVE));
        assertEquals(clearsAtStart, cacheStats.count("transactionalCache", OpType.CLEAR));

        // commit the transaction
        txn.commit();

        // TODO: remove is called twice for each remove (in beforeCommit and afterCommit) - check this is correct.
        assertEquals(removesAtStart + 16, cacheStats.count("transactionalCache", OpType.REMOVE));
        assertEquals(hitsAtStart + 3, cacheStats.count("transactionalCache", OpType.GET_HIT));
        assertEquals(missesAtStart + 4, cacheStats.count("transactionalCache", OpType.GET_MISS));
        assertEquals(putsAtStart + 5, cacheStats.count("transactionalCache", OpType.PUT));
        // Performing a clear would affect the other stats, so a separate test is required.
        assertEquals(clearsAtStart + 0, cacheStats.count("transactionalCache", OpType.CLEAR));
    } catch (Throwable e) {
        if (txn.getStatus() == Status.STATUS_ACTIVE) {
            txn.rollback();
        }
        throw e;
    }
}

From source file:org.alfresco.repo.cache.CacheTest.java

public void testTransactionalCacheStatsDisabled() throws Throwable {
    // add item to global cache
    TransactionalCache.putSharedCacheValue(backingCacheNoStats, "stats-test1", "v", null);
    TransactionalCache.putSharedCacheValue(backingCacheNoStats, "stats-test2", "v", null);
    TransactionalCache.putSharedCacheValue(backingCacheNoStats, "stats-test3", "v", null);

    TransactionService transactionService = serviceRegistry.getTransactionService();
    UserTransaction txn = transactionService.getUserTransaction();

    for (OpType opType : OpType.values()) {
        try {//from  ww  w .ja  v a  2s.  c om
            cacheStats.count("transactionalCacheNoStats", opType);
            fail("Expected NoStatsForCache error.");
        } catch (NoStatsForCache e) {
            // Good
        }
    }

    try {
        // begin a transaction
        txn.begin();

        // Perform some puts
        transactionalCacheNoStats.put("stats-test4", "v");
        transactionalCache.put("stats-test5", "v");
        transactionalCache.put("stats-test6", "v");
        transactionalCache.put("stats-test7", "v");
        transactionalCache.put("stats-test8", "v");

        // Perform some gets...
        // hits
        transactionalCache.get("stats-test3");
        transactionalCache.get("stats-test2");
        transactionalCache.get("stats-test1");
        // repeated hits won't touch the shared cache
        transactionalCache.get("stats-test2");
        transactionalCache.get("stats-test1");
        // misses - not yet committed
        transactionalCache.get("stats-miss1");
        transactionalCache.get("stats-miss2");
        transactionalCache.get("stats-miss3");
        transactionalCache.get("stats-miss4");
        // repeated misses won't touch the shared cache
        transactionalCache.get("stats-miss2");
        transactionalCache.get("stats-miss3");

        // Perform some removals
        transactionalCache.remove("stats-test1");
        transactionalCache.remove("stats-test2");
        transactionalCache.remove("stats-test3");
        transactionalCache.remove("stats-test9");
        transactionalCache.remove("stats-test10");
        transactionalCache.remove("stats-test11");
        transactionalCache.remove("stats-test12");
        transactionalCache.remove("stats-test13");

        // Check nothing has changed - changes not written through until commit or rollback
        for (OpType opType : OpType.values()) {
            try {
                cacheStats.count("transactionalCacheNoStats", opType);
                fail("Expected NoStatsForCache error.");
            } catch (NoStatsForCache e) {
                // Good
            }
        }

        // commit the transaction
        txn.commit();

        // Post-commit, nothing should have changed.
        for (OpType opType : OpType.values()) {
            try {
                cacheStats.count("transactionalCacheNoStats", opType);
                fail("Expected NoStatsForCache error.");
            } catch (NoStatsForCache e) {
                // Good
            }
        }
    } catch (Throwable e) {
        if (txn.getStatus() == Status.STATUS_ACTIVE) {
            txn.rollback();
        }
        throw e;
    }
}

From source file:org.alfresco.repo.cache.CacheTest.java

public void testTransactionalCacheStatsForClears() throws Throwable {
    // add item to global cache
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test1", "v", null);
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test2", "v", null);
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test3", "v", null);

    TransactionService transactionService = serviceRegistry.getTransactionService();
    UserTransaction txn = transactionService.getUserTransaction();

    final long hitsAtStart = cacheStats.count("transactionalCache", OpType.GET_HIT);
    final long missesAtStart = cacheStats.count("transactionalCache", OpType.GET_MISS);
    final long putsAtStart = cacheStats.count("transactionalCache", OpType.PUT);
    final long removesAtStart = cacheStats.count("transactionalCache", OpType.REMOVE);
    final long clearsAtStart = cacheStats.count("transactionalCache", OpType.CLEAR);

    try {// w w w  . j  av a 2 s  .  c o m
        // begin a transaction
        txn.begin();

        // Perform some puts
        transactionalCache.put("stats-test4", "v");
        transactionalCache.put("stats-test5", "v");
        transactionalCache.put("stats-test6", "v");
        transactionalCache.put("stats-test7", "v");
        transactionalCache.put("stats-test8", "v");

        // Perform some gets...
        // hits
        transactionalCache.get("stats-test3");
        transactionalCache.get("stats-test2");
        transactionalCache.get("stats-test1");
        // repeated hits won't touch the shared cache
        transactionalCache.get("stats-test2");
        transactionalCache.get("stats-test1");
        // misses - not yet committed
        transactionalCache.get("stats-miss1");
        transactionalCache.get("stats-miss2");
        transactionalCache.get("stats-miss3");
        transactionalCache.get("stats-miss4");
        // repeated misses won't touch the shared cache
        transactionalCache.get("stats-miss2");
        transactionalCache.get("stats-miss3");

        // Perform some removals
        transactionalCache.remove("stats-test1");
        transactionalCache.remove("stats-test2");
        transactionalCache.remove("stats-test3");
        transactionalCache.remove("stats-test9");
        transactionalCache.remove("stats-test10");
        transactionalCache.remove("stats-test11");
        transactionalCache.remove("stats-test12");
        transactionalCache.remove("stats-test13");

        // Perform some clears
        transactionalCache.clear();
        transactionalCache.clear();

        // Check nothing has changed yet - changes not written through until commit or rollback
        assertEquals(hitsAtStart, cacheStats.count("transactionalCache", OpType.GET_HIT));
        assertEquals(missesAtStart, cacheStats.count("transactionalCache", OpType.GET_MISS));
        assertEquals(putsAtStart, cacheStats.count("transactionalCache", OpType.PUT));
        assertEquals(removesAtStart, cacheStats.count("transactionalCache", OpType.REMOVE));
        assertEquals(clearsAtStart, cacheStats.count("transactionalCache", OpType.CLEAR));

        // commit the transaction
        txn.commit();

        assertEquals(clearsAtStart + 2, cacheStats.count("transactionalCache", OpType.CLEAR));
        // There are no removes or puts propagated to the shared cache, as a result of the clears.
        assertEquals(removesAtStart + 0, cacheStats.count("transactionalCache", OpType.REMOVE));
        assertEquals(putsAtStart + 0, cacheStats.count("transactionalCache", OpType.PUT));
        assertEquals(hitsAtStart + 3, cacheStats.count("transactionalCache", OpType.GET_HIT));
        assertEquals(missesAtStart + 4, cacheStats.count("transactionalCache", OpType.GET_MISS));
    } catch (Throwable e) {
        if (txn.getStatus() == Status.STATUS_ACTIVE) {
            txn.rollback();
        }
        throw e;
    }
}

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

@SuppressWarnings("unchecked")
public void doImport() {
    UserTransaction userTransaction = null;
    try {//  www .jav  a  2s. com
        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 {//ww  w. j  a  v  a 2 s . c o m
        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 w  w  w.  j  av  a  2s  . c  o m

    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

/**
 * 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 a  2s .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./*from ww  w . ja  va  2 s . 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

/**
 * Test that when we execute a replication task, the
 *  right stuff ends up being moved for us
 *///  w  w w  .  ja va2s .  c  o  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/*from   w  ww .  ja v a2  s. c om*/
 */
public void testDeltaIssue() throws Exception {
    luceneFTS.pause();
    final NodeService pns = (NodeService) ctx.getBean("NodeService");

    testTX.commit();
    testTX = transactionService.getUserTransaction();
    testTX.begin();
    luceneFTS.pause();
    buildBaseIndex();
    runBaseTests();
    testTX.commit();

    Thread thread = new Thread(new Runnable() {

        public void run() {
            try {
                authenticationComponent.setSystemUserAsCurrentUser();
                UserTransaction tx = transactionService.getUserTransaction();
                tx = transactionService.getUserTransaction();
                tx.begin();

                SearchParameters sp = new SearchParameters();
                sp.addStore(rootNodeRef.getStoreRef());
                sp.setLanguage(SearchService.LANGUAGE_LUCENE);
                sp.setQuery("PATH:\"//.\"");
                sp.excludeDataInTheCurrentTransaction(false);
                ResultSet results = serviceRegistry.getSearchService().query(sp);
                for (ResultSetRow row : results) {
                    System.out.println("row = " + row.getQName());
                }
                assertEquals(15, results.length());
                results.close();

                sp = new SearchParameters();
                sp.addStore(rootNodeRef.getStoreRef());
                sp.setLanguage(SearchService.LANGUAGE_LUCENE);
                sp.setQuery("PATH:\"//.\"");
                sp.excludeDataInTheCurrentTransaction(false);
                results = serviceRegistry.getSearchService().query(sp);
                assertEquals(15, results.length());
                results.close();

                Map<QName, Serializable> props = new HashMap<QName, Serializable>();
                props.put(ContentModel.PROP_TITLE, "woof");
                pns.addAspect(n1, ContentModel.ASPECT_TITLED, props);

                sp = new SearchParameters();
                sp.addStore(rootNodeRef.getStoreRef());
                sp.setLanguage(SearchService.LANGUAGE_LUCENE);
                sp.setQuery("PATH:\"//.\"");
                sp.excludeDataInTheCurrentTransaction(false);
                results = serviceRegistry.getSearchService().query(sp);
                assertEquals(15, results.length());
                results.close();

                tx.rollback();
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }

        }

    });

    thread.start();
    thread.join();

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

    SearchParameters sp = new SearchParameters();
    sp.addStore(rootNodeRef.getStoreRef());
    sp.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp.setQuery("PATH:\"//.\"");
    sp.excludeDataInTheCurrentTransaction(false);
    ResultSet results = serviceRegistry.getSearchService().query(sp);
    assertEquals(16, results.length());
    results.close();

    sp = new SearchParameters();
    sp.addStore(rootNodeRef.getStoreRef());
    sp.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp.setQuery("PATH:\"//.\"");
    sp.excludeDataInTheCurrentTransaction(false);
    results = serviceRegistry.getSearchService().query(sp);
    assertEquals(16, results.length());
    results.close();

    runBaseTests();

    sp = new SearchParameters();
    sp.addStore(rootNodeRef.getStoreRef());
    sp.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp.setQuery("PATH:\"//.\"");
    sp.excludeDataInTheCurrentTransaction(false);
    results = serviceRegistry.getSearchService().query(sp);
    assertEquals(16, results.length());
    results.close();

    Map<QName, Serializable> props = new HashMap<QName, Serializable>();
    props.put(ContentModel.PROP_TITLE, "woof");
    pns.addAspect(n1, ContentModel.ASPECT_TITLED, props);

    sp = new SearchParameters();
    sp.addStore(rootNodeRef.getStoreRef());
    sp.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp.setQuery("PATH:\"//.\"");
    sp.excludeDataInTheCurrentTransaction(false);
    results = serviceRegistry.getSearchService().query(sp);
    assertEquals(16, results.length());
    results.close();

    pns.setProperty(n1, ContentModel.PROP_TITLE, "cube");

    sp = new SearchParameters();
    sp.addStore(rootNodeRef.getStoreRef());
    sp.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp.setQuery("PATH:\"//.\"");
    sp.excludeDataInTheCurrentTransaction(false);
    results = serviceRegistry.getSearchService().query(sp);
    assertEquals(16, results.length());
    results.close();

    testTX.rollback();

}