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:com.enioka.jqm.tools.Helpers.java

/**
 * Creates or updates a node.<br>//  w ww  .  j a  v a  2 s.  c  o  m
 * This method makes the assumption metadata is valid. e.g. there MUST be a single default queue.<br>
 * Call {@link #updateConfiguration(EntityManager)} before to be sure if necessary.
 * 
 * @param nodeName
 *            name of the node that should be created or updated (if incompletely defined only)
 * @param em
 *            an EntityManager on which a transaction will be opened.
 */
static void updateNodeConfiguration(String nodeName, EntityManager em) {
    // Node
    Node n = null;
    try {
        n = em.createQuery("SELECT n FROM Node n WHERE n.name = :l", Node.class).setParameter("l", nodeName)
                .getSingleResult();
    } catch (NoResultException e) {
        jqmlogger.info("Node " + nodeName
                + " does not exist in the configuration and will be created with default values");
        em.getTransaction().begin();

        n = new Node();
        n.setDlRepo(System.getProperty("user.dir") + "/outputfiles/");
        n.setName(nodeName);
        n.setPort(0);
        n.setRepo(System.getProperty("user.dir") + "/jobs/");
        n.setTmpDirectory(System.getProperty("user.dir") + "/tmp/");
        n.setRootLogLevel("INFO");
        em.persist(n);
        em.getTransaction().commit();
    }

    // Deployment parameters
    DeploymentParameter dp = null;
    long i = (Long) em.createQuery("SELECT COUNT(dp) FROM DeploymentParameter dp WHERE dp.node = :localnode")
            .setParameter("localnode", n).getSingleResult();
    if (i == 0) {
        jqmlogger.info(
                "As this node is not bound to any queue, it will be set to poll from the default queue with default parameters");
        Queue q = em.createQuery("SELECT q FROM Queue q WHERE q.defaultQueue = true", Queue.class)
                .getSingleResult();
        em.getTransaction().begin();
        dp = new DeploymentParameter();
        dp.setNbThread(5);
        dp.setNode(n);
        dp.setPollingInterval(1000);
        dp.setQueue(q);
        em.persist(dp);

        em.getTransaction().commit();
    }
}

From source file:com.sixsq.slipstream.persistence.Run.java

public static Run updateRunState(Run run, States newState, boolean retry) {
    EntityManager em = PersistenceUtil.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();//from ww w .ja  v  a 2  s .c  o m
    try {
        run = Run.loadFromUuid(run.getUuid(), em);
        run.setState(newState);
        transaction.commit();
        em.close();
    } catch (Exception e) {
        String error = "error setting run state: " + newState;
        if (retry) {
            Logger.getLogger("restlet").warning(error + " retrying...");
        } else {
            Logger.getLogger("restlet").severe(error);
        }
        // retry once
        if (retry) {
            updateRunState(run, newState, false);
        }
    }
    return run;
}

From source file:com.soen.ebanking.dao.ObjectDao.java

public void addObject(Object entity) {
    EntityManager em = this.getEMF().createEntityManager();
    try {//from w  w w  .  j a  va2 s.  c o  m
        em.getTransaction().begin();
        em.persist(entity);
        em.getTransaction().commit();
    } finally {
        em.close();
    }
}

From source file:com.soen.ebanking.dao.ObjectDao.java

public void deleteObject(Object object, long id, Class<T> ClassName) {
    EntityManager em = this.getEMF().createEntityManager();
    try {//  w  w  w .ja v  a2s  . co  m
        em.getTransaction().begin();
        T entity = em.find(ClassName, id);
        em.remove(entity);
        em.getTransaction().commit();
    } finally {
        em.close();
    }
}

From source file:ict.DoLoginServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from ww w.  j a  v  a 2s  .  co  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    try {
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("WSPU");
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();

        String _request = request.getParameter("AAA");
        String userID = new String(Base64.decodeBase64(_request));

        String _request_ = request.getParameter("BBB");
        String userPassword = new String(Base64.decodeBase64(_request_));

        //String userID = request.getParameter("userID");
        //String userPassword = request.getParameter("userPassword");
        User tmp = new User();
        tmp.setUserID(userID);
        tmp.setPassword(userPassword);
        System.out.println("*****" + tmp.getUserID());

        User user = entityManager.find(User.class, tmp.getUserID());
        if (user.getPassword().equals(tmp.getPassword())) {
            entityManager.getTransaction().commit();
            entityManager.close();
            entityManagerFactory.close();
            request.getSession(true).setAttribute("user", user.getUserName());
        }

    } catch (Exception e) {
        System.out.println("****ERROR:****" + e.getMessage());
    }
    response.sendRedirect("index.jsp");
}

From source file:br.edimarmanica.fazenda.control.LoadBBControl.java

