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.webbfontaine.valuewebb.gtns.TTGTNSSynchronizer.java

protected static void updateTT(TtGen ttGen, String operation) {
    LOGGER.debug("Going to execute {0} operation on TT with id {1}.", operation, ttGen.getId());

    assert !StringUtils.isEmpty(operation) && ttGen != null : "ttGen and requestedOperation must not be null";

    UserTransaction utx = null;
    try {/*from ww w .  j  a  v  a  2 s  .  c o  m*/
        utx = Transaction.instance();
        utx.begin();

        TtGenHome ttGenHome = createTTHomeInstance(ttGen);
        if (ttGenHome.performDirectTaskWithoutDocumentCheck(operation).equals(UPDATED)) {
            if (RESPONSE_OK.equals(operation)) {
                utx.commit();
                utx = Transaction.instance();
                utx.begin();
                ttGenHome.pickUp();
            }
            utx.commit();
        } else {
            LOGGER.error("Failed to execute {0} operation for TT with id {1}. Will continue with next TTs",
                    operation, ttGen.getId());
            utx.rollback();
        }
    } catch (Exception e) {
        LOGGER.error("Exception on updating TT with id: {0} for operation: {1} fails", e, ttGen.getId(),
                operation);
        if (utx != null) {
            try {
                utx.rollback();
            } catch (SystemException sex) {
                LOGGER.error("", sex);
            }
        }
    }
}

From source file:com.netpace.cms.sso.filter.TransactionalHelper.java

public Object doInTransaction(Transactionable callback) {
    UserTransaction tx = transactionService.getUserTransaction();
    Object result;/* w w  w.  j a v  a 2s . co m*/
    try {
        tx.begin();
        result = callback.execute();
        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 execute transactional method", ex);
        }
    }

    return result;

}

From source file:com.autentia.common.util.ejb.web.jsf.OpenTransactionInViewPatternJSFBeforeRestoreViewListener.java

public void beforePhase(PhaseEvent phaseEvent) {
    final UserTransaction utx;
    try {//  w w w  .jav  a  2 s.c  o  m
        utx = (UserTransaction) JndiUtils.jndiLookup("UserTransaction");
        utx.begin();
        log.debug("Transaction begins");

    } catch (Exception e) {
        log.fatal("Cannot begin transaction.", e);
    }
}

From source file:org.alfresco.trashcan.TrashcanCleanerTest.java

/**
 * /*from   ww  w  .  ja v  a 2 s  .c om*/
 * Generic method that asserts that for the <b>nodesCreate</b> existing on
 * archive store the execution of trashcan clean will leave remaining
 * undeleted <b>nodesRemain</b>.
 * 
 * @param nodesCreate
 * @param nodesRemain
 * @throws Throwable
 */
private void cleanBatchTest(int nodesCreate, int nodesRemain) throws Throwable {
    UserTransaction userTransaction1 = transactionService.getUserTransaction();
    try {
        userTransaction1.begin();
        TrashcanCleaner cleaner = new TrashcanCleaner(nodeService, BATCH_SIZE, -1);
        createAndDeleteNodes(nodesCreate);
        long nodesToDelete = cleaner.getNumberOfNodesInTrashcan();
        System.out.println(String.format("Existing nodes to delete: %s", nodesToDelete));
        cleaner.clean();
        nodesToDelete = cleaner.getNumberOfNodesInTrashcan();
        System.out.println(String.format("Existing nodes to delete after: %s", nodesToDelete));
        assertEquals(nodesRemain, nodesToDelete);
        System.out.println("Clean trashcan...");
        cleaner.clean();
        userTransaction1.commit();
    } catch (Throwable e) {
        try {
            userTransaction1.rollback();
        } catch (IllegalStateException ee) {
        }
        throw e;
    }
}

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 ww . j  av  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.webbfontaine.valuewebb.action.fcvr.FCVRSendScheduler.java

protected void updateTT(TtGen ttGen, String operation) {
    LOGGER.debug("Going to execute {0} operation on TT with id {1}.", operation, ttGen.getId());

    UserTransaction utx = null;
    try {/*from  ww w  .  j a va  2 s .  com*/
        utx = Transaction.instance();
        utx.begin();

        TtGenHome ttGenHome = createTTHomeInstance(ttGen);
        if (ttGenHome.performDirectTaskWithoutDocumentCheck(operation).equals(UPDATED)) {
            utx.commit();
        } else {
            LOGGER.error("Failed to execute {0} operation for TT with id {1}. Will continue with next TTs",
                    operation, ttGen.getId());
            utx.rollback();
        }
    } catch (Exception e) {
        LOGGER.error("Exception on updating TT with id: {0} for operation: {1} fails", e, ttGen.getId(),
                operation);
        if (utx != null) {
            try {
                utx.rollback();
            } catch (SystemException sex) {
                LOGGER.error("", sex);
            }
        }
    }
}

From source file:de.fme.topx.component.TopXUpdateComponent.java

