Example usage for javax.persistence EntityTransaction begin

List of usage examples for javax.persistence EntityTransaction begin

Introduction

In this page you can find the example usage for javax.persistence EntityTransaction begin.

Prototype

public void begin();

Source Link

Document

Start a resource transaction.

Usage

From source file:org.easy.criteria.BaseDAO.java

/**
 * {@link javax.persistence.EntityManager#getTransaction()#begin())}
 *//*from   ww w  . ja  v  a2  s  . c o m*/
public EntityTransaction beginTransaction() {
    EntityTransaction transaction = _entityManager.getTransaction();
    transaction.begin();
    return transaction;
}

From source file:org.opencastproject.kernel.security.persistence.OrganizationDatabaseImpl.java

/**
 * @see org.opencastproject.kernel.security.persistence.OrganizationDatabase#deleteOrganization(java.lang.String)
 *///from  w w w.j  a v  a2  s .c  o  m
@Override
public void deleteOrganization(String orgId) throws OrganizationDatabaseException, NotFoundException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        JpaOrganization organization = getOrganizationEntity(orgId);
        if (organization == null)
            throw new NotFoundException("Organization " + orgId + " does not exist");

        em.remove(organization);
        tx.commit();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not delete organization: {}", e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new OrganizationDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.kernel.security.persistence.OrganizationDatabaseImpl.java

/**
 * @see org.opencastproject.kernel.security.persistence.OrganizationDatabase#storeOrganization(org.opencastproject.security.api.Organization)
 */// w  w  w. ja va 2s.c  om
@Override
public void storeOrganization(Organization org) throws OrganizationDatabaseException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        JpaOrganization organizationEntity = getOrganizationEntity(org.getId());
        if (organizationEntity == null) {
            JpaOrganization organization = new JpaOrganization(org.getId(), org.getName(), org.getServers(),
                    org.getAdminRole(), org.getAnonymousRole(), org.getProperties());
            em.persist(organization);
        } else {
            organizationEntity.setName(org.getName());
            organizationEntity.setAdminRole(org.getAdminRole());
            organizationEntity.setAnonymousRole(org.getAnonymousRole());
            organizationEntity.setServers(org.getServers());
            organizationEntity.setProperties(org.getProperties());
            em.merge(organizationEntity);
        }
        tx.commit();
    } catch (Exception e) {
        logger.error("Could not update organization: {}", e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new OrganizationDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:nl.b3p.kaartenbalie.service.SecurityRealm.java

/** Checks wether an user, given his username and password, is allowed to use the system.
 *
 * @param username String representing the username.
 * @param password String representing the password.
 *
 * @return a principal object containing the user if he has been found as a registered user. Otherwise this object wil be empty (null).
 *///from   ww  w  .j a v  a2s .c  om
@Override
public Principal authenticate(String username, String password) {

    String encpw = null;
    try {
        encpw = KBCrypter.encryptText(password);
    } catch (Exception ex) {
        log.error("error encrypting password: ", ex);
    }
    Object identity = null;
    EntityTransaction tx = null;
    try {
        identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.REALM_EM);
        EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.REALM_EM);
        tx = em.getTransaction();
        tx.begin();
        try {
            User user = (User) em
                    .createQuery("from User u where " + "u.timeout > :nu "
                            + "and lower(u.username) = lower(:username) " + "and u.password = :password")
                    .setParameter("nu", new Date()).setParameter("username", username)
                    .setParameter("password", encpw).getSingleResult();
            // if we get a result, this means successful login
            // set lastloginstatus to null to indicate success
            user.setLastLoginStatus(null);

            return user;
        } catch (NoResultException nre) {
            log.debug("No results using encrypted password");
        }
        // if login not succesful, set userstate to LOGIN_STATE_WRONG_PASSW
        User wrong_password_user = (User) em
                .createQuery(
                        "from User u where " + "u.timeout > :nu " + "and lower(u.username) = lower(:username) ")
                .setParameter("nu", new Date()).setParameter("username", username).getSingleResult();
        wrong_password_user.setLastLoginStatus(User.LOGIN_STATE_WRONG_PASSW_OR_ACCOUNT_EXPIRED);
        em.flush();
        log.warn("Login failure for username " + username);
    } catch (Exception e) {
        log.error("Exception checking user credentails", e);
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
    } finally {
        if (tx != null && tx.isActive() && !tx.getRollbackOnly()) {
            tx.commit();
        }
        MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.REALM_EM);
    }

    return null;
}

