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.github.jinahya.persistence.ShadowTest.java

@Test(enabled = false, invocationCount = 1)
public void testPersist() {
    final EntityManager manager = LocalPU.createEntityManager();
    try {//from   w  ww  .  ja  v  a2s  . c  o m
        final EntityTransaction transaction = manager.getTransaction();
        transaction.begin();
        try {
            final Shadow shadow = persistInstance(manager, null, null);
            transaction.commit();
        } catch (Exception e) {
            LocalPU.printConstraintViolation(e);
            transaction.rollback();
            e.printStackTrace(System.err);
            Assert.fail(e.getMessage());
        }
    } finally {
        manager.close();
    }
}

From source file:test.unit.be.fedict.hsm.entity.PersistenceTest.java

@Test
public void testApplicationKey() throws Exception {
    ApplicationEntity applicationEntity = new ApplicationEntity("app");

    EntityTransaction entityTransaction = this.entityManager.getTransaction();
    entityTransaction.begin();
    this.entityManager.persist(applicationEntity);
    entityTransaction.commit();//from   w w w.ja  v a 2s .c om
    long appId = applicationEntity.getId();

    entityTransaction.begin();
    applicationEntity = this.entityManager.find(ApplicationEntity.class, appId);
    ApplicationKeyEntity applicationKeyEntity = new ApplicationKeyEntity(applicationEntity, "alias");
    ApplicationKeyEntity applicationKeyEntity2 = new ApplicationKeyEntity(applicationEntity, "alias2");
    this.entityManager.persist(applicationKeyEntity);
    this.entityManager.persist(applicationKeyEntity2);
    entityTransaction.commit();
    this.entityManager.close();

    this.entityManager = this.entityManagerFactory.createEntityManager();
    entityTransaction = this.entityManager.getTransaction();
    entityTransaction.begin();
    applicationKeyEntity = this.entityManager.find(ApplicationKeyEntity.class,
            new ApplicationKeyId(appId, "alias"));
    assertEquals("alias", applicationKeyEntity.getName());
    assertEquals("app", applicationKeyEntity.getApplication().getName());

    List<ApplicationKeyEntity> resultList = ApplicationKeyEntity.getApplicationKeys(this.entityManager,
            applicationEntity);
    assertEquals(2, resultList.size());
    for (ApplicationKeyEntity result : resultList) {
        LOG.debug("key: " + result.getName());
    }
}

From source file:com.github.jinahya.persistence.ShadowTest.java

@Test(enabled = false, invocationCount = 1)
public void testPuthenticate() {
    final EntityManager manager = LocalPU.createEntityManager();
    try {/*from  w ww.  j ava 2 s.  c o  m*/
        final EntityTransaction transaction = manager.getTransaction();
        transaction.begin();
        try {
            final String username = newUsername(manager);
            final byte[] password = newPassword();

            final Shadow shadow = persistInstance(manager, username, password);

            Assert.assertTrue(shadow.puthenticate(shadow, password));

            transaction.commit();
        } catch (Exception e) {
            LocalPU.printConstraintViolation(e);
            transaction.rollback();
            e.printStackTrace(System.err);
            Assert.fail(e.getMessage());
        }
    } finally {
        manager.close();
    }
}

From source file:org.sakaiproject.kernel.social.FriendsListener.java

/**
 * {@inheritDoc}/*from  w ww  .j  ava  2 s  . c  o m*/
 *
 * @see org.sakaiproject.kernel.jcr.api.JcrContentListener#onEvent(int,
 *      java.lang.String, java.lang.String, java.lang.String)
 */
