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:se.alingsas.alfresco.repo.utils.byggreda.ByggRedaUtil.java

/**
 * Import a document//  w ww .  j av  a  2s  .c  om
 * 
 * @param site
 * @param sourcePath
 * @param document
 * @return
 */
private ByggRedaDocument importDocument(SiteInfo site, String sourcePath, ByggRedaDocument document) {
    final String currentDestinationPath = destinationPath + "/" + document.getPath();
    UserTransaction trx = getTransactionService().getNonPropagatingUserTransaction();

    try {
        trx.begin();
        // Check if file exists already
        FileInfo repoFileFolder = getRepoFileFolder(site,
                currentDestinationPath + "/" + document.getFileName());
        if (repoFileFolder != null) {
            if (this.updateExisting) {
                try {
                    String fullFilenamePath = checkFileExistsIgnoreExtensionCase(
                            sourcePath + "/" + document.getFileName());
                    if (fullFilenamePath == null) {
                        throw new java.io.FileNotFoundException();
                    }
                    File f = new File(fullFilenamePath);
                    if (!f.exists()) {
                        throw new java.io.FileNotFoundException();
                    }
                    if (!f.exists()) {
                        throw new java.io.FileNotFoundException();
                    }
                    LOG.debug("File " + document.getFileName()
                            + " already exists, attempting to creating a new version at "
                            + currentDestinationPath);
                    final NodeRef workingCopy = checkOutCheckInService.checkout(repoFileFolder.getNodeRef());

                    addProperties(workingCopy, document, true);

                    createFile(workingCopy, site, sourcePath, document);

                    final Map<String, Serializable> properties = new HashMap<String, Serializable>();
                    properties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR);
                    NodeRef checkin = checkOutCheckInService.checkin(workingCopy, properties);
                    document.setNodeRef(checkin);
                    if (checkin != null && nodeService.exists(checkin)) {
                        document.setReadSuccessfully(true);
                        document.setStatusMsg("Filen " + sourcePath + "/" + document.getFileName()
                                + " uppdaterades till ny version");
                        trx.commit();
                    } else {
                        document.setReadSuccessfully(false);
                        document.setStatusMsg("Uppdatering av fil " + currentDestinationPath + "/"
                                + document.getFileName() + " misslyckades.");
                        LOG.error(document.getStatusMsg());
                        throw new Exception(document.getStatusMsg());
                    }
                } catch (java.io.FileNotFoundException e) {
                    document.setReadSuccessfully(false);
                    document.setStatusMsg("Inlsning av fil misslyckades, filen " + sourcePath + "/"
                            + document.getFileName() + " kunde inte hittas.");
                    LOG.error(document.getStatusMsg());
                    throw new Exception(document.getStatusMsg(), e);
                } catch (FileExistsException e) {
                    document.setReadSuccessfully(false);
                    document.setStatusMsg("Inlsning av fil misslyckades, mlfilen " + currentDestinationPath
                            + " finns redan.");
                    LOG.error(document.getStatusMsg());
                    throw new Exception(document.getStatusMsg(), e);
                } catch (Exception e) {
                    document.setReadSuccessfully(false);
                    document.setStatusMsg(e.getMessage());
                    LOG.error("Error importing document " + document.getRecordNumber(), e);
                    throw new Exception(document.getStatusMsg(), e);
                }
            } else {
                document.setReadSuccessfully(false);
                document.setStatusMsg("Filen existerar redan, hoppar ver.");
                LOG.debug("File already exists");
                trx.commit();
            }
        } else {
            try {
                String fullFilenamePath = checkFileExistsIgnoreExtensionCase(
                        sourcePath + "/" + document.getFileName());
                if (fullFilenamePath == null) {
                    throw new java.io.FileNotFoundException();
                }
                File f = new File(fullFilenamePath);
                if (!f.exists()) {
                    throw new java.io.FileNotFoundException();
                }
                NodeRef folderNodeRef = createFolder(destinationPath, document.getPath(),
                        document.getOriginalPath(), site);
                final FileInfo fileInfo = fileFolderService.create(folderNodeRef, document.getFileName(),
                        AkDmModel.TYPE_AKDM_BYGGREDA_DOC);
                document.setNodeRef(fileInfo.getNodeRef());
                addProperties(document.getNodeRef(), document, false);
                createFile(document.getNodeRef(), site, sourcePath, document);
                createVersionHistory(document.getNodeRef());
                document.setReadSuccessfully(true);
                LOG.debug("Imported document " + document.getRecordDisplay());
                trx.commit();
            } catch (java.io.FileNotFoundException e) {
                document.setReadSuccessfully(false);
                document.setStatusMsg("Inlsning av fil misslyckades, filen " + sourcePath + "/"
                        + document.getFileName() + " kunde inte hittas.");
                LOG.error(document.getStatusMsg());
                throw new Exception(document.getStatusMsg(), e);
            } catch (FileExistsException e) {
                document.setReadSuccessfully(false);
                document.setStatusMsg("Inlsning av fil misslyckades, mlfilen " + currentDestinationPath
                        + " finns redan.");
                LOG.error(document.getStatusMsg());
                throw new Exception(document.getStatusMsg(), e);
            } catch (Exception e) {
                document.setReadSuccessfully(false);
                document.setStatusMsg("Fel vid inlsning av fil, systemmeddelande: " + e.getMessage());
                LOG.error("Error importing document " + document.getRecordNumber(), e);
                throw new Exception(document.getStatusMsg(), e);
            }
        }
    } catch (Exception e) {
        try {
            if (trx.getStatus() == Status.STATUS_ACTIVE) {
                trx.rollback();
            } else {
                LOG.error("The transaction was not active", e);
            }
            return document;
        } catch (Exception e2) {
            LOG.error("Exception: ", e);
            LOG.error("Exception while rolling back transaction", e2);
            throw new RuntimeException(e2);
        }

    }
    return document;

}

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

