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:it.doqui.index.ecmengine.business.publishing.EcmEnginePublisherBean.java

/**
 * Esegue il rollback della transazione specificata in input ignorando
 * le eventuali eccezioni./*from   www . ja v a2s  . com*/
 *
 * @param transaction La transazione di cui eseguire il rollback.
 */
protected static void rollbackQuietely(UserTransaction transaction) {
    try {
        transaction.rollback();
    } catch (Throwable t) {
        logger.warn("[EcmEnginePublisherBean::rollbackQuietely] Ignored exception during rollback: "
                + t.getMessage());
    }
}

From source file:com.bluexml.side.alfresco.repo.content.cleanup.TrashcanCleaner.java

public int execute() {
    if (logger.isDebugEnabled())
        logger.debug("execute TrashcanCleaner");
    int nbDeleted = 0;
    if (this.protectedDays > 0) {
        Date fromDate = new Date(0);
        Date toDate = new Date(
                new Date().getTime() - (1000L * 60L * 60L * 24L * Long.valueOf(this.protectedDays)));

        if (logger.isDebugEnabled())
            logger.debug("Date =" + toDate);

        if (toDate == null) {
            throw new RuntimeException("Error while building the query. - Date is null");
        }// w  ww .  ja va  2s . c  om

        String strFromDate = ISO8601DateFormat.format(fromDate);
        String strToDate = ISO8601DateFormat.format(toDate);
        StringBuilder buf = new StringBuilder(128);
        buf.append("@").append(Repository.escapeQName(ContentModel.PROP_ARCHIVED_DATE)).append(":").append("[")
                .append(strFromDate).append(" TO ").append(strToDate).append("] ");

        String query = buf.toString();

        SearchParameters sp = new SearchParameters();
        sp.setLanguage(SearchService.LANGUAGE_LUCENE);
        sp.setQuery(query);

        NodeRef archiveRootRef = this.nodeArchiveService.getStoreArchiveNode(Repository.getStoreRef());
        sp.addStore(archiveRootRef.getStoreRef());
        if (logger.isDebugEnabled()) {
            logger.debug("Trashcan cleaner query : ");
            logger.debug(query);
        }

        UserTransaction tx = null;
        ResultSet results = null;
        try {
            tx = this.transactionService.getNonPropagatingUserTransaction(false);
            tx.begin();

            results = this.searchService.query(sp);
            List<NodeRef> deletedItemsToPurge = results.getNodeRefs();
            if (logger.isInfoEnabled()) {
                logger.info("Trashcan Cleaner is about to purge the following items :");
                for (NodeRef item : deletedItemsToPurge) {
                    String itemName = (String) this.nodeService.getProperty(item, ContentModel.PROP_NAME);
                    logger.info(" - " + itemName);
                }
            }
            this.nodeArchiveService.purgeArchivedNodes(deletedItemsToPurge);

            tx.commit();
            nbDeleted = deletedItemsToPurge.size();
        } catch (Throwable err) {
            if (logger.isWarnEnabled())
                logger.warn("Error while cleaning the trashcan : " + err.getMessage());
            try {
                if (tx != null) {
                    tx.rollback();
                }
            } catch (Exception tex) {
                if (logger.isWarnEnabled())
                    logger.warn("Error while during the rollback : " + tex.getMessage());
            }
        } finally {
            if (results != null) {
                results.close();
            }
        }
    }
    return nbDeleted;
}

From source file:org.intalio.tempo.web.AlfrescoFacesPortlet.java