public void onEvent(int type, String userID, String filePath, String fileName) {
    if (filePath.startsWith(privatePathBase)) {
        System.err.println("++++++++++++++++++++++++++ Checking event matches " + fileName + " "
                + KernelConstants.FRIENDS_FILE + " " + fileName.equals(KernelConstants.FRIENDS_FILE));
        if (fileName.equals(KernelConstants.FRIENDS_FILE)) {
            String friendsBody = null;
            InputStream in = null;
            try {
                in = jcrNodeFactoryService.getInputStream(filePath);
                friendsBody = IOUtils.readFully(in, "UTF-8");
                if (friendsBody != null && friendsBody.length() > 0) {
                    System.err.println("Converting " + friendsBody + " to Bean");
                    FriendsBean friendsBean = beanConverter.convertToObject(friendsBody, FriendsBean.class);

                    Query query = entityManager.createNamedQuery(FriendsIndexBean.FINDBY_UUID);
                    query.setParameter(FriendsIndexBean.PARAM_UUID, friendsBean.getUuid());
                    List<?> friendsIndexBeanList = query.getResultList();
                    List<FriendsIndexBean> toAdd = Lists.newArrayList();
                    List<FriendsIndexBean> toRemove = Lists.newArrayList();
                    List<FriendsIndexBean> toUpdate = Lists.newArrayList();

                    for (Object o : friendsIndexBeanList) {
                        FriendsIndexBean friendIndexBean = (FriendsIndexBean) o;
                        if (!friendsBean.hasFriend(friendIndexBean.getFriendUuid())) {
                            toRemove.add(friendIndexBean);
                        }
                    }

                    for (FriendBean friendBean : friendsBean.getFriends()) {
                        boolean found = false;
                        String newFriendUuid = friendBean.getFriendUuid();
                        for (Object o : friendsIndexBeanList) {
                            FriendsIndexBean friendIndexBean = (FriendsIndexBean) o;
                            String friendUuid = friendIndexBean.getFriendUuid();
                            if (newFriendUuid.equals(friendUuid)) {
                                found = true;
                                if (friendBean.getLastUpdate() > friendIndexBean.getLastUpdate()) {
                                    UserProfile userProfile = profileResolverService.resolve(friendUuid);
                                    friendIndexBean.copy(friendBean, userProfile);

                                    toUpdate.add(friendIndexBean);
                                }
                                break;
                            }
                        }
                        if (!found) {
                            UserProfile userProfile = profileResolverService.resolve(newFriendUuid);
                            toAdd.add(new FriendsIndexBean(friendBean, userProfile));
                        }
                    }

                    EntityTransaction transaction = entityManager.getTransaction();
                    transaction.begin();
                    for (FriendsIndexBean gm : toRemove) {
                        entityManager.remove(gm);
                    }
                    for (FriendsIndexBean gm : toAdd) {
                        entityManager.persist(gm);
                    }
                    for (FriendsIndexBean gm : toUpdate) {
                        entityManager.persist(gm);
                    }
                    transaction.commit();
                }

            } catch (UnsupportedEncodingException e) {
                LOG.error(e);
            } catch (IOException e) {
                LOG.warn("Failed to read userenv " + filePath + " cause :" + e.getMessage());
                if (debug)
                    LOG.debug(e);
            } catch (RepositoryException e) {
                LOG.warn("Failed to read userenv for " + filePath + " cause :" + e.getMessage());
                if (debug)
                    LOG.debug(e);
            } catch (JCRNodeFactoryServiceException e) {
                LOG.warn("Failed to read userenv for " + filePath + " cause :" + e.getMessage());
                if (debug)
                    LOG.debug(e);
            } finally {
                try {
                    in.close();
                } catch (Exception ex) {
                }
            }
        }
    }
}

From source file:com.github.jinahya.persistence.ShadowTest.java

@Test(enabled = true, invocationCount = 1)
public void testNassword0() {
    final EntityManager manager = LocalPU.createEntityManager();
    try {//from w w w.j a  v  a 2s .c  o  m
        final EntityTransaction transaction = manager.getTransaction();
        transaction.begin();
        try {
            final String username = newUsername(manager);
            final byte[] password = newPassword();
            Shadow shadow = persistInstance(manager, username, password);
            Assert.assertTrue(shadow.puthenticate(shadow, password));
            System.out.println("=========================================");
            LOGGER.log(Level.INFO, "mortons: {0}", MORTONS(manager, 0, 1024));
            final byte[] nassword = newPassword();
            shadow.nassword(shadow, password, nassword);
            shadow = manager.merge(shadow);
            manager.flush();
            System.out.println("=========================================");
            LOGGER.log(Level.INFO, "mortons: {0}", MORTONS(manager, 0, 1024));
            Assert.assertFalse(shadow.puthenticate(shadow, password));
            Assert.assertTrue(shadow.puthenticate(shadow, nassword));
            transaction.commit();
        } catch (Exception e) {
            transaction.rollback();
            e.printStackTrace(System.err);
            Assert.fail(e.getMessage());
        }
    } finally {
        manager.close();
    }
}

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.test.NewsITCase.java

/**
 * Test persistence./*from w  ww .  j a  v a 2 s  . co  m*/
 *
 * @throws Exception the exception
 */
