Example usage for javax.persistence EntityManager getTransaction

List of usage examples for javax.persistence EntityManager getTransaction

Introduction

In this page you can find the example usage for javax.persistence EntityManager getTransaction.

Prototype

public EntityTransaction getTransaction();

Source Link

Document

Return the resource-level EntityTransaction object.

Usage

From source file:com.enioka.jqm.test.helpers.TestHelpers.java

public static void cleanup(EntityManager em) {
    em.getTransaction().begin();
    em.createQuery("DELETE GlobalParameter WHERE 1=1").executeUpdate();
    em.createQuery("DELETE Deliverable WHERE 1=1").executeUpdate();
    em.createQuery("DELETE DeploymentParameter WHERE 1=1").executeUpdate();
    em.createQuery("DELETE Message WHERE 1=1").executeUpdate();
    em.createQuery("DELETE History WHERE 1=1").executeUpdate();
    em.createQuery("DELETE JobDefParameter WHERE 1=1").executeUpdate();
    em.createQuery("DELETE RuntimeParameter WHERE 1=1").executeUpdate();
    em.createQuery("DELETE JobInstance WHERE 1=1").executeUpdate();
    em.createQuery("DELETE Node WHERE 1=1").executeUpdate();
    em.createQuery("DELETE JobDef WHERE 1=1").executeUpdate();
    em.createQuery("DELETE Queue WHERE 1=1").executeUpdate();
    em.createQuery("DELETE JndiObjectResourceParameter WHERE 1=1").executeUpdate();
    em.createQuery("DELETE JndiObjectResource WHERE 1=1").executeUpdate();
    em.createQuery("DELETE PKI WHERE 1=1").executeUpdate();
    em.createQuery("DELETE RPermission WHERE 1=1").executeUpdate();
    em.createQuery("DELETE RRole WHERE 1=1").executeUpdate();
    em.createQuery("DELETE RUser WHERE 1=1").executeUpdate();

    em.getTransaction().commit();//from w w w.  j a v  a2s.c  om

    try {
        // Conf dir may contain certificates and certificate stores
        if ((new File("./conf")).isDirectory()) {
            FileUtils.deleteDirectory(new File("./conf"));
        }
        // All logs
        if ((new File("./logs")).isDirectory()) {
            FileUtils.deleteDirectory(new File("./logs"));
        }
        // The war...
        if ((new File("./webapp")).isDirectory()) {
            FileUtils.deleteDirectory(new File("./webapp"));
        }
        // Where files created by payloads are stored
        File f = TestHelpers.node == null ? null : new File(TestHelpers.node.getDlRepo());
        if (f != null && f.isDirectory()) {
            FileUtils.cleanDirectory(new File(TestHelpers.node.getDlRepo()));
        }
        // Temp dir where files downloaded by the API are stored (supposed to be self-destructible file but anyway)
        if ((new File(System.getProperty("java.io.tmpdir") + "/jqm")).isDirectory()) {
            FileUtils.cleanDirectory(new File(System.getProperty("java.io.tmpdir") + "/jqm"));
        }
    } catch (IOException e) {
        // Nothing to do
    }
}

From source file:com.enioka.jqm.tools.Main.java

private static void root(String password) {
    EntityManager em = null;
    try {//from  ww  w.j  ava  2 s .  c  o  m
        em = Helpers.getNewEm();
        em.getTransaction().begin();
        RRole r = Helpers.createRoleIfMissing(em, "administrator", "all permissions without exception", "*:*");

        RUser u = Helpers.createUserIfMissing(em, "root", "all powerful user", r);
        u.setPassword(password);
        Helpers.encodePassword(u);

        em.getTransaction().commit();
    } catch (Exception ex) {
        jqmlogger.fatal("Could not parse and import the file", ex);
    } finally {
        Helpers.closeQuietly(em);
    }
}

From source file:controllers.base.SareTransactionalAction.java

public static <T> T execute(SareTxRunnable<T> action, Context ctx) throws Throwable {
    Validate.notNull(action);// www  . ja  v  a2  s .c  o m

    T result = null;
    EntityManager em = null;
    try {
        // create entity manager, add it to args, and begin transaction before the call.
        Logger.info(LoggedAction.getLogEntry(ctx, "creating entity manager"));
        em = createEntityManager();
        em.getTransaction().begin();

        // call the actual action.
        result = action.run(em);

        // commit active transaction after the call.
        if (em.isOpen() && em.getTransaction().isActive()) {
            em.getTransaction().commit();
        }
    } catch (Throwable e) {
        // rollback on error.
        if (em.isOpen() && em.getTransaction().isActive()) {
            Logger.info(LoggedAction.getLogEntry(ctx, "rolling back transaction"));
            em.getTransaction().rollback();
        }

        // rethrow.
        throw e;
    } finally {
        // close entity manager.
        if (em != null && em.isOpen()) {
            em.close();
        }
    }

    return result;
}

From source file:au.org.ands.vocabs.toolkit.db.AccessPointUtils.java

/** Save a new access point to the database.
 * @param ap The access point to be saved.
 *//*from  w w w.ja v a  2s .  com*/
public static void saveAccessPoint(final AccessPoint ap) {
    EntityManager em = DBContext.getEntityManager();
    em.getTransaction().begin();
    em.persist(ap);
    em.getTransaction().commit();
    em.close();
}

From source file:au.org.ands.vocabs.toolkit.db.AccessPointUtils.java

/** Update an existing access point in the database.
 * @param ap The access point to be update.
 *//* w  ww  . ja  v  a2s. c  om*/
