Example usage for javax.persistence EntityTransaction commit

List of usage examples for javax.persistence EntityTransaction commit

Introduction

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

Prototype

public void commit();

Source Link

Document

Commit the current resource transaction, writing any unflushed changes to the database.

Usage

From source file:org.isatools.isatab.commandline.PersistenceShellCommand.java

/**
 * TODO: this is a patch used until we are able to make the auto-indexing upon load feature working
 * It is called after persistence.//from  w w  w  .  j  a va2 s . com
 *
 * @param store               must contain the studies that have to be reindexed (with proper accession).
 * @param hibernateProperties - The hibernate properties indicating DB properties and Index location/Strategy,
 *                            and so forth.
 */
public static void reindexStudies(BIIObjectStore store, Properties hibernateProperties) {
    // Need to initialize this here, otherwise above config will fail
    log = Logger.getLogger(PersistenceShellCommand.class);

    hibernateProperties.setProperty("hibernate.search.indexing_strategy", "event");
    hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "update");
    hibernateProperties.setProperty("hbm2ddl.drop", "false");

    EntityManagerFactory emf1 = Persistence.createEntityManagerFactory("BIIEntityManager", hibernateProperties);
    EntityManager entityManager1 = emf1.createEntityManager();

    StudyDAO studyDAO = DaoFactory.getInstance(entityManager1).getStudyDAO();
    FullTextEntityManager fullTxtEm = Search.getFullTextEntityManager(entityManager1);
    EntityTransaction tnx = entityManager1.getTransaction();

    tnx.begin();
    for (Study study : store.valuesOfType(Study.class)) {
        Study dbStudy = studyDAO.getByAcc(study.getAcc());
        if (dbStudy != null) {
            out.println("Indexing Study #" + dbStudy.getAcc());
            fullTxtEm.index(dbStudy);
            log.info("Indexing of Study # " + dbStudy.getAcc() + " is complete!");
        }

    }
    log.info("Commiting & closing Entity Manager.");
    tnx.commit();
    entityManager1.close();
}

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

/**
 * return the publisher//from  w w w.  j a v a2  s  . co 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.oxymores.chronix.core.ChronixContext.java

/**
 * Creates a new Context. This calls initContext, so no need to call it beforehand.
 * /*  w w w  . jav  a  2s.  c  om*/
 * @param appConfDirectory
 * @param transacUnitName
 * @param historyUnitName
 * @param brokerInterface
 * @param simulation
 * @return
 * @throws ChronixPlanStorageException
 */
public static ChronixContext loadContext(String appConfDirectory, String transacUnitName,
        String historyUnitName, String brokerInterface, boolean simulation, String historyDBPath,
        String transacDbPath) throws ChronixPlanStorageException {
    log.info(String.format("Creating a new context from configuration database %s", appConfDirectory));

    if (!(new File(appConfDirectory).isDirectory())) {
        throw new ChronixPlanStorageException("Directory " + appConfDirectory + " does not exist", null);
    }

    ChronixContext ctx = initContext(appConfDirectory, transacUnitName, historyUnitName, brokerInterface,
            simulation);
    ctx.historyDbPath = historyDBPath;
    ctx.transacDbPath = transacDbPath;

    // List files in directory - and therefore applications
    File[] fileList = ctx.configurationDirectory.listFiles();
    HashMap<String, File[]> toLoad = new HashMap<String, File[]>();

    for (int i = 0; i < fileList.length; i++) {
        // Convention is app_(data|network)_UUID_version_.crn. Current
        // version is CURRENT, edited is WORKING, other versions are 1..n
        File f = fileList[i];
        String fileName = f.getName();

        if (fileName.startsWith("app_") && fileName.endsWith(".crn") && fileName.contains("CURRENT")
                && fileName.contains("data")) {
            // This is a current app DATA file.
            String id = fileName.split("_")[2];
            if (!toLoad.containsKey(id)) {
                toLoad.put(id, new File[2]);
            }
            toLoad.get(id)[0] = f;
        }
    }

    // ///////////////////
    // Load apps
    // ///////////////////

    for (File[] ss : toLoad.values()) {
        ctx.loadApplication(ss[0], simulation);
    }

    // ///////////////////
    // Post load checkup & inits
    // ///////////////////

    if (ctx.applicationsById.values().size() > 0) {
        EntityManager em = ctx.getTransacEM();
        EntityTransaction tr = em.getTransaction();
        tr.begin();
        for (Application a : ctx.applicationsById.values()) {
            for (Calendar c : a.calendars.values()) {
                c.createPointers(em);
            }
        }
        tr.commit();
        tr.begin();
        for (Application a : ctx.applicationsById.values()) {
            for (State s : a.getStates()) {
                s.createPointers(em);
            }
        }
        tr.commit();
    }

    // TODO: cleanup event data (elements they reference may have been
    // removed)

    // TODO: validate apps

    // Done!
    return ctx;
}

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// w ww. 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 w ww  .  ja  v a  2  s.  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 ava  2  s  . c  om
    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:org.apache.juddi.replication.ReplicationNotifier.java

/**
 * returns the latest version of the replication config or null if there
 * is no config/*from   w w  w .ja  v a2s .com*/
 *
 * @return
 */
public static org.uddi.repl_v3.ReplicationConfiguration FetchEdges() {

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = null;
    org.uddi.repl_v3.ReplicationConfiguration item = new org.uddi.repl_v3.ReplicationConfiguration();
    try {
        tx = em.getTransaction();
        tx.begin();
        Query q = em
                .createQuery("SELECT item FROM ReplicationConfiguration item order by item.serialNumber DESC");
        q.setMaxResults(1);
        ReplicationConfiguration results = (ReplicationConfiguration) q.getSingleResult();
        //   ReplicationConfiguration find = em.find(ReplicationConfiguration.class, null);
        if (results != null) {
            MappingModelToApi.mapReplicationConfiguration(results, item);
        }

        tx.commit();
        return item;
    } catch (Exception ex) {
        //log.error("error", ex);
        //no config available
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
    } finally {
        em.close();
    }
    return null;
}

From source file:modelo.DaoTiposActividadesImpl.java

@Override
public void modificarActividad(TipoActividad act) {

    EntityTransaction tx = em.getTransaction();
    tx.begin();//  w ww. j  a v a2  s.c o m
    em.merge(act);
    tx.commit();
    em.close();
}

From source file:modelo.DaoTiposActividadesImpl.java

@Transactional()

@Override/*from  w w w  .  j av  a2 s  .c  o m*/
public void guardarActividad(TipoActividad act) {

    EntityTransaction tx = em.getTransaction();
    tx.begin();
    em.persist(act);

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

From source file:modelo.DaoTiposActividadesImpl.java

@Override
public void eliminarActividad(int idtipoActividad) {
    /* EntityManager em=this.obtenerEntityManager();
     Actividad act=em.find(Actividad.class,idactividades);
     EntityTransaction tx=em.getTransaction();
     tx.begin();/*  w w w.  ja  v a  2  s. co m*/
     em.remove(act);
     tx.commit();
     em.close();*/

    String jpql = "delete from Actividad act where act.idactividades=?1";

    Query q = em.createQuery(jpql);
    q.setParameter(1, idtipoActividad);
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    q.executeUpdate();
    tx.commit();
    em.close();

}