@Test
public void testPersistence() throws Exception {

    long size = countNews();

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

        News news = new News();

        news.setContent("Spider-man was seen.");
        news.setHeadline("The amazing spider-man");
        news.setFs_id(1l);
        news.setLanguage("DE");
        news.setTeaser("spider-man");

        NewsCategory sport = new NewsCategory();
        sport.setFs_id(2l);
        sport.setName("Sport");
        sport.setLanguage("DE");

        NewsMetaCategory soccer = new NewsMetaCategory();
        soccer.setFs_id(3l);
        soccer.setLanguage("DE");
        soccer.setName("Fussball");

        if (sport.getMetaCategories() == null) {
            sport.setMetaCategories(new ArrayList<NewsMetaCategory>());
        }
        sport.getMetaCategories().add(soccer);

        if (news.getCategories() == null) {
            news.setCategories(new ArrayList<NewsCategory>());
        }
        news.getCategories().add(sport);

        em.persist(news);
        em.flush();
        tx.commit();

        assertEquals("Entity not filled", size + 1, countNews());

        Query query = em.createQuery("SELECT mc FROM metaCategory mc WHERE fs_id=3");
        NewsMetaCategory metaCat = (NewsMetaCategory) query.getSingleResult();
        assertNotNull(metaCat);

        query = em.createQuery(
                "SELECT c FROM category c join c.metaCategories mc WHERE mc.fs_id=" + metaCat.getFs_id());
        NewsCategory category = (NewsCategory) query.getSingleResult();
        assertNotNull(category);

        query = em.createQuery("SELECT n FROM news n join n.categories c WHERE c.fs_id=" + category.getFs_id());
        News n = (News) query.getSingleResult();
        assertNotNull(n);

    } finally {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }

}

From source file:com.github.jinahya.persistence.ShadowTest.java

@Test(enabled = false, invocationCount = 1)
public void testNassword() {
    final EntityManager manager = LocalPU.createEntityManager();
    try {//from   www. ja va  2s.c  o  m
        final EntityTransaction transaction = manager.getTransaction();
        transaction.begin();
        try {
            final String username = newUsername(manager);
            byte[] password = newPassword();

            Shadow shadow = persistInstance(manager, username, password);
            LOGGER.log(Level.INFO, "morton.list: {0}", MORTONS(manager, 0, 1024));

            for (int i = 0; i < 3; i++) {
                System.out.println("-------------------------------------");
                Assert.assertTrue(shadow.puthenticate(shadow, password));
                final byte[] nassword = newPassword();
                shadow.nassword(shadow, password, nassword);
                shadow = manager.merge(shadow);
                manager.flush();
                LOGGER.log(Level.INFO, "morton.list: {0}", MORTONS(manager, 0, 1024));
                Assert.assertFalse(shadow.puthenticate(shadow, password));
                Assert.assertTrue(shadow.puthenticate(shadow, nassword));
                password = nassword;
            }

            transaction.commit();
        } catch (Exception e) {
            LocalPU.printConstraintViolation(e);
            transaction.rollback();
            e.printStackTrace(System.err);
            Assert.fail(e.getMessage());
        }
    } finally {
        manager.close();
    }
}

From source file:net.sf.ehcache.openjpa.datacache.TestEhCache.java

@Test
public void testClearCache() {
    EntityManagerFactory emf = em.getEntityManagerFactory();

    EntityManager entityManager = emf.createEntityManager();
    EntityTransaction tx = entityManager.getTransaction();
    tx.begin();
    SubQObject subQObject = new SubQObject("one", "two");
    QObject qObject = new QObject("one");
    PObject pObject = new PObject("one");
    entityManager.persist(subQObject);/*from  w w  w .j  ava 2  s.c o  m*/
    entityManager.persist(qObject);
    entityManager.persist(pObject);
    tx.commit();
    assertTrue(getCache(subQObject.getClass()).contains(getOpenJPAId(subQObject, subQObject.getId())));
    assertTrue(getCache(qObject.getClass()).contains(getOpenJPAId(qObject, qObject.getId())));
    assertTrue(getCache(pObject.getClass()).contains(getOpenJPAId(pObject, pObject.getId())));
    evictAllOfType(qObject.getClass(), false);
    assertFalse("QObject entries should be all gone",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(qObject.getClass(), qObject.getId()));
    assertTrue("SubQObject entries should still be in the cache",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(subQObject.getClass(), subQObject.getId()));
    assertTrue("This PObject object should still be in the cache",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(pObject.getClass(), pObject.getId()));
    tx = entityManager.getTransaction();
    tx.begin();
    qObject = new QObject("two");
    entityManager.persist(qObject);
    tx.commit();
    evictAllOfType(qObject.getClass(), true);
    assertFalse("QObject entries should be all gone",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(qObject.getClass(), qObject.getId()));
    assertFalse("SubQObject entries should be all gone",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(subQObject.getClass(), subQObject.getId()));
    assertTrue("This PObject object should still be in the cache",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(pObject.getClass(), pObject.getId()));
    tx = entityManager.getTransaction();
    tx.begin();
    qObject = new QObject("three");
    entityManager.persist(qObject);
    subQObject = new SubQObject("two", "two");
    entityManager.persist(subQObject);
    tx.commit();
    evictAllOfType(subQObject.getClass(), false);
    assertTrue("QObject entries should still be in the cache",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(qObject.getClass(), qObject.getId()));
    assertFalse("SubQObject entries should be all gone",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(subQObject.getClass(), subQObject.getId()));
    assertTrue("This PObject object should still be in the cache",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(pObject.getClass(), pObject.getId()));
    tx = entityManager.getTransaction();
    tx.begin();
    subQObject = new SubQObject("three", "three");
    entityManager.persist(subQObject);
    tx.commit();
    evictAllOfType(pObject.getClass(), true);
    assertTrue("QObject entries should still be in the cache",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(qObject.getClass(), qObject.getId()));
    assertTrue("SubQObject entries should still be in the cache",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(subQObject.getClass(), subQObject.getId()));
    assertFalse("This PObject object should be gone",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(pObject.getClass(), pObject.getId()));
}

