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.filesys.auth.ftp.FTPAuthenticatorBase.java

/**
 * Check if the user is an administrator user name
 * //from www .  ja  va  2 s  .com
 * @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 w w w .  ja  va 2 s.  c om
 * 
 * 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();//  w  w  w.  j  a v a  2  s.  c  o  m

    // 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);
    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  ww. j  a  v a2 s  .c o m*/
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  w  w  w  .  jav a  2  s.  c  o  m
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  w  ww  .  j av  a2 s .  c  om
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)
 */// ww w  . ja  v  a  2  s  .  c o  m
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 .j  a va  2 s  .  co 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 + "'.");
    }
}

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

/**
 * @see org.alfresco.module.vti.handler.DwsServiceHandler#removeDwsUser(java.lang.String, java.lang.String)
 *///from w w w.  ja  v a  2 s. c  om
public void removeDwsUser(String dwsUrl, String id) {
    FileInfo dwsInfo = pathHelper.resolvePathFileInfo(dwsUrl);

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

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

        doRemoveDwsUser(dwsInfo, id);

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

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

        throw new VtiHandlerException(VtiError.NO_PERMISSIONS);
    }

    if (logger.isDebugEnabled()) {
        logger.debug(
                "User with name '" + id + "' was successfully removed from site: " + dwsInfo.getName() + ".");
    }
}

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

/**
 * @see org.alfresco.module.vti.handler.MethodHandler#checkInDocument(java.lang.String, java.lang.String, java.lang.String, boolean, java.util.Date, boolean)
 */// ww w . j a v  a  2 s. co  m
public DocMetaInfo checkInDocument(String serviceName, String documentName, String comment,
        boolean keepCheckedOut, Date timeCheckedout, boolean validateWelcomeNames) {
    // timeCheckedout ignored
    if (logger.isDebugEnabled()) {
        logger.debug("Checkin document: " + documentName + ". Site name: " + serviceName);
    }

    for (String urlPart : documentName.split("/")) {
        if (VtiUtils.hasIllegalCharacter(urlPart)) {
            throw new VtiHandlerException(VtiHandlerException.HAS_ILLEGAL_CHARACTERS);
        }
    }

    FileInfo fileFileInfo = getPathHelper().resolvePathFileInfo(serviceName + "/" + documentName);
    AlfrescoMethodHandler.assertValidFileInfo(fileFileInfo);
    AlfrescoMethodHandler.assertFile(fileFileInfo);
    FileInfo documentFileInfo = fileFileInfo;

    DocumentStatus documentStatus = getDocumentHelper().getDocumentStatus(documentFileInfo.getNodeRef());

    // if document isn't checked out then throw exception
    if (VtiDocumentHelper.isCheckedout(documentStatus) == false) {
        if (logger.isDebugEnabled()) {
            logger.debug("Document is not checked out.");
        }
        throw new VtiHandlerException(VtiHandlerException.DOC_NOT_CHECKED_OUT);
    }

    // if document is checked out, but user isn't owner, then throw exception
    if (VtiDocumentHelper.isCheckoutOwner(documentStatus) == false) {
        if (logger.isDebugEnabled()) {
            logger.debug("Unable to perform check in. Not an owner!!!");
        }
        throw new VtiHandlerException(VtiHandlerException.DOC_CHECKED_OUT);
    }

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

        if (VtiDocumentHelper.isLongCheckedout(documentStatus)) {
            // long-term checkout
            Map<String, Serializable> props = new HashMap<String, Serializable>(1, 1.0f);
            props.put(Version.PROP_DESCRIPTION, comment);
            props.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR);

            NodeRef resultNodeRef = getCheckOutCheckInService().checkin(
                    getCheckOutCheckInService().getWorkingCopy(documentFileInfo.getNodeRef()), props, null,
                    keepCheckedOut);

            documentFileInfo = getFileFolderService().getFileInfo(resultNodeRef);
        } else {
            // short-term checkout
            getLockService().unlock(documentFileInfo.getNodeRef());
            documentFileInfo = getFileFolderService().getFileInfo(documentFileInfo.getNodeRef());
        }

        tx.commit();
        if (logger.isDebugEnabled()) {
            logger.debug("Document successfully checked in.");
        }
    } catch (Throwable e) {
        try {
            tx.rollback();
        } catch (Exception tex) {
        }
        throw VtiExceptionUtils.createRuntimeException(e);
    }

    DocMetaInfo docMetaInfo = new DocMetaInfo(false);
    docMetaInfo.setPath(documentName);
    setDocMetaInfo(documentFileInfo, docMetaInfo);

    return docMetaInfo;
}