private void setAuthenticatedUser(PortletRequest req, String userName) {

    WebApplicationContext ctx = (WebApplicationContext) getPortletContext()
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    TransactionService transactionService = serviceRegistry.getTransactionService();
    NodeService nodeService = serviceRegistry.getNodeService();

    AuthenticationComponent authComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent");
    AuthenticationService authService = (AuthenticationService) ctx.getBean("authenticationService");
    PersonService personService = (PersonService) ctx.getBean("personService");

    // Get a list of the available locales
    ConfigService configServiceService = (ConfigService) ctx.getBean("webClientConfigService");
    LanguagesConfigElement configElement = (LanguagesConfigElement) configServiceService.getConfig("Languages")
            .getConfigElement(LanguagesConfigElement.CONFIG_ELEMENT_ID);

    m_languages = configElement.getLanguages();

    // Set up the user information
    UserTransaction tx = transactionService.getUserTransaction();
    NodeRef homeSpaceRef = null;/*from w w w.j av  a  2 s  .  co m*/
    User user;
    try {
        tx.begin();
        // Set the authentication
        authComponent.setCurrentUser(userName);
        user = new User(userName, authService.getCurrentTicket(), personService.getPerson(userName));
        homeSpaceRef = (NodeRef) nodeService.getProperty(personService.getPerson(userName),
                ContentModel.PROP_HOMEFOLDER);
        if (homeSpaceRef == null) {
            logger.warn("Home Folder is null for user '" + userName + "', using company_home.");
            homeSpaceRef = (NodeRef) nodeService.getRootNode(Repository.getStoreRef());
        }
        user.setHomeSpaceId(homeSpaceRef.getId());
        tx.commit();
    } catch (Throwable ex) {
        logger.error(ex);

        try {
            tx.rollback();
        } catch (Exception ex2) {
            logger.error("Failed to rollback transaction", ex2);
        }

        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        } else {
            throw new RuntimeException("Failed to set authenticated user", ex);
        }
    }

    // Store the user
    req.getPortletSession().setAttribute(AuthenticationHelper.AUTHENTICATION_USER, user);
    req.getPortletSession().setAttribute(LoginBean.LOGIN_EXTERNAL_AUTH, Boolean.TRUE);

    logger.debug("...authenticated user is: " + user.getUserName() + user.getTicket());
}

From source file:edu.harvard.i2b2.crc.ejb.QueryExecutorMDB.java

/**
 * Take the XML based message and delegate to the system coordinator to
 * handle the actual processing/* w w w  .  ja va  2s.c o m*/
 * 
 * @param msg
 *            th JMS TextMessage object containing XML data
 */
