Example usage for javax.persistence EntityManager getTransaction

List of usage examples for javax.persistence EntityManager getTransaction

Introduction

In this page you can find the example usage for javax.persistence EntityManager getTransaction.

Prototype

public EntityTransaction getTransaction();

Source Link

Document

Return the resource-level EntityTransaction object.

Usage

From source file:it.infn.ct.futuregateway.apiserver.v1.InfrastructureCollectionService.java

/**
 * Register a new infrastructure./* w w w  .  j  av  a2s . c  om*/
 *
 * @param infra The infrastructure to register
 * @return The registered infrastructure
 */
@POST
@Status(Response.Status.CREATED)
@Consumes({ MediaType.APPLICATION_JSON, Constants.INDIGOMIMETYPE })
@Produces(Constants.INDIGOMIMETYPE)
public final Infrastructure createInfrastructure(final Infrastructure infra) {
    Date now = new Date();
    infra.setDateCreated(now);
    EntityManager em = getEntityManager();
    EntityTransaction et = null;
    try {
        et = em.getTransaction();
        et.begin();
        em.persist(infra);
        et.commit();
        log.debug("New infrastructure registered: " + infra.getId());
    } catch (RuntimeException re) {
        if (et != null && et.isActive()) {
            et.rollback();
        }
        log.error("Impossible to create the infrastructure");
        log.error(re);
    } finally {
        em.close();
    }
    return infra;
}

From source file:it.infn.ct.futuregateway.apiserver.v1.InfrastructureCollectionService.java

/**
 * Retrieve the application list.//from  ww w. ja  va 2 s .  c o m
 * The fields not requested for the list are cleaned.
 * @return The list of applications
 */
private List<Infrastructure> retrieveInfrastructureList() {
    List<Infrastructure> lstInfras;
    EntityManager em = getEntityManager();
    EntityTransaction et = null;
    try {
        et = em.getTransaction();
        et.begin();
        lstInfras = em.createNamedQuery("infrastructures.all", Infrastructure.class).getResultList();
        et.commit();
    } catch (RuntimeException re) {
        if (et != null && et.isActive()) {
            et.rollback();
        }
        log.error("Impossible to retrieve the infrastructure list");
        log.error(re);
        throw new RuntimeException("Impossible to access the " + "infrastructures list");
    } finally {
        em.close();
    }
    if (lstInfras != null) {
        for (Infrastructure in : lstInfras) {
            in.setDescription(null);
            in.setParameters(null);
        }
    }
    return lstInfras;
}

From source file:name.livitski.tools.persista.TransactionalWork.java

/**
 * Performs the {@link #code database operations} provided by
 * the subclass in JPA transactional brackets. If there is currently
 * no active transaction at the entity manager, a new transaction
 * is started.//from  ww  w  . j  a va2  s. c  om
 * If the code finishes normally and does not request the rollback,
 * the transaction is committed if it was started by this method
 * (local transaction).
 * If the implementor's code throws an exception or requests the
 * rollback, the local transaction is rolled back and any ongoing
 * transaction is marked
 * {@link EntityTransaction#setRollbackOnly() rollback-only}.
 * @param db the entity manager the operation will be performed with
 * @return <code>true</code> if the transaction has or may still
 * be committed
 * @throws AbstractStorageException indicates an error during
 * the operation
 * @throws RuntimeException any unchecked implementor's exceptions
 * will be rethrown
 * @see EntityManager#getTransaction()
 */
public boolean exec(final EntityManager db) throws AbstractStorageException {
    final EntityTransaction transaction = db.getTransaction();
    boolean commit = false;
    Exception status = null;
    boolean localTransaction;
    if (transaction.isActive())
        localTransaction = false;
    else {
        transaction.begin();
        localTransaction = true;
    }
    try {
        commit = code(db);
        return commit;
    } catch (AbstractStorageException fault) {
        status = fault;
        throw fault;
    } catch (RuntimeException fault) {
        status = fault;
        throw fault;
    } finally {
        if (!localTransaction) {
            if (commit)
                db.flush();
            else
                transaction.setRollbackOnly();
        } else if (!commit || transaction.getRollbackOnly()) {
            try {
                transaction.rollback();
            } catch (RuntimeException fault) {
                if (null != status)
                    log().error("Transaction rollback failed", fault);
                else
                    throw fault;
            }
        } else // commit local transaction
        {
            try {
                transaction.commit();
            } catch (RuntimeException fault) {
                throw fault;
            }
        }
    }
}

From source file:com.epam.training.taranovski.web.project.repository.implementation.BasicSkillRepositoryImplementation.java

@Override
public List<BasicSkill> getSkillsNotInEmployee(Employee employee) {
    EntityManager em = entityManagerFactory.createEntityManager();
    List<BasicSkill> list = new LinkedList<>();
    try {/*w w w. j  a va 2s .  c  o  m*/
        em.getTransaction().begin();

        TypedQuery<BasicSkill> query = em.createNamedQuery("BasicSkill.findSkillsNotInEmployee",
                BasicSkill.class);
        query.setParameter("employee", employee);
        list = query.getResultList();

        em.getTransaction().commit();
    } catch (RuntimeException e) {
        Logger.getLogger(BasicSkillRepositoryImplementation.class.getName()).info(e);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        em.close();
    }

    return list;
}