From source file:org.apache.james.user.jpa.JPAUsersRepository.java

/**
 * Update the repository with the specified user object. A user object with
 * this username must already exist.//from  w ww.  j av a  2  s  . c o m
 * 
 * @throws UsersRepositoryException
 */
public void updateUser(User user) throws UsersRepositoryException {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    final EntityTransaction transaction = entityManager.getTransaction();
    try {
        if (contains(user.getUserName())) {
            transaction.begin();
            entityManager.merge(user);
            transaction.commit();
        } else {
            getLogger().debug("User not found");
            throw new UsersRepositoryException("User " + user.getUserName() + " not found");
        }
    } catch (PersistenceException e) {
        getLogger().debug("Failed to update user", e);
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw new UsersRepositoryException("Failed to update user " + user.getUserName(), e);
    } finally {
        entityManager.close();
    }
}

From source file:com.busimu.core.dao.impl.UserMngDaoPolicyJpaImpl.java

/**
 * {@inheritDoc}/*  w  w  w.  j a v a 2 s .  c om*/
 */
@Override
public User activateUser(User user, String licenseCode) {
    EntityManager em = ((EntityManagerHolder) TransactionSynchronizationManager.getResource(emf))
            .getEntityManager();
    EntityTransaction tx = em.getTransaction();
    License l = getLicenseByCode(em, licenseCode);
    if (l != null) {
        if (!tx.isActive()) {
            tx.begin();
        }
        user.setType(User.Type.valueOf(l.getType().name()));
        user.setStatus(User.Status.ACTIVE);
        user = em.merge(user);
        em.remove(l);
        tx.commit();
    }
    return user;
}

From source file:org.debux.webmotion.jpa.Transactional.java

/**
 * Create the transaction and the GenericDAO if the entity name is not 
 * empty or null.//from   w  w  w .jav a  2  s . co m
 * 
 * @param request set EntityManager, EntityTransaction and GenericDAO into the request
 * @param persistenceUnitName precise the persistence unit
 * @param packageEntityName precise the package of entity
 * @param entityName precise the class name of the entity
 * 
 * @throws Exception catch execption to rollback the transaction
 */
public void tx(HttpServletRequest request, String persistenceUnitName, Properties properties,
        String packageEntityName, String entityName) throws Exception {

    // Create factory
    if (persistenceUnitName == null || persistenceUnitName.isEmpty()) {
        persistenceUnitName = DEFAULT_PERSISTENCE_UNIT_NAME;
    }
    EntityManagerFactory factory = factories.get(persistenceUnitName);
    if (factory == null) {
        Configuration subset = properties.subset(persistenceUnitName);
        java.util.Properties additionalProperties = ConfigurationConverter.getProperties(subset);

        factory = Persistence.createEntityManagerFactory(persistenceUnitName, additionalProperties);
        factories.put(persistenceUnitName, factory);
    }

    // Create manager
    EntityManager manager = (EntityManager) request.getAttribute(CURRENT_ENTITY_MANAGER);
    if (manager == null) {
        manager = factory.createEntityManager();
        request.setAttribute(CURRENT_ENTITY_MANAGER, manager);
    }

    // Create generic DAO each time if callback an action on an other entity
    if (entityName != null) {
        String fullEntityName = null;
        if (packageEntityName != null && !packageEntityName.isEmpty()) {
            fullEntityName = packageEntityName + "." + entityName;
        } else {
            fullEntityName = entityName;
        }

        GenericDAO genericDAO = new GenericDAO(manager, fullEntityName);
        request.setAttribute(CURRENT_GENERIC_DAO, genericDAO);

    } else {
        request.setAttribute(CURRENT_GENERIC_DAO, null);
    }

    // Create transaction
    EntityTransaction transaction = (EntityTransaction) request.getAttribute(CURRENT_ENTITY_TRANSACTION);
    if (transaction == null) {
        transaction = manager.getTransaction();
        request.setAttribute(CURRENT_ENTITY_TRANSACTION, transaction);

        transaction.begin();

        try {
            doProcess();
        } catch (Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw e;
        }

        if (transaction.isActive()) {
            transaction.commit();
        }
        manager.close();

    } else {
        doProcess();
    }
}

