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.encryption.KeyStoreTests.java

@Before
public void setup() throws SystemException, NotSupportedException {
    transactionService = (TransactionService) ctx.getBean("transactionService");
    keyStoreChecker = (KeyStoreChecker) ctx.getBean("keyStoreChecker");
    encryptionKeysRegistry = (EncryptionKeysRegistry) ctx.getBean("encryptionKeysRegistry");
    keyResourceLoader = (KeyResourceLoader) ctx.getBean("springKeyResourceLoader");
    backupEncryptor = (DefaultEncryptor) ctx.getBean("backupEncryptor");

    toDelete = new ArrayList<String>(10);

    AuthenticationUtil.setRunAsUserSystem();
    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();
}

From source file:org.alfresco.filesys.alfresco.AlfrescoTxDiskDriver.java

/**
 * Create and start a transaction, if not already active
 * /*from ww  w  .j  a  v  a2  s .com*/
 * @param sess SrvSession
 * @param readOnly boolean
 * @exception AlfrescoRuntimeException
 */
private final void beginTransaction(SrvSession sess, boolean readOnly) throws AlfrescoRuntimeException {
    // Do nothing if we are already in a retrying transaction
    Boolean inRetryingTransaction = m_inRetryingTransaction.get();

    if (inRetryingTransaction != null && inRetryingTransaction) {
        return;
    }

    // Initialize the per session thread local that holds the transaction

    sess.initializeTransactionObject();

    // Get the filesystem transaction

    FilesysTransaction filesysTx = (FilesysTransaction) sess.getTransactionObject().get();
    if (filesysTx == null) {
        filesysTx = new FilesysTransaction();
        sess.getTransactionObject().set(filesysTx);
    }

    // If there is an active transaction check that it is the required type

    if (filesysTx.hasTransaction()) {
        // Get the active transaction

        UserTransaction tx = filesysTx.getTransaction();

        // Check if the current transaction is marked for rollback

        try {
            if (tx.getStatus() == Status.STATUS_MARKED_ROLLBACK || tx.getStatus() == Status.STATUS_ROLLEDBACK
                    || tx.getStatus() == Status.STATUS_ROLLING_BACK) {
                //  Rollback the current transaction

                tx.rollback();
            }
        } catch (Exception ex) {
        }

        // Check if the transaction is a write transaction, if write has been requested

        if (readOnly == false && filesysTx.isReadOnly() == true) {
            // Commit the read-only transaction

            try {
                tx.commit();
            } catch (Exception ex) {
                throw new AlfrescoRuntimeException(
                        "Failed to commit read-only transaction, " + ex.getMessage());
            } finally {
                // Clear the active transaction

                filesysTx.clearTransaction();
            }
        }
    }

    // Create the transaction

    if (filesysTx.hasTransaction() == false) {
        try {
            // Create a new transaction

            UserTransaction userTrans = m_transactionService.getUserTransaction(readOnly);
            userTrans.begin();

            // Store the transaction

            filesysTx.setTransaction(userTrans, readOnly);

            // DEBUG

            if (logger.isDebugEnabled())
                logger.debug("Created transaction readOnly=" + readOnly);
        } catch (Exception ex) {
            throw new AlfrescoRuntimeException("Failed to create transaction, " + ex.getMessage());
        }
    }

    //  Store the transaction callback

    sess.setTransaction(this);
}

From source file:org.alfresco.filesys.auth.ftp.FTPAuthenticatorBase.java

/**
 * Check if the user is an administrator user name
 * //from w  ww  . j av  a 2  s .c  o  m
 * @param cInfo ClientInfo
 */
protected final void checkForAdminUserName(ClientInfo cInfo) {

    // Check if the user name is an administrator

    UserTransaction tx = getTransactionService().getUserTransaction();

    try {
        tx.begin();

        if (cInfo.getLogonType() == ClientInfo.LogonNormal
                && getAuthorityService().isAdminAuthority(cInfo.getUserName())) {

            // Indicate that this is an administrator logon

            cInfo.setLogonType(ClientInfo.LogonAdmin);
        }
        tx.commit();
    } catch (Throwable ex) {
        try {
            tx.rollback();
        } catch (Throwable ex2) {
            logger.error("Failed to rollback transaction", ex2);
        }

        // Re-throw the exception

        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        } else {
            throw new RuntimeException("Error during execution of transaction.", ex);
        }
    }
}

