Example usage for javax.persistence EntityTransaction isActive

List of usage examples for javax.persistence EntityTransaction isActive

Introduction

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

Prototype

public boolean isActive();

Source Link

Document

Indicate whether a resource transaction is in progress.

Usage

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 www . j a v a  2 s .  co 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  ww  .j a va 2  s.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();/*from  ww w . j  a  v  a2s.c om*/
    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/*ww w.j  av a2s.c  o m*/
 *
 * @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 w  w  w . 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  ww w  .  j  av  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;//from ww w . j  a  v a 2  s.  c  o  m
    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();// ww w. j  a va  2s.  c o  m
                log.info("Rolled back persistence transaction.");
            } else {
                tx.commit();
                log.debug("Committed persistence transaction.");
            }
        }
        em.close();
        provider.removeEntityManager();
    }
}

From source file:br.com.blackhouse.internet.bindings.intercept.TransactionalInterceptor.java

@AroundInvoke
public Object invoke(InvocationContext context) throws Exception {
    EntityTransaction transaction = entityManager.getTransaction();

    try {/*from w  w  w  .  j a v  a  2 s . co  m*/
        if (!transaction.isActive()) {
            transaction.begin();
        }

        return context.proceed();

    } catch (Exception e) {
        logger.error("Exception in transactional method call", e);

        if (transaction != null) {
            transaction.rollback();
        }

        throw e;

    } finally {
        if (transaction != null && transaction.isActive()) {
            transaction.commit();
        }
    }

}

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

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (log.isDebugEnabled())
        log.debug("filtering " + ((HttpServletRequest) request).getRequestURI());

    try {// w w  w . j ava2 s  .  co m
        chain.doFilter(request, response);
    } catch (Exception ex) {
        try {
            EntityManager em = provider.getEntityManager(false);
            if (em != null) {
                EntityTransaction tx = em.getTransaction();
                if (tx.isActive()) {
                    tx.setRollbackOnly();
                }
            }
        } finally {
            throw new ServletException(ex);
        }
    } finally {
        doAfter();
    }
}