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:com.busimu.core.dao.impl.UserMngDaoPolicyJpaImpl.java

private void initExampleData() throws Exception {
    EntityManager em = emf.createEntityManager();
    try {/*from   w  w  w  . j a  va  2 s. c o  m*/
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        User player1 = new User("student@busimu.com", "ssssss", "s", User.Type.STUDENT);
        player1.setStatus(User.Status.ACTIVE);
        User player2 = new User("zhangsan@busimu.com", "123456", "", User.Type.STUDENT);
        player2.setStatus(User.Status.ACTIVE);
        User player3 = new User("lisi@busimu.com", "123456", "?", User.Type.STUDENT);
        player3.setStatus(User.Status.ACTIVE);
        User teacher = new User("teacher@busimu.com", "tttttt", "t", User.Type.TEACHER);
        teacher.setStatus(User.Status.ACTIVE);
        em.persist(player1);
        em.persist(player2);
        em.persist(player3);
        em.persist(teacher);

        Campaign campaign = teacher.createCampagin("", Campaign.Type.COURSE);
        SimMarket south = campaign.addMarket("??");
        SimMarket central = campaign.addMarket("?");
        SimMarket north = campaign.addMarket("?");
        SimMarket east = campaign.addMarket("?");
        SimMarket west = campaign.addMarket("");
        SimCorporation ibm = south.addCorporation("IBM", new Color(128, 128, 255));
        SimCorporation ericsson = south.addCorporation("Ericsson", Color.BLUE);
        SimCorporation oracle = south.addCorporation("Oracle", Color.RED);
        for (int i = 0; i < 8; i++) {
            campaign.addRound();
        }

        player2.addCampaign(campaign);
        player3.addCampaign(campaign);
        em.persist(campaign);

        Team t1 = new Team("anoym1");
        Team t2 = new Team("anoym2");
        Team t3 = new Team("anoym3");
        t1.addCorporation(ibm);
        t2.addCorporation(ericsson);
        t3.addCorporation(oracle);
        em.persist(t1);
        em.persist(t2);
        em.persist(t3);

        Campaign runningCampaign = teacher.createCampagin("", Campaign.Type.COURSE);
        SimMarket m1 = runningCampaign.addMarket("");
        SimMarket m2 = runningCampaign.addMarket("");
        SimMarket m3 = runningCampaign.addMarket("");
        SimCorporation corp1 = m1.addCorporation("", Color.ORANGE);
        for (int i = 0; i < 3; i++) {
            runningCampaign.addRound();
        }
        player1.addCampaign(runningCampaign);
        player2.addCampaign(runningCampaign);
        player3.addCampaign(runningCampaign);
        runningCampaign.setStatus(Campaign.Status.ONGOING);

        Team t11 = new Team("anoym11");
        t11.addCorporation(corp1);
        t11.addUser(player1);
        t11.addUser(player2);
        t11.addUser(player3);
        em.persist(t11);

        tx.commit();
    } finally {
        em.close();
    }
}

From source file:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java

/**
 * Deletes a news article from the db//from  w  w  w.  j  a v a  2 s  .  com
 *
 * @param entity The article to delete
 */
public void delete(UXBEntity entity) throws Exception {

    EntityManager em = null;
    EntityTransaction tx = null;
    try {

        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();

        //         Query query = em.createQuery(new StringBuilder().append("SELECT x FROM Article x WHERE x.aid = ").append(entity.getUuid()).append(" AND x.language='").append(entity.getLanguage()).append("'").toString());
        Query query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM article x WHERE x.aid = :fsid AND x.language=:language").toString());
        query.setParameter("fsid", Long.parseLong(entity.getUuid()));
        query.setParameter("language", entity.getLanguage());

        if (!query.getResultList().isEmpty()) {
            Article art = (Article) query.getSingleResult();
            em.remove(art);
        }
        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.setRollbackOnly();
            throw e;
        }
        logger.error("Failure while deleting from the database", e);
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }
}

From source file:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java

/**
 * Deletes every article older than the creationTime of the UXBEntity
 *
 * @param entity Entity containing the expireDate (= createTime of the entity)
 *///from  w w  w.j  ava  2  s  . c  o m