/**
 * End an active transaction//ww w .j  ava 2s  .c om
 * 
 * @param sess SrvSession
 * @param tx Object
 */
public void endTransaction(SrvSession sess, Object tx) {

    // Check that the transaction object is valid

    if (tx == null)
        return;

    // Get the filesystem transaction

    FilesysTransaction filesysTx = (FilesysTransaction) tx;

    // Check if there is an active transaction

    if (filesysTx != null && filesysTx.hasTransaction()) {
        // Get the active transaction

        UserTransaction ftx = filesysTx.getTransaction();

        try {
            // Commit or rollback the transaction

            if (ftx.getStatus() == Status.STATUS_MARKED_ROLLBACK || ftx.getStatus() == Status.STATUS_ROLLEDBACK
                    || ftx.getStatus() == Status.STATUS_ROLLING_BACK) {
                // Transaction is marked for rollback

                ftx.rollback();

                // DEBUG

                if (logger.isDebugEnabled())
                    logger.debug("End transaction (rollback)");
            } else {
                // Commit the transaction

                ftx.commit();

                // DEBUG

                if (logger.isDebugEnabled())
                    logger.debug("End transaction (commit)");
            }
        } catch (Exception ex) {
            if (logger.isDebugEnabled())
                logger.debug("Failed to end transaction, " + ex.getMessage());
            //              throw new AlfrescoRuntimeException("Failed to end transaction", ex);
        } finally {
            // Clear the current transaction

            sess.clearTransaction();
        }
    }
}

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

/**
 * Create and start a transaction, if not already active
 * //ww w. j  a  va 2s. co m
 * @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
 * /*w w  w  .j  a v a2s. c  om*/
 * @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  ww.  j a  va2  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.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  ava 2s.  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)
 *///  ww w. java2s .  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 w  w  .  j a  v  a  2  s.co  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)
 *//*from w ww .  j  a  va 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)
 *//* w  w  w  .  j  a va 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 + "'.");
    }
}