From source file:org.apache.juddi.api.impl.UDDICustodyTransferImpl.java

public void transferEntities(TransferEntities body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*from   w  w w.  j ava  2 s  . c o  m*/
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidateCustodyTransfer(publisher).validateTransferEntities(em, body);

        // Once validated, the ownership transfer is as simple as switching the publisher
        KeyBag keyBag = body.getKeyBag();
        List<String> keyList = keyBag.getKey();
        for (String key : keyList) {
            UddiEntity uddiEntity = em.find(UddiEntity.class, key);
            uddiEntity.setAuthorizedName(publisher.getAuthorizedName());

            if (uddiEntity instanceof BusinessEntity) {
                BusinessEntity be = (BusinessEntity) uddiEntity;

                List<BusinessService> bsList = be.getBusinessServices();
                for (BusinessService bs : bsList) {
                    bs.setAuthorizedName(publisher.getAuthorizedName());

                    List<BindingTemplate> btList = bs.getBindingTemplates();
                    for (BindingTemplate bt : btList)
                        bt.setAuthorizedName(publisher.getAuthorizedName());
                }
            }
        }

        // After transfer is finished, the token can be removed
        org.uddi.custody_v3.TransferToken apiTransferToken = body.getTransferToken();
        String transferTokenId = new String(apiTransferToken.getOpaqueToken());
        org.apache.juddi.model.TransferToken modelTransferToken = em
                .find(org.apache.juddi.model.TransferToken.class, transferTokenId);
        em.remove(modelTransferToken);

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(CustodyTransferQuery.TRANSFER_ENTITIES, QueryStatus.SUCCESS, procTime);

    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }

}

From source file:org.apache.juddi.api.impl.UDDICustodyTransferImpl.java

@SuppressWarnings("unchecked")
public void discardTransferToken(DiscardTransferToken body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//w w  w.j  a  v  a2 s  .com
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidateCustodyTransfer(publisher).validateDiscardTransferToken(em, body);

        org.uddi.custody_v3.TransferToken apiTransferToken = body.getTransferToken();
        if (apiTransferToken != null) {
            String transferTokenId = new String(apiTransferToken.getOpaqueToken());
            org.apache.juddi.model.TransferToken modelTransferToken = em
                    .find(org.apache.juddi.model.TransferToken.class, transferTokenId);
            if (modelTransferToken != null)
                em.remove(modelTransferToken);
        }

        KeyBag keyBag = body.getKeyBag();
        if (keyBag != null) {
            List<String> keyList = keyBag.getKey();
            Vector<DynamicQuery.Parameter> params = new Vector<DynamicQuery.Parameter>(0);
            for (String key : keyList) {
                // Creating parameters for key-checking query
                DynamicQuery.Parameter param = new DynamicQuery.Parameter("UPPER(ttk.entityKey)",
                        key.toUpperCase(), DynamicQuery.PREDICATE_EQUALS);

                params.add(param);
            }

            // Find the associated transfer tokens and remove them.
            DynamicQuery getTokensQry = new DynamicQuery();
            getTokensQry.append("select distinct ttk.transferToken from TransferTokenKey ttk").pad();
            getTokensQry.WHERE().pad().appendGroupedOr(params.toArray(new DynamicQuery.Parameter[0]));

            Query qry = getTokensQry.buildJPAQuery(em);
            List<org.apache.juddi.model.TransferToken> tokensToDelete = qry.getResultList();
            if (tokensToDelete != null && tokensToDelete.size() > 0) {
                for (org.apache.juddi.model.TransferToken tt : tokensToDelete)
                    em.remove(tt);
            }
        }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(CustodyTransferQuery.DISCARD_TRANSFERTOKEN, QueryStatus.SUCCESS, procTime);

    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}