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: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  v  a  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.juddi.validation.ValidateValueSetValidation.java

/**
 * return the publisher/*from w w w . j a  v  a  2s. 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:com.ecarride.App.java

public static void ResetDriverWorkStatus() {
    Iterator<TlcDriver> iterator = tlcDrivers.iterator();
    while (iterator.hasNext()) {
        TlcDriver temp = iterator.next();
        if (!temp.isInTrouble())
            continue;
        EntityTransaction updateTransaction = entityManager.getTransaction();
        updateTransaction.begin();
        Query query = entityManager
                .createQuery("UPDATE Driver d SET d.baseApproved = 0, d.status = 0" + "WHERE d.id= :id");
        query.setParameter("id", temp.getDriver().getId());
        query.executeUpdate();/*from  w w  w .j  a  v  a  2 s.co  m*/
        updateTransaction.commit();
    }
}

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 .j a  v  a  2s  .  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:org.oxymores.chronix.core.ChronixContext.java

/**
 * Creates a new Context. This calls initContext, so no need to call it beforehand.
 * /*from   w w w .  ja  va  2  s.c o m*/
 * @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  w w .jav 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:org.apache.juddi.config.Install.java

protected static void install(Configuration config)
        throws JAXBException, DispositionReportFaultMessage, IOException, ConfigurationException {

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();

    UddiEntityPublisher rootPublisher = null;

    try {/*  w w  w  .  j av  a 2 s .  co m*/
        tx.begin();
        boolean seedAlways = config.getBoolean("juddi.seed.always", false);
        boolean alreadyInstalled = alreadyInstalled(config);
        if (!seedAlways && alreadyInstalled)
            new FatalErrorException(new ErrorMessage("errors.install.AlreadyInstalled"));

        String rootPublisherStr = config.getString(Property.JUDDI_ROOT_PUBLISHER);
        String fileRootTModelKeygen = rootPublisherStr + FILE_TMODELKEYGEN;
        TModel rootTModelKeyGen = (TModel) buildInstallEntity(fileRootTModelKeygen, "org.uddi.api_v3", config);
        String fileRootBusinessEntity = rootPublisherStr + FILE_BUSINESSENTITY;
        org.uddi.api_v3.BusinessEntity rootBusinessEntity = (org.uddi.api_v3.BusinessEntity) buildInstallEntity(
                fileRootBusinessEntity, "org.uddi.api_v3", config);

        String rootPartition = getRootPartition(rootTModelKeyGen);
        String nodeId = getNodeId(rootBusinessEntity.getBusinessKey(), rootPartition);

        String fileRootPublisher = rootPublisherStr + FILE_PUBLISHER;
        if (!alreadyInstalled) {
            log.info("Loading the root Publisher from file " + fileRootPublisher);

            rootPublisher = installPublisher(em, fileRootPublisher, config);
            installRootPublisherKeyGen(em, rootTModelKeyGen, rootPartition, rootPublisher, nodeId);
            rootBusinessEntity.setBusinessKey(nodeId);
            installBusinessEntity(true, em, rootBusinessEntity, rootPublisher, rootPartition, config);
        } else {
            log.debug("juddi.seed.always reapplies all seed files except for the root data.");
        }

        List<String> juddiPublishers = getPublishers(config);
        for (String publisherStr : juddiPublishers) {
            String filePublisher = publisherStr + FILE_PUBLISHER;
            String fileTModelKeygen = publisherStr + FILE_TMODELKEYGEN;
            TModel tModelKeyGen = (TModel) buildInstallEntity(fileTModelKeygen, "org.uddi.api_v3", config);
            String fileBusinessEntity = publisherStr + FILE_BUSINESSENTITY;
            org.uddi.api_v3.BusinessEntity businessEntity = (org.uddi.api_v3.BusinessEntity) buildInstallEntity(
                    fileBusinessEntity, "org.uddi.api_v3", config);
            UddiEntityPublisher publisher = installPublisher(em, filePublisher, config);
            if (publisher == null) {
                throw new ConfigurationException("File " + filePublisher + " not found.");
            } else {
                if (tModelKeyGen != null)
                    installPublisherKeyGen(em, tModelKeyGen, publisher, nodeId);
                if (businessEntity != null)
                    installBusinessEntity(false, em, businessEntity, publisher, null, config);
                String fileTModels = publisherStr + FILE_TMODELS;
                installSaveTModel(em, fileTModels, publisher, nodeId, config);
            }
        }

        tx.commit();
    } catch (DispositionReportFaultMessage dr) {
        log.error(dr.getMessage(), dr);
        tx.rollback();
        throw dr;
    } catch (JAXBException je) {
        log.error(je.getMessage(), je);
        tx.rollback();
        throw je;
    } catch (IOException ie) {
        log.error(ie.getMessage(), ie);
        tx.rollback();
        throw ie;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

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.// w w w . java 2s .co  m
 * - 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 ww .j av a 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:modelo.DaoTiposActividadesImpl.java

@Override
public void modificarActividad(TipoActividad act) {

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