public void onMessage(Message msg) {
    MapMessage message = null;
    QueueConnection conn = null;
    QueueSession session = null;
    QueueSender sender = null;
    QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance();
    Queue replyToQueue = null;
    UserTransaction transaction = sessionContext.getUserTransaction();
    // default timeout three minutes
    int transactionTimeout = 0;

    try {

        transactionTimeout = this.readTimeoutPropertyValue(SMALL_QUEUE);
        if (callingMDBName.equalsIgnoreCase(QueryExecutorMDB.MEDIUM_QUEUE)) {
            // four hours
            // transactionTimeout = 14400;
            transactionTimeout = this.readTimeoutPropertyValue(MEDIUM_QUEUE);
        } else if (callingMDBName.equalsIgnoreCase(QueryExecutorMDB.LARGE_QUEUE)) {
            // twelve hours
            // transactionTimeout = 43200;
            transactionTimeout = this.readTimeoutPropertyValue(LARGE_QUEUE);
        }

        transaction.setTransactionTimeout(transactionTimeout);

        transaction.begin();
        message = (MapMessage) msg;
        String sessionId = msg.getJMSCorrelationID();
        replyToQueue = (Queue) msg.getJMSReplyTo();
        log.debug("Extracting the message [" + msg.getJMSMessageID() + " ] on " + callingMDBName);
        transaction.commit();
        ExecRunnable er = new ExecRunnable(transaction, transactionTimeout, callingMDBName, message, sessionId);
        er.execute();

    } catch (Exception ex) {
        ex.printStackTrace();
        try {
            if (transaction.getStatus() != 4) {

                transaction.rollback();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.error("Error extracting message", ex);
    } finally {

        QueryManagerBeanUtil qmBeanUtil = new QueryManagerBeanUtil();
        qmBeanUtil.closeAll(sender, null, conn, session);
    }
}

From source file:it.doqui.index.ecmengine.business.personalization.multirepository.bootstrap.MultiTAdminServiceImpl.java

public void deployTenants(final TenantDeployer deployer, Log logger) {
    if (deployer == null) {
        throw new AlfrescoRuntimeException("Deployer must be provided");
    }/*from w ww.  ja  v  a2 s .co m*/
    if (logger == null) {
        throw new AlfrescoRuntimeException("Logger must be provided");
    }

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

        List<org.alfresco.repo.tenant.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 {
                authenticationComponent.clearCurrentSecurityContext();
            } catch (Exception ex) {
            }
            throw new AlfrescoRuntimeException("Failed to get tenants", e);
        }

        String currentUser = AuthenticationUtil.getCurrentUserName();

        if (tenants != null) {
            try {
                for (org.alfresco.repo.tenant.Tenant tenant : tenants) {
                    if (tenant.isEnabled()) {
                        try {
                            // switch to admin in order to deploy within context of tenant domain
                            // assumes each tenant has default "admin" user
                            AuthenticationUtil.runAs(new RunAsWork<Object>() {
                                public Object doWork() {
                                    // init the service within tenant context
                                    deployer.init();
                                    return null;
                                }
                            }, getTenantAdminUser(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
                        }
                    }
                }
            } finally {
                if (currentUser != null) {
                    AuthenticationUtil.setCurrentUser(currentUser);
                }
            }
        }
    }
}

From source file:it.doqui.index.ecmengine.business.personalization.multirepository.bootstrap.MultiTAdminServiceImpl.java

public void undeployTenants(final TenantDeployer deployer, Log logger) {
    if (deployer == null) {
        throw new AlfrescoRuntimeException("Deployer must be provided");
    }//from w  ww. j  av a  2 s  . c  o m
    if (logger == null) {
        throw new AlfrescoRuntimeException("Logger must be provided");
    }

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

        List<org.alfresco.repo.tenant.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 {
                authenticationComponent.clearCurrentSecurityContext();
            } catch (Exception ex) {
            }
            throw new AlfrescoRuntimeException("Failed to get tenants", e);
        }

        String currentUser = AuthenticationUtil.getCurrentUserName();

        if (tenants != null) {
            try {
                for (org.alfresco.repo.tenant.Tenant tenant : tenants) {
                    if (tenant.isEnabled()) {
                        try {
                            // switch to admin in order to deploy within context of tenant domain
                            // assumes each tenant has default "admin" user
                            AuthenticationUtil.runAs(new RunAsWork<Object>() {
                                public Object doWork() {
                                    // destroy the service within tenant context
                                    deployer.destroy();
                                    return null;
                                }
                            }, getTenantAdminUser(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 {
                if (currentUser != null) {
                    AuthenticationUtil.setCurrentUser(currentUser);
                }
            }
        }
    }
}

From source file:fr.openwide.talendalfresco.rest.server.ContentImportCommandServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from ww  w . ja  v a2s.  com
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String uri = req.getRequestURI();

    if (logger.isDebugEnabled())
        logger.debug(
                "Processing URL: " + uri + (req.getQueryString() != null ? ("?" + req.getQueryString()) : ""));

    AuthenticationStatus status = servletAuthenticate(req, res);
    if (status == AuthenticationStatus.Failure) {
        return;
    }

    setNoCacheHeaders(res);

    uri = uri.substring(req.getContextPath().length());
    StringTokenizer t = new StringTokenizer(uri, "/");
    int tokenCount = t.countTokens();
    if (tokenCount < 3) {
        throw new IllegalArgumentException("Command Servlet URL did not contain all required args: " + uri);
    }

    t.nextToken(); // skip servlet name

    // get the command processor to execute the command e.g. "workflow"
    String procName = t.nextToken();

    // get the command to perform
    String command = t.nextToken();

    // get any remaining uri elements to pass to the processor
    String[] urlElements = new String[tokenCount - 3];
    for (int i = 0; i < tokenCount - 3; i++) {
        urlElements[i] = t.nextToken();
    }

    // retrieve the URL arguments to pass to the processor
    Map<String, String> args = new HashMap<String, String>(8, 1.0f);
    Enumeration names = req.getParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        args.put(name, req.getParameter(name));
    }

    try {
        // get configured command processor by name from Config Service
        CommandProcessor processor = createCommandProcessor(procName);

        // validate that the processor has everything it needs to run the command
        if (processor.validateArguments(getServletContext(), command, args, urlElements) == false) {
            redirectToLoginPage(req, res, getServletContext());
            return;
        }

        ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
        UserTransaction txn = null;
        try {
            if (!(processor instanceof RestCommandProcessor)
                    || ((RestCommandProcessor) processor).isTransactional()) {
                // [talendalfresco] disable tx for ImportCommand
                txn = serviceRegistry.getTransactionService().getUserTransaction();
                txn.begin();
            }

            // inform the processor to execute the specified command
            if (processor instanceof ExtCommandProcessor) {
                ((ExtCommandProcessor) processor).process(serviceRegistry, req, res, command);
            } else {
                processor.process(serviceRegistry, req, command);
            }

            if (!(processor instanceof RestCommandProcessor)
                    || ((RestCommandProcessor) processor).isTransactional()) {
                // [talendalfresco] disable tx for ImportCommand
                // commit the transaction
                txn.commit();
            }
        } catch (Throwable txnErr) {
            if (!(processor instanceof RestCommandProcessor)
                    || ((RestCommandProcessor) processor).isTransactional()) {
                // [talendalfresco] disable tx for ImportCommand
                try {
                    if (txn != null) {
                        txn.rollback();
                    }
                } catch (Exception tex) {
                }
            }
            throw txnErr;
        }

        String returnPage = req.getParameter(ARG_RETURNPAGE);
        if (returnPage != null && returnPage.length() != 0) {
            if (logger.isDebugEnabled())
                logger.debug("Redirecting to specified return page: " + returnPage);

            res.sendRedirect(returnPage);
        } else {
            if (logger.isDebugEnabled())
                logger.debug("No return page specified, displaying status output.");

            if (res.getContentType() == null) {
                res.setContentType("text/html");
            }

            // request that the processor output a useful status message
            PrintWriter out = res.getWriter();
            processor.outputStatus(out);
            out.close();
        }
    } catch (Throwable err) {
        throw new AlfrescoRuntimeException("Error during command servlet processing: " + err.getMessage(), err);
    }
}

From source file:com.atolcd.repo.web.scripts.archive.ArchivedNodesDelete.java

/**
 * This method gets all deleted nodes for current user from the archive
 * which were originally contained within the specified StoreRef.
 *///from  w  ww.j  ava2s  . c om
private List<NodeRef> filterDeletedNodes(StoreRef storeRef, String username) {
    List<NodeRef> deletedNodes = null;

    if (username != null && username.length() > 0) {

        UserTransaction tx = null;
        ResultSet results = null;

        try {

            tx = serviceRegistry.getTransactionService().getNonPropagatingUserTransaction(false);
            tx.begin();

            if (storeRef != null) {
                String query = String.format(SEARCH_USERPREFIX, username)
                        + String.format(SEARCH_ALL, ContentModel.ASPECT_ARCHIVED);
                SearchParameters sp = new SearchParameters();
                sp.setLanguage(SearchService.LANGUAGE_LUCENE);
                sp.setQuery(query);
                sp.addStore(storeRef); // the Archived Node store

                results = serviceRegistry.getSearchService().query(sp);
                deletedNodes = new ArrayList<NodeRef>(results.length());
            }

            if (results != null && results.length() != 0) {
                NodeService nodeService = serviceRegistry.getNodeService();

                for (ResultSetRow row : results) {
                    NodeRef nodeRef = row.getNodeRef();

                    if (nodeService.exists(nodeRef)) {
                        deletedNodes.add(nodeRef);
                    }
                }
            }

            tx.commit();
        } catch (Throwable err) {
            if (logger.isWarnEnabled())
                logger.warn("Error while browsing the archive store: " + err.getMessage());
            try {
                if (tx != null) {
                    tx.rollback();
                }
            } catch (Exception tex) {
                if (logger.isWarnEnabled())
                    logger.warn("Error while during the rollback: " + tex.getMessage());
            }
        } finally {
            if (results != null) {
                results.close();
            }
        }
    }

    return deletedNodes;
}

From source file:com.pararede.alfresco.security.AlfrescoContainerSecurityFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    HttpSession httpSession = httpRequest.getSession();

    String userName = httpRequest.getUserPrincipal().getName();
    User userAuth = AuthenticationHelper.getUser(httpRequest, httpResponse);
    if ((userAuth == null) || !userName.equals(userAuth.getUserName())) {
        try {//from   w  w  w  . j  a  v a 2 s.c o m
            TransactionService transactionService = this.registry.getTransactionService();
            UserTransaction tx = transactionService.getUserTransaction();
            try {
                tx.begin();

                // remove the session invalidated flag (used to remove last username cookie by
                // AuthenticationFilter)
                httpSession.removeAttribute(AuthenticationHelper.SESSION_INVALIDATED);

                if (logger.isDebugEnabled()) {
                    logger.debug("Authenticating user " + userName);
                }
                AuthenticationService authenticationService = getAuthenticationService();
                authenticationService.authenticate(userName, null);

                PersonService personService = this.registry.getPersonService();
                userAuth = new User(userName, authenticationService.getCurrentTicket(),
                        personService.getPerson(userName));

                NodeService nodeService = this.registry.getNodeService();
                NodeRef homeSpaceRef = (NodeRef) nodeService.getProperty(personService.getPerson(userName),
                        ContentModel.PROP_HOMEFOLDER);
                if (!nodeService.exists(homeSpaceRef)) {
                    throw new InvalidNodeRefException(homeSpaceRef);
                }
                userAuth.setHomeSpaceId(homeSpaceRef.getId());

                httpSession.setAttribute(AuthenticationHelper.AUTHENTICATION_USER, userAuth);
                httpSession.setAttribute(LoginBean.LOGIN_EXTERNAL_AUTH, true);

                tx.commit();
            } catch (Throwable e) {
                tx.rollback();
                throw new ServletException(e);
            }
        } catch (SystemException e) {
            throw new ServletException(e);
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("User " + userName + " already authenticated");
        }

        AuthenticationStatus status = AuthenticationHelper.authenticate(httpSession.getServletContext(),
                httpRequest, httpResponse, false);
        if (status != AuthenticationStatus.Success) {
            throw new ServletException("User not correctly autheticated");
        }
    }

    chain.doFilter(request, response);
}

From source file:com.sirma.itt.cmf.integration.workflow.alfresco4.CMFWorkflowDeployer.java

/**
 * Deploy the Workflow Definitions.// www .  j  av  a2 s.c  o m
 */
public void init() {
    PropertyCheck.mandatory(this, "transactionService", transactionService);
    PropertyCheck.mandatory(this, "authenticationContext", authenticationContext);
    PropertyCheck.mandatory(this, "workflowService", workflowService);

    String currentUser = authenticationContext.getCurrentUserName();
    if (currentUser == null) {
        authenticationContext.setSystemUserAsCurrentUser();
    }
    if (!transactionService.getAllowWrite()) {
        logger.warn("Repository is in read-only mode; not deploying workflows.");
        return;
    }

    UserTransaction userTransaction = transactionService.getUserTransaction();
    try {
        userTransaction.begin();

        // bootstrap the workflow models and static labels (from classpath)
        if (models != null && resourceBundles != null
                && ((models.size() > 0) || (resourceBundles.size() > 0))) {
            DictionaryBootstrap dictionaryBootstrap = new DictionaryBootstrap();
            dictionaryBootstrap.setDictionaryDAO(dictionaryDAO);
            dictionaryBootstrap.setTenantService(tenantService);
            dictionaryBootstrap.setModels(models);
            dictionaryBootstrap.setLabels(resourceBundles);
            dictionaryBootstrap.bootstrap(); // also registers with
            // dictionary
        }

        // bootstrap the workflow definitions (from classpath)
        if (workflowDefinitions != null) {
            for (Properties workflowDefinition : workflowDefinitions) {
                deployFromProperties(workflowDefinition);
            }
        }

        userTransaction.commit();
    } catch (Exception e) {
        // rollback the transaction
        try {
            if (userTransaction != null) {
                userTransaction.rollback();
            }
        } catch (Exception ex) {
            // NOOP
        }
    } finally {
        if (currentUser == null) {
            authenticationContext.clearCurrentSecurityContext();
        }
    }
}