/**
 * increase the hitcount for the given noderef by using the aspect
 * <code>topx:countable</code>. Does not fire events for other behaviours.
 * Using admin use to increment because not everybody has
 * /* ww w. j av  a  2  s.c o  m*/
 * @param nodeRef
 * @param userName
 *            current user who reads or updates the document.
 * @param counterUserProperty
 * @throws SystemException
 * @throws NotSupportedException
 * @throws HeuristicRollbackException
 * @throws HeuristicMixedException
 * @throws RollbackException
 * @throws IllegalStateException
 * @throws SecurityException
 */
@SuppressWarnings("unchecked")
public Integer increaseHitcount(final NodeRef nodeRef, final String userName, final QName counterProperty,
        final QName counterDateProperty, final QName counterUserProperty)
        throws NotSupportedException, SystemException, SecurityException, IllegalStateException,
        RollbackException, HeuristicMixedException, HeuristicRollbackException {
    UserTransaction transaction = transactionService.getNonPropagatingUserTransaction(false);
    transaction.begin();

    try {
        Preconditions.checkNotNull(nodeRef, "Passed noderef should not be null");
        Preconditions.checkArgument(nodeService.exists(nodeRef),
                "Node[" + nodeRef + "] must exist in the repository");
        filter.disableAllBehaviours();
        Map<QName, Serializable> newProperties = Maps.newHashMap();
        Integer counter = (Integer) nodeService.getProperty(nodeRef, counterProperty);
        if (counter == null) {
            counter = setHitCountProperties(nodeRef, counterProperty, counterDateProperty, counterUserProperty,
                    newProperties, 1, userName);
        } else {
            boolean shouldCount = true;
            Map<QName, Serializable> properties = nodeService.getProperties(nodeRef);
            Serializable usersValue = properties.get(counterUserProperty);

            List<String> users;
            if (!(usersValue instanceof List)) {
                users = Lists.newArrayList((String) usersValue);
            } else {
                users = (List<String>) usersValue;
            }

            if (users != null) {
                int userIndex = users.indexOf(userName);
                if (userIndex != -1) {
                    List<Date> counterDates = (List<Date>) properties.get(counterDateProperty);
                    Date lastUserReadDate = counterDates.get(userIndex);
                    // only count one download for a
                    // document of
                    // a user per day
                    if (DateUtils.isSameDay(lastUserReadDate, new Date())) {
                        shouldCount = false;
                        LOG.info("User " + userName + " already downloads/updates document " + nodeRef
                                + " today. Skip counting.");
                    }
                }
            }
            if (shouldCount) {
                counter = setHitCountProperties(nodeRef, counterProperty, counterDateProperty,
                        counterUserProperty, newProperties, counter, userName);
            }

        }
        transaction.commit();
        LOG.info("Commiting transaction for Node " + nodeRef);
        return counter;
    } finally {
        filter.enableAllBehaviours();
        if (transaction.getStatus() == javax.transaction.Status.STATUS_ACTIVE) {
            transaction.rollback();
            LOG.warn("Had to rollback the transaction for Node " + nodeRef);
        }

    }
}

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

/**
 * /*  w  w w . j  av a2  s. com*/
 * @param httpReq
 * @param httpRes
 * @return processor which can output to the res
 * @throws Throwable if error in txn
 */
private RestCommandProcessor login(HttpServletRequest httpReq, HttpServletResponse httpRes) throws Throwable {
    // getting login parameters
    Map<String, String> args = new HashMap<String, String>(3, 1.0f);
    args.put(RestConstants.PROP_LOGIN_USERNAME, httpReq.getParameter("username"));
    args.put(RestConstants.PROP_LOGIN_PASSWORD, httpReq.getParameter("password"));

    RestCommandProcessor processor = new RestCommandProcessor();

    // validate that the processor has everything it needs to run the command
    if (!processor.validateArguments(this.context, LOGIN_COMMAND_NAME, args, null)) {
        // returning processor with error state
        return processor;
    }

    ServiceRegistry serviceRegistry = getServiceRegistry(this.context);
    UserTransaction txn = null;
    try {
        txn = serviceRegistry.getTransactionService().getUserTransaction();
        txn.begin();
        processor.process(serviceRegistry, httpReq, httpRes, LOGIN_COMMAND_NAME);
        txn.commit();
        return processor;

    } catch (Throwable txnErr) {
        try {
            if (txn != null) {
                txn.rollback();
            }
        } catch (Exception tex) {
        }
        throw txnErr;
    }
}

From source file:org.spring.data.gemfire.app.service.vendor.GemFireGemstoneService.java

protected <IN, OUT> OUT doInTransaction(final TransactionCallback<IN, OUT> callback, IN parameter) {
    UserTransaction userTransaction = null;

    try {//from   w ww  .ja v  a2s  . c  o  m
        userTransaction = (UserTransaction) getCache().getJNDIContext().lookup(USER_TRANSACTION_JNDI_LOCATION);
        userTransaction.begin();

        OUT returnValue = callback.doInTransaction(parameter);

        userTransaction.commit();

        return returnValue;
    } catch (Exception e) {
        e.printStackTrace(System.err);
        rollback(userTransaction);

        if (e instanceof IllegalGemstoneException) {
            throw (IllegalGemstoneException) e;
        } else {
            throw new RuntimeException(
                    String.format("Transaction failed due to unexpected Exception: %1$s!", e.getMessage()), e);
        }
    }
}

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 w  w.  j  av a2s.c  o  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;
}