From source file:com.epam.training.taranovski.web.project.repository.implementation.BasicSkillRepositoryImplementation.java

@Override
public List<BasicSkill> getSkillsNotInVacancy(Vacancy vacancy) {
    EntityManager em = entityManagerFactory.createEntityManager();
    List<BasicSkill> list = new LinkedList<>();
    try {//from   www . ja  v a2 s.  co m
        em.getTransaction().begin();

        TypedQuery<BasicSkill> query = em.createNamedQuery("BasicSkill.findSkillsNotInVacancy",
                BasicSkill.class);
        query.setParameter("vacancy", vacancy);
        list = query.getResultList();

        em.getTransaction().commit();
    } catch (RuntimeException e) {
        Logger.getLogger(BasicSkillRepositoryImplementation.class.getName()).info(e);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        em.close();
    }

    return list;
}

From source file:org.SRV.testServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    double value1 = Double.parseDouble(request.getParameter("val1"));
    double value2 = Double.parseDouble(request.getParameter("val2"));

    UserDetails user = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    String username = user.getUsername();
    //com.seostella_springsecuritybasics_war_1.0.0-BUILD-SNAPSHOTPU
    entityManagerFactory = Persistence.createEntityManagerFactory("org.SRV_war_1.0.0-BUILD-SNAPSHOTPU");

    double result = 0;
    switch (request.getParameter("operation").charAt(0)) {
    case '+':
        result = value1 + value2;/*w w  w .j  a v  a  2 s  .  c o m*/
        break;
    case '-':
        result = value1 - value2;
        break;
    case '*':
        result = value1 * value2;
        break;
    case '/':
        result = value1 / value2;
        break;
    default:
        break;
    }

    EntityManager entityManager = entityManagerFactory.createEntityManager();
    entityManager.getTransaction().begin();
    Date date = new Date();
    Essence essence = new Essence();
    essence.setLogin(username);
    essence.setDate(date);
    essence.setValue1(Double.toString(value1));
    essence.setValue2(Double.toString(value2));
    essence.setOperation(request.getParameter("operation"));
    essence.setResult(Double.toString(result));
    entityManager.persist(essence);
    entityManager.getTransaction().commit();
    entityManager.clear();
    entityManager.close();
    entityManagerFactory.close();
    JSONObject obj;
    obj = new JSONObject();
    obj.put("result", result);
    //response.getOutputStream().print(obj.toString());
    response.getWriter().write(obj.toString());
}

From source file:com.epam.training.taranovski.web.project.repository.implementation.EmployerRepositoryImplementation.java

@Override
public boolean update(Employer employer) {
    EntityManager em = entityManagerFactory.createEntityManager();
    boolean success = true;
    try {/*w ww  .j ava  2 s .c om*/
        em.getTransaction().begin();

        em.merge(employer);
        em.flush();

        em.getTransaction().commit();
        success = true;
    } catch (RuntimeException e) {
        Logger.getLogger(BasicSkillRepositoryImplementation.class.getName()).info(e);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
            success = false;
        }
        em.close();
    }

    return success;
}

From source file:com.epam.training.taranovski.spring.repository.oracle.AdminRepositoryOracle.java

/**
 *
 * @param id/* w ww  .  j  a  v a2 s .  c  o m*/
 * @return
 */
@Override
public Admin getById(int id) {
    EntityManager em = emf.createEntityManager();
    Admin admin;
    try {
        em.getTransaction().begin();
        admin = em.find(Admin.class, id);
        em.getTransaction().commit();
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        em.close();
    }

    return admin;
}

From source file:it.infn.ct.futuregateway.apiserver.v1.ApplicationCollectionService.java

/**
 * Retrieve the application list./*from   w  w  w .ja v  a2  s . co m*/
 * The fields not requested for the list are cleaned.
 * @return The list of applications
 */
private List<Application> retrieveApplicationList() {
    List<Application> lstApps;
    EntityManager em = getEntityManager();
    EntityTransaction et = null;
    try {
        et = em.getTransaction();
        et.begin();
        lstApps = em.createNamedQuery("applications.all", Application.class).getResultList();
        et.commit();
    } catch (RuntimeException re) {
        if (et != null && et.isActive()) {
            et.rollback();
        }
        log.error("Impossible to retrieve the Application list");
        log.error(re);
        throw new RuntimeException("Impossible to access the " + "application list");
    } finally {
        em.close();
    }
    if (lstApps != null) {
        for (Application ap : lstApps) {
            ap.setDescription(null);
            ap.setParameters(null);
        }
    }
    return lstApps;
}

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).
 */// www.j a va 2s. com
@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;
}