Example usage for javax.persistence EntityTransaction rollback

List of usage examples for javax.persistence EntityTransaction rollback

Introduction

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

Prototype

public void rollback();

Source Link

Document

Roll back the current resource transaction.

Usage

From source file:es.us.isa.ideas.utilities.PopulateDatabase.java

public static void main(String[] args) {

    ApplicationContext ctx;//  www  . ja v a 2s. co m
    EntityManagerFactory emf;
    EntityManager em;
    EntityTransaction et;

    ctx = new ClassPathXmlApplicationContext("utilities/PopulateDatabase.xml");

    emf = Persistence.createEntityManagerFactory("persistenceUnit");
    em = emf.createEntityManager();
    et = em.getTransaction();

    et.begin();
    try {
        for (Entry<String, Object> entry : ctx.getBeansWithAnnotation(Entity.class).entrySet()) {
            em.persist(entry.getValue());
            System.out.println(String.format("Persisting (%s, %s@%d)", entry.getKey(),
                    entry.getValue().getClass().getName(), entry.getValue().hashCode()));
        }
        et.commit();
    } catch (Exception oops) {
        oops.printStackTrace();
        et.rollback();
        oops.printStackTrace();
    } finally {
        if (em.isOpen())
            em.close();
        if (emf.isOpen())
            emf.close();
        ((ClassPathXmlApplicationContext) ctx).close();
    }
}

From source file:utilities.PopulateDatabase.java

public static void main(String[] args) throws Throwable {
    ApplicationContext applicationContext;
    EntityManagerFactory entityManagerFactory;
    EntityManager entityManager;/*w ww.java2s . co m*/
    EntityTransaction entityTransaction;

    applicationContext = new ClassPathXmlApplicationContext("classpath:PopulateDatabase.xml");

    entityManagerFactory = Persistence.createEntityManagerFactory(PersistenceUnit);
    entityManager = entityManagerFactory.createEntityManager();
    entityTransaction = entityManager.getTransaction();

    initialise(entityManagerFactory, entityManager);

    entityTransaction.begin();
    try {
        for (Entry<String, Object> entry : applicationContext.getBeansWithAnnotation(Entity.class).entrySet()) {
            String beanName;
            DomainEntity entity;

            beanName = entry.getKey();
            entity = (DomainEntity) entry.getValue();
            entityManager.persist(entity);
            System.out.println(String.format("Persisting (%s, %s, %d)", beanName, entity.getClass().getName(),
                    entity.getId()));
        }
        entityTransaction.commit();
    } catch (Exception oops) {
        oops.printStackTrace();
        entityTransaction.rollback();
    } finally {
        if (entityManager.isOpen())
            entityManager.close();
        if (entityManagerFactory.isOpen())
            entityManagerFactory.close();
    }
}

From source file:org.spc.ofp.tubs.domain.common.CommonRepository.java

/**
  * rollbackQuietly rolls back a pending EntityTransaction.
  * @param transaction Pending EntityTransaction, can be null.
  *//*from   ww  w  . j  av a 2s .c  o  m*/
private static void rollbackQuietly(final EntityTransaction transaction) {
    if (null == transaction) {
        return;
    }
    try {
        if (transaction.isActive()) {
            transaction.rollback();
        }
    } catch (Exception ignoreMe) {
    } //NOPMD
}

From source file:org.apache.juddi.validation.ValidateValueSetValidation.java

public static Tmodel GetTModel_MODEL_IfExists(String tmodelKey) throws ValueNotAllowedException {
    EntityManager em = PersistenceManager.getEntityManager();

    Tmodel model = null;/*from  w w w.  j ava2s . c o m*/
    if (em == null) {
        //this is normally the Install class firing up
        log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullEM"));
        return null;
    } else {

        EntityTransaction tx = em.getTransaction();
        try {

            tx.begin();
            model = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey);
            tx.commit();
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            em.close();
        }

    }
    return model;
}

