Example usage for javax.transaction UserTransaction commit

List of usage examples for javax.transaction UserTransaction commit

Introduction

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

Prototype

void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException,
        IllegalStateException, SystemException;

Source Link

Document

Complete the transaction associated with the current thread.

Usage

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.");
    }//  w ww . ja  v  a  2  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
 *//*www.  j a  v a 2s . c o 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.// w  w w. j  a  v  a  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  ww w.  ja va  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  av a  2  s  .  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 w  w .j  av a 2s  . c om*/
 */
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();
}

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

/**
 * @throws Exception/*from www.  j  a  v  a 2  s  .c om*/
 */
public void testIssueAR47() throws Exception {
    // This bug arose from repeated deletes and adds creating empty index
    // segments.
    // Two segements each containing one deletyed entry were merged together
    // producing a single empty entry.
    // This seemed to be bad for lucene - I am not sure why

    // So we add something, add and delete someting repeatedly and then
    // check we can still do the search.

    // Running in autocommit against the index
    testTX.commit();
    UserTransaction tx = transactionService.getUserTransaction();
    tx.begin();
    ChildAssociationRef testFind = nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN,
            QName.createQName("{namespace}testFind"), testSuperType);
    tx.commit();

    ADMLuceneSearcherImpl searcher = buildSearcher();

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

    for (int i = 0; i < 100; i++) {
        UserTransaction tx1 = transactionService.getUserTransaction();
        tx1.begin();
        ChildAssociationRef test = nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN,
                QName.createQName("{namespace}test"), testSuperType);
        tx1.commit();

        UserTransaction tx2 = transactionService.getUserTransaction();
        tx2.begin();
        nodeService.deleteNode(test.getChildRef());
        tx2.commit();
    }

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

From source file:org.alfresco.repo.tenant.MultiTAdminServiceImpl.java

@Override
public void startTenants() {
    AuthenticationUtil.setMtEnabled(true);

    // initialise the tenant admin service and status of tenants (using attribute service)
    // note: this requires that the repository schema has already been initialised

    // register dictionary - to allow enable/disable tenant callbacks
    register(dictionaryComponent);/*from  w ww . j  a  v a 2  s.c o  m*/

    if (isTenantDeployer(tenantFileContentStore)) {
        // register file store - to allow enable/disable tenant callbacks
        // note: tenantFileContentStore must be registed before dictionaryRepositoryBootstrap
        register(tenantDeployer(tenantFileContentStore), 0);
    }

    UserTransaction userTransaction = transactionService.getUserTransaction();

    try {
        authenticationContext.setSystemUserAsCurrentUser();
        userTransaction.begin();

        // bootstrap Tenant Service internal cache
        List<Tenant> tenants = getAllTenants();

        int enabledCount = 0;
        int disabledCount = 0;

        for (Tenant tenant : tenants) {
            if ((!(isTenantRoutingContentStore(tenantFileContentStore)))
                    && (!tenantFileContentStore.getRootLocation().equals(tenant.getRootContentStoreDir()))) {
                // eg. ALF-14121 - MT will not work with replicating-content-services-context.sample if tenants are not co-mingled
                throw new AlfrescoRuntimeException(
                        "MT: cannot start tenants - TenantRoutingContentStore is not configured AND not all tenants use co-mingled content store");
            }

            String tenantDomain = tenant.getTenantDomain();

            if (tenant.isEnabled()) {
                // notify tenant deployers registered so far ...
                notifyAfterEnableTenant(tenantDomain);
                enabledCount++;
            } else {
                disabledCount++;

                if (logger.isDebugEnabled()) {
                    logger.debug("Tenant disabled: " + tenantDomain);
                }
            }
        }

        userTransaction.commit();

        if ((enabledCount + disabledCount) == 0) {
            AuthenticationUtil.setMtEnabled(false); // explicitly disable if there are no tenants
        }

        if (logger.isInfoEnabled() && ((enabledCount + disabledCount) > 0)) {
            logger.info(String.format("Alfresco Multi-Tenant startup - %d enabled tenants, %d disabled tenants",
                    enabledCount, disabledCount));
        } else if (logger.isDebugEnabled()) {
            logger.debug(
                    String.format("Alfresco Multi-Tenant startup - %d enabled tenants, %d disabled tenants",
                            enabledCount, disabledCount));
        }
    } catch (Throwable e) {
        // rollback the transaction
        try {
            if (userTransaction != null) {
                userTransaction.rollback();
            }
        } catch (Exception ex) {
        }
        throw new AlfrescoRuntimeException("Failed to bootstrap tenants", e);
    } finally {
        authenticationContext.clearCurrentSecurityContext();
    }
}