From source file:org.apache.ranger.audit.provider.DbAuditProvider.java

private boolean beginTransaction() {
    EntityTransaction trx = getTransaction();

    if (trx != null && !trx.isActive()) {
        trx.begin();
    }//from   w ww .  j a v a 2  s.co  m

    if (trx == null) {
        LOG.warn("DbAuditProvider.beginTransaction(): trx is null");
    }

    return trx != null;
}

From source file:org.sigmah.server.dao.hibernate.TransactionalInterceptor.java

@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    EntityManager em = injector.getInstance(EntityManager.class);
    EntityTransaction tx = em.getTransaction();

    //allow joining of transactions if there is an enclosing @Transactional method
    if (tx.isActive()) {

        if (log.isDebugEnabled()) {
            log.debug("[invoke] Transaction already active, just proceed the method.");
        }//from   w  w  w  .j  a  v a  2 s. co  m

        return methodInvocation.proceed();
    }

    tx.begin();

    if (log.isDebugEnabled()) {
        log.debug("[invoke] Begins an entity transaction.");
    }

    Object result = attemptInvocation(methodInvocation, tx);

    // everything was normal so commit the txn (do not move into try block as it interferes
    // with the advised method's throwing semantics)
    tx.commit();

    if (log.isDebugEnabled()) {
        log.debug("[invoke] Commits the transaction.");
    }

    return result;
}

From source file:nl.b3p.kaartenbalie.core.server.persistence.MyEMFDatabase.java

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);

    DataMonitoring//from   w  w w.ja  va 2s. co  m
            .setEnableMonitoring(getConfigValue(config, "reporting", "disabled").equalsIgnoreCase("enabled"));
    AccountManager
            .setEnableAccounting(getConfigValue(config, "accounting", "disabled").equalsIgnoreCase("enabled"));

    Object identity = null;
    try {
        openEntityManagerFactory(defaultKaartenbaliePU);
        identity = createEntityManager(MyEMFDatabase.INIT_EM);
        log.debug("Getting entity manager ......");
        EntityManager em = getEntityManager(MyEMFDatabase.INIT_EM);
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        //            ReportGenerator.startupClear(em);
        tx.commit();
    } catch (Throwable e) {
        log.warn("Error creating EntityManager: ", e);
        throw new ServletException(e);
    } finally {
        log.debug("Closing entity manager .....");
        closeEntityManager(identity, MyEMFDatabase.INIT_EM);
    }

    cachePath = getConfigValue(config, "cache", "/");
    if (cachePath != null) {
        cachePath = getServletContext().getRealPath(cachePath);
        log.debug("cache pad: " + cachePath);
    }

    rg = new Random();

    String allowedUpload = config.getInitParameter("allowed_upload_files");
    if (allowedUpload != null && allowedUpload.length() > 0) {
        allowedUploadFiles = allowedUpload.split(",");
    }

    // load global context params
    initGlobalContextParams(config);

    // configure kb via properties
    KBConfiguration.configure();
}