Example usage for javax.persistence EntityManager close

List of usage examples for javax.persistence EntityManager close

Introduction

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

Prototype

public void close();

Source Link

Document

Close an application-managed entity manager.

Usage

From source file:au.org.ands.vocabs.toolkit.test.arquillian.ArquillianTestUtils.java

/** Do a full export of the database in DBUnit format.
 * @param exportFilename The name of the file into which the
 *      export is to go.//from w w w .  ja v  a2 s . co m
 * @throws DatabaseUnitException If a problem with DBUnit.
 * @throws HibernateException If a problem getting the underlying
 *          JDBC connection.
 * @throws IOException If a problem writing the export.
 * @throws SQLException If DBUnit has a problem performing
 *           performing JDBC operations.
 */
public static void exportFullDBData(final String exportFilename)
        throws DatabaseUnitException, HibernateException, IOException, SQLException {
    EntityManager em = DBContext.getEntityManager();
    try (Connection conn = em.unwrap(SessionImpl.class).connection()) {
        IDatabaseConnection connection = new H2Connection(conn, null);
        IDataSet fullDataSet = connection.createDataSet();
        FlatXmlDataSet.write(fullDataSet, new FileOutputStream(exportFilename));
    }
    em.close();
}

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

/** Get access point by access point id.
 * @param id access point id// w  w  w  .j  a v  a  2  s  .com
 * @return the access point
 */
public static AccessPoint getAccessPointById(final int id) {
    EntityManager em = DBContext.getEntityManager();
    AccessPoint ap = em.find(AccessPoint.class, id);
    em.close();
    return ap;
}

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.
 *///ww w  .  j  av  a 2  s  .  c o m
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

/** Save a new access point to the database.
 * @param ap The access point to be saved.
 *//*from   w  w w. ja  v  a  2  s.c  o m*/
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:org.opentides.dao.impl.AuditLogDaoImpl.java

/**
 * Saves the log event into the database.
 * @param shortMessage//www . j  a v a  2  s.c om
 * @param message
 * @param entity
 */
public static void logEvent(String message, BaseEntity entity) {
    Long userId = entity.getAuditUserId();
    String username = entity.getAuditUsername();

    if (ApplicationStartupListener.isApplicationStarted()) {
        if (userId == null) {
            _log.error("No userId specified for audit logging on object [" + entity.getClass().getName()
                    + "] for message [" + message + "]. Retrieving user from interceptor.");
            SessionUser user = SecurityUtil.getSessionUser();
            userId = user.getId();
            username = user.getUsername();
        }
    } else {
        userId = new Long(0);
        username = "System Evolve";
    }

    EntityManager em = DatabaseUtil.getEntityManager();
    try {
        em.getTransaction().begin();
        AuditLog record = new AuditLog(message, entity.getId(), entity.getClass(), entity.getReference(),
                userId, username);
        em.persist(record);
        em.flush();
        em.getTransaction().commit();
    } finally {
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
}

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

/** Get all access points.
 * @return A list of AccessPoints/*www  . ja v a2  s . com*/
 */
public static List<AccessPoint> getAllAccessPoints() {
    EntityManager em = DBContext.getEntityManager();
    TypedQuery<AccessPoint> query = em.createNamedQuery(AccessPoint.GET_ALL_ACCESSPOINTS, AccessPoint.class);
    List<AccessPoint> aps = query.getResultList();
    em.close();
    return aps;
}

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

private static void importJobDef(String xmlpath) {
    try {/*  ww  w . ja v a2s.c o m*/
        EntityManager em = Helpers.getNewEm();
        if (em.createQuery("SELECT q FROM Queue q WHERE q.defaultQueue = true").getResultList().size() != 1) {
            jqmlogger.fatal(
                    "Cannot import a Job Definition when there are no queues defined. Create at least an engine first to create one");
            em.close();
            return;
        }

        String[] pathes = xmlpath.split(",");
        for (String path : pathes) {
            XmlJobDefParser.parse(path, em);
        }
        em.close();
    } catch (Exception e) {
        throw new JqmRuntimeException("Could not import file", e);
    }
}

From source file:nl.b3p.kaartenbalie.core.server.persistence.MyEMFDatabase.java

public static void closeEntityManager(Object ownership, String emKey) {
    if (ownership != null && ((Owner) ownership).identity) {
        log.debug("Identity is accepted. Now closing the session for key: " + emKey);
        EntityManager localEm = (EntityManager) getThreadLocal(emKey);
        if (localEm == null) {
            log.warn("EntityManager is missing. Either it's already closed or never initialized for key: "
                    + emKey);/*from   ww w  .  jav  a 2s  .  co m*/
            return;
        }
        clearThreadLocal(emKey);
        localEm.close();
    } else {
        log.debug("Identity is rejected. Ignoring the request for key: " + emKey);
    }
}

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

/** Get all access points for a version.
 * @param version The version./* w  ww. j  ava  2 s  .c o  m*/
 * @return The list of access points for this version.
 */
public static List<AccessPoint> getAccessPointsForVersion(final Version version) {
    EntityManager em = DBContext.getEntityManager();
    TypedQuery<AccessPoint> q = em.createNamedQuery(AccessPoint.GET_ACCESSPOINTS_FOR_VERSION, AccessPoint.class)
            .setParameter(AccessPoint.GET_ACCESSPOINTS_FOR_VERSION_VERSIONID, version.getId());
    List<AccessPoint> aps = q.getResultList();
    em.close();
    return aps;
}

From source file:actors.SessionCleaner.java

public static boolean clean(WebSession session, boolean timedout, boolean forceCleanup) {
    if (session == null) {
        return false;
    }/*from   ww w .j av  a  2 s. c  o  m*/

    Logger.info("deleting session " + UuidUtils.normalize(session.getId()));
    List<ProgressObserverToken> poTokens = ProgressObserverToken.find.where().eq("session", session).findList();
    for (ProgressObserverToken poToken : poTokens) {
        poToken.delete();
    }

    if (session.getStatus() == SessionStatus.ALIVE || forceCleanup) {
        session.setStatus(timedout ? SessionStatus.TIMEDOUT : SessionStatus.KILLED);
        session.update();

        // if the session is not authenticated, delete all stores owned.
        if (!SessionedAction.isAuthenticated(session)) {
            EntityManager em = SareTransactionalAction.createEntityManager();
            em.getTransaction().begin();

            // delete all owned stores.
            for (String uuid : new PersistentDocumentStoreController().getAllUuids(em,
                    UuidUtils.normalize(session.getId()))) {
                Logger.info("deleting store " + uuid + " owned by " + UuidUtils.normalize(session.getId()));
                PersistentDocumentStore store = em.find(PersistentDocumentStore.class, UuidUtils.toBytes(uuid));
                if (store != null) {
                    em.remove(store);
                }
            }

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

    return true;
}