From source file:org.apache.oozie.tools.OozieDBImportCLI.java

private static void importFrom(EntityManager entityManager, ZipFile zipFile, String table, Class<?> clazz,
        String fileName) throws JPAExecutorException, IOException {
    EntityTransaction transaction = entityManager.getTransaction();
    transaction.begin();// ww  w .j  av  a2 s .  c  o  m
    try {
        int size = importFromJSONtoDB(entityManager, zipFile, fileName, clazz);
        transaction.commit();
        System.out.println(size + " rows imported to " + table);
    } catch (Exception e) {
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw new RuntimeException("Import failed to table " + table + ".", e);
    }
}

From source file:org.apache.juddi.validation.ValidateValueSetValidation.java

/**
 * return the publisher/* w ww.  ja va 2  s  . c  om*/
 *
 * @param tmodelKey
 * @return
 * @throws ValueNotAllowedException
 */
public static TModel GetTModel_API_IfExists(String tmodelKey) throws ValueNotAllowedException {
    EntityManager em = PersistenceManager.getEntityManager();

    TModel apitmodel = null;
    if (em == null) {
        //this is normally the Install class firing up
        log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullEM"));
        return null;
    } else {

        EntityTransaction tx = em.getTransaction();
        try {
            Tmodel modelTModel = null;
            tx.begin();
            modelTModel = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey);
            if (modelTModel != null) {
                apitmodel = new TModel();
                try {
                    MappingModelToApi.mapTModel(modelTModel, apitmodel);
                } catch (DispositionReportFaultMessage ex) {
                    log.warn(ex);
                    apitmodel = null;
                }

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

    }
    return apitmodel;
}

From source file:org.apache.juddi.config.Install.java

/**
 * Checks if there is a database with a root publisher. If it is not found
 * an//from   www  .j a v  a 2  s  .  c o  m
 * 
 * @param config
 * @return true if it finds a database with the root publisher in it.
 * @throws ConfigurationException
 */
protected static boolean alreadyInstalled(Configuration config) throws ConfigurationException {

    String rootPublisherStr = config.getString(Property.JUDDI_ROOT_PUBLISHER);
    org.apache.juddi.model.Publisher publisher = null;
    int numberOfTries = 0;
    while (numberOfTries++ < 100) {
        EntityManager em = PersistenceManager.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            publisher = em.find(org.apache.juddi.model.Publisher.class, rootPublisherStr);
            tx.commit();
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            em.close();
        }
        if (publisher != null)
            return true;

        if (config.getBoolean(Property.JUDDI_LOAD_INSTALL_DATA, Property.DEFAULT_LOAD_INSTALL_DATA)) {
            log.debug("Install data not yet installed.");
            return false;
        } else {
            try {
                log.info("Install data not yet installed.");
                log.info("Going to sleep and retry...");
                Thread.sleep(1000l);
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
    throw new ConfigurationException("Could not load the Root node data. Please check for errors.");
}

From source file:es.uvigo.ei.sing.rubioseq.gui.util.DBInitializer.java

/**
 * This method is responsible for the initializacion of the BD, that is:
 * - Creating the default RUbioSeqConfiguration.
 * - Creating the default users./*from   www  .j a  v  a 2s .  c  om*/
 * - Creating a datastore pointing to "/" for the admin user.
 * 
 * This method also plays a key role in the deployment of the application 
 * since it prints the message "[DBInitializer] DB initialized." which is
 * triggered by the launch-rubioseq-gui.sh in order to know that the app. is
 * deployed and launch a browser.
 * 
 * @author hlfernandez
 */
static void initDatabase() {
    System.out.println("[DBInitializer] Initializing DB ...");

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("rubioseq-database");
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = null;
    try {
        /*
         * Store Global Configuration
         */
        if (em.createQuery("SELECT u FROM RUbioSeqConfiguration u").getResultList().size() == 0) {
            RUbioSeqConfiguration config = new RUbioSeqConfiguration();
            config.setRubioseqCommand("/opt/RUbioSeq3.7/RUbioSeq.pl");
            config.setPrivateDatastoresRootDirectory("/path/to/private/datastores/root");
            config.setCreatePrivateDatastoresOnUserRegistration(false);

            tx = em.getTransaction();
            try {
                tx.begin();
                em.persist(config);
                tx.commit();
            } finally {
                if (tx != null && tx.isActive()) {
                    tx.rollback();
                }
            }
        }
        /*
         * Create Default Users
         */
        if (em.createQuery("SELECT u FROM User u").getResultList().size() == 0) {
            User user = new User();
            user.setUsername("rubiosequser");
            user.setPassword(DigestUtils.md5Hex("rubioseqpass"));
            user.setAdmin(false);
            user.setEmail("rubiosequser@rubioseg.org");

            tx = em.getTransaction();
            try {
                tx.begin();
                em.persist(user);
                tx.commit();
            } finally {
                if (tx != null && tx.isActive()) {
                    tx.rollback();
                }
            }

            user = new User();
            user.setUsername("admin");
            user.setPassword(DigestUtils.md5Hex("admin"));
            user.setAdmin(true);
            user.setEmail("rubiosequser@rubioseg.org");

            tx = em.getTransaction();
            try {
                tx.begin();
                em.persist(user);
                tx.commit();
            } finally {
                if (tx != null && tx.isActive()) {
                    tx.rollback();
                }
            }
        }
        /*
         * Create Default Datastores
         */
        boolean createDefaultAdminDatastore = true;
        List<User> adminUsers = getAdminUsers(em);
        @SuppressWarnings("unchecked")
        List<DataStore> datastores = (List<DataStore>) em.createQuery("SELECT d FROM DataStore d")
                .getResultList();
        for (User adminUser : adminUsers) {
            if (datastores.size() == 0) {
                createDefaultAdminDatastore = true;
            } else {
                for (DataStore d : datastores) {
                    if (d.getUser() != null && d.getUser().equals(adminUser) && d.getPath().equals("/")) {
                        createDefaultAdminDatastore = false;
                    }
                }
            }
            if (createDefaultAdminDatastore) {
                DataStore adminDS = new DataStore();
                adminDS.setUser(adminUser);
                adminDS.setPath("/");
                adminDS.setMode(DataStoreMode.Private);
                adminDS.setType(DataStoreType.Input_Output);
                adminDS.setName(adminUser.getUsername() + "_default");

                tx = em.getTransaction();
                try {
                    tx.begin();
                    em.persist(adminDS);
                    tx.commit();
                } finally {
                    if (tx != null && tx.isActive()) {
                        tx.rollback();
                    }
                }
            }
        }
    } finally {
        em.close();
    }

    System.out.println("[DBInitializer] DB initialized.");
}

From source file:nl.b3p.kaartenbalie.service.servlet.GeneralServlet.java

public static User checkLogin(HttpServletRequest request, String pcode) throws Exception {
    User user = null;/*w  w  w .  j a  va 2 s . com*/
    Object identity = null;
    EntityTransaction tx = null;

    try {
        identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.INIT_EM);
        EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.INIT_EM);
        tx = em.getTransaction();
        tx.begin();

        user = checkLogin(request, pcode, em);

        tx.commit();
    } finally {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.INIT_EM);
    }

    return user;
}

From source file:com.pocketgorilla.stripesem.TransactionFilter.java

private void doAfter() {
    EntityManager em = provider.getEntityManager(false);
    if ((em != null) && (em.isOpen())) {
        EntityTransaction tx = em.getTransaction();
        if (tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
                log.info("Rolled back persistence transaction.");
            } else {
                tx.commit();/*from  w  w w. j a  va 2 s . com*/
                log.debug("Committed persistence transaction.");
            }
        }
        em.close();
        provider.removeEntityManager();
    }
}