From source file:org.alfresco.filesys.repo.ContentDiskDriver.java

/**
 * Registers a device context object for this instance
 * of the shared device. The same DeviceInterface implementation may be used for multiple
 * shares./*from   ww  w  .j  ava 2 s.com*/
 * 
 * WARNING: side effect, will commit or roll back current user transaction context.
 * 
 * @param ctx the context
 * @exception DeviceContextException
 */
//  MER TODO - transaction handling in registerContext needs changing
@Override
public void registerContext(DeviceContext ctx) throws DeviceContextException {
    super.registerContext(ctx);

    ContentContext context = (ContentContext) ctx;

    // Wrap the initialization in a transaction

    UserTransaction tx = getTransactionService().getUserTransaction(true);

    try {
        // Use the system user as the authenticated context for the filesystem initialization

        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());

        // Start the transaction

        if (tx != null)
            tx.begin();

        // Get the store
        String storeValue = context.getStoreName();
        StoreRef storeRef = new StoreRef(storeValue);

        // Connect to the repo and ensure that the store exists

        if (!nodeService.exists(storeRef)) {
            throw new DeviceContextException("Store not created prior to application startup: " + storeRef);
        }
        NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef);

        // Get the root path
        String rootPath = context.getRootPath();

        // Find the root node for this device

        List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, rootPath, null, namespaceService,
                false);

        NodeRef rootNodeRef = null;

        if (nodeRefs.size() > 1) {
            throw new DeviceContextException("Multiple possible roots for device: \n" + "   root path: "
                    + rootPath + "\n" + "   results: " + nodeRefs);
        } else if (nodeRefs.size() == 0) {
            // Nothing found

            throw new DeviceContextException("No root found for device: \n" + "   root path: " + rootPath);
        } else {
            // We found a node

            rootNodeRef = nodeRefs.get(0);
        }

        // Check if a relative path has been specified

        String relPath = context.getRelativePath();

        if (relPath != null && relPath.length() > 0) {
            // Find the node and validate that the relative path is to a folder

            NodeRef relPathNode = cifsHelper.getNodeRef(rootNodeRef, relPath);
            if (cifsHelper.isDirectory(relPathNode) == false)
                throw new DeviceContextException("Relative path is not a folder, " + relPath);

            // Use the relative path node as the root of the filesystem

            rootNodeRef = relPathNode;
        } else {

            // Make sure the default root node is a folder

            if (cifsHelper.isDirectory(rootNodeRef) == false)
                throw new DeviceContextException("Root node is not a folder type node");
        }

        // Commit the transaction

        // MER 16/03/2010 - Why is this transaction management here?
        tx.commit();
        tx = null;

        // Record the root node ref
        context.setRootNodeRef(rootNodeRef);
    } catch (Exception ex) {
        logger.error("Error during create context", ex);

        // MER BUGBUG Exception swallowed - will result in null pointer errors at best.
        throw new DeviceContextException("unable to register context", ex);
        // MER END
    } finally {
        // Restore authentication context

        AuthenticationUtil.popAuthentication();

        // If there is an active transaction then roll it back

        if (tx != null) {
            try {
                tx.rollback();
            } catch (Exception ex) {
                logger.warn("Failed to rollback transaction", ex);
            }
        }
    }

    // Check if locked files should be marked as offline
    if (context.getOfflineFiles()) {
        // Enable marking locked files as offline
        isLockedFilesAsOffline = true;

        // Logging

        logger.info("Locked files will be marked as offline");
    }

    // Enable file state caching

    //        context.enableStateCache(serverConfig, true);

    // Install the node service monitor

    if (!context.getDisableNodeMonitor() && m_nodeMonitorFactory != null) {

        // Create the node monitor

        NodeMonitor nodeMonitor = m_nodeMonitorFactory.createNodeMonitor(context);
        context.setNodeMonitor(nodeMonitor);
    }

    // Check if oplocks are enabled

    if (context.getDisableOplocks() == true)
        logger.warn("Oplock support disabled for filesystem " + ctx.getDeviceName());

    // Start the quota manager, if enabled

    if (context.hasQuotaManager()) {

        try {

            // Start the quota manager

            context.getQuotaManager().startManager(this, context);
            logger.info("Quota manager enabled for filesystem");
        } catch (QuotaManagerException ex) {
            logger.error("Failed to start quota manager", ex);
        }
    }
}

