Example usage for javax.transaction UserTransaction begin

List of usage examples for javax.transaction UserTransaction begin

Introduction

In this page you can find the example usage for javax.transaction UserTransaction begin.

Prototype

void begin() throws NotSupportedException, SystemException;

Source Link

Document

Create a new transaction and associate it with the current thread.

Usage

From source file: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  a  v a2  s  .co  m
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  w w . ja va 2 s  .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;
}

From source file:org.alfresco.util.transaction.SpringAwareUserTransactionTest.java

public void testMismatchedBeginCommit() throws Exception {
    UserTransaction txn1 = getTxn();
    UserTransaction txn2 = getTxn();/*from  www. j a v  a2s.com*/

    testNoTxnStatus();

    txn1.begin();
    txn2.begin();

    txn2.commit();
    txn1.commit();

    checkNoStatusOnThread();

    txn1 = getTxn();
    txn2 = getTxn();

    txn1.begin();
    txn2.begin();

    try {
        txn1.commit();
        fail("Failure to detect mismatched transaction begin/commit");
    } catch (RuntimeException e) {
        // expected
    }
    txn2.commit();
    txn1.commit();

    checkNoStatusOnThread();
}

From source file:com.someco.servlets.AuthenticationFilter.java

/**
 * Set the authenticated user./*  w  w w .  ja v a2 s  . com*/
 * 
 * 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:nc.noumea.mairie.alfresco.webScript.SynchroniseAgentWebScript.java

@Override
public Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {

    logger.info("DEBUT Web Script SynchroniseAgentWebScript");

    Map<String, Object> model = new HashMap<String, Object>();
    model.put("nomWebScript", "SynchroniseAgentWebScript");

    long startTime = System.currentTimeMillis();

    if (!isSiteSirhExist()) {
        logger.debug("Site SIRH not exist");

        long endTime = System.currentTimeMillis();

        model.put("nbrAgentCree", "Site SIRH not exist");
        model.put("tempsExecution", endTime - startTime);

        return model;
    }/*from w  w  w. j a  va 2  s  .  c o  m*/

    List<AgentWithServiceDto> listAgentsSIRH = sirhWsConsumer.getListeAgentsMairie();

    List<String> listEmployeeNumber = new ArrayList<String>();
    for (AgentWithServiceDto agent : listAgentsSIRH) {
        if (!listEmployeeNumber.contains(getEmployeeNumberFromIdAgent(agent.getIdAgent()))) {
            listEmployeeNumber.add(getEmployeeNumberFromIdAgent(agent.getIdAgent()));
        }
    }

    logger.info("Nombre d'agents retournes par SIRH : " + listAgentsSIRH.size());

    List<LightUserDto> listUsersRadi = radiWsConsumer.getListAgentCompteAD(listEmployeeNumber);

    logger.info("Nombre d'agents retournes par RADI : " + listUsersRadi.size());

    int nbrAgentCree = 0;
    for (AgentWithServiceDto agent : listAgentsSIRH) {

        LightUserDto userRadi = getLightUserRadiDto(listUsersRadi, agent);

        if (null == userRadi) {
            logger.debug("User not exist in RADI : " + agent.getIdAgent());
            continue;
        }

        logger.debug("User find in RADI : " + agent.getIdAgent());

        // nous gerons nous meme les transactions
        // car nous avons eu "TransactionalCache' is full"
        // cela ralentit fortement Alfresco
        UserTransaction trx = serviceRegistry.getTransactionService().getNonPropagatingUserTransaction(false);
        try {
            if (!personService.personExists(userRadi.getsAMAccountName())) {

                trx.begin();

                personService.setCreateMissingPeople(true);
                NodeRef person = personService
                        .createPerson(createDefaultProperties(userRadi.getsAMAccountName(), agent.getPrenom(),
                                agent.getNom(), userRadi.getMail(), agent.getIdAgent()));

                trx.commit();

                if (null != person) {
                    nbrAgentCree++;
                }
            } else {
                logger.debug("User already exist in alfresco : " + agent.getIdAgent() + " "
                        + userRadi.getsAMAccountName());
            }
        } catch (Throwable e) {
            try {
                trx.rollback();
                logger.error(e.getMessage());
            } catch (IllegalStateException | SecurityException | SystemException e1) {
                logger.error(e1.getMessage());
            }
        }
    }

    long endTime = System.currentTimeMillis();

    model.put("nbrAgentCree", nbrAgentCree);
    model.put("tempsExecution", endTime - startTime);

    logger.debug(nbrAgentCree + " users crs.");

    logger.info("FIN Web Script SynchroniseAgentWebScript");

    return model;
}

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  w w w.  j  a v a2  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:com.bluexml.side.Integration.alfresco.sql.synchronization.schemaManagement.SchemaCreation.java

private boolean doExecuteReplication(QName modelName) {
    boolean success = true;

    UserTransaction userTransaction = transactionService.getUserTransaction();
    try {//from   ww w.j a v  a  2  s.  com
        userTransaction.begin();
        contentReplication.addExistingData(modelName);
        userTransaction.commit();
    } catch (Exception e) {
        success = false;
        try {
            userTransaction.rollback();
        } catch (Exception e1) {
            logger.error("Cannot rollback transaction !");
            e1.printStackTrace();
        }
        e.printStackTrace();
    }
    return success;
}

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

/**
 * Deploy the Workflow Definitions.//from w w  w . j  a v  a2 s  .co  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()) {
        if (logger.isWarnEnabled())
            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) {
                // retrieve workflow specification
                String engineId = workflowDefinition.getProperty(ENGINE_ID);
                if (engineId == null || engineId.length() == 0) {
                    throw new WorkflowException("Workflow Engine Id must be provided");
                }

                String location = workflowDefinition.getProperty(LOCATION);
                if (location == null || location.length() == 0) {
                    throw new WorkflowException("Workflow definition location must be provided");
                }

                Boolean redeploy = Boolean.valueOf(workflowDefinition.getProperty(REDEPLOY));
                String mimetype = workflowDefinition.getProperty(MIMETYPE);

                // retrieve input stream on workflow definition
                ClassPathResource workflowResource = new ClassPathResource(location);

                // deploy workflow definition
                if (!redeploy && workflowService.isDefinitionDeployed(engineId,
                        workflowResource.getInputStream(), mimetype)) {
                    if (logger.isDebugEnabled())
                        logger.debug("Workflow deployer: Definition '" + location + "' already deployed");
                } else {
                    if (!redeploy && workflowService.isDefinitionDeployed(engineId,
                            workflowResource.getInputStream(), mimetype)) {
                        if (logger.isDebugEnabled())
                            logger.debug("Workflow deployer: Definition '" + location + "' already deployed");
                    } else {
                        WorkflowDeployment deployment = workflowService.deployDefinition(engineId,
                                workflowResource.getInputStream(), workflowResource.getFilename());
                        logDeployment(location, deployment);
                    }
                }

            }
        }

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

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

/**
 * Deploy the Workflow Definitions.//  w w  w. j  a  v  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();
        }
    }
}

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

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///  www.j  a  va  2s  .co m
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);
    }
}