public void cleanup(UXBEntity entity) throws Exception {

    EntityManager em = null;
    EntityTransaction tx = null;
    try {

        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();

        Query query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM article x WHERE x.lastmodified<:expiredate ").toString());
        query.setParameter("expiredate", entity.getCreateTime());

        if (!query.getResultList().isEmpty()) {
            for (Object obj : query.getResultList()) {
                Article art = (Article) obj;
                em.remove(art);
            }
        }
        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.setRollbackOnly();
            throw e;
        }
        logger.error("Failure while deleting from the database", e);
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }

}

From source file:uk.ac.horizon.ug.locationbasedgame.author.CRUDServlet.java

/** Create on POST.
 * E.g. curl -d '{...}' http://localhost:8888/author/configuration/
 * @param req/*from   w ww .j ava  2 s  . c  o  m*/
 * @param resp
 * @throws ServletException
 * @throws IOException
 */
private void doCreate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // TODO Auto-generated method stub
    try {
        Object o = parseObject(req);
        Key key = validateCreate(o);
        // try adding
        EntityManager em = EMF.get().createEntityManager();
        EntityTransaction et = em.getTransaction();
        try {
            et.begin();
            if (em.find(getObjectClass(), key) != null)
                throw new RequestException(HttpServletResponse.SC_CONFLICT,
                        "object already exists (" + key + ")");
            em.persist(o);
            et.commit();
            logger.info("Added " + o);
        } finally {
            if (et.isActive())
                et.rollback();
            em.close();
        }
        resp.setCharacterEncoding(ENCODING);
        resp.setContentType(JSON_MIME_TYPE);
        Writer w = new OutputStreamWriter(resp.getOutputStream(), ENCODING);
        JSONWriter jw = new JSONWriter(w);
        listObject(jw, o);
        w.close();
    } catch (RequestException e) {
        resp.sendError(e.getErrorCode(), e.getMessage());
    } catch (Exception e) {
        logger.log(Level.WARNING, "Getting object of type " + getObjectClass(), e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        return;
    }
}

From source file:org.apache.ranger.audit.destination.DBAuditDestination.java

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

    if (trx != null && !trx.isActive()) {
        trx.begin();
    }/*from www.j  a  va2 s .c  om*/

    if (trx == null) {
        logger.warn("DBAuditDestination.beginTransaction(): trx is null");
    }

    return trx != null;
}

From source file:info.dolezel.jarss.rest.v1.ws.UnreadNotificationEndpoint.java