From source file:org.alfresco.module.org_alfresco_module_wcmquickstart.publish.PublishTest.java

public void xtestWebSiteHierarchy() throws Exception {
    // Start transaction
    UserTransaction userTransaction = transactionService.getUserTransaction();
    userTransaction.begin();

    // Get company home
    companyHome = repository.getCompanyHome();

    // Create webroot (downcasting to check default properties are set)
    NodeRef editorialWebroot = fileFolderService
            .create(companyHome, "editorial" + GUID.generate(), ContentModel.TYPE_FOLDER).getNodeRef();
    assertNotNull(editorialWebroot);/*from  ww w  .j a  va  2 s.  co  m*/
    nodeService.setType(editorialWebroot, TYPE_WEB_SITE);

    NodeRef liveWebroot = fileFolderService
            .create(companyHome, "live" + GUID.generate(), ContentModel.TYPE_FOLDER).getNodeRef();
    assertNotNull(liveWebroot);
    nodeService.setType(liveWebroot, TYPE_WEB_SITE);

    nodeService.createAssociation(editorialWebroot, liveWebroot, WebSiteModel.ASSOC_PUBLISH_TARGET);

    // Create child folder
    NodeRef section = fileFolderService.create(editorialWebroot, "section", WebSiteModel.TYPE_WEB_ROOT)
            .getNodeRef();
    assertNotNull(section);

    // Create child folder of section
    NodeRef sectionChild = fileFolderService.create(section, "childSection", ContentModel.TYPE_FOLDER)
            .getNodeRef();
    assertNotNull(sectionChild);
    assertEquals(TYPE_SECTION, nodeService.getType(sectionChild));

    // Create content in child section
    NodeRef page = fileFolderService.create(sectionChild, "myFile.txt", ContentModel.TYPE_CONTENT).getNodeRef();
    ContentWriter writer = contentService.getWriter(page, ContentModel.PROP_CONTENT, true);
    writer.setEncoding("UTF-8");
    writer.setMimetype("text/html");
    writer.putContent("<html><head><title>Hello</title></head><body></body></html>");
    NodeRef nonpage = fileFolderService.create(sectionChild, "myFile.bob", ContentModel.TYPE_CONTENT)
            .getNodeRef();
    writer = contentService.getWriter(nonpage, ContentModel.PROP_CONTENT, true);
    writer.setEncoding("UTF-8");
    writer.setMimetype("text/plain");
    writer.putContent("Some asset only text.");

    userTransaction.commit();
    userTransaction = transactionService.getUserTransaction();
    userTransaction.begin();

    // Check all assets have been marked up correctly
    assertTrue("Page does not have webasset aspect applied.", nodeService.hasAspect(page, ASPECT_WEBASSET));
    assertTrue("Non-page does not have webasset aspect applied.",
            nodeService.hasAspect(nonpage, ASPECT_WEBASSET));

    String targetName = "test" + GUID.generate();
    TransferTarget transferTarget = transferService.createTransferTarget(targetName);
    transferTarget.setUsername("user");
    transferTarget.setPassword("hello".toCharArray());
    transferTarget.setEndpointHost("host");
    transferTarget.setEndpointProtocol("http");
    transferTarget.setEndpointPort(80);
    transferService.saveTransferTarget(transferTarget);
    userTransaction.commit();

    //A little breath to give time for the page's parent sections to be populated.
    Thread.sleep(200);

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

    //        nodeFactory.addPathMapping(new Pair<Path, Path>(nodeService.getPath(editorialWebroot), nodeService.getPath(liveWebroot)));
    //        TransferDefinition def = new TransferDefinition();
    //      def.setNodes(section, sectionChild, page);
    //      transferService.transfer(targetName, def);

    publishService.enqueuePublishedNodes(section, sectionChild, page);

    long start = System.currentTimeMillis();

    publishService.publishQueue(editorialWebroot);

    userTransaction.commit();
    log.debug("Transfer took " + (System.currentTimeMillis() - start) + "ms");

    userTransaction = transactionService.getUserTransaction();
    userTransaction.begin();
    assertFalse(nodeService.getChildAssocs(liveWebroot).isEmpty());

    NodeRef liveSection = fileFolderService.searchSimple(liveWebroot, "section");
    assertNotNull(liveSection);
    assertTrue(TYPE_SECTION.equals(nodeService.getType(liveSection)));

    NodeRef liveChildSection = fileFolderService.searchSimple(liveSection, "childSection");
    assertNotNull(liveChildSection);
    assertTrue(TYPE_SECTION.equals(nodeService.getType(liveChildSection)));

    NodeRef livePage = fileFolderService.searchSimple(liveChildSection, "myFile.txt");
    assertNotNull(livePage);
    assertNotNull(nodeService.getProperty(livePage, PROP_PARENT_SECTIONS));
    assertTrue(((List) nodeService.getProperty(livePage, PROP_PARENT_SECTIONS)).contains(liveChildSection));

    userTransaction.commit();
}

