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:com.someco.servlets.AuthenticationFilter.java

/**
 * Set the authenticated user./*ww  w.j a  v a 2s .co  m*/
 * 
 * It does not check that the user exists at the moment.
 * 
 * @param req
 * @param httpSess
 * @param userName
 */
private void setAuthenticatedUser(HttpServletRequest req, HttpSession httpSess, String userName) {
    // Set the authentication
    authComponent.setCurrentUser(userName);

    // Set up the user information
    UserTransaction tx = transactionService.getUserTransaction();
    NodeRef homeSpaceRef = null;
    User user;
    try {
        tx.begin();
        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
    httpSess.setAttribute(AuthenticationHelper.AUTHENTICATION_USER, user);
    httpSess.setAttribute(LoginBean.LOGIN_EXTERNAL_AUTH, Boolean.TRUE);

    // Set the current locale from the Accept-Lanaguage header if available
    Locale userLocale = parseAcceptLanguageHeader(req, m_languages);

    if (userLocale != null) {
        httpSess.setAttribute(LOCALE, userLocale);
        httpSess.removeAttribute(MESSAGE_BUNDLE);
    }

    // Set the locale using the session
    I18NUtil.setLocale(Application.getLanguage(httpSess));

}

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  .j a va2  s .co m

        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:com.zaizi.alfresco.crowd.sso.filter.CrowdSSOAuthenticationFilter.java

/**
 * <p>Sets the username passed as parameter as current user, trying to create the user and home if possible, using person service</p>
 * @param request The {@code HttpServletRequest} request
 * @param httpSession the {@code HttpSession} session
 * @param userName The username//from ww w . ja v  a 2  s .  co  m
 */
private void setAuthenticatedUser(HttpServletRequest request, HttpSession httpSession, String userName) {
    this.authenticationComponent.setCurrentUser(userName);

    UserTransaction tx = this.transactionService.getUserTransaction();
    NodeRef homeSpaceRef = null;
    User user;
    try {
        tx.begin();
        user = new User(userName, this.authenticationService.getCurrentTicket(),
                this.personService.getPerson(userName));
        homeSpaceRef = (NodeRef) this.nodeService.getProperty(this.personService.getPerson(userName),
                ContentModel.PROP_HOMEFOLDER);
        if (homeSpaceRef == null) {
            this.logger.warn("Home Folder is null for user '" + userName + "', using company_home.");
            homeSpaceRef = this.nodeService.getRootNode(Repository.getStoreRef());
        }
        user.setHomeSpaceId(homeSpaceRef.getId());
        tx.commit();
    } catch (Throwable ex) {
        this.logger.error(ex);
        try {
            tx.rollback();
        } catch (Exception ex2) {
            this.logger.error("Failed to rollback transaction", ex2);
        }

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

    /* Setting the user as current user in the session */
    httpSession.setAttribute(AuthenticationHelper.AUTHENTICATION_USER, user);
    /* Sets Login external auth */
    httpSession.setAttribute(ALF_LOGIN_EXTERNAL_AUTH, true);
}

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/*  ww w. j  a  va2 s  . com*/
 * 
 * @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:fr.openwide.talendalfresco.rest.server.ContentImportCommandServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//* ww  w.  j  av a 2  s .  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: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;//w  ww  . ja v a 2 s.c  o  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: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");
    }//  w  ww  .  ja  v  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() {
                                    // 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 w  w. j a v  a 2s  .  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() {
                                    // 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: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 w w.ja v  a2  s.  com
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.atolcd.repo.web.scripts.archive.ArchivedNodesGet.java

/**
 * This method gets all deleted nodes for current user from the archive
 * which were originally contained within the specified StoreRef.
 *//*w  ww  .jav  a 2s.  c om*/
private List<ArchivedNodeState> filterDeletedNodes(StoreRef storeRef, String username) {
    List<ArchivedNodeState> 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<ArchivedNodeState>(results.length());
            }

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

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

                    if (nodeService.exists(nodeRef)) {
                        ArchivedNodeState state = ArchivedNodeState.create(nodeRef, serviceRegistry);
                        deletedNodes.add(state);
                    }
                }
            }

            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;
}