private boolean load(Pessoa pessoa, String file) {

    EntityManager em = Conexao.getEntityManager();
    em.getTransaction().begin();

    boolean error = false;

    try (CSVParser parser = CSVParser.parse(new File(file), Charset.forName("ISO-8859-1"),
            CSVFormat.EXCEL.withHeader())) {
        for (CSVRecord record : parser) {
            TipoCaixa tc = new TipoCaixa();
            tc.setCdBb(new BigInteger(record.get("Nmero do documento")));

            if (tc.getCdBb() != null) {
                List<TipoCaixa> tcs = daoTipo.search(tc);
                if (tcs != null && tcs.size() == 1) {
                    Caixa caixa = new Caixa();
                    caixa.setCdTipoCaixa(tcs.get(0));
                    caixa.setCdPessoa(pessoa);
                    caixa.setVlCaixa((new BigDecimal(record.get("Valor"))).abs());
                    caixa.setDtPagamento(new Date(record.get("Data")));
                    caixa.setDtVencimento(new Date(record.get("Data")));
                    caixa.setDsCaixa("IMPORTAO BB 02");
                    em.persist(caixa);/*from   w  ww. j  a  v  a2s .  co m*/
                }
            }

        }
    } catch (IOException ex) {
        Logger.getLogger(LoadBBControl.class.getName()).log(Level.SEVERE, null, ex);
        error = true;
    }

    if (!error) {
        em.getTransaction().commit();
    } else {
        em.getTransaction().rollback();
    }
    em.close();
    return !error;
}

From source file:eu.clarin.cmdi.virtualcollectionregistry.VirtualCollectionRegistryMaintenanceImpl.java

protected void purgeDeletedCollections(EntityManager em, final Date nowDatePurge) {
    em.getTransaction().begin();
    TypedQuery<VirtualCollection> q = em.createNamedQuery("VirtualCollection.findAllByState",
            VirtualCollection.class);
    q.setParameter("state", VirtualCollection.State.DELETED);
    q.setParameter("date", nowDatePurge);
    q.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    for (VirtualCollection vc : q.getResultList()) {
        vc.setState(VirtualCollection.State.DEAD);
        em.remove(vc);/* ww w.  j  a  v a  2 s . c o  m*/
        logger.debug("purged virtual collection (id={})", vc.getId());
    }
    em.getTransaction().commit();
}

From source file:eu.clarin.cmdi.virtualcollectionregistry.VirtualCollectionRegistryMaintenanceImpl.java

protected void handleCollectionsInError(EntityManager em, final Date nowDateError) {
    em.getTransaction().begin();
    TypedQuery<VirtualCollection> q = em.createNamedQuery("VirtualCollection.findAllByState",
            VirtualCollection.class);
    q.setParameter("state", VirtualCollection.State.ERROR);
    q.setParameter("date", nowDateError);
    q.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    for (VirtualCollection vc : q.getResultList()) {
        VirtualCollection.State currentState = vc.getState();
        logger.info("Found [{}] in error state.", vc.getName(), currentState);
        //TODO: handle virtual collections in error state
    }// w  w w  .  j  ava 2 s.co  m
    em.getTransaction().commit();
}

From source file:eu.clarin.cmdi.virtualcollectionregistry.VirtualCollectionRegistryMaintenanceImpl.java

protected void allocatePersistentIdentifiers(EntityManager em, final Date nowDateAlloc) {
    em.getTransaction().begin();
    TypedQuery<VirtualCollection> q = em.createNamedQuery("VirtualCollection.findAllByStates",
            VirtualCollection.class);
    List<VirtualCollection.State> states = new LinkedList<>();
    states.add(VirtualCollection.State.PUBLIC_PENDING);
    states.add(VirtualCollection.State.PUBLIC_FROZEN_PENDING);
    q.setParameter("states", states);
    q.setParameter("date", nowDateAlloc);
    q.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    for (VirtualCollection vc : q.getResultList()) {
        allocatePersistentIdentifier(em, vc);
    }// www.j a va  2s.c o m
    em.getTransaction().commit();
}

From source file:com.soen.ebanking.dao.ObjectDao.java

public void updateObject(Object entity, long id, Class<T> ClassName) {
    EntityManager em = this.getEMF().createEntityManager();
    try {//from   w  w  w  . ja  va 2s . c om
        em.getTransaction().begin();
        this.t = (T) em.find(ClassName, id);
        Object orig = entity;
        Object dest = this.t;
        BeanUtils.copyProperties(dest, orig);
        entity = t;
        t = null;
        em.getTransaction().commit();
    } catch (IllegalAccessException ex) {
        Logger.getLogger(ObjectDao.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvocationTargetException ex) {
        Logger.getLogger(ObjectDao.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        em.close();
    }
}