From source file:org.alfresco.module.vti.handler.alfresco.AbstractAlfrescoDwsServiceHandler.java

/**
 * @see org.alfresco.module.vti.handler.DwsServiceHandler#createDws(java.lang.String, java.lang.String, java.util.List, java.lang.String, java.util.List, java.lang.String,
 *      java.lang.String, org.alfresco.repo.SessionUser)
 *//*from   w  w w .  j av  a2 s. c om*/
public DwsBean createDws(String parentDwsUrl, String name, List<UserBean> users, String title,
        List<DocumentBean> documents, String host, String context, SessionUser user) {
    if (dwsExists(name)) {
        throw new DwsException(DwsError.SERVER_FAILURE);
    }

    if (false == stringExists(name)) {
        name = title;
    }
    if (false == stringExists(name)) {
        // Both title and name empty so generate GUID.
        name = GUID.generate();
        title = name;
    } else {
        int i = 1;
        while (dwsExists(name)) {
            name = name + "_" + i;
            i++;
        }
        title = name;
    }
    UserTransaction tx = transactionService.getUserTransaction(false);
    String createdDwsUrl = null;
    try {
        tx.begin();

        String createdDwsName = doCreateDws(name, title, user);
        createdDwsUrl = doGetDwsCreationUrl(parentDwsUrl, createdDwsName);

        tx.commit();
    } catch (Throwable e) {
        try {
            tx.rollback();
        } catch (Exception tex) {
            //NOOP
        }

        if (e instanceof AccessDeniedException) {
            throw new DwsException(DwsError.NO_ACCESS);
        }
        throw new DwsException(DwsError.SERVER_FAILURE);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Document workspace with name '" + title + "' was successfully created.");
    }

    return doGetResultBean(parentDwsUrl, createdDwsUrl, host, context);
}

From source file:org.alfresco.module.vti.handler.alfresco.AbstractAlfrescoDwsServiceHandler.java

/**
 * @see org.alfresco.module.vti.handler.DwsServiceHandler#deleteDws(java.lang.String, org.alfresco.repo.SessionUser)
 *//*from www.  ja v  a2s. c  om*/
public void deleteDws(String dwsUrl, SessionUser user) {
    FileInfo dwsFileInfo = pathHelper.resolvePathFileInfo(dwsUrl);

    if (dwsFileInfo == null || dwsFileInfo.isFolder() == false) {
        throw new VtiHandlerException(VtiError.NOT_FOUND);
    }

    UserTransaction tx = transactionService.getUserTransaction(false);
    try {
        tx.begin();

        doDeleteDws(dwsFileInfo, user);

        tx.commit();
    } catch (Throwable e) {
        try {
            tx.rollback();
        } catch (Exception tex) {
            //NOOP
        }

        if (e instanceof AccessDeniedException) {
            throw new DwsException(DwsError.NO_ACCESS);
        }

        throw new DwsException(DwsError.FAILED, e);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Document workspace with name '" + dwsFileInfo.getName() + "' was successfully deleted.");
    }
}

From source file:org.alfresco.module.vti.handler.alfresco.AbstractAlfrescoDwsServiceHandler.java

/**
 * @see org.alfresco.module.vti.handler.DwsServiceHandler#createFolder(java.lang.String)
 *//*from  www. ja  v  a 2  s. c  o  m*/