@OnWebSocketMessage
public void onMessage(Session session, String text) {
    EntityManager em = null;// w w w. j av a  2  s .c  o  m
    EntityTransaction tx = null;
    try {
        JsonReader reader;
        JsonObject object;
        Token token;

        em = HibernateUtil.getEntityManager();
        tx = em.getTransaction();

        tx.begin();

        reader = Json.createReader(new StringReader(text));
        object = reader.readObject();

        token = Token.loadToken(em, object.getString("token"));
        if (token == null) {
            tx.rollback();

            Logger.getLogger(UnreadNotificationEndpoint.class.getName()).log(Level.WARNING,
                    "Invalid token provided over WebSocket");
            session.close();
        } else {
            synchronized (sessions) {
                sessions.put(session, token.getUser());
            }
            synchronized (userSessions) {
                userSessions.put(token.getUser(), session);
            }
        }

        tx.commit();
    } catch (Exception ex) {
        if (tx != null)
            tx.rollback();

        Logger.getLogger(UnreadNotificationEndpoint.class.getName()).log(Level.SEVERE,
                "Error processing incoming WebSocket message", ex);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.sakaiproject.kernel.authz.simple.AclListener.java

/**
 * {@inheritDoc}/*www  . j a v  a 2s  .c  o m*/
 *
 * @see org.sakaiproject.kernel.jcr.api.JcrContentListener#onEvent(int,
 *      java.lang.String, java.lang.String, java.lang.String)
 */
public void handleEvent(int type, String userID, String filePath) {
    try {
        if ((type == Event.PROPERTY_ADDED || type == Event.PROPERTY_CHANGED
                || type == Event.PROPERTY_REMOVED)) {

            ArrayList<AclIndexBean> toCreate = new ArrayList<AclIndexBean>();
            ArrayList<AclIndexBean> toUpdate = new ArrayList<AclIndexBean>();
            ArrayList<AclIndexBean> toDelete = new ArrayList<AclIndexBean>();

            Query query = entityManager.createNamedQuery(AclIndexBean.Queries.FINDBY_PATH);
            query.setParameter(AclIndexBean.QueryParams.FINDBY_PATH_PATH, filePath);
            List<?> currentIndex = query.getResultList();

            try {
                Node node = jcrNodeFactoryService.getNode(filePath);
                Property acl = node.getProperty(JCRConstants.MIX_ACL);
                for (Value val : acl.getValues()) {
                    AccessControlStatement acs = new JcrAccessControlStatementImpl(val.getString());

                    switch (type) {
                    case Event.PROPERTY_ADDED:
                        if (inList(acs, currentIndex) == null) {
                            toCreate.add(convert(acs));
                        }
                        break;
                    case Event.PROPERTY_CHANGED:
                        AclIndexBean indexBean = inList(acs, currentIndex);
                        if (indexBean != null) {
                            toUpdate.add(indexBean);
                        }
                        break;
                    case Event.PROPERTY_REMOVED:
                        if (inList(acs, currentIndex) == null) {
                            toDelete.add(convert(acs));
                        }
                        break;
                    }
                }

                EntityTransaction trans = entityManager.getTransaction();
                trans.begin();
                try {
                    if (!toCreate.isEmpty()) {
                        for (AclIndexBean bean : toCreate) {
                            entityManager.persist(bean);
                        }
                    } else if (!toUpdate.isEmpty()) {
                        for (AclIndexBean bean : toUpdate) {
                            entityManager.persist(bean);
                        }
                    } else if (!toDelete.isEmpty()) {
                        for (AclIndexBean bean : toDelete) {
                            entityManager.remove(bean);
                        }
                    }
                    trans.commit();
                } catch (Exception e) {
                    LOG.error("Transaction rolled back due to a problem when updating the ACL index: "
                            + e.getMessage(), e);
                    trans.rollback();
                }
            } catch (PathNotFoundException e) {
                // nothing to care about. this happens when there is no ACL
                // on the node
            } catch (RepositoryException e) {
                // nothing we can do
                LOG.error(e.getMessage(), e);
            } catch (JCRNodeFactoryServiceException e) {
                // nothing we can do
                LOG.error(e.getMessage(), e);
            }
        }
    } finally {
        try {
            cacheManagerService.unbind(CacheScope.REQUEST);
        } catch (Exception ex) {
            // not interested
        }
        try {
            cacheManagerService.unbind(CacheScope.THREAD);
        } catch (Exception ex) {
            // not interested
        }
    }
}

From source file:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java

/**
 * Add or update a news article in the db
 *
 * @param entity The NewsItem//from   w  w w  . j  a v  a 2 s . c o m
 */
public void add(UXBEntity entity) throws Exception {

    Article art = buildArticle(entity);

    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();

        Query query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM article x WHERE x.aid = :fsid AND x.language=:language").toString());
        query.setParameter("fsid", art.getAid());
        query.setParameter("language", art.getLanguage());

        /*
        * If the item exists in the db, we update the content and the title of the existing item
        */
        if (query.getResultList().size() > 0) {
            Article db = (Article) query.getSingleResult();
            db.setContent(art.getContent());
            db.setTitle(art.getTitle());
            db.setUrl(art.getUrl());
            db.setCreated(art.getCreated());
            db.setAid(art.getAid());
            db.setLanguage(art.getLanguage());
            db.setVersion(art.getVersion());
            db.setLastmodified(art.getLastmodified());

            art = db;
        }
        // save to db
        em.persist(art);
        em.flush();

        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.setRollbackOnly();
            throw e;
        }
        logger.error("Failure while writing to the database", e);
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }
}

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   w w w .ja va2 s .c  o m*/
 * 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:nl.b3p.kaartenbalie.service.SecurityRealm.java

@Override
public Principal getAuthenticatedPrincipal(String username, String password) {
    Object identity = null;/*from www  . ja va 2s. c om*/
    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 " + "lower(u.username) = lower(:username) ")
                    .setParameter("username", username).getSingleResult();
            return user;
        } catch (NoResultException nre) {
            return null;
        }
    } catch (Exception e) {
        log.error("Exception getting authenticated user from database", 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;
}