public static void updateAccessPoint(final AccessPoint ap) {
    EntityManager em = DBContext.getEntityManager();
    em.getTransaction().begin();
    em.merge(ap);
    em.getTransaction().commit();
    em.close();
}

From source file:au.org.ands.vocabs.toolkit.db.AccessPointUtils.java

/** Delete all access points of a certain type for a version.
 * @param version The version.//www .java  2s  .  c  o m
 * @param type The type of access point to look for.
 */
public static void deleteAccessPointsForVersionAndType(final Version version, final String type) {
    EntityManager em = DBContext.getEntityManager();
    em.getTransaction().begin();
    Query q = em.createNamedQuery(AccessPoint.DELETE_ACCESSPOINTS_FOR_VERSION_AND_TYPE)
            .setParameter(AccessPoint.DELETE_ACCESSPOINTS_FOR_VERSION_AND_TYPE_VERSIONID, version.getId())
            .setParameter(AccessPoint.DELETE_ACCESSPOINTS_FOR_VERSION_AND_TYPE_TYPE, type);
    q.executeUpdate();
    em.getTransaction().commit();
    em.close();
}

From source file:fredboat.db.entity.SearchResult.java

/**
 * @param playerManager the PlayerManager to perform encoding and decoding with
 * @param provider      the search provider that shall be used for this search
 * @param searchTerm    the query to search for
 * @param maxAgeMillis  the maximum age of the cached search result; provide a negative value for eternal cache
 * @return the cached search result; may return null for a non-existing or outdated search
 *///from  w w  w  .ja v a2s  .  c o m
public static AudioPlaylist load(AudioPlayerManager playerManager, SearchUtil.SearchProvider provider,
        String searchTerm, long maxAgeMillis) throws DatabaseNotReadyException {
    DatabaseManager dbManager = FredBoat.getDbManager();
    if (dbManager == null || !dbManager.isAvailable()) {
        throw new DatabaseNotReadyException();
    }

    EntityManager em = dbManager.getEntityManager();
    SearchResult sr;
    SearchResultId sId = new SearchResultId(provider, searchTerm);
    try {
        em.getTransaction().begin();
        sr = em.find(SearchResult.class, sId);
        em.getTransaction().commit();
    } catch (PersistenceException e) {
        log.error("Unexpected error while trying to look up a search result for provider {} and search term {}",
                provider.name(), searchTerm, e);
        throw new DatabaseNotReadyException(e);
    } finally {
        em.close();
    }

    if (sr != null && (maxAgeMillis < 0 || System.currentTimeMillis() < sr.timestamp + maxAgeMillis)) {
        return sr.getSearchResult(playerManager);
    } else {
        return null;
    }
}

From source file:com.fpuna.preproceso.PreprocesoTS.java

/**
 *
 * @param trainingSetFeatureList//from   w ww . ja  v  a  2 s  . c om
 */
public static void GuardarFeature(List<TrainingSetFeature> trainingSetFeatureList) {
    EntityManager entityManager = Persistence.createEntityManagerFactory("PreprocesoTSPU")
            .createEntityManager();

    entityManager.getTransaction().begin();

    Iterator<TrainingSetFeature> Iterator = trainingSetFeatureList.iterator();
    while (Iterator.hasNext()) {
        entityManager.persist(Iterator.next());
    }

    entityManager.getTransaction().commit();
    entityManager.close();
}

From source file:entity.files.SYSFilesTools.java

public static boolean deleteFile(SYSFiles sysfile) {
    boolean success = false;
    EntityManager em = OPDE.createEM();

    try {/*from   w  w w . ja va2s . c  o  m*/
        em.getTransaction().begin();
        SYSFiles mySYSFile = em.merge(sysfile);
        em.remove(mySYSFile);
        em.getTransaction().commit();
        success = true;
    } catch (OptimisticLockException ole) {
        OPDE.warn(ole);
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
            OPDE.getMainframe().emptyFrame();
            OPDE.getMainframe().afterLogin();
        }

        OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
        success = false;
    } catch (Exception ex) {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        success = false;
    } finally {
        em.close();
    }

    if (success) {
        try {
            FileTransferClient ftp = getFTPClient();
            ftp.deleteFile(sysfile.getRemoteFilename());
            ftp.disconnect();
            OPDE.info("DELETING FILE FROM FTPSERVER: " + sysfile.getFilename() + " (" + sysfile.getMd5() + ")");
        } catch (Exception e) {
            OPDE.error(e);
            success = false;
        }
    }

    return success;
}

From source file:entity.files.SYSFilesTools.java

public static void detachFiles(SYSFiles[] files, SYSFilesContainer sysFilesContainer) {

    FileTransferClient ftp = getFTPClient();

    if (ftp != null) {
        EntityManager em = OPDE.createEM();
        try {//www.  j  av a2  s  .  c om
            em.getTransaction().begin();

            for (SYSFiles sysfile : files) {
                SYSFilesLink link = em.merge(sysFilesContainer.detachFile(sysfile));
                em.remove(link);
            }

            em.getTransaction().commit();
        } catch (OptimisticLockException ole) {
            OPDE.warn(ole);
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                OPDE.getMainframe().emptyFrame();
                OPDE.getMainframe().afterLogin();
            }
            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
        } catch (Exception ex) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            OPDE.fatal(ex);
        } finally {
            em.close();
            try {
                ftp.disconnect();
            } catch (Exception e) {
                OPDE.error(e);
            }
        }
    }
}