public void createFolder(String url) {

    for (String part : VtiPathHelper.removeSlashes(url).split("/")) {
        if (VtiUtils.hasIllegalCharacter(part)) {
            throw new DwsException(DwsError.FOLDER_NOT_FOUND);
        }
    }

    FileInfo folderFileInfo = pathHelper.resolvePathFileInfo(url);

    if (folderFileInfo != null) {
        throw new DwsException(DwsError.ALREADY_EXISTS);
    }

    Pair<String, String> parentChildPaths = VtiPathHelper.splitPathParentChild(url);

    String parentPath = parentChildPaths.getFirst();
    FileInfo parentFileInfo = pathHelper.resolvePathFileInfo(parentPath);
    if (parentFileInfo == null) {
        throw new DwsException(DwsError.FOLDER_NOT_FOUND);
    }

    String dwsName = parentChildPaths.getSecond();
    if (dwsName.length() == 0) {
        throw new DwsException(DwsError.FOLDER_NOT_FOUND);
    }

    UserTransaction tx = transactionService.getUserTransaction(false);
    try {
        tx.begin();

        folderFileInfo = fileFolderService.create(parentFileInfo.getNodeRef(), dwsName,
                ContentModel.TYPE_FOLDER);

        tx.commit();
    } catch (Throwable e) {
        try {
            tx.rollback();
        } catch (Exception tex) {
            //NOOP
        }

        if (e instanceof AccessDeniedException) {
            throw new DwsException(DwsError.NO_ACCESS);
        }

        throw VtiExceptionUtils.createRuntimeException(e);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Folder with url '" + url.substring(url.indexOf('/', 1)) + "' was created.");
    }
}

From source file:org.alfresco.module.vti.handler.alfresco.AbstractAlfrescoDwsServiceHandler.java

/**
 * @see org.alfresco.module.vti.handler.DwsServiceHandler#deleteFolder(java.lang.String)
 *//*  w  w  w .  ja  v a2  s  .  c om*/
public void deleteFolder(String url) {
    FileInfo folderFileInfo = pathHelper.resolvePathFileInfo(url);

    if (folderFileInfo == null) {
        throw new VtiHandlerException(VtiError.NOT_FOUND);
    }

    if (folderFileInfo.isFolder() == false) {
        throw new VtiHandlerException(VtiError.NOT_FOUND);
    }

    UserTransaction tx = transactionService.getUserTransaction(false);
    try {
        tx.begin();

        fileFolderService.delete(folderFileInfo.getNodeRef());

        tx.commit();
    } catch (Throwable e) {
        try {
            tx.rollback();
        } catch (Exception tex) {
            //NOOP
        }

        if (e instanceof AccessDeniedException) {
            throw new VtiHandlerException(VtiError.NO_PERMISSIONS);
        }
        throw VtiExceptionUtils.createRuntimeException(e);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Folder with url '" + url.substring(url.indexOf('/', 1)) + "' was deleted.");
    }
}

From source file:org.alfresco.module.vti.handler.alfresco.AbstractAlfrescoDwsServiceHandler.java

/**
 * @see org.alfresco.module.vti.handler.DwsServiceHandler#renameDws(java.lang.String, java.lang.String)
 *///from w w w. ja v a 2 s  .  c  o m
public void renameDws(String oldDwsUrl, String title) {
    FileInfo dwsFileInfo = pathHelper.resolvePathFileInfo(oldDwsUrl);

    if (dwsFileInfo == null) {
        throw new VtiHandlerException(VtiError.NOT_FOUND);
    }

    UserTransaction tx = transactionService.getUserTransaction(false);
    try {
        tx.begin();

        nodeService.setProperty(dwsFileInfo.getNodeRef(), ContentModel.PROP_TITLE, title);

        tx.commit();
    } catch (Throwable e) {
        try {
            tx.rollback();
        } catch (Exception tex) {
            //NOOP
        }

        if (e instanceof AccessDeniedException) {
            throw new VtiHandlerException(VtiError.NO_PERMISSIONS);
        }

        throw VtiExceptionUtils.createRuntimeException(e);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Rename DWS title from '" + dwsFileInfo.getName() + "' to '" + title + "'.");
    }
}