From source file:org.alfresco.repo.tenant.MultiTAdminServiceImpl.java

@Override
public void deployTenants(final TenantDeployer deployer, Log logger) {
    if (deployer == null) {
        throw new AlfrescoRuntimeException("Deployer must be provided");
    }//from   ww  w  . j a  va2s  .  com
    if (logger == null) {
        throw new AlfrescoRuntimeException("Logger must be provided");
    }

    if (tenantService.isEnabled()) {
        UserTransaction userTransaction = transactionService.getUserTransaction();
        authenticationContext.setSystemUserAsCurrentUser();

        List<Tenant> tenants = null;
        try {
            userTransaction.begin();
            tenants = getAllTenants();
            userTransaction.commit();
        } catch (Throwable e) {
            // rollback the transaction
            try {
                if (userTransaction != null) {
                    userTransaction.rollback();
                }
            } catch (Exception ex) {
            }
            throw new AlfrescoRuntimeException("Failed to get tenants", e);
        } finally {
            authenticationContext.clearCurrentSecurityContext();
        }

        for (Tenant tenant : tenants) {
            if (tenant.isEnabled()) {
                try {
                    // deploy within context of tenant domain
                    TenantUtil.runAsSystemTenant(new TenantRunAsWork<Object>() {
                        public Object doWork() {
                            // init the service within tenant context
                            deployer.init();
                            return null;
                        }
                    }, tenant.getTenantDomain());

                } catch (Throwable e) {
                    logger.error("Deployment failed" + e);

                    StringWriter stringWriter = new StringWriter();
                    e.printStackTrace(new PrintWriter(stringWriter));
                    logger.error(stringWriter.toString());

                    // tenant deploy failure should not necessarily affect other tenants
                }
            }
        }
    }
}

From source file:org.alfresco.repo.tenant.MultiTAdminServiceImpl.java

@Override
public void undeployTenants(final TenantDeployer deployer, Log logger) {
    if (deployer == null) {
        throw new AlfrescoRuntimeException("Deployer must be provided");
    }/*from   ww  w  .ja  v a  2s  . com*/
    if (logger == null) {
        throw new AlfrescoRuntimeException("Logger must be provided");
    }

    if (tenantService.isEnabled()) {
        UserTransaction userTransaction = transactionService.getUserTransaction();
        authenticationContext.setSystemUserAsCurrentUser();

        List<Tenant> tenants = null;
        try {
            userTransaction.begin();
            tenants = getAllTenants();
            userTransaction.commit();
        } catch (Throwable e) {
            // rollback the transaction
            try {
                if (userTransaction != null) {
                    userTransaction.rollback();
                }
            } catch (Exception ex) {
            }
            try {
                authenticationContext.clearCurrentSecurityContext();
            } catch (Exception ex) {
            }
            throw new AlfrescoRuntimeException("Failed to get tenants", e);
        }

        try {
            AuthenticationUtil.pushAuthentication();
            for (Tenant tenant : tenants) {
                if (tenant.isEnabled()) {
                    try {
                        // undeploy within context of tenant domain
                        TenantUtil.runAsSystemTenant(new TenantRunAsWork<Object>() {
                            public Object doWork() {
                                // destroy the service within tenant context
                                deployer.destroy();
                                return null;
                            }
                        }, tenant.getTenantDomain());
                    } catch (Throwable e) {
                        logger.error("Undeployment failed" + e);

                        StringWriter stringWriter = new StringWriter();
                        e.printStackTrace(new PrintWriter(stringWriter));
                        logger.error(stringWriter.toString());

                        // tenant undeploy failure should not necessarily affect other tenants
                    }
                }
            }
        } finally {
            AuthenticationUtil.popAuthentication();
        }
    }
}